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, dvs, ps, io_sys) = ModelingToolkit.generate_control_function(
sys, [u]; simplify = true
)We can inspect the state realization chosen by MTK
dvs1-element Vector{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}}:
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_val = [rand()]
u_val = [rand()]
@test f[1](x_val, u_val, p, 1) ≈ -p[] * (x_val + u_val)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$.
g = ModelingToolkit.build_explicit_observed_function(io_sys, [x + u * t]; inputs = [u])
@test g([1.0], [2.0], p, 3.0) ≈ [7.0]Test PassedInput-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
ModelingToolkitBase.generate_control_function — Function
generate_control_function(sys::ModelingToolkitBase.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.
generate_control_function(sys, inputs = default_codegen_inputs(sys),
disturbance_inputs = disturbances(sys); kwargs...) -> (; f, dvs, ps, io_sys)Generate the dynamics of an input-output system as callable functions of its state, inputs, parameters, and independent variable.
Arguments
sys::AbstractSystem: The system to generate dynamics for. An unscheduled system is compiled withmtkcompile; a scheduled system is used as given.inputs: Symbolic variables that form the generated input argumentu. By default, declared inputs are used for scheduled systems and external inputs for unscheduled systems.disturbance_inputs: Unknown disturbance inputs. Their state and dynamics are retained, but their values are set to zero and are not function arguments.
Keywords
known_disturbance_inputs = nothing: Disturbance inputs supplied as a final generated argumentw; they are removed from the parameter arguments.implicit_dae::Bool = false: Generate residual dynamics for an implicit DAE.simplify::Bool = false: Forwarded tomtkcompilewhensysis unscheduled.split::Bool = true: Forwarded tomtkcompileto select split-system generation.eval_expression::Bool = false: Evaluate generated code ineval_moduleinstead of returning a runtime-generated function.eval_module::Module = @__MODULE__: Module used wheneval_expression = true.disturbance_argument = false: Deprecated compatibility option. Useknown_disturbance_inputsinstead.kwargs...: Forwarded toSymbolics.CodegenFunctionOptions.
Returns
A named tuple with:
f: A pair(f_oop, f_iip)of generated out-of-place and in-place dynamics wrappers. The basic call signatures aref_oop(x, u, p..., t)andf_iip(dx, x, u, p..., t). With known disturbances, both have a finalwargument.dvs: The selected state variables, ordered as thexargument off.ps: The selected parameter variables, ordered as the parameter arguments off.io_sys: The scheduled system used to generatef.
Example
using ModelingToolkitBase
import ModelingToolkitBase: t_nounits as t, D_nounits as D
@variables x(t) u(t)
@parameters k
@named sys = System([D(x) ~ -k * (x + u)], t)
(; f, dvs, ps, io_sys) = generate_control_function(sys, [u]; simplify = true)
p = [2.0]
f[1]([1.0], [3.0], p, 0.0) # [-8.0]ModelingToolkitBase.build_explicit_observed_function — Function
build_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 = Val(false): If true and the observed value is a vector, then return both the in place and out of place methods. Can take booleantrueorfalsevalues, butVal(true)orVal(false)is preferred.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 functiondisturbance_inputs = nothingsymbolic variables representing unknown disturbance inputs (removed from parameters, not added as function arguments)known_disturbance_inputs = nothingsymbolic variables representing known disturbance inputs (removed from parameters, added as function arguments)checkbounds: whether to check bounds when destructuring parameters (defaults tofalse, i.e. generated code is wrapped in@inbounds)throw = trueif true, throw an error when generating a function fortsthat reference variables that do not exist.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 havetknown_disturbance_inputsif provided; these are disturbance inputs that are known and provided as arguments
For example, a function g(op, unknowns, p..., inputs, t, known_disturbances) will be the in-place function generated if return_inplace is true, ts is a vector, an array of inputs inputs is given, known_disturbance_inputs is provided, and param_only is false for a time-dependent system.