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 self.s.x > 1.0
...    def indicate_y_over_t(self, t):
...        return self.s.y > t
>>> 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_t')

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_t(0.0)
True
>>> ex2.return_true_indicators(0.0)
['high_x', 'y_over_t']

A history may be created using create_hist:

>>> ex.create_hist([0.0, 1.0])
i.high_x:                       array(2)
i.y_over_t:                     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_t:                     array(2)
s.x:                            array(2)
s.y:                            array(2)
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.

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 = 4.0
>>> ex.s
ExampleState(x=4.0, y=4.0)
>>> ex2.s
ExampleState(x=3.0, y=4.0)
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_mut_containers()

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)

Create state history of the object over the timerange.

Parameters:

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

Returns:

hist – A history of each recorded block property over the given timerange.

Return type:

History

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

Create networkx graph of the Block and its methods.

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()

Return list of mutable roles.

find_roletype_initiators(roletype)
flexible_roles = []
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, no_flows=False)
get_flex_role_objs(*flexible_roles, flex_prefixes=False)

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

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, time=0.0, 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.

  • time (float, optional) – Time to evaluate indicators at. The default is None.

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

Examples

>>> exec(example_object_code)
>>> ExampleObject().get_node_attrs()
{'s': ExampleState(x=1.0, y=1.0), 'indicators': ['y_over_t']}
>>> ExampleObject().get_node_attrs(roles=["none"])
{'indicators': ['y_over_t']}
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_roledicts(*roledicts, with_immutable=True)

Get all roles in roledicts.

get_roles(*roletypes, with_immutable=True, no_flows=False, **kwargs)

Get all roles.

get_roles_as_dict(*roletypes, with_immutable=True, with_prefix=False, flex_prefixes=False, with_flex=True, no_flows=False, **kwargs)

Return all roles and their objects as a dict.

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

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_role_dict(spec, name_end='s', set_attr=False)

Create a collection dict for the attribute ‘spec’.

Works by finding all attributes from the obj’s parameter with the name ‘spec’ in them and adding them to the dict. Adds the dict to the object.

Used in more flexible classes like Coords and Geom to enable properties to be set via parameters.

Parameters:
  • spec (str) – Name of the attributes to initialize

  • name_end (str) – Last letter or set of lettersof the attribute used to give the role name to where the dictionary will be placed. It may be “ions” with collections. Default is ‘s’.

  • set_attr (bool) – Whether to also add the individual attributes attr to the obj

init_roles(roletype, **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, **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.

name
reset()
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

return_true_indicators(time=0.0)

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

roledicts = []
roletypes = ['container']
rolevars = []
root
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.

track
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.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='')

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.reset()
>>> t
Timer test_timer: mode= standby, time= 0.0
containers
copy()

Copy the Timer.

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
name
reset()

Reset the time to zero.

roletypes = []
rolevars = ['time', 'mode']
root
set_timer(time, tstep=-1.0, 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.

track

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:

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

Bases: BaseObject

Base class for defining geometries.

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

Roles

sState

State defining mutable geom properties (e.g., allocation, color, etc)

pParam

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

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']
>>> exp.all_at(1.0, 0.1)
['on']
>>> exp.all_at(0.0, 0.0)
[]
at(pt, buffername='shape')

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

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

  • buffername (str) – Name of buffer property

Returns:

at – Whether x,y is within the buffer.

Return type:

bool

container_p

alias of Parameter

container_s

alias of State

copy(*args, **kwargs)

Copy the Geom with given *args and **kwargs.

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='', **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 for all shapes.

Returns:

  • fig (figure) – Matplotlib figure object

  • ax (axis) – Corresponding matplotlib axis

vect_at_shape(pt, buffername='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

  • buffername (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={'xys':((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, buffername='shape')

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

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

  • buffername (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.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
>>> exp = ExLine()
>>> exp.at((1.0, 1.0), "on")
True
>>> exp.at((0.0, 0.0), "on")
True
>>> exp.at((2.0, 2.0), "on")
False

Additionally, note the underlying shapely attribute at .shape:

>>> type(exp.shape)
<class 'shapely.geometry.linestring.LineString'>

As well as the buffer (on):

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

alias of LineParam

shapely_class

alias of LineString

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 attribute at .shape:

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

as well as the buffer (on):

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

alias of PointParam

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.at((0.1, 0.05))
True
>>> egp.at((0.4, 0.3))
False

Additionally, note the underlying shapely attribute at .shape:

>>> type(egp.shape)
<class 'shapely.geometry.polygon.Polygon'>
container_p

alias of PolyParam

shapely_class

alias of Polygon

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

Bases: Parameter

Parameter defining lines. May be extended with buffers.

Fields

xystuple

tuple of points ((x1, y1), …) defining shapely.LineString.

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(LineParam):
...     xys: tuple = ((0.0, 0.0), (1.0, 1.0))
...     buffer_on: float = 1.0
>>> exlp = ExLineParam()
>>> exlp.as_args()
(((0.0, 0.0), (1.0, 1.0)),)
as_args()

Create arguments for shapely LineString class based on fields.

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

Bases: Parameter

Parameter defining points. May be extended with buffers.

Fields

xfloat

x-location of point.

yfloat

y-location of point.

Examples

a point with center at 1.0, 1.0 and radius of 1.0 defining whether something is on the point would be defined by the parameter:

>>> class ExPointParam(PointParam):
...    x: float = 1.0
...    y: float = 1.0
...    buffer_on: float = 1.0
>>> expa = ExPointParam()
>>> expa.as_args()
([1.0, 1.0],)
as_args()

Create arguments for shapely Point class based on fields.

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)), )
>>> expp = ExPolyParam()
>>> expp.as_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)),))
as_args()

Create arguments for shapely Polygon class based on fields.

fmdtools.define.object.coords

Defines Coords class for representing coordinate systems.

Has classes:

class fmdtools.define.object.coords.Coords(*args, 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

init_p: CoordsParam

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

init_r: Rand

Random number generator. sets the .r container.

init_properties: method

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

Examples

>>> class ExampleCoords(Coords):
...    container_p = ExampleCoordsParam
...    def init_properties(self, *args, **kwargs):
...        self.set_pts([[0.0, 0.0], [10.0, 0.0]], "v", 10.0)

Instantiating a class with (see ExampleCoordsParam):

  • 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.

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

>>> ex = ExampleCoords()
>>> 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]
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.]])
add_coords_roles()

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

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

copy()

Copy the Coords object.

Examples

>>> ex = ExampleCoords()
>>> ex.set(0, 0, "st", 25.0)
>>> cop = ex.copy()
>>> cop.get(0, 0, "st")
25.0
>>> np.all(ex.st == cop.st)
True
>>> id(ex.st) == id(cop.st)
False
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

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
init_properties(*args, **kwargs)

Initialize arrays with non-default values.

return_mutables()

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

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=True, z='', xlabel='x', ylabel='y', title='', legend_args=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. 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_args (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_args=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_args (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.

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.

collect_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

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:

>>> class ExampleCoordsParam(CoordsParam):
...     feature_a: tuple = (bool, False)
...     feature_v: tuple = (float, 1.0)
...     state_st: tuple = (float, 0.0)
...     point_start: tuple = (0.0, 0.0)
...     collect_high_v: tuple = ("v", 5.0, np.greater)
>>> ex = ExampleCoordsParam()