Input output
An input-output system is a system on the form
\[\begin{aligned} M \dot x &= f(x, u, p, t) \\ y &= g(x, u, p, t) \end{aligned}\]
where $x$ is the state, $u$ is the input and $y$ is an output (in some contexts called an observed variables in MTK).
While many uses of ModelingToolkit for simulation do not require the user to think about inputs and outputs (IO), there are certain situations in which handling IO explicitly may be important, such as
- Linearization
- Control design
- System identification
- FMU export
- Real-time simulation with external data inputs
- Custom interfacing with other simulation tools
This documentation page lists utilities that are useful for working with inputs and outputs in ModelingToolkit.
Generating a dynamics function with inputs, $f$
ModelingToolkit can generate the dynamics of a system, the function $M\dot x = f(x, u, p, t)$ above, such that the user can pass not only the state $x$ and parameters $p$ but also an external input $u$. To this end, the function ModelingToolkit.generate_control_function exists.
This function takes a vector of variables that are to be considered inputs, i.e., part of the vector $u$. Alongside returning the function $f$, ModelingToolkit.generate_control_function also returns the chosen state realization of the system after simplification. This vector specifies the order of the state variables $x$, while the user-specified vector u specifies the order of the input variables $u$.
This function expects sys to be un-simplified, i.e., mtkcompile or @mtkcompile should not be called on the system before passing it into this function. generate_control_function calls a special version of mtkcompile internally.
Example:
The following example implements a simple first-order system with an input u and state x. The function f is generated using generate_control_function, and the function f is then tested with random input and state values.
using ModelingToolkit
import ModelingToolkit: t_nounits as t, D_nounits as D
@variables x(t)=0 u(t)=0 y(t)
@parameters k = 1
eqs = [D(x) ~ -k * (x + u)
y ~ x]
@named sys = System(eqs, t)
f, x_sym, ps = ModelingToolkit.generate_control_function(sys, [u], simplify = true);We can inspect the state realization chosen by MTK
x_sym1-element Vector{SymbolicUtils.BasicSymbolic{Real}}:
x(t)as expected, x is chosen as the state variable.
Now we can test the generated function f with random input and state values
p = [1]
x = [rand()]
u = [rand()]
@test f[1](x, u, p, 1) ≈ -p[] * (x + u) # Test that the function computes what we expect D(x) = -k*(x + u)Test PassedGenerating an output function, $g$
ModelingToolkit can also generate a function that computes a specified output of a system, the function $y = g(x, u, p, t)$ above. This is done using the function ModelingToolkit.build_explicit_observed_function. When generating an output function, the user must specify the output variable(s) of interest, as well as any inputs if inputs are relevant to compute the output.
The order of the user-specified output variables determines the order of the output vector $y$.
Input-output variable metadata
See Symbolic Metadata. Metadata specified when creating variables is not directly used by any of the functions above, but the user can use the accessor functions ModelingToolkit.inputs(sys) and ModelingToolkit.outputs(sys) to obtain all variables with such metadata for passing to the functions above. The presence of this metadata is not required for any IO functionality and may be omitted.
Linearization
See Linearization.
Docstrings
ModelingToolkit.generate_control_function — Functiongenerate_control_function(sys::ModelingToolkit.AbstractSystem, input_ap_name::Union{Symbol, Vector{Symbol}, AnalysisPoint, Vector{AnalysisPoint}}, dist_ap_name::Union{Symbol, Vector{Symbol}, AnalysisPoint, Vector{AnalysisPoint}}; system_modifier = identity, kwargs)When called with analysis points as input arguments, we assume that all analysis points corresponds to connections that should be opened (broken). The use case for this is to get rid of input signal blocks, such as Step or Sine, since these are useful for simulation but are not needed when using the plant model in a controller or state estimator.
(f_oop, f_ip), x_sym, p_sym, io_sys = generate_control_function(
sys::System,
inputs = unbound_inputs(sys),
disturbance_inputs = disturbances(sys);
implicit_dae = false,
simplify = false,
split = true,
)For a system sys with inputs (as determined by unbound_inputs or user specified), generate functions with additional input argument u
The returned functions are the out-of-place (f_oop) and in-place (f_ip) forms:
f_oop : (x,u,p,t) -> rhs
f_ip : (xout,x,u,p,t) -> nothingThe return values also include the chosen state-realization (the remaining unknowns) x_sym and parameters, in the order they appear as arguments to f.
If disturbance_inputs is an array of variables, the generated dynamics function will preserve any state and dynamics associated with disturbance inputs, but the disturbance inputs themselves will (by default) not be included as inputs to the generated function. The use case for this is to generate dynamics for state observers that estimate the influence of unmeasured disturbances, and thus require unknown variables for the disturbance model, but without disturbance inputs since the disturbances are not available for measurement. To add an input argument corresponding to the disturbance inputs, either include the disturbance inputs among the control inputs, or set disturbance_argument=true, in which case an additional input argument w is added to the generated function (x,u,p,t,w)->rhs.
Example
using ModelingToolkit: generate_control_function, varmap_to_vars, defaults
f, x_sym, ps = generate_control_function(sys, expression=Val{false}, simplify=false)
p = varmap_to_vars(defaults(sys), ps)
x = varmap_to_vars(defaults(sys), x_sym)
t = 0
f[1](x, inputs, p, t)ModelingToolkit.build_explicit_observed_function — Functionbuild_explicit_observed_function(sys, ts; kwargs...) -> Function(s)Generates a function that computes the observed value(s) ts in the system sys, while making the assumption that there are no cycles in the equations.
Arguments
sys: The system for which to generate the functionts: The symbolic observed values whose value should be computed
Keywords
return_inplace = false: If true and the observed value is a vector, then return both the in place and out of place methods.expression = false: Generates a JuliaExprcomputing the observed value ifexpression` is trueeval_expression = false: If true andexpression = false, evaluates the returned function in the moduleeval_moduleoutput_type = Arraythe type of the array generated by a out-of-place vector-valued functionparam_only = falseif true, only allow the generated function to access system parametersinputs = nothingadditinoal symbolic variables that should be provided to the generated functioncheckbounds = truechecks bounds if true when destructuring parametersop = Operatorsets the recursion terminator for the walk done byvarsto identify the variables that appear ints. See the documentation forvarsfor more detail.throw = trueif true, throw an error when generating a function fortsthat reference variables that do not exist.mkarray: only used if the output is an array (that is,!isscalar(ts)andtsis not a tuple, in which case the result will always be a tuple). Called asmkarray(ts, output_type)wheretsare the expressions to put in the array andoutput_typeis the argument of the same name passed to buildexplicitobserved_function.cse = true: Whether to use Common Subexpression Elimination (CSE) to generate a more efficient function.wrap_delays = is_dde(sys): Whether to add an argument for the history function and use it to calculate all delayed variables.
Returns
The return value will be either:
- a single function
f_oopif the input is a scalar or if the input is a Vector butreturn_inplaceis false - the out of place and in-place functions
(f_ip, f_oop)ifreturn_inplaceis true and the input is aVector
The function(s) f_oop (and potentially f_ip) will be:
RuntimeGeneratedFunctions by default,- A Julia
Exprifexpressionis true, - A directly evaluated Julia function in the module
eval_moduleifeval_expressionis true andexpressionis false.
The signatures will be of the form g(...) with arguments:
outputfor in-place functionsunknownsifparam_onlyisfalseinputsifinputsis an array of symbolic inputs that should be available intsp...unconditionally; note that in the case ofMTKParametersmore than one parameters argument may be present, so it must be splattedtif the system is time-dependent; for example systems of nonlinear equations will not havet
For example, a function g(op, unknowns, p..., inputs, t) will be the in-place function generated if return_inplace is true, ts is a vector, an array of inputs inputs is given, and param_only is false for a time-dependent system.