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:
Defines |
|
Defines geometry classes using the shapely library. |
|
Defines |
|
Defines |
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:
objectBase 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:
- 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:
- 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:
- Returns:
h – History of states with structure {‘XX’:log} for indicator obj.indicate_XX
- Return type:
- 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:
- 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:
typeBase 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:
ModelGraphObjectgraph 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:
BaseObjectClass 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:
Geom: Base geometry classGeomPoint: Class defining points.PointParam: Class definingGeomPointattributes.GeomLine: Class defining lines.LineParam: Class definingGeomLineattributes.GeomPoly: Class defining polygons.
- class fmdtools.define.object.geom.Geom(*args, s={}, p={}, track='default', **kwargs)
Bases:
BaseGeomBase 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
- 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.GeomLine(*args, s={}, p={}, track='default', **kwargs)
Bases:
GeomPoint 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.GeomPoint(*args, s={}, p={}, track='default', **kwargs)
Bases:
GeomPoint 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:
GeomPolygon 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:
ParameterParameter 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 defineCoordsattributes.Coords, which is used to define coordinate systems.
- class fmdtools.define.object.coords.Coords(track='default', **kwargs)
Bases:
BaseCoordsClass 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’.
- 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:
ParameterDefines 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.