Model building reference
This page lists functionality and utilities related to building hierarchical models. It is recommended to read the page on the System before this.
Common definitions of t and D
ModelingToolkit provides common definitions for the independent variable t (time) and the derivative with respect to it D.
Missing docstring for ModelingToolkit.t_nounits. Check Documenter's build log for details.
Missing docstring for ModelingToolkit.D_nounits. Check Documenter's build log for details.
Missing docstring for ModelingToolkit.t. Check Documenter's build log for details.
Missing docstring for ModelingToolkit.D. Check Documenter's build log for details.
Users are recommended to use the appropriate common definition in their models. The required definitions can be imported with convenient aliased names. For example:
using ModelingToolkit: t_nounits as t, D_nounits as DAllows using t and D to refer to t_nounits and D_nounits respectively.
Hierarchical model composition
The System data structure can represent a tree-like hierarchy of systems for building models from composable blocks. The ModelingToolkit.get_systems function can be used for querying the subsystems of a system. The @component macro should be used when writing building blocks for model composition.
Every constructor function should build either a component or a connector. Components define the dynamics of the system. Connectors are used to connect components together and propagate information between them. See also @connector.
Scoping of variables
When building hierarchical systems, is is often necessary to pass variables from a parent system to the subsystems. If done naively, this will result in the child system assuming it "owns" the variables passed to it and any occurrences of those variables in the child system will be namespaced. To prevent this, ModelingToolkit has the concept of variable scope. The scope allows specifying which system a variable belongs to relative to the system in which it is used.
Note that the scopes must be applied to individual variables and not expressions. For example, ParentScope(x + y) is incorrect. Instead, ParentScope(x) + ParentScope(y) is the correct usage. Applying the same scope (more generally, the same function) to all variables in an expression is a common task, and ModelingToolkit exposes a utility for the same:
Missing docstring for ModelingToolkit.apply_to_variables. Check Documenter's build log for details.
It is still tedious to manually use apply_to_variables on any symbolic expression passed to a subsystem. The @named macro automatically wraps all symbolic arguments in ParentScope and uses the identifier being assigned as the name of the system.
Exploring the tree structure
The System type implements the AbstractTrees interface. This can be used to explore the hierarchical structure.
Connection semantics
ModelingToolkit implements connection semantics similar to those in the Modelica specification. We do not support the concept of inner and outer elements or expandable connectors. Connectors in ModelingToolkit are systems with the appropriate metadata added via the @connector macro.
Connections can be expanded using expand_connections.
Missing docstring for expand_connections. Check Documenter's build log for details.
Similar to the stream and flow keyword arguments in the specification, ModelingToolkit allows specifying how variables in a connector behave in a connection.
Missing docstring for ModelingToolkit.Equality. Check Documenter's build log for details.
These are specified using the connect metadata. ModelingToolkit also supports instream. Refer to the Modelica specification on Stream connectors for more information.
System composition utilities
ModelingToolkit.substitute_component — Function
substitute_component(
sys::ModelingToolkitBase.AbstractSystem,
rule::Pair{T<:ModelingToolkitBase.AbstractSystem, T<:ModelingToolkitBase.AbstractSystem}
) -> Any
Given a hierarchical system sys and a rule lhs => rhs, replace the subsystem lhs in sys by rhs. The lhs must be the namespaced version of a subsystem of sys (e.g. obtained via sys.inner.component). The rhs must be valid as per the following conditions:
rhsmust not be namespaced.- The name of
rhsmust be the same as the unnamespaced name oflhs. - Neither one of
lhsorrhscan be marked as complete. - Both
lhsandrhsmust share the same independent variable. rhsmust contain at least all of the unknowns and parameters present inlhs.- Corresponding unknowns in
rhsmust share the same connection and causality (input/output) metadata as their counterparts inlhs. - For each subsystem of
lhs, there must be an identically named subsystem ofrhs. These two corresponding subsystems must satisfy conditions 3, 4, 5, 6, 7. If the subsystem oflhsis a connector, the corresponding subsystem ofrhsmust also be a connector of the same type.
sys also cannot be marked as complete.
Flattening systems
The hierarchical structure can be flattened. This operation is performed during simplification.
System simplification
Systems can be simplified to reformulate them in a way that enables it to be solved numerically, and also perform other optimizations. This is done via the mtkcompile function. Connection expansion and flattening are preprocessing steps of simplification.
ModelingToolkitBase.mtkcompile — Function
function mtkcompile(sys::System; kwargs...)Compile the given system into a form that ModelingToolkit can generate code for. Also performs a variety of symbolic-numeric enhancements. For ODEs, this includes processes such as order reduction, index reduction, alias elimination and tearing. A subset of the unknowns of the system may be eliminated as observables, eliminating the need for the numerical solver to solve for these variables.
Does not rely on metadata to identify variables/parameters/brownians. Instead, queries the system for which symbolic quantites belong to which category. Any variables not present in the equations of the system will be removed in this process.
Keyword Arguments
- When
simplify=true, thesimplifyfunction will be applied during the tearing process. allow_symbolic=false,allow_parameter=true, andconservative=falselimit the coefficient types during tearing. In particular,conservative=truelimits tearing to only solve for trivial linear systems where the coefficient has the absolute value of $1$.fully_determined=truecontrols whether or not an error will be thrown if the number of equations don't match the number of inputs, outputs, and equations.inputs,outputsanddisturbance_inputsare passed as keyword arguments.All inputsget converted to parameters and are allowed to be unconnected, allowing models wheren_unknowns = n_equations - n_inputs.sort_eqs=truecontrols whether equations are sorted lexicographically before simplification or not.
It is also possible (though not always advisable) to build numerical problems from systems without passing them through mtkcompile. To do this, the system must first be marked as "complete" via the complete function. This process is used to indicate that a system will not be modified further and allows ModelingToolkit to perform any necessary preprocessing to it. mtkcompile calls complete internally.
Exploring the results of simplification
Similar to how full_equations returns the equations of a system with all variables eliminated during mtkcompile substituted, we can perform this substitution on an arbitrary expression.
Missing docstring for ModelingToolkit.substitute_observed. Check Documenter's build log for details.
Missing docstring for ModelingToolkit.empty_substitutions. Check Documenter's build log for details.
Missing docstring for ModelingToolkit.get_substitutions. Check Documenter's build log for details.
Experimental simplification
ModelingToolkit may have a variety of experimental simplification passes. These are not enabled by default, but can be used by passing to the additional_passes keyword argument of mtkcompile.
ModelingToolkit.IfLifting — Function
If lifting converts (nested) if statements into a series of continuous events + a logically equivalent if statement + parameters.
Lifting proceeds through the following process:
- rewrite comparisons to be of the form eqn [op] 0; subtract the RHS from the LHS
- replace comparisons with generated parameters; for each comparison eqn [op] 0, generate an event (dependent on op) that sets the parameter
Event handling
Time-dependent systems may have several events. These are used to trigger discontinuities in the model. They compile to standard callbacks from DiffEqCallbacks.jl.
Missing docstring for ModelingToolkit.SymbolicContinuousCallback. Check Documenter's build log for details.
Missing docstring for ModelingToolkit.SymbolicDiscreteCallback. Check Documenter's build log for details.
The affect functions for the above callbacks can be symbolic or user-defined functions. Symbolic affects are handled using equations as described in the Events section of the documentation. User-defined functions can be used via ImperativeAffect.
Missing docstring for ModelingToolkit.ImperativeAffect. Check Documenter's build log for details.
Modelingtoolkitize
ModelingToolkit can take some numerical problems created non-symbolically and build a symbolic representation from them.
Missing docstring for modelingtoolkitize. Check Documenter's build log for details.
Using FMUs
ModelingToolkit is capable of importing FMUs as black-box symbolic models. Currently only a subset of FMU features are supported. This functionality requires importing FMI.jl.
ModelingToolkit.FMIComponent — Function
FMIComponent(
::Val{Ver};
fmu,
tolerance,
communication_step_size,
reinitializealg,
type,
name
)
A component that wraps an FMU loaded via FMI.jl. The FMI version (2 or 3) should be provided as a Val to the function. Supports Model Exchange and CoSimulation FMUs. All inputs, continuous variables and outputs must be FMI.fmi2Real or FMI.fmi3Float64. Does not support events or discrete variables in the FMU. Does not support automatic differentiation. Parameters of the FMU will have defaults corresponding to their initial values in the FMU specification. All other variables will not have a default. Hierarchical names in the FMU of the form namespace.variable are transformed into symbolic variables with the name namespace__variable.
Keyword Arguments
fmu: The FMU loaded viaFMI.loadFMU.tolerance: The tolerance to provide to the FMU. Not used for v3 FMUs since it is not supported by FMI.jl.communication_step_size: The periodic interval at which communication with CoSimulation FMUs will occur. Must be provided for CoSimulation FMU components.reinitializealg: The DAE initialization algorithm to use for the callback managing the FMU. For CoSimulation FMUs whose states/outputs are used in algebraic equations of the system, this needs to be an algorithm that will solve for the new algebraic variables. For example,OrdinaryDiffEqCore.BrownFullBasicInit().type: Either:MEor:CSdepending on whetherfmuis a Model Exchange or CoSimulation FMU respectively.name: The name of the system.
Model transformations
ModelingToolkit exposes a variety of transformations that can be applied to models to aid in symbolic analysis.
Missing docstring for liouville_transform. Check Documenter's build log for details.
Missing docstring for fractional_to_ordinary. Check Documenter's build log for details.
Missing docstring for linear_fractional_to_ordinary. Check Documenter's build log for details.
Missing docstring for change_of_variables. Check Documenter's build log for details.
Missing docstring for stochastic_integral_transform. Check Documenter's build log for details.
Missing docstring for Girsanov_transform. Check Documenter's build log for details.
Missing docstring for change_independent_variable. Check Documenter's build log for details.
Missing docstring for add_accumulations. Check Documenter's build log for details.
Missing docstring for noise_to_brownians. Check Documenter's build log for details.
Missing docstring for convert_system_indepvar. Check Documenter's build log for details.
Hybrid systems
Hybrid systems are dynamical systems involving one or more discrete-time subsystems. These discrete time systems follow clock semantics - they are synchronous systems and the relevant variables are only defined at points where the clock ticks.
While ModelingToolkit is unable to simplify, compile and solve such systems on its own, it has the ability to represent them. Compilation strategies can be implemented independently on top of mtkcompile using the additional_passes functionality.
ModelingToolkit uses the clock definition in SciMLBase
Missing docstring for SciMLBase.TimeDomain. Check Documenter's build log for details.
Missing docstring for SciMLBase.SolverStepClock. Check Documenter's build log for details.
Missing docstring for SciMLBase.Continuous. Check Documenter's build log for details.
State machines
While ModelingToolkit has the capability to represent state machines, it lacks the ability to compile and simulate them.