Variable¶
- class component_model.variable.Variable(model, name: str, description: str = '', causality: str | None = 'parameter', variability: str | None = 'fixed', initial: str | None = None, typ: type | None = None, start: str | int | float | bool | Enum | tuple | list | ndarray | None = None, rng: tuple | None = tuple(), annotations: dict | None = None, value_check: Check = Check.all, on_step: Callable | None = None, on_set: Callable | None = None, owner: Any | None = None, value_reference: int | None = None)¶
Bases:
ScalarVariable
Interface variable of an FMU. Can be a (python type) scalar variable or a numpy array. The class extends pythonfmu.ScalarVariable, not using the detailed types (Real, Integer, …), as the type is handled internally (automatically or explicit, see below). The recommended way to instantiate a Variable is through string values (with units for start and rng), but also dimensionless quantities and explicit class types are accepted.
For proper understanding and usage the following should be noted:
The Variable value is per default owned by the related model (see self.model). Through the owner parameter this can be changes. In structured models like the crane_fmu this might be adequate.
The current value of the variable directly accessible through the owner. Direct value access assumes always internal units (per default: SI units) and range checking is not performed.
Other access to the value is achieved through the self.getter() and the self.setter( v) functions, which are also used by the FMU getxxx and setxxx functions (external access). Unit transformation and range checking is performed within getter() and setter(), i.e. the setter function assumes a value in display units and transforms it into internal units and the getter function assumes internal units and makes the value available as display units. For example an angle variable might be defined as degrees (display units), but will internally always be handled as radians.
It is recommended to register the Variable object as self.name within the owner (model or sub-object of model), i.e. provide access as private object. In addition the model has access to the variable object through the OrderedDict .vars = {value_reference : variable object, …}.
Compound variables (e.g. numpy arrays), should always allow setting of single elements. Due to limitations in fmi2 all variables are translated to ScalarVariables, using the syntax np-variable[idx].
For variables it is sometimes required to perform actions additional to the standard setter actions (unit trnsformation and range checking). Such actions can be defined through the self.on_set() hook. For compound variables on_set should only be run when all elements have received their new value. This is ensured through the internal dirty mechanism. on_set() should therefore always address the whole variable, not single elements.
For variables it is sometimes convenient to perform a fixed action at each step of the simulation. This can be conveniently done through the on_step(time,dt) hook.
- Parameters:
model (obj) – The model object where this variable relates to. Use model.add_variable( name, …) to define variables
name (str) – Variable name, unique for whole FMU.
description (str) – Optional description of variable
causality (str) – The causality setting as string
variability (str) – The variability setting as string
initial (str) – Optional definition how the variable is initialized. Provide this explicitly if the default value is not suitable.
typ (type) – Optional explicit type of variable to expect as start and value. Since initial values are often set with strings (with units, see below), this is set explicitly. If None, _typ is set to Enum/str if derived from these after disection or float if a number. ‘int’ is not automatically detected.
start (PyType) –
The initial value of the variable.
Optionally, the unit can be included, providing the initial value as string, evaluating to quantity of type typ a display unit and base unit. Note that the quantities are always converted to standard units of the same type, while the display unit may be different, i.e. the preferred user communication.
rng (tuple) = () –
Optional range of the variable in terms of a tuple of the same type as initial value. Should be specified with units (as string).
If an empty tuple is specified, the range is automatically determined. That is only possible float or enum type variables, where the former evaluates to (-inf, inf). Maximum or minimum int values do not exist in Python, such that these always must be provided explicitly. It is not possible to set only one of the elements of the tuple automatically.
If None is specified, the initial value is chosen, i.e. no range. None can be applied to the whole tuple or to single elements of the tuple. E.g. (1,None) sets the range to (1, start)
For some variable types (e.g. str) no range is expected.
annotations (dict) – Optional variable annotations provided as dict
value_check (Check) – Setting for checking of units and range according to Check. The two aspects should be set with OR (|), e.g. Check.units | Check.r_none leads to only units transformations but no range checking.
on_step (callable) – Optional possibility to register a function of (time, dt) to be run during .do_step, e.g. if the variable represents a speed, the object can be translated speed*dt, if |speed|>0
on_set (callable) – Optional possibility to specify a pre-processing function of (newval) to be run when the variable is initialized or changed. This is useful for conditioning of input variables, so that calculations can be done once after a value is changed and do not need to be repeated on every simulation step. If given, the function shall apply to the whole (vecor) variable, and after unit conversion and range checking. The function is completely invisible by the user specifying inputs to the variable.
None (owner =) – Optional possibility to overwrite the default value owner (the related model). This is convenient for structured models, like a crane, where the model is the crane itself, consisting of booms, where the boom variables (length, angle,…) should be directly accessible by the boom - the crane itself needs only to relate to the first boom.
- __init__(model, name: str, description: str = '', causality: str | None = 'parameter', variability: str | None = 'fixed', initial: str | None = None, typ: type | None = None, start: str | int | float | bool | Enum | tuple | list | ndarray | None = None, rng: tuple | None = tuple(), annotations: dict | None = None, value_check: Check = Check.all, on_step: Callable | None = None, on_set: Callable | None = None, owner: Any | None = None, value_reference: int | None = None)¶
Methods
__init__
(model, name[, description, ...])auto_type
(val[, allow_int])Determine the Variable type from a provided example value.
check_range
(value[, idx, disp])Check the provided 'value' with respect to the range.
fmi_type_str
(val)Translate the provided type to a proper fmi type and return it as string.
getter
()Get the value (output a value from the model), including range checking and unit conversion.
requires_start
(v)Test if a variable requires a start attribute
setter
(value[, idx])Set the value (input to model from outside), including range checking and unit conversion.
to_xml
()Convert the variable to XML node.
Generate <ScalarVariable> XML code with respect to this variable and return xml element.
Attributes
Variable causality - None if not set
description
Variable description - None if not set
Variable initial status - None if not set
name
Variable name
value_reference
Variable reference index
Variable variability - None if not set
- classmethod auto_type(val: str | int | float | bool | Enum | tuple | list | ndarray, allow_int: bool = False)¶
Determine the Variable type from a provided example value. Since variables can be initialized using strings with units, the type can only be determined when the value is disected. Moreover, the value may indicate an integer, while the variable is designed a float. Therefore int Variables must be explicitly specified.
- check_range(value: str | int | float | bool | Enum | tuple | list | ndarray | None, idx: int | None = None, disp: bool = True) bool ¶
Check the provided ‘value’ with respect to the range.
- Parameters:
value (PyType|Compound) – the value to check. Scalars may be wrapped into a vector
disp (bool) – denotes whether the value is expected in display units (default) or units
- Return type:
True/False with respect to whether val is the right type and is within range.
- fmi_type_str(val: str | int | float | bool | Enum) str ¶
Translate the provided type to a proper fmi type and return it as string. See types defined in schema fmi2Unit.xsd.
- getter()¶
Get the value (output a value from the model), including range checking and unit conversion. The whole variable value is returned. The return value can be indexed/sliced to get elements of compound variables.
- setter(value: str | int | float | bool | Enum | tuple | list | ndarray, idx: int | None = None)¶
Set the value (input to model from outside), including range checking and unit conversion.
For compound values, the whole ‘array’ should be provided, but elements which remain unchanged can be replaced by None. Alternatively, single elements can be set by providing the index explicitly.
- xml_scalarvariables()¶
Generate <ScalarVariable> XML code with respect to this variable and return xml element. For compound variables, all elements are included.
Note that ScalarVariable attributes should all be listed in __attrs dictionary. Since we do not use the derived classes Real, … we need to generate the detailed variable definitions here. The following attributes are so far not supported: declaredType, derivative, reinit.
- Return type:
List of ScalarVariable xml elements
- property causality: Fmi2Causality¶
Variable causality - None if not set
- Type:
Fmi2Causality
or None
- property check¶
- property display¶
- property initial: Initial¶
Variable initial status - None if not set
- Type:
Fmi2Initial
or None
- property range¶
- property start¶
- property typ¶
- property unit¶
- property variability: Fmi2Variability¶
Variable variability - None if not set
- Type:
Fmi2Variability
or None