fonsim.core package
Submodules
fonsim.core.component module
Class Component
2020, July 21
- class fonsim.core.component.Component(label)[source]
Bases:
object
Components to build a system with
This base class provides a starting ground to build components usable in a FONSim system. Several examples are found in the FONSim standard library (see the
fonsim.components
package). Also, be sure to check out the tutorial on custom components.Interaction with other components The component terminals (instances of
Terminal
) specify the possibilities for interaction with other components. They are added using the methodComponent.set_terminals()
. Example of adding two fluidic terminals with labels ‘a’ and ‘b’:self.set_terminals(Terminal('a', terminal_fluidic, {'pressure': 'p0', 'massflow': 'mf0'}), Terminal('b', terminal_fluidic, {'pressure': 'p1', 'massflow': 'mf1'}))
The list
terminal_fluidic
contains twoVariable
instances, one for pressure and one for massflow. It is defined in components/terminals.py. If theComponent.auto()
andComponent.auto_state()
methods are used to define methodsComponent.evaluate()
andComponent.update_state()
, then the variable labels ‘p0’, ‘mf0’ etc. will be used further on (for an example, please see the tutorial linked to earlier on). The lists of terminals and of the terminal variables are respectively kept in the member variablesterminals
andarguments
.States State variables are added using the
Component.set_states()
method. These variables are considered to be local because they are not accessible to other components. Example of adding a single state with label ‘mass’:self.set_states(Variable('mass', 'local', label='m', initial_value=5e-3))
The state variables are subsequently available as a list in the member variable
states
.Internal behavior The two methods
Component.evaluate()
andComponent.update_state()
govern the internal behaviour. The former specifies a relation between the terminal and state variables that should be respected at each discrete timestep and the latter expresses how the state variables change over a timestep given a previous state and the terminal variables.There are two ways to define these methods. By far the easiest is to use the
Component.auto()
andComponent.auto_state()
methods, as a method or as a decorator, because this allows to refer to the terminal and state variables by their label. The documentation of these two methods discusses how to do so. This is also the approach discussed in the custom component tutorial mentioned earlier.The second way is to conform to form of the
Component.evaluate()
Component.update_state()
methods. This requires variables to be referred to by their index in the passed arrays, making this method prone to errors if done manually. Knowing the indices to use requires either searching the terminal variables in the member variablearguments
or putting the variables in that member variable in a particular order, preferably usingComponent.set_arguments()
. Note thatComponent.set_terminals()
modifiesarguments
.Storage of the state and terminal variable values The state data (e.g. amount of fluid inside actuator) is saved as 2D-array in the components themselves (and the solver always refers to these) while the argument data (e.g. pressure, flow in/out) is saved as a list of _references_ to nameless 1D-arrays created by the solver. The component object provides functionality for the solver to allocate memory for the states, but not for allocating the variables. The solver takes care of calling these functions necessary. The object property
state_history
holds the 2D-array and object propertyargument_history
holds a list with references to the 1D-arrays.- Parameters
label – Component name.
- auto(func)[source]
Wrapper for Component.evaluate Wrapper that converts a function taking as arguments terminal and state variable labels to a function taking arrays and conforming to the
Component.evaluate()
signature. Often used as a decorator.If the given function
func
returns a Numpy array and a list, then it is assumed that the former is the array of residuals and the latter the component jacobian. Else, if it returns one Numpy array, it is assumed that that is the array of residuals, and FONSim will automatically estimate the jacobian using finite differences.The following example demonstrates the creation of a residual and a jacobian. The third and the fourth line specify the derivatives of the first residual (with array index 0) respectively to the variables mf0 and mf1.
values, jacobian = np.zeros(1, dtype=float), [{},] values[0] = mf0 + mf1 jacobian[0]['mf0'] = 1 jacobian[0]['mf1'] = 1 return values, jacobian
- Parameters
func –
simplified update_state
function- Returns
new
update_state
function
- auto_state(func)[source]
Wrapper for
Component.update_state
Wrapper that converts a function having as parameters terminal and state variable labels to a function taking arrays and conforming to theComponent.update_state()
signature. Often used as a decorator.If the given function
func
returns two dictionaries, then it is assumed that the former contains the updated states and the latter the component jacobian. Else, if it returns only one dictionary, it is assumed that it contains the updated states, and FONSim will automatically estimate the jacobian using finite differences.The following example demonstrates the creation of an updated state and a jacobian. The third and the fourth line specify the derivatives of the state m respectively to the variables p and mf.
jacobian = {} m_new = m + dt * mf jacobian['m/p'] = 0 jacobian['m/mf'] = dt return {'m': m_new}, jacobian
- Parameters
func –
simplified update_state
function- Returns
new
update_state
function
- evaluate(values, jacobian_state, jacobian_arguments, state, arguments, elapsed_time)[source]
Evaluates the component internal equations. This method should be static.
Note: only evaluate left-hand side (LH) of equation, equation should be structured such that RH is always zero.
- Parameters
values – array where the equation residuals will be stored.
jacobian_state – array where the jacobian to the state will be stored.
jacobian_arguments – array where the jacobian to the arguments will be stored.
state – numerical values belonging to the state Variables.
arguments – numerical values belonging to the Variables.
elapsed_time – ? TODO.
- Returns
None
- get(variable_key, terminal_label=None)[source]
Same as method
self.get_all
, but returns only the first return value.
- get_all(variable_key, terminal_label=None)[source]
Get simulation results. Supports ‘smart matching’ by comparing string distances.
- Parameters
variable_key – key of variable, e.g. ‘pressure’
terminal_label – label of terminal, e.g. ‘a’
- Returns
Numpy ndarray object and Terminal object
- get_state(label)[source]
Get simulation results. Supports ‘smart matching’ by comparing string distances.
- Parameters
label – state label, e.g. ‘volume’
- Returns
Numpy ndarray object
- get_terminal(terminallabel=None)[source]
Returns Terminal object. If no label given, returns the first unconnected terminal. If label given, returns terminal with that label. If no terminal found, returns None.
- Parameters
terminallabel – Label of terminal
- Returns
Terminal object
- set_arguments(*arguments)[source]
Overwrite component arguments list with the provided Variable objects.
- Parameters
arguments – one or more Variable objects
- Returns
None
- set_states(*states)[source]
Overwrite component states list with the provided Variable objects.
- Parameters
states – one or more Variable objects
- Returns
None
- set_terminals(*terminals)[source]
Overwrite component terminals list with the provided Terminal objects and attach those terminals to the component.
- Parameters
terminals – one or more Terminal objects
- Returns
None
- update_state(state_new, jacobian, state, arguments, dt)[source]
Evaluates the update to the component state. This method should be static.
- Parameters
state_new – array where the new state values will be stored.
jacobian – array where the jacobian to the arguments will be stored.
state – numerical values belonging to the state Variables.
arguments – numerical values belonging to the Variables.
dt – time discretization timestep.
- Returns
None
fonsim.core.node module
Class Node
2021, January 14
- class fonsim.core.node.Node(*terminals)[source]
Bases:
object
Connection between multiple component terminals
- add_terminals(*terminals)[source]
Connect terminals to the node
- Parameters
terminals – Terminal object. Multiple can be provided
- Returns
None
- contains_terminal(terminal)[source]
Check if the node contains the requested terminal
- Parameters
terminal – Terminal object
- Returns
Boolean
- get_variables(orientation=None, key=None)[source]
Get a list of all variables with the provided orientation and/or key associated with the node.
- Parameters
orientation – optional string specifying requested variable orientation
key – optional string specifying requested variable key
- Returns
list of Variable objects
fonsim.core.setnumpythreads module
https://gitlab.com/abaeyens/fonsim/-/issues/19
2022, June 04
fonsim.core.simulation module
Class Simulation
2020, July 22
- class fonsim.core.simulation.Simulation(system_to_simulate, duration=10, step=(None, None), step_min=None, step_max=None, discretization='backward', relative_solving_tolerance=0.01, minimum_solving_tolerance=1e-10, go_backwards_allowed=True, max_steps=0, verbose=0)[source]
Bases:
object
Class to convert network information (how the components are connected to each other) and component information (equations for each component) to a single non-linear system of equations (function vector + Jacobian) describing the whole system.
Solving this system is to be done by a solver. This object contains a solver object in the property self.solver. (Future functionality: possibility to select a solver manually etc.)
The parameter
step
controls the simulation timestep. It can be a scalar value, in which case the simulation timestep is constant, or a tuple, in which case the first and second elements denote the minimum and maximum timestep, and the solver will automatically adjust its timestep within this range. Elements of Nonetype are guessed by the solver based roughly on the following three rules:satisfy
max_steps
scale timestep with
duration
step_min << step_max
do at least 1e2 steps such that time dependent references are sampled reasonably well
at least 1e4 steps possible, such that there are no visible discretization effects when full resulted viewed full screen
These rules are subject to change and therefore it is strongly recommended that the
step
parameter be fully specified once suitable values for the subject at hand have been found.The parameter
discretization
sets the discretization method to be used by the solver. This parameter is passed to the solver and is not used otherwise in this class. The following discretization methods are available: backward (implicit/backward Euler), forward (explicit/forward Euler), and tustin (trapezoid). The default is backward because it gives the most stability and rarely shows time discretization jitter (triangles). However, tustin gives a smaller phase shift, and forward tends to be better at hiding modeling deficiencies.The parameter
minimum_solving_tolerance
is used as an absolute lower bound for the allowed solving error. The default value of 1e-15 is close to machine precision when using 64-bit floating point.The parameter
relative_solving_tolerance
expresses the allowed solving error for each argument relative to the observed value range of that argument. The default value of 1e-2 (= 1 %) is sufficient for most practical purposes given that the modelling error tends to be far larger.The Class Solver interacts heavily with the System class and expects the following methods to be available:
evaluate_equations()
update_state()
equation_to_string()
as well as the following properties:
system
phi
,H
andA
arguments
nb_arguments
andnb_network_equations
times
andduration
andverbose
phi_range
- Parameters
system_to_simulate – System object with components and how they are connected
duration – amount of time the system will be simulated for
step – time increment
step_min – will be deprecated, use `step` Minimum simulation timestep.
step_max – will be deprecated, use `step` Maximum simulation timestep.
max_steps – maximum amount of time increments before the simulation is terminated prematurely. A value of 0 disables this behavior (default)
discretization – discretization method, ‘backward’, ‘forward’ or ‘tustin’
relative_solving_tolerance – Allowed solving error for an argument relative to the typical magnitude of that argument.
minimum_solving_tolerance – Minimum allowed solving error. Defaults to 1e-10 to avoid non-convergence warnings due to minor numerical inaccuracies.
go_backwards_allowed – Whether the solver is allowed to run on a simulation step that precedes the given step. Defaults to True but can be disabled to maintain compatibility with components that did work in older FONSim versions.
verbose –
level of information printed in the console during the simulation. All messages belonging to a level with a number lower than or equal to the provided parameter will be displayed, with the possible levels being:
-1: simulation start and end messages
0 (default): simulation progress in % steps
1: system matrices on iterations with bad convergence
- check_issolvable()[source]
Warns when number of equations doesn’t equal number of unknowns.
- Returns
None
- equation_to_string(equation_index)[source]
Return a string describing the equation with the provided index in a human-readable format. For a network equation, this string contains the involved variables and their coefficients. For a component equation, this string mentions the component label and the index of the equation in the list of equations of that particular component.
- Parameters
equation_index – index of the row in the simulation equation matrix corresponding to the desired equation
- Return eq_str
string representing the equation
- evaluate_equations(simstep, g, H, elapsed_time, dt, discretization, force_update_all_states=False)[source]
Evaluate component equations to obtain evaluated function vector (equation residuals) and jacobian. This method will call the method
Component.evaluate()
on each component. This method will also call the methodComponent.update_state()
on each component.The parameter
discretization
sets the discretization method. In case of forward Euler discretization, the component equations are evaluated with the arguments and state belonging to stepsimstep
. The state is not touched. In case of backward Euler discretization, the component equations are evaluated with the arguments ofsimstep
and the state propagated fromsimstep - 1
tosimstep
using the arguments ofsimstep
. Finally, in the case of tustin discretization, the component equations are also evaluated with the arguments ofsimstep
but the state is propagated fromsimstep - 1
tosimstep
using the mean of the arguments atsimstep
and atsimstep + 1
. In none of the cases the propagated state is written out.By default,
force_update_all_states
isFalse
, which forces component states that do not locally depend on any arguments (their derivative to all arguments equals zero) to remain constant within the inner loop iterations. This avoids the emergence of an additional mathematically correct, though physically incorrect, solution.Note: This function does not evaluate (or update) the network equations (upper part of the jacobian ‘H’)!
- Parameters
simstep – simulation timestep index to start from
g – numpy ndarray for the evaluated function vector
H – numpy ndarray for the evaluated jacobian
elapsed_time – time elapsed
dt – timestep
discretization – discretization method, see above
force_update_all_states – whether to update all state values
- Returns
None
- extend_memory(nb_extra_steps)[source]
Increase the size of the simulation memory without overwriting previous results. This deals with the same entities as described in the documentation of initialize_memory
- Parameters
nb_extra_steps – amount of time steps by which to increase the memory
- Returns
None
- fill_argument_tolerances(argument_tolerances, argument_tolerances_inv)[source]
Fills the given array argument_tolerances with the product of argument value range and the desired relative solving tolerance. Array argument_tolerances should be 1D and have length self.nb_arguments.
- Parameters
argument_tolerances – array to fill
argument_tolerances_inv – array to fill
- Returns
None
- fill_component_equation_tolerances(equation_tolerances, equation_tolerances_inv)[source]
Fills the given arrays with the equation tolerances for the component equations (all equations with index larger than self.nb_network_equations). The two array should be 1D and have at least length
self.nb_network_equations + self.nb_component_equations
. The second array is filled with the inverse of the first. The equation tolerances are derived by multiplying the Jacobian H with the argument (Variable) tolerances, aka by projecting argument space on the equation space, and then taking minimum nonzero absolute value of each row.The bottom, component-part of the Jacobian H presents a linearization of the component equations for a particular argument vector. It is preferable that the equation tolerances are updated in every iteration of the Newton outer loop because components can switch from equations and the corresponding derivatives (and thus values in H) can vary greatly from iteration to iteration.
- Parameters
equation_tolerances – array to fill
equation_tolerances_inv – array to fill
- Returns
None
- fill_network_equation_tolerances(equation_tolerances, equation_tolerances_inv)[source]
Fills the given arrays with the equation tolerances for the network equations (first
self.nb_network_equations equations
). The two arrays should be 1D and have at least lengthself.nb_network_equations
. The second array is filled with the inverse for the first. The nonzero network equations multipliers are 1 or -1, so the equation tolerance equals the minimum variable solving tolerance of that equation (row in Jacobian H).- Parameters
equation_tolerances – array to fill
equation_tolerances_inv – array to fill
- Returns
None
- fill_network_matrix(A)[source]
Fill the network matrix. The network matrix is constant over the simulation, at least supposing the network configuration does not change. It is thus sufficient to calculate it a single time.
There are two types of network equations, one for across variables and one for through variables. At each node, all across variables have to be equal. Thus for each node n-1 equations, n being the number of components attached to that node. Concerning the through variables, the sum of all through variables should be zero at each node, thus one equation for each node.
- Parameters
A – system Jacobian matrix, numpy ndarray n x n, n=len(phi)
- Returns
None
- fill_state_tolerances(state_tolerances, state_tolerances_inv)[source]
Fills the given array state_tolerances with the product of the state value range and the desired relative solving tolerance. Array state_tolerances should be 1D and have length self.nb_states.
- Parameters
state_tolerances – array to fill
- Returns
None
- init_matrixconstruction()[source]
Create some LUT-style lists and dicts so data can be moved around quickly in the simulation loop.
- Returns
None
- initialize_memory(nb_steps)[source]
Initialize all arrays that will hold the simulation results through time. This includes - The vector with time values - Component argument and state histories (in Component class) - The simulation phi matrix with all arguments over time All previously stored results are overwritten. This method initializes the arrays with zeros and therefore does not use the
initial_value
attribute of the Variable objects.- Parameters
nb_steps – estimated amount of time steps in the simulation
- Returns
None
- map_phi_to_components(phi)[source]
Send addresses of arguments over time to components, so one can get the data from the component without passing by the Simulation object. Furthermore, it avoids duplicating the data.
- Parameters
phi – numpy ndarray m x n with the argument vector over time (m = nb timesteps and n = nb arguments)
- Returns
None
- map_state_to_components(state)[source]
Send addresses of state over time to components, so one can get the data from the component without passing by the Simulation object. Furthermore, it avoids duplicating the data.
- Parameters
state – numpy ndarray m x n with the state vector over time (m = nb timesteps and n = nb states)
- Returns
None
- print_equations()[source]
Print a human-readable representation of the full system of equations to the console.
- Returns
None
- print_system_matrix_column_indices()[source]
Print table of column indices and the corresponding arguments
- print_system_matrix_row_indices()[source]
Print table of row indices and the corresponding components
- set_initial_values_phi(step=0)[source]
Takes the initial values from the component argument Variable objects and writes them to the simulation memory (matrix ‘phi’).
- Parameters
step – simulation step at which to write the initial value
- Returns
None
- set_initial_values_state(step=0)[source]
Takes the initial values from the component state Variable objects and writes them to the simulation memory (matrix ‘state’).
- Parameters
step – simulation step at which to write the initial value
- Returns
None
- slice_memory(start_step, end_step)[source]
Decrease the size of the simulation memory by taking a slice out of it. This deals with the same entities as described in the documentation of initialize_memory
# TODO update such that takes slice as argument
- Parameters
start_step – index of the first time step in the range to maintain
end_step – index of the first time step outside the range to maintain
- Returns
None
- update_state(simstep_args, simstep_state, dt, discretization)[source]
Propagate the state variables in all components from step
simstep_state
tosimstep_state + 1
using the arguments (in self.phi) at stepsimstep_args
. This method will call the methodComponent.update_state()
on each component.- Parameters
simstep_args – Simulation timestep index to read arguments at.
simstep_state – Simulation timestep index to read states at (they are then written to the next step).
dt – timestep
discretization – discretization method
- Returns
None
fonsim.core.solver module
Classes with available solvers
A solver takes care of solving the (non-linear) system of equations generated by the Simulation object. This object can interact with the Simulation object.
The Simulation class expects the following methods from the solver object:
get_nb_steps_estimate()
run_step(simulation_step_index)
- Current solvers:
2020, July 23
- class fonsim.core.solver.BaseNewton(simulation, supported_discretization_methods, discretization)[source]
Bases:
object
Base class designed to ease creating new solvers by providing common solver functionality such as the Newton solver for solving systems of nonlinear equations.
The discretization method is set with the parameter
discretization
. The solver always solves the arguments for the selected timestep (in the methodrun_step
), and the solving is always done with the state values of that timestep, however the handling of the state differs. Most of the solvers in FONSim support several of the following three discretization methods (specified as a string):forward: propagates the state to the next step.
backward: propagates the state from the previous to the current step with the arguments of the current step
tustin: propagates the state from the previous to the current step with the mean of the arguments of the previous and the current step
- Parameters
simulation – Simulation object
supported_discretization_methods – the discretization methods the inherited class supports, must be set by child class
discretization – see above
- apply_solver_bias(bias=1e-12, step=0, quasirandom=False)[source]
Give elements in the solution vector a small positive value, to ease starting the simulation
If
quasirandom=True
, the assigned biases come from a random number generator initialized with a constant seed (i.e. the bias array is the same on each method call).- Parameters
bias – bias value added to the solution vector entries
step – simulation step for which this bias is applied
quasirandom – whether to vary bias values
- Returns
None
- get_all_variables(simstep)[source]
- Parameters
simstep – simulation step at which variables are queried
- Returns
np array with the values of all arguments and component states at the desired simulation step
- get_residual(simstep, res=None, dt=None, discretization=None)[source]
Evaluate the simulation system of equations at the provided timestep to get the residual vector. See the related method
Simulation.evaluate_equations()
for more documentation, as most arguments are passed to that method unmodified.- Parameters
simstep – index of simulation timestep at which the system of equations is evaluated
res – optional initialized residual vector that will be overwritten by this function in place
dt – timestep
discretization – discretization method, gets passed to
Simulation.evaluate_equations()
- Returns
evaluated residual vector
- newton_solver(step, iterations=100, alpha=1.0, discretization=None, min_nb_iterations=1)[source]
Newton method for solving the system equations and storing the solution in the simulation phi vector at an time step
- Parameters
step – step index for which the system will be solved and the solution will be stored. The initialization for the solver can be done externally by setting self.sim.phi[step] to the initial guess
iterations – maximum number of newton solver iterations. 100 (default) gives good results although it often converges in one step and otherwise mostly in less than ten
alpha – correction constant for damped Newton method
discretization – discretization method, gets passed to
solver.BaseNewton.get_residual()
- Returns
flag indicating exit status of the solver for this step:
0: maximum amount of iterations reached without convergence
1: solver converged quickly
2: solver converged slowly
- class fonsim.core.solver.NewtonAdaptiveTimeStep02(simulation, step, discretization)[source]
Bases:
BaseNewton
Supported discretization methods: ‘backward’ and ‘tustin’. ‘forward’ is not yet supported.
Please see base class for more information.
- Parameters
simulation – Simulation object
step – minimum and maximum time increment
discretization – discretization method
- class fonsim.core.solver.NewtonConstantTimeStep(simulation, step, discretization)[source]
Bases:
BaseNewton
Supported discretization methods: ‘forward’, ‘backward’ and ‘tustin’.
Please see the base class for more information.
- Parameters
simulation – Simulation object
step – fixed time increment
discretization – discretization method
fonsim.core.system module
Class System
2020, July 22
- class fonsim.core.system.System(label=None)[source]
Bases:
object
A System is a collection of interconnected components. It contains the Component objects and keeps track of how they are connected to each other. A System with components is created by first creating the System object, then adding components to this object and finally connecting these components to each other.
- Parameters
label – Label of the system, optional and currently not important.
- add(*components)[source]
Add components to the system.
- Parameters
components – Component object(s) to be added to the system
- Returns
None
- connect(*args)[source]
Connect two or more components together by connecting their terminals. In case terminals are not specified directly, the Component objects decide on which of their terminals to connect. The connections are made in sequential pairs using the method
System.connect_two_components
which in turn uses the methodself.connect_two_terminals
.The components and/or terminals to connect should be as specified in the method
System.get_component_and_terminal
.For instead connecting all components to a common Node, use the method
System.connect_common
.- Parameters
args – component terminals
- Returns
None
- connect_common(*args)[source]
Connect two or more component terminals together. In case terminals are not specified directly, the Component objects decide on which of their terminals to connect. All Terminals are connected to each other, aka to a common Node. Making the connection is handled with the method
self.connect_two_terminals
.The components and/or terminals to connect should be as specified in the method
System.get_component_and_terminal
.For instead making sequential connections, use the method
System.connect
.- Parameters
args – component terminals
- Returns
None
- connect_two_components(component_a, component_b)[source]
Connect two Components to each other. The connection is made using the method
self.connect_two_terminals
.The component arguments component_a and component_b can be as specified in the method
System.get_component_and_terminal
.- Parameters
component_a – First component, see description
component_b – Second component, see description
- Returns
None
- connect_two_terminals(terminal_a, terminal_b)[source]
Connect two system terminals together in a Node. These nodes exist for the workings of the solver and have nothing to do with any nodes in the fluidic networks being simulated.
- Parameters
terminal_a – Terminal object
terminal_b – Terminal object
- Returns
None
- get(component_label)[source]
- Parameters
component_label – Label of the desired component.
- Returns
Component object with the given label.
- get_component_and_terminal(arg)[source]
Get a pair of a Component and a Terminal given an argument
arg
. This argument can be:a string specifying a component label present in the system
a Component object
a Terminal object
a Tuple with first the component label and then the terminal label as strings
If multiple choices are available, this method may make an undefined choice.
- Parameters
arg – see desription
- Returns
Component object, Terminal object
fonsim.core.terminal module
Class Terminal
2020, July 22
- class fonsim.core.terminal.Terminal(label, variables, variable_labels={})[source]
Bases:
object
Component connection point with local through and across variables.
Note: In any particular Terminal object, there cannot be more than one variable with the same key.
- Parameters
label – Label to refer to the Terminal later on. Free to choose.
variables – Variable objects that will belong to the Terminal.
- get_variable(key)[source]
Return the variable object attached to the terminal with the provided key, for example ‘pressure’. If there is no variable with the requested key, None is returned.
- Parameters
key – key of the variable to return
- Return variable
attached variable with the matching key
- get_variables(orientation=None)[source]
Get list of all terminal variables with the given orientation. The orientation can be either “through” or “across”. If not provided or None, all variables regardless of orientation are returned
- Parameters
orientation – optional string specifying desired variable orientation
- Returns
list of Variable objects
fonsim.core.variable module
Class Variable
2020, July 21
- class fonsim.core.variable.Variable(key, orientation, terminal=None, label='None', initial_value=0.0, range=(-inf, inf))[source]
Bases:
object
A
Variable
object is used to denote the presence of a yet unknown numerical value. For each Variable object, the solver will search for the optimal numerical values over time. The solver does so by solving the system of equations that connect these variables together. The variables are connected by each other by connecting the Terminal objects that contain the values to each other.The parameter ‘key’ indicates the type label. Only Variable objects with the same type label can exchange information.
The parameter ‘orientation’ should have value ‘across’ or ‘through’ or ‘free’. ‘across’ indicates that the value of the Variable will be shared with the Variable belonging to the other Terminal while ‘through’ indicates that its negative will be shared. The former is typically used with nondirectional values, such as pressure, while the latter is typically used with directional values, such as a massflow. ‘local’ indicates that it will not be shared (feature WIP).
- Parameters
key – type label, e.g. ‘pressure’, ‘massflow’
orientation – ‘across’, ‘through’ or ‘free’.
terminal – Terminal object to which Variable object get connected, default: None
label – label, used to refer to a Variable instance later on
initial_value – Initial value, default: 0
range – tuple with min and max of allowed value range
- copy_and_attach(terminal)[source]
Return a copy of the variable object attached to a given terminal. The returned variable has the same key, orientation and initial value but is otherwise unrelated to the Variable object it is called upon.
- Parameters
terminal – Terminal object to attach the variable copy to
- Return variable
attached copy of the variable object
- short_str(nb_var_chars=1)[source]
Return a short string describing the variable more as a symbol than in words. This string contains the first n letters of the variable name as well as (if applicable) the port and component it is attached to.
- Parameters
nb_var_chars – number of characters with which the variable key is abbreviated. Set to 0 to avoid abbreviation.
- Return var_str
short string representing the variable
Module contents
2020, September 17