fmdtools.define.object

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:

  • base: for BaseObject, which is used for the base object class used for both objects and blocks/architectures.

  • geom: for Geom, class and subclasses which represent geometric attributes.

  • coords: for Coords, which is used to define coordinate systems.

  • timer: for Timer, which is used to define timers (used in fmdtools.define.container.time.Time containers).

fmdtools.define.object.base

Description: A module defining BaseObjects.

Classes in this module:

  • BaseObject: Base object class used throughout.

  • ExampleObject: Example base object for testing.

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', **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)
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

>>> from fmdtools.define.container.state import ExampleState
>>> class ExampleObject(BaseObject):
...    container_s = ExampleState
>>> 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)
check_dict_creation = False
check_slots()

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

containers
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

default_track = ['i']
find_roletype_initiators(roletype)
get_all_possible_track()

Get all possible tracking options.

get_all_roles(with_immutable=True)

Get all roles in the object.

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

Get memory from a particular role.

get_roledicts(*roledicts, with_immutable=True)

Get all roles in roledicts.

get_roles(*roletypes, with_immutable=True)

Get all roles.

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_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 = []
track
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.timer

Description: A module for defining timers for use in Time containers.

Has Classes: - Timer: Class defining 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)

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']
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

Module for defining geometries using the shapely library.

Now:

Static Geoms, with properties tied to parameters and states representing allocations.

Future:

Dynamic Geoms, with properties tied to states

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.

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.

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.

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.

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.

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

Module for creating x-y arrays to represent gridworlds.

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

Bases: BaseObject

Class for generating, accessing, and setting gridworld properties.

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

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.]])
build()

Set features as immutable.

check_role(roletype, rolename)

Check that the rolename for coords is ‘c’.

container_p

alias of CoordsParam

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(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("v", 10.0, np.equal)
array([[ 0.,  0.],
       [10.,  0.]])
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(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")
10.0
>>> ex.get(12.0, 4.9, "v")
10.0
>>> ex.get(50.0, 50.0, "v")
1.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_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': False, 'v': 10.0, 'st': 0.0}
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
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_grids(*args, **kwargs)

Prepare class with defined features.

init_properties(*args, **kwargs)

Initialize arrays with non-default values.

return_mutables()

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

return_states()

Return the mutable states of a Coords object.

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")
100.0
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_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")
-20.0
>>> ex.get(80, 80, "st")
-20.0

or:

>>> ex.set_pts([(50,50), [80,80]], "st", [-10.0, -5.0])
>>> ex.get(50, 50, "st")
-10.0
>>> ex.get(80, 80, "st")
-5.0
set_rand_pts(prop, value, number, pts=None, replace=False)

Ses 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("st", 40))
5
set_range(prop, value, xmin=0, xmax='max', ymin=0, ymax='max', inclusive=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.

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", 0.0)
>>> 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., 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.]])
>>> 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(prop, collections={}, legend_args=False, **kwargs)

Plot a property and set of collections on the grid.

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

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

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

  • **kwargs (kwargs) – 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='', 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.

  • 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_property(prop, xlab='x', ylab='y', proplab='prop', **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.

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

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

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

  • **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_z(prop, z='prop', z_res=10, collections={}, xlab='x', ylab='y', zlab='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 {}.

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

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

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

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.

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(14.0, 12.0)
array([10., 10.])
to_index(*args)

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

Parameters:

*args (number, number,...) – 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.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.

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.

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

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