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$.

Un-simplified system

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

dvs
1-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 Passed

Generating 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 Passed

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

    ModelingToolkitBase.generate_control_functionFunction
    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.

    source
    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 with mtkcompile; a scheduled system is used as given.
    • inputs: Symbolic variables that form the generated input argument u. 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 argument w; they are removed from the parameter arguments.
    • implicit_dae::Bool = false: Generate residual dynamics for an implicit DAE.
    • simplify::Bool = false: Forwarded to mtkcompile when sys is unscheduled.
    • split::Bool = true: Forwarded to mtkcompile to select split-system generation.
    • eval_expression::Bool = false: Evaluate generated code in eval_module instead of returning a runtime-generated function.
    • eval_module::Module = @__MODULE__: Module used when eval_expression = true.
    • disturbance_argument = false: Deprecated compatibility option. Use known_disturbance_inputs instead.
    • kwargs...: Forwarded to Symbolics.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 are f_oop(x, u, p..., t) and f_iip(dx, x, u, p..., t). With known disturbances, both have a final w argument.
    • dvs: The selected state variables, ordered as the x argument of f.
    • ps: The selected parameter variables, ordered as the parameter arguments of f.
    • io_sys: The scheduled system used to generate f.

    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]
    source
    ModelingToolkitBase.build_explicit_observed_functionFunction
    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 function
    • ts: 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 boolean true or false values, but Val(true) or Val(false) is preferred.
    • expression = false: Generates a Julia Exprcomputing the observed value ifexpression` is true
    • eval_expression = false: If true and expression = false, evaluates the returned function in the module eval_module
    • output_type = Array the type of the array generated by a out-of-place vector-valued function
    • param_only = false if true, only allow the generated function to access system parameters
    • inputs = nothing additinoal symbolic variables that should be provided to the generated function
    • disturbance_inputs = nothing symbolic variables representing unknown disturbance inputs (removed from parameters, not added as function arguments)
    • known_disturbance_inputs = nothing symbolic variables representing known disturbance inputs (removed from parameters, added as function arguments)
    • checkbounds: whether to check bounds when destructuring parameters (defaults to false, i.e. generated code is wrapped in @inbounds)
    • throw = true if true, throw an error when generating a function for ts that 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_oop if the input is a scalar or if the input is a Vector but return_inplace is false
    • the out of place and in-place functions (f_ip, f_oop) if return_inplace is true and the input is a Vector

    The function(s) f_oop (and potentially f_ip) will be:

    • RuntimeGeneratedFunctions by default,
    • A Julia Expr if expression is true,
    • A directly evaluated Julia function in the module eval_module if eval_expression is true and expression is false.

    The signatures will be of the form g(...) with arguments:

    • output for in-place functions
    • unknowns if param_only is false
    • inputs if inputs is an array of symbolic inputs that should be available in ts
    • p... unconditionally; note that in the case of MTKParameters more than one parameters argument may be present, so it must be splatted
    • t if the system is time-dependent; for example systems of nonlinear equations will not have t
    • known_disturbance_inputs if 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.

    source