fmdtools.define.container

Package defining system variables other base constructs.

The containers subpackage provides the elemental building puzzle pieces needed (i.e., containers for holding states, modes, etc.) to develop simulations, shown below.

fmdtools container classes

Container classes in fmdtools and their inheritance.

These classes are provided in the following modules:

fmdtools.define.container.base

Defines BaseContainer class which other containers inherit from.

fmdtools.define.container.mode

Defines Mode class for defining (faulty and otherwise) mode s.

fmdtools.define.container.state

Defines State class for representing variables that change over time.

fmdtools.define.container.parameter

Defines Parameter class to represent attributes that do not change.

fmdtools.define.container.rand

Defines Rand class and other methods defining random properties used in blocks.

fmdtools.define.container.time

Defines Time class for containing timers and time-related constructs.

fmdtools.define.container.base

Defines BaseContainer class which other containers inherit from.

class fmdtools.define.container.base.BaseContainer

Bases: dataobject

Base container class.

A container is a dataobject (from the recordclass library) that fulfills a specific role in a block. This class inherits from dataobject for low memory footprint and has a number of methods for making attribute assignment/copying/tracking easier.

asdict()

Return fields as a dictionary.

assign(obj, *fields, as_copy=True, **fielddict)

Set the same-named values of the current object to those of another.

Further arguments specify which values. e.g.,:

>>> p1 = ExContainer(x=0.0, y=0.0)
>>> p2 = ExContainer(x=10.0, y=20.0)
>>> p1.assign(p2, 'x', 'y')
>>> p1.x
10.0
>>> p1.y
20.0

Can also be used to assign list values to a variable, e.g.,:

>>> p1.assign([3.0,4.0], 'x', 'y')
>>> p1.x
3.0
>>> p1.y
4.0

Can also provide kwargs in case value names don’t match, e.g.,:

>>> p1.assign(p2, x='y', y='x')
>>> p1.x
20.0
>>> p1.y
10.0
as_copy: bool,

set to True for dicts/sets to be copied rather than referenced

base_type()

Return fmdtools type of the model class.

check_role(roletype, rolename)

Check that the container will be given the correct name for its class.

The correct container-names correspond to the role for the class embody, e.g.:

State : s Rand : r Mode : m Parameter : p SimParam : sp

copy()

Create an independent copy of the container with the same attributes.

Returns:

cop – Copy of the container with the same attributes as self.

Return type:

BaseContainer

Examples

>>> ex = ExContainer(4.0, 5.0)
>>> ex2 = ex.copy()
>>> ex2
ExContainer(x=4.0, y=5.0)
>>> ex_nest = ExNestContainer(ex2, 40.0)
>>> ex_nest.copy()
ExNestContainer(e1=ExContainer(x=4.0, y=5.0), z=40.0)
create_hist(timerange=None, track=None, default_str_size='<U20')

Create a History corresponding to the State.

Parameters:
  • 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:

hist – History of fields specified in track.

Return type:

History

Examples

>>> nest_hist = ExNestContainer().create_hist()
>>> nest_hist
e1:
--x:                            array(1)
--y:                            array(1)
z:                              array(1)
>>> nest_hist.e1.x
[1.0]
default_track = 'all'
get_code(source)

Get the code defining the Container.

get_field_dict(obj, *fields, **fielddict)

Get dict of values from object corresponding to Container fields.

Parameters:
  • obj (dataobject, list, tuple, or ndarray) – Object to get field dictionary from.

  • *fields (str) – Names of corresponding fields (in self.__fields__)

  • **fielddict – Mapping of fields in obj corresponding to fields in self.

Returns:

field_dict – Dictionary of fields and their values.

Return type:

dict

Examples

>>> ex = ExContainer(1.0, 2.0)
>>> ex.get_field_dict([5.0])
{'x': 5.0}
>>> ex2 = ExContainer(3.0, 4.0)
>>> ex.get_field_dict(ex2)
{'x': 3.0, 'y': 4.0}
>>> ex.get_field_dict({'x': 3.0, 'z': 40.0}, x='x', y='z')
{'x': 3.0, 'y': 40.0}
>>> ex.get_field_dict(ex)
{'x': 1.0, 'y': 2.0}
get_memory()

Get approximate memory impact of dataobject and its fields.

get_track(track)

Get tracking params for a given dataobject (State, Mode, Rand, etc).

Parameters:
  • obj (dataobject) – State/Mode/Rand. Requires .default_track class variable.

  • track (track) – str/tuple. Attributes to track. ‘all’ tracks all fields ‘default’ tracks fields defined in default_track for the dataobject ‘none’ tracks none of the fields

Returns:

track – fields to track

Return type:

tuple

get_true_field(fieldname, *args, **kwargs)

Get the value that will be set to fieldname given *args and **kwargs.

get_true_fields(*args, force_kwargs=False, **kwargs)

Resolve the args to pass given certain defaults, *args and **kwargs.

NOTE: must be used for pickling, since pickle passes arguments as *args and not **kwargs.

get_typename()

Containers are typed as containers unless specified otherwise.

init_hist_att(hist, att, timerange, track, str_size='<U20')

Initialize a field in the history.

reset()
return_mutables()

Return mutable aspects of the container.

rolename = 'x'
set_arg_type(*args, **kwargs)

Set Parameter field input to the predetermined field type.

e.g., if the input to parameter is int for a float field, this converts it to a float in initialization.

Parameters:
  • obj (dataobject (or class)) – dataobject to get argument type for

  • *args (*args) – args to dataobject

  • **kwargs (**kwargs) – kwargs to dataobject

Returns:

  • *new_args (tuple) – new args to dataobject (with proper type)

  • **new_kwargs (dict) – new kwargs to dataobject (with proper type)

set_field(fieldname, value, as_copy=True)

Set the field of the container to the given value.

Parameters:
  • fieldname (str) – Name of the field.

  • value (value) – Value to set the field to.

  • as_copy (bool, optional) – Whether to copy value. The default is True.

Examples

>>> ex_nest = ExNestContainer()
>>> ex_inside = ExContainer(3.0, 4.0)
>>> ex_nest.set_field('e1', ex_inside)
>>> ex_nest
ExNestContainer(e1=ExContainer(x=3.0, y=4.0), z=20.0)
to_default(*fieldnames)

Reset given fields to their default values.

Examples

>>> ex = ExContainer(3.0, 4.0)
>>> ex.to_default()
>>> ex
ExContainer(x=1.0, y=2.0)
>>> ex = ExContainer(4.0, 5.0)
>>> ex.to_default('x')
>>> ex
ExContainer(x=1.0, y=5.0)
class fmdtools.define.container.base.ExContainer(x: float = 1.0, y: float = 2.0)

Bases: BaseContainer

Create class ExContainer instance

x: float
y: float
class fmdtools.define.container.base.ExNestContainer(e1: ExContainer = ExContainer(x=1.0, y=2.0), z: float = 20.0)

Bases: BaseContainer

Create class ExNestContainer instance

e1: ExContainer
z: float
fmdtools.define.container.base.check_container_pick(container, *args, **kwargs)

Check that a given container class or object will pickle.

Examples

>>> ex = ExContainer()
>>> check_container_pick(ex)
True
>>> check_container_pick(ExContainer, x=2.0)
True
>>> check_container_pick(ExContainer, 5.0, 40.0)
True

fmdtools.define.container.mode

The following template shows the basic syntax to use to define modes:

Structure of a Mode Class

Mode class template/example.

Defines Mode class for defining (faulty and otherwise) mode s.

Has classes:

  • Fault: Class for defining fault parameters

  • Mode: Class for defining the mode property (and associated probability model) held in Blocks.

class fmdtools.define.container.mode.ExampleMode(faults: set = set(), faultmodes: dict = {}, mode_state_dict: dict = {}, mode: str = 'standby')

Bases: Mode

Create class ExampleMode instance

exclusive = True
faultmodes: dict
faults: set
fm_args = {'no_charge': (1e-05, 100, {'standby': 1.0}), 'short': (1e-05, 100, {'supply': 1.0})}
mode: str
mode_state_dict: dict
opermodes = ('supply', 'charge', 'standby')
class fmdtools.define.container.mode.Fault

Bases: BaseContainer

Stores Default Attributes for modes to use in Mode.faultmodes.

Fields

probfloat

Mode probability or rate per operation

costfloat

Individual mode cost (e.g., of repair)

phasesdict

Opportunity vector mapping phases of operation to relative probability. i.e., phase_probability = Fault.prob * Fault.phases[phase]

unitsstr

Units on probability. Can be a unit of continuous (‘sec’, ‘min’, ‘hr’, ‘day’) or discrete (‘sim’) time. Default is ‘sim’.

calc_rate(time, phasemap={}, sim_time=1.0, sim_units='hr', weight=1.0)

Calculate the rate of a given fault mode.

Parameters:
  • time (float) – Time the fault will be injected.

  • phasemap (PhaseMap, optional) – Map of phases/modephases that define operations the mode will be injected during (and maps to the opportunity vector phases). The default is {}.

  • sim_time (float, optional) – Duration of the simulation. Used to determine fault exposure time when time-units (‘sec’, ‘min’, etc) define the fault rate. The default is 1.0.

  • sim_units (float, optional) – Simulation time units. Used to determine fault exposure time when time-units define the fault rate. The default is ‘hr’.

  • weight (float, optional) – Weight for the fault/scenario (e.g., for multiple scens.). The default is 1.

Returns:

rate – Calculated rate of the scenario with the given information.

Return type:

float

Examples

>>> # Calculating the rate of a mode in the 'on phase':
>>> from fmdtools.analyze.phases import PhaseMap
>>> pm = PhaseMap({'on': [0, 5], 'off': [6, 10]})
>>> exfault = Fault(prob=0.5, phases = {'on': 0.9, 'off': 0.1}, units='hr')
>>> rate = exfault.calc_rate(4, pm, sim_time=10.0, sim_units='min')
>>> # note that this rate is the same as what we would calculate:
>>> manual_calc = 0.5 * 6 * 0.9 / 60
>>> manual_calc == rate
True
>>> rate_off = exfault.calc_rate(7, pm, sim_time=10.0, sim_units='min')
>>> # note that the interval for off (6-10) is 5 while (0-5) is 6
>>> manual_calc_off = 0.5 * 5 * 0.1 / 60
>>> manual_calc_off == rate_off
True
cost: float
phases: dict
prob: float
units: str
class fmdtools.define.container.mode.Mode(*args, s_kwargs={}, **kwargs)

Bases: BaseContainer

Class for defining the mode property (and probability model) held in Blocks.

Mode is meant to be inherited in order to define the specific faults related to a given Block.

Class Variables

opermodestuple

Names of non-faulty operational modes.

failratefloat

Overall failure rate for the block. The default is 1.0. Note that if a failrate is provided, the prob argument in faultparams is a conditional probability (e.g. Fault.prob = Mode.failrate * Mode.faultparams[‘mode’][‘prob’]).

probtypestr, optional

Type of probability in the probability model, a per-time ‘rate’ or per-run ‘prob’. The default is ‘rate’.

unitsstr, optional

Type of units (‘sec’/’min’/’hr’/’day’) used for the rates. Default is ‘sim’, which is unitless (prob/simulation).

phasesdict

Phases to inject faults in.

exclusiveTrue/False

Whether fault modes are exclusive of each other or not. Default is False (i.e. more than one can be present).

longnamesdict

Longer names for the faults (if desired). {faultname: longname}

faultsset

Set of faults present (or not) at any given time.

modestr

Name of the current mode. the default is ‘nominal’.

fm_argsdict

Arguments to Mode.init_faultmodes().

he_argstuple

Arguments for add_he_rate defining a human error probability model.

sfs_argstuple

Arguments for self.init_single_faultstates (franges, {kwargs}).

nfs_argstuple

Arguments for self.init_n_faultstates (*args, {kwargs}).

fsm_argstuple

Arguments for self.init_faultstates_modes (manual_modes, {kwargs}).

These fields are then used in simulation and elsewhere.

Fields

faultsset

Set of faults present (or not) at any given time

modestr

Name of the current mode. the default is ‘nominal’

mode_state_dict: dict

Maps modes to states. Assigned by init_faultstates methods.

faultmodesdict

Dictionary of Fault defining possible fault modes and their properties

Examples

>>> class ExampleMode(Mode):
...    fm_args = {"no_charge": (1e-5, 100, {'standby': 1.0}),
...              "short": (1e-5, 100, {'supply': 1.0})}
...    opermodes = ("supply", "charge", "standby")
...    exclusive = True
...    mode: str = "standby"
>>> exm = ExampleMode()
>>> exm.mode
'standby'
>>> exm.any_faults()
False
>>> exm.faultmodes
{'no_charge': Fault(prob=1e-05, cost=100, phases={'standby': 1.0}, units='sim'), 'short': Fault(prob=1e-05, cost=100, phases={'supply': 1.0}, units='sim')}
add_fault(*faults)

Add fault (a str) to the block.

Parameters:

*fault (str(s)) – name(s) of the fault to add to the black

add_he_rate(gtp, EPCs={'na': [1, 0]})

Calculate self.failrate based on a human error probability model.

Parameters:
  • gtp (float) – Generic Task Probability. (from HEART)

  • EPCs (Dict or list) –

    Error producing conditions (and respective factors) for a given task (from HEART). Used in format:

    • Dict {‘name’:[EPC factor, Effect proportion]} or

    • list [[EPC factor, Effect proportion],[[EPC factor, Effect proportion]]]

any_faults()

Check if the block has any fault modes.

base_type()

Return fmdtools type of the model class.

default_track = ('mode', 'faults')
exclusive = False
failrate = 1.0
faultmodes: dict
faults: set
fm_args = {}
fsm_args = ()
has_fault(*faults)

Check if the block has fault (a str).

Parameters:

*faults (strs) – names of the fault to check.

he_args = ()
in_mode(*modes)

Check if the system is in a given operational mode.

Parameters:

*modes (strs) – names of the mode to check

init_faultmodes(fm_args)

Initialize the self.faultmodes dictionary from the parameters of the Mode.

Parameters:

fm_args (dict or tuple) –

Dictionary/tuple of arguments defining faultmodes, which can have forms:
  • tuple (‘fault1’, ‘fault2’, ‘fault3’) (just the respective faults)

  • dict {‘fault1’: args, ‘fault2’: kwargs}, where args and kwargs are

args or kwargs to Fault (prob, phases, cost, units, etc).

init_faultstate_modes(manual_modes, **kwargs)

Associate modes manual_modes with provided faultstates.

Parameters:
  • manual_modes (dict, optional) –

    Dictionary/Set of faultmodes with structure, which has the form:
    • dict {‘fault1’: [atts], ‘fault2’: atts}, where atts may be of form:
      • states: {state1: val1, state2, val2}

  • **kwargs (kwargs) – Entries for the Fault (e.g., phases, etc)

init_hist_att(hist, att, timerange, track, str_size='<U20')

Add field ‘att’ to history. Accommodates faults and mode tracking.

init_n_faultstates(franges, n='all', seed=42, **kwargs)

Associate n faultstate mode combinations as faults.

Parameters:
  • franges (dict, optional) –

    Dictionary of form {‘state’:{val1, val2…}) of ranges for each health state

    (if used to generate modes). The default is {}.

  • n (int, optional) – Number of faultstate combinations to sample. The default is ‘all’.

  • seed (int, optional) – Seed used in selection (if n!=’all). The default is 42.

  • **kwargs (kwargs) – Entries for the Fault (e.g., phases, etc)

init_single_faultstates(franges, **kwargs)

Associate modes with given faultstates as faults.

Modes generated for each frange (but not combined).

Parameters:
  • franges (dict, optional) – Dictionary of form {‘state’:{val1, val2…}) of ranges for each health state (if used to generate modes). The default is {}.

  • **kwargs (kwargs) – Entries for the Fault (e.g., phases, etc)

longnames = {}
mode = 'nominal'
mode_state_dict: dict
nfs_args = ()
no_fault(fault)

Check if the block does not have fault (a str).

Parameters:

fault (str) – name of the fault to check.

opermodes = ('nominal',)
phases = {}
remove_any_faults(opermode=False, warnmessage=False)

Reset fault mode to nominal and returns to the given operational mode.

Parameters:
  • opermode (str (optional)) – operational mode to return to when the fault mode is removed

  • warnmessage (str/False) – Warning to give when performing operation. Default is False (no warning)

remove_fault(fault_to_remove, opermode=False, warnmessage=False)

Remove fault in the set of faults and returns to given operational mode.

Parameters:
  • fault_to_replace (str) – name of the fault to remove

  • opermode (str (optional)) – operational mode to return to when the fault mode is removed

  • warnmessage (str/False) – Warning to give when performing operation. Default is False (no warning)

replace_fault(fault_to_replace, fault_to_add)

Replace fault_to_replace with fault_to_add in the set of faults.

Parameters:
  • fault_to_replace (str) – name of the fault to replace

  • fault_to_add (str) – name of the fault to add in its place

return_mutables()

Return mutable aspects of the container.

rolename = 'm'
set_field(fieldname, value, as_copy=True)

Extend BaseContainer.assign to not set faultmodes (always the same).

set_mode(mode)

Set a mode in the block.

Parameters:

mode (str) – name of the mode to enter.

sfs_args = ()
to_fault(fault)

Move from the current fault mode to a new fault mode.

Parameters:

fault (str) – name of the fault mode to switch to

units = 'sim'
units_set = ('sec', 'min', 'hr', 'day', 'sim')
update_modestates()

Update states of the model associated with a specific fault mode.

(see init_faultstates)

fmdtools.define.container.state

Defines State class for representing variables that change over time.

State classes are used to represent mutables properties of the system that change over time.

State classes are extended and deployed by the user, as shown below:

example state class

Example of extending the State class to hold x/y fields.

The following template shows the basic syntax used to define states:

Structure of a State Class

State class template/example.

class fmdtools.define.container.state.State

Bases: BaseContainer

Class for working with model states.

States which are variables in the model which change over time.

State is meant to be extended in the model definition object to add the corresponding field related to a simulation, e.g.,

>>> class ExampleState(State):
...     x : float=1.0
...     y : float=1.0

Creates a class point with fields x and y which are tagged as floats with default values of 1.0.

Instancing State gives normal read/write access, e.g., one can do:

>>> p = ExampleState()
>>> p.x
1.0

or:

>>> p = ExampleState(x=10.0)
>>> p.x
10.0
add(*states)

Return the addition of given attributes of the State.

Examples

>>> p = ExampleState(x=1.0, y=2.0)
>>> p.add('x','y')
3.0
base_type()

Return fmdtools type of the model class.

div(*states)

Return the division of given attributes of the State.

Examples

>>> p = ExampleState(x=1.0, y=2.0)
>>> p.div('x','y')
0.5
get(*attnames, **kwargs)

Return the given attribute names (strings) as a numpy array.

Mainly useful for reducing length of lines/adding clarity to assignment statements. e.g.,:

>>> p = ExampleState(x=1.0, y=2.0)
>>> p_arr = p.get("x", "y")
>>> p_arr
array([1., 2.])
>>> p.get("x")
1.0
>>> p.get("x", "y", as_array=False)
[1.0, 2.0]
gett(*attnames)

Alternative to self.get that returns a tuple, not an array.

Useful when a numpy array would translate the underlying data types poorly (e.g., np.array([1,’b’] would make 1 a string–using a tuple instead preserves the data type)).

Examples

>>> ExampleState().gett("x")
1.0
>>> ExampleState().gett("x", "y")
(1.0, 1.0)
inc(**kwargs)

Increment the given arguments by a given value.

Mainly useful for reducing length/adding clarity to increment statements, e.g.,:

>>> p = ExampleState(x=1.0, y=1.0)
>>> p.inc(x=1, y=2)
>>> p.x
2.0
>>> p.y
3.0

Can additionally be provided with a second value denoting a limit on the increments e.g.,:

>>> p = ExampleState(x=1.0, y=1.0)
>>> p.inc(x=(3, 5.0))
>>> p.x
4.0
>>> p.inc(x=(3, 5.0))
>>> p.x
5.0
init_hist_att(hist, att, timerange, track, str_size='<U20')

Extend init_hist_attr to use _set to get history size.

limit(**kwargs)

Enforce limits on the value of a given property.

Mainly useful for reducing length/adding clarity to increment statements. e.g.,:

>>> p = ExampleState(x=200.0, y=-200.0)
>>> p.limit(x=(0.0,100.0), y=(0.0, 100.0))
>>> p.x
100.0
>>>
0.0
mul(*states)

Return the multiplication of given attributes of the State.

Examples

>>> p = ExampleState(x=2.0, y=3.0)
>>> p.mul("x","y")
6.0
put(as_copy=True, **kwargs)

Set the given fields to a given value.

Mainly useful for reducing length/adding clarity to assignment statements.

Parameters:
  • as_copy (bool) – set to True for dicts/sets to be copied rather than referenced

  • **kwargs (values) – fields and values to set.

Examples

>>> p = ExampleState()
>>> p.put(x=2.0, y=2.0)
>>> p.x
2.0
>>> p.y
2.0
roundto(**kwargs)

Round the given arguments to a given resolution.

Examples

>>> p = ExampleState(x=1.75850)
>>> p.roundto(x=0.1)
>>> p.x
1.8
same(*args, **kwargs)

Test whether a given iterable values has the same value as each in the state.

Examples

>>> p = ExampleState(x=1.0, y=2.0)
>>> p.same([1.0, 2.0], "x", "y")
True
>>> p.same([0.0, 2.0], "x", "y")
False
>>> p.same([1.0], 'x')
True
>>> p.same(x=1.0, y=2.0)
True
>>> p.same(x=0.0, y=0.0)
False
set_atts(**kwargs)

Set the given arguments to a given value.

Mainly useful for reducing length/adding clarity to assignment statements in __init__ methods (self.put is recomended otherwise so that the iteration is on function/flow states) e.g.,

>>> p = ExampleState()
>>> p.set_atts(x=2.0, y=2.0)
>>> p.x
2.0
>>> p.y
2.0
sub(*states)

Return the subtraction of given attributes of the State.

Examples

>>> p = ExampleState(x=1.0, y=2.0)
>>> p.sub('x','y')
-1.0
values()

Return the values of the defined fields for the state.

warn(*messages, stacklevel=2)

Print warning message(s) when called.

Parameters:
  • *messages (str) – Strings to make up the message (will be joined by spaces)

  • stacklevel (int) – Where the warning points to. The default is 2 (points to the place in the model)

fmdtools.define.container.parameter

Defines Parameter class to represent attributes that do not change.

Parameter classes are used to represent immutable properties of the system. Parameter classes are extended and deployed by the user, as shown below:

example state class

Example of extending the Parameter class to hold x/y/z fields.

The following template shows the basic syntax to use to define parameters:

Structure of a Parameter Class

Parameter class template/example.

class fmdtools.define.container.parameter.Parameter(*args, strict_immutability=True, check_type=True, check_pickle=True, set_type=True, check_lim=True, **kwargs)

Bases: BaseContainer

The Parameter class defines model/function/flow values which are immutable.

That is, the same from model instantiation through a simulation. Parameters inherit from recordclass, giving them a low memory footprint, and use type hints and ranges to ensure parameter values are valid. e.g.,:

Examples

>>> class ExampleParameter(Parameter, readonly=True):
...    x: float = 1.0
...    y: float = 3.0
...    z: float = 0.0
...    x_lim = (0, 10)
...    y_set = (1.0, 2.0, 3.0, 4.0)

defines a parameter with float x and y fields with default values of 30 and x_lim minimum/maximum values for x and y_set possible values for y. Note that readonly=True should be set to ensure fields are not changed.

This parameter can then be instantiated using:

>>> p = ExampleParameter(x=1.0, y=2.0)
>>> p.x
1.0
>>> p.y
2.0
>>> p.copy()
ExampleParameter(x=1.0, y=2.0, z=0.0)
base_type()

Return fmdtools type of the model class.

check_immutable()

Check if a known/common mutable or a known/common immutable.

If known immutable, raise exception. If not known mutable, give a warning.

Raises:

Exception – Throws exception if a known mutable (e.g., dict, set, list, etc)

check_lim(k, v)

Checks to ensure the value v for field k is within the defined limits self.k_lim or set constraints self.k_set

Parameters:
  • k (str) – Field to check

  • v (mutable) – Value for the field to check

Raises:

Exception – Notification that the field is outside limits/set constraints.

check_pickle()

Checks to make sure pickled object will get *args and **kwargs

check_type()

Check to ensure Parameter type-hints are being followed.

Raises:

Exception – Raises exception if a field is not the same as its defined type.

copy()

Create an independent copy of the container with the same attributes.

Returns:

cop – Copy of the container with the same attributes as self.

Return type:

BaseContainer

Examples

>>> ex = ExContainer(4.0, 5.0)
>>> ex2 = ex.copy()
>>> ex2
ExContainer(x=4.0, y=5.0)
>>> ex_nest = ExNestContainer(ex2, 40.0)
>>> ex_nest.copy()
ExNestContainer(e1=ExContainer(x=4.0, y=5.0), z=40.0)
copy_with_vals(**kwargs)

Creates a copy of itself with modified values given by kwargs

reset()

Do nothing since the parameter is immutable.

return_mutables()

Return mutable aspects of the container.

fmdtools.define.container.rand

Defines Rand class and other methods defining random properties used in blocks.

Has Classes and Functions:

  • Rand: Superclass for Block random properties.

  • get_pdf_for_rand(): Gets the corresponding probability mass/density for random sample x from ‘randname’ function in numpy.

  • get_scipy_pdf_helper(): Gets probability mass/density for the outcome x from the distribution “randname”. Used as a helper function in determining stochastic model state probability

  • get_pdf_for_dist(): Gets the corresponding probability mass/density (from scipy) for outcome x for probability distributions with name ‘randname’ in numpy.

class fmdtools.define.container.rand.ExampleRand(*args, seed=42, run_stochastic=False, probs=[], s_kwargs={})

Bases: Rand

Example Rand for testing and docs.

probdens: float
probs: list
rng: Generator
run_stochastic: bool
s: RandState
seed: int
class fmdtools.define.container.rand.Rand(*args, seed=42, run_stochastic=False, probs=[], s_kwargs={})

Bases: BaseContainer

Class for defining and interacting with random states of the model.

rng

random number generator

Type:

np.random.default_rng

probs

probability of the given states

Type:

list

seed

state for the random number generator

Type:

int

Examples

Rand is meant to be extended in model definition with random states, e.g.:

>>> class RandState(State):
...     noise: float=1.0
>>> class ExampleRand(Rand):
...     s: RandState = RandState()

Which enables the use of set_rand_state, update_stochastic_states, etc for updating these states with methods called from the rng when run_stochastic=True.

>>> exr = ExampleRand(run_stochastic=True)
>>> exr.set_rand_state('noise', 'normal', 1.0, 1.0)
>>> exr.s
RandState(noise=1.3047170797544314)

Checking copy:

>>> exr2 = exr.copy()
>>> exr2.s
RandState(noise=1.3047170797544314)
>>> exr2.run_stochastic
True
>>> exr2.rng.__getstate__()['state'] == exr.rng.__getstate__()['state']
True
base_type()

Return fmdtools type of the model class.

default_track = ('s', 'probdens')
get_rand_states(auto_update_only=False)

Get the randomly-assigned states associated with the Rand at self.s.

Parameters:

auto_update_only (bool, optional) – Whether to only get auto-updated states. The default is False.

Returns:

rand_states – States in self.s

Return type:

dict

Examples

>>> ExampleRand().get_rand_states()
{'noise': 1.0}
>>> ExampleRand().get_rand_states(auto_update_only=True)
{}
init_hist_att(hist, att, timerange, track, str_size='<U20')

Add field ‘att’ to history. Accommodates track_pdf option.

probdens: float
probs: list
reset()

Reset Rand to the initial state.

return_mutables()

Return mutable aspects of the container.

return_probdens()
rng: Generator
rolename = 'r'
run_stochastic: bool
seed: int
set_field(fieldname, value, as_copy=True)

Extend BaseContainer.assign to accomodate the rng.

set_rand_state(statename, methodname, *args)

Update the given random state with a given method and arguments.

(if in run_stochastic mode)

Parameters:
  • statename (str) – name of the random state defined

  • methodname – str name of the numpy method to call in the rng

  • *args (args) – arguments for the numpy method

set_rng(other_rng)

Set the state of the rng in the Rand to the same state as other_rng.

update_seed(seed)

Update the random seed to the given value.

update_stochastic_states()

Update the defined stochastic states defined to auto-update.

class fmdtools.define.container.rand.RandState

Bases: State

Example random state for testing and docs.

noise: float
fmdtools.define.container.rand.get_pdf_for_dist(x, randname, args)

Get the scipy probability mass/density for outcome x from numpy random draw.

Parameters:
  • x (int/float/array) – samples to get probability mass/density of

  • randname (str) – Name of numpy.random distribution

  • args (tuple) – Arguments sent to numpy.random distribution

Returns:

prob

Return type:

float/array of probability densities

fmdtools.define.container.rand.get_pdf_for_rand(x, randname, args)

Get the probability density/mass function for random sample x.

Pulled from ‘randname’ function in numpy.

Parameters:
  • x (int/float/array) – samples to get probability mass/density of

  • randname (str) – Name of numpy.random distribution

  • args (tuple) – Arguments sent to numpy.random distribution

Returns:

prob

Return type:

float/array of probability densities

fmdtools.define.container.rand.get_scipy_pdf_helper(x, randname, args, pmf=False)

Get probability mass/density for the outcome x.

Pulled from the distribution “randname” in scipy with arguments “args”.

Used as a helper function in determining stochastic model state probability

Parameters:
  • x (int/float/array) – samples to get probability mass/density of

  • randname (str) – Name of scipy.stats probability distribution

  • args (tuple) – Arguments to send to scipy.stats.randname.pdf

  • pmf (Bool, optional) – Whether the distribution uses a probability mass function instead of a pdf. The default is False.

Returns:

prob

Return type:

float/array of probability densities

fmdtools.define.container.time

Defines Time class for containing timers and time-related constructs.

class fmdtools.define.container.time.ExtendedTime(*args, **kwargs)

Bases: Time

Example extended time class for testing, etc.

dt: float
run_times: int
t_ind: int
t_loc: float
time: float
timernames = ('t1', 't2')
timers: dict
use_local: bool
class fmdtools.define.container.time.Time(*args, **kwargs)

Bases: BaseContainer

Class for defining all time-based aspects of a Block (e.g., time, timestep, timers).

time

real time for the model

Type:

float

dt

timestep size

Type:

float

t_ind

index of the given time

Type:

int

t_loc

local time (e.g., for actions with durations)

Type:

float

run_times

number of times to run the behavior if running at a different timestep than global

Type:

int

timers

dictionary of instantiated timers

Type:

dict

use_local

Whether to use the local timetep (vs global timestep)

Type:

bool

timernames

Names of timers to instantiate.

Type:

tuple

Examples

Extending the time class gives one access to a dict of timers:

>>> class ExtendedTime(Time):
...     timernames = ('t1', 't2')
>>> t = ExtendedTime()
>>> t.timers['t1']
Timer t1: mode= standby, time= 0.0

These timers can then be used:

>>> t.timers['t1'].inc(1.0)
>>> t.timers['t1']
Timer t1: mode= ticking, time= 1.0

Checking copy:

>>> t2 = t.copy()
>>> t2.timers
{'t1': Timer t1: mode= ticking, time= 1.0, 't2': Timer t2: mode= standby, time= 0.0}

Check that copied timers are independent:

>>> t2.timers['t1'].__hash__() == t.timers['t1'].__hash__()
False
base_type()

Return fmdtools type of the model class.

default_track = 'timers'
dt: float
init_hist_att(hist, att, timerange, track, str_size='<U20')

Add field ‘att’ to history. Accommodates time and timer tracking.

local_dt = 1.0
reset()

Reset time to the initial state.

return_mutables()

Return mutable aspects of the container.

rolename = 't'
run_times: int
set_timestep()

Set the timestep of the function given.

If using the option use_local, local_timestep is used instead of global_timestep.

t_ind: int
t_loc: float
time: float
timernames = ()
timers: dict
use_local: bool