fmdtools.define.object

Package defining various model building blocks.

The object subpackage provides a representation of base-level objects (i.e., timers, geometric points/lines, coordinates) which can be used to construct a simulation.

These different object classes are provided in the following modules:

fmdtools.define.object.base

Defines BaseObject class used to define objects.

fmdtools.define.object.geom

Defines geometry classes using the shapely library.

fmdtools.define.object.coords

Defines Coords class for representing coordinate systems.

fmdtools.define.object.timer

Defines Timer class for representing timers.

fmdtools.define.object.base

Defines BaseObject class used to define objects.

Classes in this module:

  • BaseObject: Base object class used throughout.

  • ObjectGraph: Generic ModelGraph representation for objects.

Functions contained in this module:

  • check_pickleability():Checks to see which attributes of an object will pickle (and thus parallelize)”

class fmdtools.define.object.base.BaseObject(name='', roletypes=[], track='default', root='', **kwargs)

Bases: object

Base object for Blocks, Flows, and Architectures.

Enables the instantiation of roles via class variables and object parameters, as well as representation of indictators and tracking.

Examples

The roletypes class variable lets one add specific types of roles to the class. By default, ‘container’ is included in roletypes, enabling:

>>> from fmdtools.define.container.state import ExampleState
>>> class ExampleObject(BaseObject):
...    container_s = ExampleState
...    def indicate_high_x(self):
...        return bool(self.s.x > 1.0)
...    def indicate_y_over_x(self):
...        return bool(self.s.y > self.s.x)
>>> ex = ExampleObject()
>>> ex.roletypes
['container']
>>> ex.containers
('s',)
>>> ex.s
ExampleState(x=1.0, y=1.0)

If an already-instanced role is passed, the BaseObject will take this copy instead of instancing its own:

>>> ex2 = ExampleObject(s=ExampleState(2.0, 4.0))
>>> ex2.s
ExampleState(x=2.0, y=4.0)

The method indicate_high_x is called an indicator. Indicators show up in the indicators property:

>>> ex.indicators
('high_x', 'y_over_x')

And are used to evaluate conditions, e.g.:

>>> ex.indicate_high_x()
False
>>> ex2.indicate_high_x()
True

Time may be used as an optional argument to indicators:

>>> ex.indicate_y_over_x()
False
>>> ex2.return_true_indicators()
['high_x', 'y_over_x']

A history may be created using create_hist:

>>> ex.create_hist([0.0, 1.0])
i.high_x:                       array(2)
i.y_over_x:                     array(2)

Note that adding roles to the class often means modifying default_track. Initializing all possible using the ‘all’ option:

>>> ex = ExampleObject(track='all')
>>> ex.create_hist([0.0, 1.0])
i.high_x:                       array(2)
i.y_over_x:                     array(2)
s.x:                            array(2)
s.y:                            array(2)

Objects are also jsonable and may be saved/loaded from a json format: >>> js = ex2.tojson() >>> ex3 = ExampleObject.fromjson(js) >>> ex3.s ExampleState(x=2.0, y=4.0) >>> ex3.save(“ex3.json”) >>> ex4 = ExampleObject.load(“ex3.json”, delete=True) >>> ex4.s ExampleState(x=2.0, y=4.0)

add_subgraph_edges(g, roles_to_connect=[], **kwargs)

Add non-role edges to the graph for the roles.

as_modelgraph(gtype=<class 'fmdtools.define.object.base.ObjectGraph'>, **kwargs)

Create and return the corresponding ModelGraph for the Object.

asdict(*roletypes, jsonable=False, exclude=[], with_flex=True, as_copy=False, **kwargs)

Return all aspects of the object in a dictionary.

Used to create jsonable representations of the object.

Parameters:
  • *roletypes (str) – Roletypes to get (will otherwise populate as default roletypes).

  • jsonable (bool, optional) – Whether to convert to json-able types. The default is False.

  • **kwargs (kwargs) – Keyword arguments to get_roles_as_dict

Returns:

dic – Dictionary with all object attributes.

Return type:

dict

assign_roles(roletype, other_obj, **kwargs)

Assign copies of the roles of another BaseObject to the current object.

Used in object copying to ensure copies have the same attributes as the current.

Parameters:
  • roletype (str) – Roletype to assign.

  • other_obj (BaseObject) – Object to assign from

  • **kwargs (kwargs) – Any keyword arguments to the role copy method.

Examples

>>> exec(example_object_code)
>>> ex = ExampleObject(s={'x': 1.0, 'y': 2.0})
>>> ex2 = ExampleObject(s={'x': 3.0, 'y': 4.0})
>>> ex.assign_roles('container', ex2)
>>> ex.s
ExampleState(x=3.0, y=4.0)

Note that these these roles should be independent after assignment:

>>> ex.s.x = np.float64(4.0)
>>> ex.s
ExampleState(x=4.0, y=4.0)
>>> ex2.s
ExampleState(x=3.0, y=4.0)
attrs = ('name', 'root', 'track')
base_type()

Return fmdtools type of the model class.

check_dict_creation = False
check_slots()

Check if __slots__ were defined for the class to preemt __dict__ creation.

containers = ()
copy(*args, exclude=['flow'], **kwargs)

Copy the object at the current state.

Parameters:

flows (dict) – Dict of flows to use in the copy.

Returns:

copy – Copy of the curent architecture.

Return type:

Architecture

copy_mutes(*mute_types, **kwargs)

Return copies of the mutable containers.

create_graph(g=None, name='', with_methods=True, with_root=True, with_inheritance=False, end_at_fmdtools=True, **kwargs)

Create a networkx graph view of the Block.

Parameters:
  • g (nx.Graph) – Existing networkx graph (if any). Default is None.

  • name (str) – Name of the node. Default is ‘’, which uses the get_full_name().

  • with_methods (bool) – Whether to include methods. Default is True.

  • end_at_fmdtools (bool) – Whether to end inheritance graph at first fmdtools class. Default is True.

  • **kwargs (kwargs) – Keyword arguments to create_role_subgraph.

Returns:

g – Networkx graph.

Return type:

nx.Graph

create_hist(timerange, track=None)

Create state history of the object over the timerange.

Parameters:

timerange (array) – Numpy array of times to initialize in the dictionary.

Returns:

  • hist (History) – A history of each recorded block property over the given timerange.

  • track (Track) – Argument to set track. Only used if history has not already been created. Default is None.

create_method_subgraph(g=None, name='', **kwargs)

Create networkx graph of the Block and its methods.

classmethod create_name(name='')

Create a name for the object (default is class name).

create_repr(rolenames=[], with_classname=True, with_name=True, one_line=False)

Provide a repl-friendly string showing the states of the Object.

Returns:

repr – console string

Return type:

str

create_role_con_edges(g, roles_to_connect=[], role='connection', edgetype='connection')

Connect roles at the same level of hierarchy.

create_role_subgraph(g=None, name='', role_nodes=['all'], recursive=False, with_containment=True, with_inheritance=False, with_methods=True, with_subgraph_edges=True, end_at_fmdtools=True, **kwargs)

Create a networkx graph view of the Block and its roles.

Parameters:
  • g (nx.Graph) – Existing networkx graph (if any). Default is None.

  • name (str) – Name of the node. Default is ‘’, which uses the get_full_name().

  • role_nodes (list, optional) – Roletypes to include in the subgraph. The default is [“all”].

  • recursive (bool, optional) – Whether to add nodes to the subgraph recursively from contained objects.

  • with_containment (bool) – Whether to include containment edges. Default is True.

  • with_inheritance (bool) – Whether to include class inheritance subgraphs. Default is False. The default is False.

  • with_methods (bool) – Whether to include methods as nodes. Default is False.

  • with_subgraph_edges (bool) – Whether to include subgraph edges, e.g. function/flow containment in an architecture graph.

  • end_at_fmdtools (bool) – Whether to end inheritance graph at first fmdtools class. Default is True.

  • **kwargs (kwargs) – kwargs to add_node

Returns:

g – Networkx graph.

Return type:

nx.Graph

default_track = ['i']
find_mutables(exclude=[])

Return list of mutable roles.

find_roletype_initiators(roletype)
flexible_roles = []
classmethod fromdict(data, **kwargs)

Instantiate object from a dict overwritten by kwargs.

classmethod fromjson(data, **kwargs)

Instantiate object from json.

Parameters:
  • data (json) – Json string.

  • **kwargs (keyword arguments.) – Keyword arguments for instantiation.

Returns:

obj – Object of the given class with roles corresponding to the given json.

Return type:

BaseObject

get_all_possible_track()

Get all possible tracking options.

get_all_roles(with_immutable=True)

Get all roles in the object.

get_att_roletype(attname, raise_if_none=False)

Get the roletype for a given attribute.

Parameters:

attname (str) – Name of a variable in the object.

Returns:

att_roletype – Type of role that initiated the variable.

Return type:

str

Examples

>>> exec(example_object_code)
>>> ExampleObject().get_att_roletype("s")
'container'
get_default_roletypes(*roletypes, exclude=[], with_flex=True)

Get the default role types for the object.

Parameters:
  • *roletypes (str) – Types of roles (e.g. ‘containers’ or ‘flows’). If not provided, all role types are included.

  • exclude (list) – Roletypes to exclude. Default is [].

  • with_flex (bool, optional) – Whether to include flexible roletypes (e.g., functions). The default is True.

Returns:

roletypes – List of default role types to iterate over, e.g. [‘containers’, ‘flows’].

Return type:

list

get_flex_dicts(*flex_roles, exclude=[])

Get flexible role dicts.

get_flex_role_objs(*flexible_roles, flex_prefixes=False)

Get the objects in flexible roles (e.g., functions, flows, components).

Parameters:
  • *flexible_roles (str) – Names of flexible roles (e.g., ‘fxns’, ‘flows’).

  • flex_prefixes (bool, optional) – Whether to include the prefixes in the keys of the returned dictionary. The default is False.

Returns:

flex_role_objs – Dict of flexible role objects with structure {‘rolename’: roleobject}

Return type:

dict

get_full_name(with_root=True)

Get the full name of the object (root + name).

get_indicators()

Get the names of the indicators.

Returns:

indicators – dict of indicator names and their associated method handles.

Return type:

dict

get_memory()

Get the memory taken up by the object and its containing roles.

Returns:

mem – Approximate memory taken by the object.

Return type:

float

get_node_attrs(roles=['container'], with_immutable=False, indicators=True, obj=False)

Get attributes from the node to attach to a graph node.

Parameters:
  • g (nx.Graph) – Graph where the object is a node.

  • roles (list, optional) – Roles to set as node attributes. The default is [‘container’].

  • with_immutable (bool, optional) – Whether to include immutable roles. The default is False.

  • indicators (bool, optional) – Whether to evaluate indicators. The default is True.

Examples

>>> exec(example_object_code)
>>> exo = ExampleObject(s={'y': 2.0})
>>> exo.get_node_attrs()
{'s': ExampleState(x=1.0, y=2.0), 'indicators': ['y_over_x']}
>>> exo.get_node_attrs(roles=["none"])
{'indicators': ['y_over_x']}
get_obj_attrs(*attrs, exclude=[])

Get non-role attributes of the object.

get_role_edgetype(attname, raise_if_none=False)

Get the edgetype for a given variable in the object.

Parameters:
  • attname (TYPE) – DESCRIPTION.

  • raise_if_none (TYPE, optional) – DESCRIPTION. The default is False.

Returns:

edgetype – Edgetype to give the contained object.

Return type:

str

get_roles(*roletypes, with_immutable=True, with_flex=True, with_prefix=False, exclude=[], **kwargs)

Get all roles from the object.

Parameters:
  • *roletypes (str) – Types of roles to get. If not provided, gets default roletypes.

  • with_immutable (bool, optional) – Whether to include immutable roles (e.g., parameters at container_p). The default is True.

  • with_flex (bool, optional) – Whether to include flexible roles. The default is True.

  • with_prefix (bool, optional) – Wheter to provide a prefix for the role.

  • **kwargs (kwargs) – (unused) keyword arguments

Returns:

roles – List of roles in the object, e.g. [‘p’, ‘s’ ‘r’] for an object with the parameter, state, and rand roles filled.

Return type:

list

get_roles_as_dict(*roletypes, with_immutable=True, with_prefix=False, with_flex=True, exclude=[], **kwargs)

Return all roles and their objects as a dict.

Parameters:
  • *roletypes (str) – Types of roles to get (e.g. “container”). If not provided, gets default roletypes.

  • with_immutable (bool, optional) – Whether to include immutable roles (e.g., parameters at container_p). The default is True.

  • with_prefix (bool, optional) – Whether to include the prefixes in the keys of the returned dictionary. The default is False.

  • exclude (bool, optional) – Roletypes and roles to exclude. The default is [].

  • with_flex (bool, optional) – Whether to include flexible roles. The default is True.

  • **kwargs (kwargs) – (unused) keyword arguments

Returns:

roles – List of roles in the object, e.g. [‘p’, ‘s’ ‘r’] for an object with the parameter, state, and rand roles filled.

Return type:

list

get_roles_values(*roletypes, with_immutable=True, with_flex=True, exclude=[], with_method=False, **kwargs)

Get the objects associated with each role.

get_typename()

Return name of the fmdtools type of the model class.

get_vars(*variables, trunc_tuple=True)

Get variable values in the object.

Parameters:

*variables (list/string) – Variables to get from the model. Can be specified as a list [‘fxnname2’, ‘comp1’, ‘att2’], or a str ‘fxnname.comp1.att2’

Returns:

variable_values – Values of variables. Passes (non-tuple) single value if only one variable.

Return type:

tuple

has_changed(update=False, exclude=[])

Check if the mutables of the object have changed.

immutable_roles = ['p']
indicators
init_indicator_hist(h, timerange, track)

Create a history for an object with indicator methods (e.g., obj.indicate_XX).

Parameters:
  • h (History) – History of Function/Flow/Model object with indicators appended in h[‘i’]

  • timerange (iterable, optional) – Time-range to initialize the history over. The default is None.

  • track (list/str/dict, optional) – argument specifying attributes for :func:`get_sub_include’. The default is None.

Returns:

h – History of states with structure {‘XX’:log} for indicator obj.indicate_XX

Return type:

History

init_indicators()

Find all indicator methods and initialize in .indicator tuple.

init_roles(roletype, initializer=None, **kwargs)

Initialize the role ‘roletype’ for a given object.

Roles defined using roletype_x in its class variables for the attribute x.

Object is instantiated with the attribute x, y, z corresponding to output of the class variable roletype_x, roletype_y, roletype_z, etc.

Parameters:
  • roletype (str) – Role to initialize (e.g., ‘container’). If none provided, initializes all.

  • **kwargs (dict) – Dictionary arguments (or already instantiated objects) to use for the attributes.

init_roletypes(*roletypes, initializer=None, **kwargs)

Initialize roletypes with given kwargs.

Parameters:
  • *roletypes (str) – Names of roles (e.g., container, flow, etc)

  • **kwargs (dict) – Dictionary arguments (or already instantiated objects) to use for the attributes.

init_track(track)

Add .track attribute based on default and input.

classmethod load(filename, delete=False, **kwargs)

Load object from json.

Parameters:
  • filename (str) – File to load from.

  • **kwargs (kwargs) – Keyword arguments for instantation

Returns:

obj – Object of the given class.

Return type:

BaseObject

mutables
name
reset()
return_mutables(exclude=[])

Return all mutable values in the block.

Used in static propagation steps to check if the block has changed.

Returns:

mutables – tuple of all mutable roles for the object.

Return type:

tuple

return_true_indicators()

Get list of indicators.

Parameters:

time (float) – Time to execute the indicator method at.

Returns:

List of inticators that return true at time

Return type:

list

roletypes = ['container']
rolevars = []
root
save(filename='', roletypes=[], **kwargs)

Save the object in a json format.

Parameters:
  • filename (str) – Name for the file. Will otherwise default to classname.json.

  • roletypes (iterable) – Rolenames argument to self.asdict()

  • **kwargs (kwargs) – Keyword arguments to self.asdict()

set_mutables(exclude=[])

Set the current mutables of the object (to check against later).

set_node_attrs(g, with_root=True, **kwargs)

Set attributes of the object to a graph.

Parameters:
  • g (nx.Graph) – Graph where the object is a node.

  • kwargs (kwargs) – Arguments to get_node_attrs.

set_vars(*args, **kwargs)

Set variables in the model to set values (useful for optimization, etc.).

Parameters:
  • varlist (list of lists/tuples) –

    List of variables to set, with possible structures:

    [[‘fxnname’, ‘att1’], [‘fxnname2’, ‘comp1’, ‘att2’], [‘flowname’, ‘att3’]] [‘fxnname.att1’, ‘fxnname.comp1.att2’, ‘flowname.att3’]

  • varvalues (list) – List of values corresponding to varlist

  • kwargs (kwargs) – attribute-value pairs. If provided, must be passed using ** syntax: mdl.set_vars(**{‘fxnname.varname’:value})

tojson(*roletypes, **kwargs)

Create a json representation of the object.

Parameters:
  • *roletypes (str) – Roletypes to convert.

  • **kwargs (kwargs) – Arguments to asdict()

Returns:

json – Json string representing the object.

Return type:

str

track
class fmdtools.define.object.base.BaseType(name, bases, dct)

Bases: type

Base type for BaseObject-based classes.

BaseType enables the use of __slots__ without defining explicit slots by relying on the defined class roletypes (e.g., containers, flows, etc) This enables lower memory use and faster access without requiring the user to define __slots__ for their classes.

class fmdtools.define.object.base.ObjectGraph(mdl, with_methods=True, with_inheritance=True, with_subgraph_edges=False, **kwargs)

Bases: ModelGraph

Objectgraph represents the definition of an Object.

set_edge_labels(title='edgetype', title2='', subtext='role', **edge_label_styles)

Create labels using Labels.from_iterator for the edges in the graph.

Parameters:
  • title (str, optional) – property to get for title text. The default is ‘id’.

  • title2 (str, optional) – property to get for title text after the colon. The default is ‘’.

  • subtext (str, optional) – property to get for the subtext. The default is ‘states’.

  • **edge_label_styles (dict) – LabelStyle arguments to overwrite.

set_node_labels(title='shortname', title2='classname', **node_label_styles)

Create labels using Labels.from_iterator for the nodes in the graph.

Parameters:
  • title (str, optional) – Property to get for title text. The default is ‘id’.

  • title2 (str, optional) – Property to get for title text after the colon. The default is ‘’.

  • subtext (str, optional) – property to get for the subtext. The default is ‘’.

  • node_label_styles (dict) – LabelStyle arguments to overwrite.

fmdtools.define.object.base.check_pickleability(obj, verbose=True, try_pick=False, pause=0.2)

Check to see which attributes of an object will pickle (and parallelize).

fmdtools.define.object.base.find_roletype_initiators(attrlist, roletype)

Find initiators from list that start with ‘roletype_’.

fmdtools.define.object.base.init_obj(name='', objclass=<class 'fmdtools.define.object.base.BaseObject'>, track='default', as_copy=False, **kwargs)

Initialize an object.

Enables one to instantiate different types of objects with given states/parameters or pass an already-constructured object.

Parameters:
  • name (str) – Name to give the flow object

  • objclass (class or object) – Class inheriting from BaseObject, or already instantiated object. Default is BaseObject.

  • track (str/dict) –

    Which model states to track over time (overwrites mdl.default_track). Default is ‘default’ Options:

    • ’default’

    • ’all’

    • ’none’

    • or a dict of form

      {'functions':{'fxn1':'att1'}, 'flows':{'flow1':'att1'}}
      

  • as_copy (bool) – If an object is provided for objclass, whether to copy that object (or just pass it). Default is False.

  • **kwargs (dict) – Other specialized roles to overrride

fmdtools.define.object.base.try_pickle_obj(obj)

Try to pickle an object. Raise exception if it doesn’t work.

fmdtools.define.object.timer

Defines Timer class for representing timers.

class fmdtools.define.object.timer.Timer(name='', time=0.0, tstep=-1.0, mode='standby', **kwargs)

Bases: BaseObject

Class for model timers used in functions (e.g. for conditional faults).

name

timer name

Type:

str

time

internal timer clock time

Type:

float

tstep

time to increment at each time-step

Type:

float

mode

the internal state of the timer

Type:

str (standby/ticking/complete)

Examples

>>> t = Timer("test_timer")
>>> t
Timer test_timer: mode= standby, time= 0.0
>>> t.set_timer(2)
>>> t
Timer test_timer: mode= set, time= 2
>>> t.inc()
>>> t
Timer test_timer: mode= ticking, time= 1.0
>>> t.inc()
>>> t
Timer test_timer: mode= complete, time= 0.0
>>> t.copy(name='copied')
Timer copied: mode= complete, time= 0.0
>>> t.reset()
>>> t
Timer test_timer: mode= standby, time= 0.0
attrs = ('name', 'root', 'track', 'time', 'tstep', 'mode')
default_track = ('time', 'mode')
inc(tstep=[])

Increment the time elapsed by tstep.

indicate_complete()

Indicate if the timer is complete (after time is done incrementing).

indicate_set()

Indicate if the timer is set (before time increments).

indicate_standby()

Indicate if the timer is in standby (time not set).

indicate_ticking()

Indictate if the timer is ticking (time is incrementing).

indicators
mode
mutables
name
reset()

Reset the time to zero.

roletypes = []
rolevars = ['time', 'mode']
root
set_timer(time, tstep=None, overwrite='always')

Set timer to a given time.

Parameters:
  • time (float) – set time to count down in the timer

  • tstep (float (default -1.0)) – time to increment the timer at each time-step

  • overwrite (str) – whether/how to overwrite the previous time. ‘always’ (default) sets the time to the given time. ‘if_more’ only overwrites the old time if the new time is greater. ‘if_less’ only overwrites the old time if the new time is less. ‘never’ doesn’t overwrite an existing timer unless it has reached 0.0. ‘increment’ increments the previous time by the new time.

t()

Return the time elapsed.

time
track
tstep

fmdtools.define.object.geom

Defines geometry classes using the shapely library.

For now, this includes static Geoms, with properties tied to parameters and states representing allocations.

In the future we hope to include Dynamic Geoms, with properties tied to states

Has classes:

  • BaseGeom: Base class for defining Geom subclasses

  • Geom: Base geometry class

  • class:

    GeomParameter: Parameter for Geom and subclasses.

  • GeomPoint: Class defining points..

  • GeomLine: Class defining lines.

  • GeomPoly: Class defining polygons.

  • GeomJSON: Class defining geometries from JSON.

  • GeomJSONParameter: Input parameter for GeomJSON.

class fmdtools.define.object.geom.BaseGeom(name='', roletypes=[], track='default', root='', **kwargs)

Bases: BaseObject

Base class for defining geometries.

Geometry objects are essentially interfaces for various shapely classes used to convey the spacial properties of a model.

all_at(*pt)

Find all geom attributes (shape, buffers, etc.) containing the point.

Parameters:

*pt (x,y,z) – Locations of x, y, z coordinates.

Returns:

all_at – Buffer/shape containing the pt.

Return type:

list

Examples

>>> exp = ExPoint()
>>> exp.all_at(1.0, 1.0)
['shape', 'on', 'around']
>>> exp.all_at(1.0, 0.1)
['on', 'around']
>>> exp.all_at(0.0, 0.0)
[]
assign_from(hist, t, *states)

Update Geom state from a given history and time.

at(pt, shape='shape')

Determine whether the point x, y is within the buffer ‘shape’.

Parameters:
  • *pt (tuple) – Locations of x, y, z coordinates.

  • shape (str) – Name of buffer property

Returns:

at – Whether x,y is within the buffer.

Return type:

bool

create_shape(shape='shape', base_shape=None)

Create the shapely object defining the class and buffers.

Parameters:

shape (str, optional) – Name of the shape. The default is ‘shape’, which produces the base shape, other names return the buffer shapes for that shape.

Returns:

Shapely object for the shape.

Return type:

shapely.geometry

reset()

Reset the Geom to initial state.

return_mutables()

Return all mutable values in the block.

Used in static propagation steps to check if the block has changed.

Returns:

mutables – tuple of all mutable roles for the object.

Return type:

tuple

show(shapes={'all': {}}, fig=None, ax=None, figsize=(4, 4), z=False, geomlabel='', legend=True, **kwargs)

Show a Geom (shape and buffers) as lines on a plot.

Parameters:
  • shapes (dict, optional) – Aspects of the Geom to plot and their corresponding plot kwargs. The default is {‘all’: {}}.

  • fig (matplotlib.figure, optional) – Existing Figure. The default is None.

  • ax (matplotlib.axis, optional) – Existing axis. The default is None.

  • figsize (tuple, optional) – Size for figure (if instantiating). The default is (4, 4).

  • z (bool/number, optional) – If plotting on a 3d axis, set z to a number which will be the z-level. The default is False.

  • geomlabel (str, optional) – Overall label for the geom (if desired). The default is ‘’.

  • **kwargs (kwargs) – overall kwargs for plt.plot (and/or consolidate_legend and add_title_xylabs) for all shapes.

Returns:

  • fig (figure) – Matplotlib figure object

  • ax (axis) – Corresponding matplotlib axis

vect_at_shape(pt, shape='shape', dist_forward=0.1)

Get the vector (x, y) at a given shape (e.g., direction of a line at pt).

Parameters:
  • pt (tuple/lost) – Point closest to shape

  • shape (str) – Name of shape/buffer. Default is ‘shape’.

  • dist_forward (float) – Distance forward along line segment to project. Give a negative number to reverse directions.

Examples

>>> e=ExLine(p={'coordinates':(((0,0),(1,1), (1,0)),)})
>>> e.vect_at_shape((0,0))
array([[0.07071068],
       [0.07071068]])
>>> e.vect_at_shape((1.5,0.5))
array([[ 0. ],
       [-0.1]])
vect_to_shape(pt, shape='shape')

Get the vector (x, y) to a given shape.

Parameters:
  • pt (tuple/list) – Point to get vector from

  • shape (str) – Name of shape/buffer. Default is ‘shape’.

Examples

>>> e = ExPoint()
>>> e.vect_to_shape((0,0))
array([[1.],
       [1.]])
>>> e.vect_to_shape((2,0))
array([[-1.],
       [ 1.]])
>>> e.vect_to_shape((1,1))
array([[0.],
       [0.]])
class fmdtools.define.object.geom.ExGeomState(*args, check_docs=False, get_fields=True, set_type=True, **kwargs)

Bases: State

Example Geom state for testing.

Has ‘occupied’ property defining whether something is at the geom or not.

class fmdtools.define.object.geom.ExLine(*args, s={}, p={}, track='default', **kwargs)

Bases: GeomLine

Example GeomLine to use in testing.

container_p

alias of ExLineParam

container_s

alias of ExGeomState

class fmdtools.define.object.geom.ExLineParam(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: GeomParameter

Example parameter defining a line with a given buffer ‘on’.

coordinates: tuple
class fmdtools.define.object.geom.ExPoint(*args, s={}, p={}, track='default', **kwargs)

Bases: GeomPoint

Example point for testing.

container_p

alias of ExPointParam

container_s

alias of ExGeomState

class fmdtools.define.object.geom.ExPointParam(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: GeomParameter

Example point parameter for testing.

Has a default center at (1.0, 1.0) and radius defining “on” of 1.0.

coordinates: tuple
class fmdtools.define.object.geom.ExPoly(*args, s={}, p={}, track='default', **kwargs)

Bases: GeomPoly

Example Polygon for use in testing.

container_p

alias of ExPolyParam

container_s

alias of ExGeomState

class fmdtools.define.object.geom.ExPolyParam(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: PolyParam

Example polygon parameter defining a basic triangle for use in testing.

class fmdtools.define.object.geom.Geom(*args, s={}, p={}, track='default', **kwargs)

Bases: BaseGeom

Base Geom object for geometries that are capable of moving/changing.

Roles

sState

State defining mutable properties (e.g., allocations, shapely class inputs)

pParam

Parameter defining immutable properties (e.g., shapely inputs, buffer)

container_p

alias of GeomParameter

container_s

alias of State

get_shape(shape='shape')

Get the shapely object defining the class (and defined buffers).

Parameters:

shape (str, optional) – Name of the shape. The default is ‘shape’, which produces the base shape, other names return the buffer shapes for that shape.

Returns:

Shapely object for the shape.

Return type:

shapely.geometry

get_shapely_args()

Get arguments for the given Shapely class.

Override to set shapely arguments from other states (e.g., not )

class fmdtools.define.object.geom.GeomJSON(*args, s={}, p={}, track='default', **kwargs)

Bases: BaseGeom

Geom object that is created from external geojson.

Examples

>>> gj = GeomJSON(p={'geojson': '{"type": "Point","coordinates": [1, 2]}'})
>>> gj.at([1,2])
True
>>> gj.at([1,3])
False
>>> gj.p.save("ex.geojson")
>>> gj = GeomJSON(p="ex.geojson")
>>> gj.at([1,2])
True
>>> gj.at([1,3])
False
>>> os.remove("ex.geojson")
container_p

alias of GeomJSONParameter

get_shape(shape='shape')

Get the shapely shape defining the class (and defined buffers).

class fmdtools.define.object.geom.GeomJSONParameter(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: Parameter

Parameter defining GeomJSON objects that use external information.

Holds the json as a string so it can be instantiated from shapely.form_json.

classmethod load(filename, delete=False, **kwargs)

Load from geojson.

save(filename, **kwargs)

Save file as geojson.

class fmdtools.define.object.geom.GeomLine(*args, s={}, p={}, track='default', **kwargs)

Bases: Geom

Point geometry representing a line and possible buffers.

Defined by parameter (xys and buffer(s)) as well as states (properties of of point).

Examples

>>> class ExLine(GeomLine):
...    container_p = ExLineParam
...    container_s = ExGeomState
>>> exl = ExLine()
>>> exl
exline ExLine
- s=ExGeomState(occupied=False, buffer_around=1.0)
>>> exl.at((1.0, 1.0), "on")
True
>>> exl.at((0.0, 0.0), "on")
True
>>> exl.at((2.0, 2.0), "on")
False

Additionally, note the underlying shapely objects returned by get_shape():

>>> type(exl.get_shape())
<class 'shapely.geometry.linestring.LineString'>

As well as the buffer (on):

>>> type(exl.get_shape('on'))
<class 'shapely.geometry.polygon.Polygon'>
>>> exl = ExLine()
>>> exl.get_shapely_args()
(((0.0, 0.0), (1.0, 1.0)),)
shapely_class

alias of LineString

class fmdtools.define.object.geom.GeomParameter(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: Parameter

Parameter defining dynamically simulable Geoms.

Give GeomParameter coordinates to define default coordinates for shapely’ default classes. Otherwise, GeomParameter can hold geojson.

Extend with ‘buffer_att’ to create buffer shapes.

Examples

A point with ends at (0.0, 0.0) and (1.0, 1.0) and radius of 1.0 defining whether something is on the line would be defined by the parameter:

>>> class ExLineParam(GeomParameter):
...     coordinates: tuple = ((0.0, 0.0), (1.0, 1.0))
...     buffer_on: float = 1.0
>>> ExLineParam()
ExLineParam(coordinates=((0.0, 0.0), (1.0, 1.0)), buffer_on=1.0)
class fmdtools.define.object.geom.GeomPoint(*args, s={}, p={}, track='default', **kwargs)

Bases: Geom

Point geometry representing x-y coordinate and buffers.

Defined by parameter (x, y and buffer(s)) as well as states (properties of of point).

Examples

>>> class ExPoint(GeomPoint):
...    container_p = ExPointParam
...    container_s = ExGeomState
>>> exp = ExPoint()
>>> exp.at((1.0, 1.0), "on")
True
>>> exp.at((0.0, 0.0), "on")
False
>>> exp.at((1.0, 0.1), "on")
True

Additionally, note the underlying shapely attributes returned by get_shape:

>>> type(exp.get_shape())
<class 'shapely.geometry.point.Point'>

as well as the buffer (on):

>>> type(exp.get_shape('on'))
<class 'shapely.geometry.polygon.Polygon'>

Finally, note how geom characteristics defined as states can change:

>>> exp.at((3.0, 1.0), 'around') # outside the default area of `around` buffer
False
>>> exp.s.buffer_around = 2.0 # set to a larger radius to capture the point
>>> exp.at((3.0, 1.0), 'around')
True
>>> exp = ExPoint()
>>> exp.get_shapely_args()
(1.0, 1.0)
shapely_class

alias of Point

class fmdtools.define.object.geom.GeomPoly(*args, s={}, p={}, track='default', **kwargs)

Bases: Geom

Polygon geometry defining shape and possible buffers.

Defined by PolyParam, which is used to instantiate the Polygon class. Also may contain a state for the given status (e.g., occupied, red/blue, etc.).

Examples

>>> class ExPoly(GeomPoly):
...    container_p = ExPolyParam
...    container_s = ExGeomState
>>> egp = ExPoly()
>>> egp
expoly ExPoly
- s=ExGeomState(occupied=False, buffer_around=1.0)
>>> egp.at((0.1, 0.05))
True
>>> egp.at((0.4, 0.3))
False

Additionally, note the underlying shapely objects returned by get_shape():

>>> type(egp.get_shape())
<class 'shapely.geometry.polygon.Polygon'>
>>> ExPoly().get_shapely_args()
(((0.0, 0.0), (1.0, 0.0), (1.0, 1.0)), (((0.3, 0.2), (0.6, 0.2), (0.6, 0.5)),))
shapely_class

alias of Polygon

class fmdtools.define.object.geom.PolyParam(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: Parameter

Parameter defining polygons. May be extended with buffers.

Fields

shelltuple

tuple of points ((x1, y1), …) defining outer shell.

holestuple

tuple of points defining holes.

Examples

The following PolyParam defines a hollow right triangle:

>>> class ExPolyParam(PolyParam):
...    shell: tuple = ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0))
...    holes: tuple = (((0.3, 0.2), (0.6, 0.2), (0.6, 0.5)), )
>>> ExPolyParam()
ExPolyParam(shell=((0.0, 0.0), (1.0, 0.0), (1.0, 1.0)), holes=(((0.3, 0.2), (0.6, 0.2), (0.6, 0.5)),))

fmdtools.define.object.coords

Defines Coords class for representing coordinate systems.

Has classes:

  • CoordsParam, which is used to define Coords attributes.

  • BaseCoords, which is used to define grids by subclasses.

  • Coords, which is used to define coordinate systems in models.

  • MetricCoords, which is used to analyze grid attributes.

class fmdtools.define.object.coords.BaseCoords(*args, track=[], **kwargs)

Bases: BaseObject

Abstract Base Coords class used for definition and analysis subclasses.

Creates a grid with given properties. Do not use for model definition. (Use Coords instead).

animate(hist, times='all', clear_fig=True, **kwargs)

Animate the coords over a history using show_from.

Parameters:
  • hist (History) – History of coords.

  • times (list/'all') – Times to animate over.

  • **kwargs (kwargs) – Arguments to self.show.

Returns:

ani – Object with animation.

Return type:

animation.Funcanimation

assign_from(hist, t, *properties)

Assign properties of the coords to a value from the history.

Useful for plotting progression of states over time.

Parameters:
  • hist (History) – History for the the coords object.

  • t (int) – Time-step to get from the history.

  • *properties (str) – Properties to assign from the history. If none provided, all are assigned.

container_p

alias of DefaultCoordsParam

find_all_prop(name, value=True, comparator=<ufunc 'equal'>)

Find all points in array satisfying statement defined by value and comparator.

Parameters:
  • name (str) – Name of the underlying property (state or feature).

  • value (bool/float/str/etc, optional) – Value to pass to comparator. The default is True.

  • comparator (function, optional) – Function to use to compare the value with the array. (e.g. np.equal, np.greater, np.less…). The default is np.equal.

Returns:

all – List of points where the comparator method returns true.

Return type:

np.array

Examples

>>> ex = ExampleCoords()
>>> ex.find_all_prop("v", 10.0, np.equal)
array([[ 0.,  0.],
       [10.,  0.]])
find_all_props(*args)

Find composite sets of points in arrays satisfying multiple conditions.

Parameters:

*args (tuples/str) – tuple of arguments to find_all, seperated by strings of conditionals.

Returns:

all – List of points satisfying conditions

Return type:

np.array

Examples

>>> ex = ExampleCoords()
>>> ex.find_all_props(("v", 10.0, np.equal))
array([[ 0.,  0.],
       [10.,  0.]])
>>> ex.st[0] = 1
>>> ex.find_all_props(("v", 10.0, np.equal), "and", ("st", 1.0, np.equal))
array([[0., 0.]])
>>> ex.find_all_props(("v", 10.0, np.equal), "or", ("st", 1.0, np.equal))
array([[ 0.,  0.],
       [ 0., 10.],
       [ 0., 20.],
       [ 0., 30.],
       [ 0., 40.],
       [ 0., 50.],
       [ 0., 60.],
       [ 0., 70.],
       [ 0., 80.],
       [ 0., 90.],
       [10.,  0.]])
>>> ex.hi_v_not_a
array([[ 0.,  0.],
       [10.,  0.]])
get(x, y, prop, outside='error')

Get the value of the property at the given scalar x/y values.

Parameters:
  • x (number) – Scalar x location

  • y (number) – Scalar y location

  • prop (str) – Name of the property to get.

  • outside (value) – Value to provide if not in range. Default is ‘error’, which throws an error

Returns:

value – Value to get from that point

Return type:

int/bool/float/…

Examples

>>> ex = ExampleCoords()
>>> ex.get(10.0, 0.0, "v")
np.float64(10.0)
>>> ex.get(12.0, 4.9, "v")
np.float64(10.0)
>>> ex.get(50.0, 50.0, "v")
np.float64(1.0)
get_neighbors(x, y, direction='all')

Get the points neighboring x and y.

Parameters:
  • x (float) – x-position

  • y (float) – y-position

  • direction (str/list) – Direction(s) to get neighbors from. Default is “all”. ‘direct’ returns the top, bottom, left, and right neighbors. ‘diagonal’ returns the four diagonal neighbors. ‘left’ returns the left neighbor. ‘right’ returns the right neighbor. ‘up’ returns the top neighbor. ‘down’ returns the bottow neighbor. ‘top-left’ returns the top left neighbor. ‘top-right’ returns the top right neighbor. ‘bottom-left’ returns the bottom left neighbor. ‘bottom-right’ returns the bottom right neighbor.

Returns:

neighbors – List of points next to the given grid point.

Return type:

list

Examples

>>> ex = ExampleCoords()
>>> ex.get_neighbors(0, 0)
[array([ 0., 10.]), array([10., 10.]), array([10.,  0.])]
>>> ex.get_neighbors(10, 10)
[array([ 0., 20.]), array([10., 20.]), array([20., 20.]), array([ 0., 10.]), array([20., 10.]), array([0., 0.]), array([10.,  0.]), array([20.,  0.])]
>>> ex.get_neighbors(10, 10, direction="left")
[array([ 0., 10.])]
>>> ex.get_neighbors(10, 10, direction="top-left")
[array([ 0., 20.])]
>>> ex.get_neighbors(10, 10, direction=["up","down"])
[array([10., 20.]), array([10.,  0.])]
>>> ex.get_neighbors(10, 10, direction="direct")
[array([10., 20.]), array([ 0., 10.]), array([20., 10.]), array([10.,  0.])]
>>> ex.get_neighbors(10, 10, direction="diagonal")
[array([ 0., 20.]), array([20., 20.]), array([0., 0.]), array([20.,  0.])]
get_properties(x, y)

Return a dictionary of all properties (features/states) at an x-y location.

Parameters:
  • x (number) – x-location to get from.

  • y (number) – y-location to get the properties from

Returns:

properties – Dictionary of property values at the given point.

Return type:

dict

Examples

>>> ex = ExampleCoords()
>>> ex.get_properties(0, 0)
{'a': np.False_, 'v': np.float64(10.0), 'st': np.float64(0.0)}
in_range(x, y)

Check to see if the x-y point is in the range of the coordinate system.

Parameters:
  • x (number) – x-position to check from.

  • y (number) – y-position to check from.

Returns:

in – Whether the point is in the range of the grid

Return type:

bool

init_grid_mesh()

Initialize grid and points arrays.

set(x, y, prop, value)

Set the value of the property at the given scalar x/y values.

Parameters:
  • x (number) – Scalar x location

  • y (number) – Scalar y location

  • prop (str) – Name of the property to get.

  • value (int/bool/float/...) – Value to set at that point

Examples

>>> ex = ExampleCoords()
>>> ex.set(15.0, 12.0, "st", 100.0)
>>> ex.get(15.0, 12.0, "st")
np.float64(100.0)
set_pts(pts, prop, value)

Set the property to a given value over a list of provided points.

Parameters:
  • pts (list) – List of points (e.g., [(1.0, 2.0), (3.0, 4.0)]) to set.

  • prop (str) – Name of the property to set.

  • value (int/bool/float or list...) – Value to set the points to. Can also pass a list.

Examples

>>> ex = ExampleCoords()
>>> ex.set_pts([(50,50), [80,80]], "st", -20.0)
>>> ex.get(50, 50, "st")
np.float64(-20.0)
>>> ex.get(80, 80, "st")
np.float64(-20.0)

or:

>>> ex.set_pts([(50,50), [80,80]], "st", [-10.0, -5.0])
>>> ex.get(50, 50, "st")
np.float64(-10.0)
>>> ex.get(80, 80, "st")
np.float64(-5.0)
set_range(prop, value, xmin=0, xmax='max', ymin=0, ymax='max', inclusive=True, outside_error=True)

Set ranges of the grid property to a given value.

Parameters:
  • prop (str) – Name of the range

  • value (value) – Value to set

  • xmin (number, optional) – Minimum x-value. The default is 0.

  • xmax (number, optional) – Maximum x-value. The default is ‘max’.

  • ymin (number, optional) – Minimum y-value. The default is 0.

  • ymax (number, optional) – Maximum y-value. The default is ‘max’.

  • inclusive (bool, optional) – Whether to include the end of the range. The default is False.

  • outside_errr (bool, optional) – whether to throw an error if the range is outside. Default is True

Examples

>>> ex = ExampleCoords()
>>> ex.set_range("st", 100.0, 20, 40, 20, 40)
>>> ex.st
array([[  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0., 100., 100., 100.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0., 100., 100., 100.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0., 100., 100., 100.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.]])
>>> ex.set_range("st", 10.0)
>>> ex.st
array([[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
       [10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]])
>>> ex.set_range("st", 0.0)
>>> ex.set_range("st", 20.0, 20, 40, 20, 40, inclusive=False)
>>> ex.st
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0., 20., 20.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0., 20., 20.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
show(properties={}, fig=None, ax=None, figsize=(5, 5), xlabel='x', ylabel='y', title='', pallette=['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'], **kwargs)

Show the properties array(s) of the BaseCoords object.

show_from(t, history={}, properties={}, clear_fig=False, traj_hist={}, traj_args=(), traj_kwargs={}, cut_traj=True, **kwargs)

Run Coords.show() at a particular time in the history.

Parameters:
  • t (int) – Time index to show the Coords object at.

  • hist (History) – History to show the Coords object at.

  • clear_fig (bool) – Whether to clear the figure beforehand. Default is False.

  • traj_hist (Hist, tuple, dict) – Optional history and arguments to the history to plot trajectories from using hist.plot_trajectories.

  • traj_args (Hist, tuple, dict) – Optional history and arguments to the history to plot trajectories from using hist.plot_trajectories.

  • traj_kwargs (Hist, tuple, dict) – Optional history and arguments to the history to plot trajectories from using hist.plot_trajectories.

  • cut_traj (bool) – Whether to cut traj_hist to the current state of Coords. Default is True.

  • **kwargs (kwargs) – kwargs for self.show

Returns:

  • fig (mpl.figure) – Plotted figure object

  • ax (mpl.axis) – Ploted axis object.

show_over_time(times, cols=2, figsize=(6, 6), titles={}, legend_loc=-1, legend_kwargs={}, subplot_kwargs={}, xlabel='x', ylabel='y', title='', **kwargs)

Show multiple frames of the Coords history over given times.

Parameters:
  • times (list) – List of times to show over.

  • cols (int, optional) – Number of columns for the multiplot. The default is 2.

  • figsize (tuple, optional) – Figure size. The default is (6, 6).

  • titles (dict, optional) – Individual titles for the plots. The default is {}.

  • legend_loc (int, optional) – Subplot to overlay the legend on. The default is -1.

  • legend_kwargs (dict, optional) – Legend keyword arguments. The default is {}.

  • subplot_kwargs (dict, optional) – . The default is {}.

  • xlabel (str, optional) – x-axis label. The default is ‘x’.

  • ylabel (str, optional) – y-axis label. The default is ‘y’.

  • title (str, optional) – Overall title. The default is ‘’.

  • **kwargs (kwargs) – Keyword arguments to Coords.show_from.

Returns:

  • fig (matplotlib.figure) – Figure with the frames.

  • axs (list) – List of subplot axes.

show_property(prop, xlabel='x', ylabel='y', title='', proplab='prop', as_bool=False, color='green', cmap='Greens', ec='black', text=False, text_kwargs={}, hatch=False, legend_kwargs={}, fig=None, ax=None, figsize=(5, 5), **kwargs)

Plot a given property ‘prop’ as a colormesh on an x-y grid.

See matplotlib.pyplot.pcolormesh.

Parameters:
  • prop (str) – Name of the property to plot.

  • xlabel (str, optional) – Label for x-axis. The default is “x”.

  • ylabel (str, optional) – Label for y-axis. The default is “y”.

  • title (str, optional) – Title for the plot. The default is ‘’.

  • proplab (str, optional) – Label for the property. The default is “prop”, which uses the name of the property provided.

  • as_bool (bool, optional) – Whether to interpret the property as a boolean where >0.0 returns as True and <=0.0 returns as False.

  • color (str, optional) – Color to use if the property is boolean. Default is ‘green’.

  • cmap (str, optional) – Colormap to use if property is continuous. Default is ‘Greens’.

  • ec (str, optional) – Default edge color. Default is ‘black’. If ‘face’, no edges are drawn.

  • text (dict, optional) – Whether to overlay text on the property. Default is False.

  • text_kwargs (dict) – kwargs to Coords.show_property_text (if text=True). Default is {}.

  • text

  • **kwargs (kwargs) – Keyword arguments to matplotlib.pyplot.pcolormesh (e.g., cmap, edgecolors)

Returns:

  • fig (mpl.figure) – Plotted figure object

  • ax (mpl.axis) – Ploted axis object.

show_property_text(prop, fontsize=8, digits=3, fig=None, ax=None, figsize=(5, 5))

Overlay text for a given property on map.

Parameters:
  • prop (str) – Property text.

  • fontsize (int, optional) – ax.text fontize argument. The default is 8.

  • digits (int, optional) – Digits of precision for property. The default is 3.

Returns:

  • fig (mpl.figure) – Plotted figure object

  • ax (mpl.axis) – Ploted axis object.

show_property_z(prop, z='prop', z_res=10, collections={}, xlabel='x', ylabel='y', zlabel='prop', proplab='prop', cmap='Greens', fig=None, ax=None, figsize=(4, 5), **kwargs)

Plot a given properties ‘prop’ and ‘z’ as a voxels on an x-y-z grid.

See mpl_toolkits.mplot3d.axes3d.Axes3D.voxels.

Parameters:
  • prop (str) – Name of the property to represent a color.

  • z (str, optional) – Name of the property to plot as z. The default is “prop”, which uses same property as prop.

  • z_res (int, optional) – Resolution to plot z at. The default is 10.

  • collections (dict, optional) – Collections to plot and their respective kwargs for show_collection. The default is {}.

  • xlabel (str, optional) – Label for x-axis. The default is “x”.

  • ylabel (str, optional) – Label for y-axis. The default is “y”.

  • zlabel (str, optional) – Label for the z-axis. The default is “prop”, which uses the name of the property.

  • proplab (str, optional) – Label for the property. The default is “prop”, which uses the name of the property provided.

  • cmap (str, optional) – Name of the matplotlib colormap to use for colors. The default is “Greens”.

  • fig (matplotlib.figure, optional) – Existing Figure. The default is None.

  • ax (matplotlib.axis, optional) – Existing axis. The default is None.

  • figsize (tuple, optional) – Size for the figure. Default is (4,4)

  • **kwargs (kwargs) – Kwargs to pass to Axes3D.voxels

Returns:

  • fig (mpl.figure) – Plotted figure object

  • ax (mpl.axis) – Ploted axis object.

to_gridpoint(*args)

Find the closest point in the grid corresponding to the given x/y values.

Parameters:

*args (number, number) – x-y value corresponding to the (unrounded) scalar location in the grid

Returns:

pt – x-y location corresponding to the (rounded) scalar location in the grid

Return type:

np.array

Examples

>>> ex = ExampleCoords()
>>> ex.to_gridpoint(3.5, 4)
array([0., 0.])
>>> ex.to_gridpoint(5.0, 0) # block range covers (-blocksize/2, blocksize/2]
array([0., 0.])
>>> ex.to_gridpoint(5.01, 0) # the next block starts at blocksize/2
array([10.,  0.])
>>> ex.to_gridpoint(14.0, 12.0)
array([10., 10.])
to_index(x, y)

Find the index of the array corresponding to the given x/y values.

Parameters:
  • x (float) – x-y values corresponding to the scalar location of the point in the grid.

  • y (float) – x-y values corresponding to the scalar location of the point in the grid.

Returns:

gridpoint – x-y integer values corresponding to the corresponding array index.

Return type:

tuple

Examples

>>> ex = ExampleCoords()
>>> ex.to_index(10, 20)
(1, 2)
>>> ex.to_index(54.234, 23.41)
(5, 2)
class fmdtools.define.object.coords.Coords(track='default', **kwargs)

Bases: BaseCoords

Class for generating, accessing, and setting gridworld properties.

Creates arrays, points, and lists of points which may correspond to desired modeling properties.

Class Variables/Modifiers

container_p: CoordsParam

Parameter controlling default grid matrix (see CoordsParam), along with other properties of interest. Sets the .p container.

container_r: Rand

Random number generator. sets the .r container.

init_properties: method

Method that initializes the (non-default) properties of the Coords.

Other Modifiers

feature_featurenametuple

Tuple (datatype, defaultvalue) defining immutable grid features to instantiate as arrays.

state_statenametuple

Tuple (datatype, defaultvalue) defining mutable grid features to instantiate as arrays.

collection_collectionnametuple

Tuple (propertyname, value, comparator) defining a collection of points to instantiate as a list, where the tuple is arguments to Coords.find_all_prop or to find_all_props

point_pointname: tuple

Tuple (x, y) referring to a point in the grid with a given name.

Examples

Defining the following classes will define a grid with a, v features, an h state, a point “start”, and a “high_v” collection:

Examples

Instantiating a class with:

  • immutable arrays a and v,

  • mutable array st,

  • point start at (0.0), and

  • collection high made up of all points where v > 10.0.

>>> class ExampleCoords(Coords):
...    feature_a = (bool, False)
...    feature_v = (float, 1.0)
...    state_st = (float, 0.0)
...    point_start = (0.0, 0.0)
...    collection_high_v = ("v", 5.0, np.greater)
...    collection_hi_v_not_a = (("v", 5.0, np.greater), "and", ("a", False, np.equal))
...    default_p = {'blocksize': 10.0}
...    def init_properties(self, **kwargs):
...        self.set_pts([[0.0, 0.0], [10.0, 0.0]], "v", 10.0)

As shown, features are normal numpy arrays set to readonly:

>>> ex = ExampleCoords()
>>> ex
examplecoords ExampleCoords
- p=DefaultCoordsParam(x_size=10, y_size=10, blocksize=10.0, gapwidth=0.0)
- r=Rand(seed=42)
- COLLECTIONS: high_v(bool), hi_v_not_a(bool)
- FEATURES: a(bool), v(float64)
- STATES: st(float64)
>>> type(ex.a)
<class 'numpy.ndarray'>
>>> np.size(ex.a)
100
>>> ex.a[0, 0] = True
Traceback (most recent call last):
  ...
ValueError: assignment destination is read-only

The main difference with states is that they can be set, e.g.,:

>>> ex.st[0, 0] = 100.0
>>> ex.st[0, 0]
np.float64(100.0)

Collections are lists of points that map to immutable properties. In ExampleCoords, all points where v > 5.0 should be a part of high_v, as shown:

>>> ex.high_v
array([[ 0.,  0.],
       [10.,  0.]])

Additionally, defined points (e.g., start) should be accessible via their names:

>>> ex.start
(0.0, 0.0)

Note that these histories are tracked:

>>> h = ex.create_hist([0, 1, 2])
>>> h.keys()
dict_keys(['r.probdens', 'st'])
>>> h.st[0]
array([[100.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.]])

Coords also save/load to json:

>>> ExampleCoords.fromjson(ex.tojson()).st[0, 0]
np.float64(100.0)
add_coords_roles()

Add points, collections, features, and states as roles to Coords.

asdict(*args, **kwargs)

Add stored kwargs to dict. Enables copying.

Examples

>>> ex = ExampleCoords()
>>> ex.set(0, 0, "st", 25.0)
>>> cop = ex.copy()
>>> cop.get(0, 0, "st")
np.float64(25.0)
>>> np.all(ex.st == cop.st)
np.True_
>>> id(ex.st) == id(cop.st)
False
base_type()

Return fmdtools type of the model class.

build()

Set features as immutable.

check_role(roletype, rolename)

Check that the rolename for coords is ‘c’.

container_r

alias of Rand

create_collection(*cargs)

Create a collection based on arguments to find_all_prob(s).

create_repr(rolenames=[''], one_line=False, **kwargs)

Create repr with showing grid properties.

find_all(*points_colls, in_points_colls=True, **prop_kwargs)

Find all points in array satisfying multiple statements.

Parameters:
  • *points_colls (str) – Name(s) of points or collections defining the set of points to check. If not provided, assumes all points.

  • in_points_colls (bool) – Whether the properties are to be searched in the given set of points/collections (True) or outside the given set of points/collections (False). The default is True

  • **prop_kwargs (kwargs) – keyword arguments corresponding to properties, values and comparators, e.g.: statename=(True, np.equal)

Returns:

all – List of points where the comparator methods returns true.

Return type:

np.array

Examples

>>> ex = ExampleCoords()
>>> ex.find_all(v=(10.0, np.equal))
array([[ 0.,  0.],
       [10.,  0.]])
>>> ex.st[0, 0] = 5.0
>>> ex.find_all(v=(10.0, np.equal), st=(0.0, np.greater))
array([[0., 0.]])
>>> ex.find_all("high_v", v=(10.0, np.equal))
array([[ 0.,  0.],
       [10.,  0.]])
>>> ex.find_all("high_v", v=(10.0, np.less))
array([], dtype=float64)
>>> ex.st[2,2] = 1.0
>>> ex.find_all("high_v", in_points_colls=False, st=(0.0, np.greater))
array([[20., 20.]])
find_closest(x, y, prop, include_pt=True, value=True, comparator=<ufunc 'equal'>)

Find the closest point in the grid satisfying a given property.

Parameters:
  • x (number) – x-position to check from.

  • y (number) – y-position to check from.

  • prop (str) – Property or collection of the grid to check.

  • include_pt (bool, optional) – Whether to include the containing grid point. The default is True.

  • value (bool/int/str, optional) – Value to compare against. The default is None, which returns the points that have the value True.

  • comparator (method, optional) – Comparator function to use (e.g., np.equal, np.greater…). The default is np.equal.

Returns:

pt – x-y position of the closest point satisfying the property.

Return type:

np.array

Examples

Can be used with default options to check collections, e.g.,:

>>> ex = ExampleCoords()
>>> ex.find_closest(20, 0, "high_v")
array([10.,  0.])

Alternatively can be used to search for the closest with a given property value, e.g.,:

>>> ex.set(0, 0, "st", 1.0)
>>> ex.find_closest(20, 0, "st", value=1.0, comparator=np.equal)
array([0., 0.])
get_all_possible_track()

Extend BaseObject to include states in tracking.

get_collection(prop)

Get the points for a given collection.

Parameters:

prop (str) – Name of the collection.

Returns:

coll – Array of points in the collection

Return type:

np.ndarray

get_property_dtype(prop)

Get defined data type of a given property.

in_area(x, y, coll)

Check to see if the point x, y is in a given collection or at a point.

Parameters:
  • x (number) – x-position to check from.

  • y (number) – y-position to check from.

  • coll (str) – Property or collection of the grid to check.

Returns:

in – Whether the point is in the collection

Return type:

bool

Examples

>>> ex = ExampleCoords()
>>> ex.in_area(0.4, 0.2, 'start')
True
>>> ex.in_area(10, 10, 'start')
False
>>> ex.in_area(-10, -10, 'start')
False
>>> ex.in_area(10, 20, 'hi_v_not_a')
False
>>> ex.in_area(10, 10, 'hi_v_not_a')
False
>>> ex.in_area(10, 0, 'hi_v_not_a')
True
init_properties(**kwargs)

Initialize arrays with non-default values.

load_property(prop, filename, delimiter=',', delete=False, **kwargs)

Load a property from a .csv or .json file.

Parameters:
  • prop (str) – Property name.

  • filename (str) – Filename to load from.

  • delimiter (str, optional) – File delimiter for json. The default is “,”.

  • delete (bool, optional) – Whether to delete the file after loading (for test). The default is False.

  • **kwargs (kwargs) – Keyword arguments to pandas.read_csv.

overwrite_properties(**kwargs)

Overwrite initialized properties with external copied/json inputs.

return_mutables()

Check if grid properties have changed (used in propagation).

save_property(prop, filename, propname='', **kwargs)

Save a property to a .csv or .json file.

Parameters:
  • prop (str) – Property name.

  • filename (str) – Filename to save to

  • **kwargs (kwargs) – Keyword arguments to DataFrame.to_csv

set_prop_dist(prop, dist, *args, **kwargs)

Randomizes a property according to a given distribution.

Parameters:
  • prop (str) – Property to set

  • dist (str) – Name of distribution to call from the rng. (see documentation for numpy.random)

  • *args (tuple, optional) – Arguments to the distribution method (e.g., (min, max)). The default is ().

  • **kwargs (kwargs, optional) – Keyword arguments to the distribution method. The default is {}.

set_rand_pts(prop, value, number, pts=None, replace=False)

Set a given number of points for a property to random value.

Parameters:
  • prop (str) – Property to set

  • value (int/float/str/etc) – Value to set the points to

  • number (int) – Number of points to set

  • pts (list, optional) – List of points to select from. The default is None (which selects from all points).

  • replace (bool, optional) – Whether to select with replacement. The default is False.

Examples

>>> ex = ExampleCoords()
>>> ex.set_rand_pts("st", 40, 5)
>>> len(ex.find_all_prop("st", 40))
5
show(properties={}, collections={}, coll_overlay=True, fig=None, ax=None, figsize=(5, 5), xlabel='x', ylabel='y', title='', pallette=['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'], **kwargs)

Plot a property and set of collections on the grid.

Parameters:
  • properties (dict) – Properties to plot and their arguments, e.g. {‘prop1’: {‘color’: ‘green’}}

  • collections (dict, optional) – Collections to plot and their respective kwargs for show_collection. The default is {}.

  • coll_overlay (bool, optional) – If True, show collections in front of properties. If False, show properties in front of collections. Default is True.

  • xlabel (str) – x-axis label.

  • ylabel (str) – y-axis label.

  • title (str) – title for the plot.

  • pallete (list) – List of colors (in order) to cycle through for each plot.

  • **kwargs (kwargs) – overall kwargs to show_property.

Returns:

  • fig (mpl.figure) – Plotted figure object

  • ax (mpl.axis) – Ploted axis object.

show_collection(prop, fig=None, ax=None, label='prop', text=False, z='', xlabel='x', ylabel='y', title='', legend_kwargs=False, text_z_offset=0.0, figsize=(4, 4), **kwargs)

Show a collection on the grid as square patches.

Parameters:
  • prop (str) – Name of the collection

  • fig (matplotlib.figure, optional) – Existing Figure. The default is None.

  • ax (matplotlib.axis, optional) – Existing axis. The default is None.

  • label (str/bool, optional) – Label for the collection. Default is ‘prop’, the collection name.

  • text (str/bool, optional) – Text to display on collection. The default is True, which shows the collection name. If False, no label is provided. If a string, the string is used as the label.

  • z (str) – Argument to plot as third dimension on 3d plot. Default is ‘’, which returns a 2d plot. If a number is provided, the plot will be 3d with the height at that constant z-value.

  • xlabel (str, optional) – Label for x-axis. The default is “x”.

  • ylabel (str, optional) – Label for y-axis. The default is “y”.

  • zlabel (str, optional) – Label for the z-axis. The default is “prop”, which uses the name of the property.

  • legend_kwargs (dict/False) – Specifies arguments to legend. Default is False, which shows no legend.

  • text_z_offset (float) – Offset for text. Default is 0.0

  • figsize (tuple) – Size for the figure. Default is (4,4)

  • **kwargs (kwargs) – Kwargs to matplotlib.patches.Rectangle

Returns:

  • fig (mpl.figure) – Plotted figure object

  • ax (mpl.axis) – Ploted axis object.

show_z(prop, z='prop', collections={}, legend_kwargs=False, voxels=True, **kwargs)

Plot a property and set of collections in a discretized version of the grid.

Parameters:
  • prop (str) – Property to plot.

  • z (str, optional) – Property to use as the height. The default is “prop”.

  • collections (dict, optional) – Collections to plot and their respective kwargs for show_collection. The default is {}.

  • legend_kwargs (dict/False) – Specifies arguments to legend. Default is False, which shows no legend.

  • voxels (bool) – Whether or not to plot the grid as voxels. Default is True.

  • **kwargs (kwargs) – kwargs to show_property3d.

Returns:

  • fig (mpl.figure) – Plotted figure object

  • ax (mpl.axis) – Ploted axis object.

class fmdtools.define.object.coords.CoordsParam(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: Parameter

Defines the underlying arrays that make up the Coords object.

Modifiers may be added to add additional properties (e.g., features, states, collections, points) to the coordinates. Additionally has class fields which may be overwritten.

Class Variables

x_sizeint

Number of rows in the x-dimension

y_sizeint

Number of rows in the y-dimension

blocksizefloat

Coordinate resolution

gapwidthfloat

Width between coordinate cells (if any). Blocksize is inclusive of this width.

create_grid(dtype, default)

Create an array with datatype dtype and default value default.

create_grid_mesh()

Create array of grid indexes.

create_repr(fields=['x_size', 'y_size', 'blocksize', 'gapwidth'], **kwargs)

Create repr-friendly string for container.

shape()

Return shape of grid.

class fmdtools.define.object.coords.DefaultCoordsParam(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: CoordsParam

Default Parameter for Coords (with no states/features).

blocksize: float64
gapwidth: float64
x_size: int32
y_size: int32
class fmdtools.define.object.coords.ExampleCoords(track='default', **kwargs)

Bases: Coords

Example of Coords class for use in documentation and testing.

init_properties(**kwargs)

Initialize points where v=10.0.

class fmdtools.define.object.coords.ExampleFileCoords(track='default', **kwargs)

Bases: Coords

Example Coords object to demonstrate and test save/load.

Examples

>>> exfc = ExampleFileCoords()
>>> exfc.object
array([[False,  True],
       [ True, False]])
>>> exfc.occupied
array([[ True, False],
       [False,  True]])
>>> exfc = ExampleFileCoords(filetype=".json")
>>> exfc.object
array([[False,  True],
       [ True, False]])
>>> exfc.occupied
array([[ True, False],
       [False,  True]])
init_properties(filetype='.csv', **kwargs)

Initialize arrays with non-default values.

class fmdtools.define.object.coords.MetricCoords(res, *args, values=[], metric=<function mean>, **kwargs)

Bases: BaseCoords

Create an array of metrics from a given result.

MetricCoords can be used to display summary statistics e.g., min, max, mean) of coords object results returned from simulations.

Parameters:
  • res (Result) – Result to get the result/histories from

  • values (list) – List of values to get. Default is [], which will not get any values.

  • metric (method) – Method to use to compute the metric.

Examples

>>> from fmdtools.analyze.result import Result
>>> r = Result({'b1.a': np.array([[0,1], [0,4]]), 'b2.a': np.array([[2,1], [2,6]])})
>>> mc = MetricCoords(r, values=['a'], metric=np.mean, p={'x_size':2, 'y_size': 2})
>>> mc.a
array([[1., 1.],
       [1., 5.]])
>>> mc = MetricCoords(r, values=['a'], metric=np.min, p={'x_size':2, 'y_size': 2})
>>> mc.a
array([[0, 1],
       [0, 4]])
fmdtools.define.object.coords.replace_array_nan(array)

Turn arrays with nans into arrays with infs.