Linearization

A nonlinear dynamical system with state (differential and algebraic) $x$ and input signals $u$

\[M \dot x = f(x, u)\]

can be linearized using the function linearize to produce a linear statespace system on the form

\[\begin{aligned} \dot x &= Ax + Bu\\ y &= Cx + Du \end{aligned}\]

The linearize function expects the user to specify the inputs $u$ and the outputs $y$ using the syntax shown in the example below. The system model is not supposed to be simplified before calling linearize:

Example

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D
@variables x(t)=0 y(t) u(t) r(t)=0
@parameters kp = 1

eqs = [u ~ kp * (r - y) # P controller
       D(x) ~ -x + u    # First-order plant
       y ~ x]           # Output equation

@named sys = System(eqs, t) # Do not call @mtkcompile when linearizing
matrices, simplified_sys = linearize(sys, [r], [y]) # Linearize from r to y
matrices
(A = [-2.0;;], B = [1.0;;], C = [1.0;;], D = [0.0;;])

The named tuple matrices contains the matrices of the linear statespace representation, while simplified_sys is an System that, among other things, indicates the unknown variable order in the linear system through

using ModelingToolkit: inputs, outputs
[unknowns(simplified_sys); inputs(simplified_sys); outputs(simplified_sys)]
3-element Vector{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}}:
 x(t)
 r(t)
 y(t)
Inputs must be unconnected

The model above has 4 variables but only three equations, there is no equation specifying the value of r since r is an input. This means that only unbalanced models can be linearized, or in other words, models that are balanced and can be simulated cannot be linearized. To learn more about this, see How to linearize a ModelingToolkit model (YouTube). Also see ModelingToolkitStandardLibrary: Linear analysis for utilities that make linearization of completed models easier.

Un-simplified system

Linearization expects sys to be un-simplified, i.e., mtkcompile or @mtkcompile should not be called on the system before linearizing.

Operating point

The operating point to linearize around can be specified with the keyword argument op like this: op = Dict(x => 1, r => 2). The operating point may include specification of unknown variables, input variables and parameters. For variables that are not specified in op, the default value specified in the model will be used if available, if no value is specified, an error is thrown.

Batch linearization and algebraic variables

If linearization is to be performed around multiple operating points, the simplification of the system has to be carried out a single time only. To facilitate this, the lower-level function ModelingToolkit.linearization_function is available. This function further allows you to obtain separate Jacobians for the differential and algebraic parts of the model. For ODE models without algebraic equations, the statespace representation above is available from the output of linearization_function as A, B, C, D = f_x, f_u, h_x, h_u.

All variables that will be fixed by an operating point must be provided in the operating point to linearization_function. For example, if the operating points fix the value of x, y and z then an operating point with constant values for these variables (e.g. Dict(x => 1.0, y => 1.0, z => 1.0)) must be provided. The constant values themselves do not matter and can be changed by subsequent operating points.

One approach to batch linearization would be to call linearize in a loop, providing a different operating point each time. For example:

using ModelingToolkitStandardLibrary
using ModelingToolkitStandardLibrary.Blocks

@parameters k=10 k3=2 c=1
@variables x(t)=0 [bounds = (-0.5, 1.5)]
@variables v(t) = 0

@named y = Blocks.RealOutput()
@named u = Blocks.RealInput()

eqs = [D(x) ~ v
       D(v) ~ -k * x - k3 * x^3 - c * v + 10u.u
       y.u ~ x]

@named duffing = System(eqs, t, systems = [y, u], initial_conditions = [u.u => 0])

# pass a constant value for `x`, since it is the variable we will change in operating points
linfun, simplified_sys = linearization_function(duffing, [u.u], [y.u]; op = Dict(x => NaN));

println(linearize(simplified_sys, linfun; op = Dict(x => 1.0)))
println(linearize(simplified_sys, linfun; op = Dict(x => 0.0)))

@time linearize(simplified_sys, linfun; op = Dict(x => 0.0))
((A = [0.0 1.0; -16.0 -1.0], B = [0.0; 10.0;;], C = [1.0 0.0], D = [0.0;;]), (x = [1.0, 0.0], p = MTKParameters{Vector{Float64}, Vector{Float64}, Tuple{}, Tuple{}, Tuple{}, Tuple{}}([10.0, 2.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], (), (), (), ()), t = 0.0))
((A = [0.0 1.0; -10.0 -1.0], B = [0.0; 10.0;;], C = [1.0 0.0], D = [0.0;;]), (x = [0.0, 0.0], p = MTKParameters{Vector{Float64}, Vector{Float64}, Tuple{}, Tuple{}, Tuple{}, Tuple{}}([10.0, 2.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], (), (), (), ()), t = 0.0))
  0.000349 seconds (291 allocations: 20.469 KiB)

However, this route is still expensive since it has to repeatedly process the symbolic map provided to op. linearize is simply a wrapper for creating and solving a ModelingToolkit.LinearizationProblem. This object is symbolically indexable, and can thus integrate with SymbolicIndexingInterface.jl for fast updates.

using SymbolicIndexingInterface

# The second argument is the value of the independent variable `t`.
linprob = LinearizationProblem(linfun, 1.0)
# It can be mutated
linprob.t = 0.0
# create a setter function to update `x` efficiently
setter! = setu(linprob, x)

function fast_linearize!(problem, setter!, value)
    setter!(problem, value)
    solve(problem)
end

println(fast_linearize!(linprob, setter!, 1.0))
println(fast_linearize!(linprob, setter!, 0.0))

@time fast_linearize!(linprob, setter!, 1.0)
((A = [0.0 1.0; -16.0 -1.0], B = [0.0; 10.0;;], C = [1.0 0.0], D = [0.0;;]), (x = [1.0, 0.0], p = MTKParameters{Vector{Float64}, Vector{Float64}, Tuple{}, Tuple{}, Tuple{}, Tuple{}}([10.0, 2.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], (), (), (), ()), t = 0.0))
((A = [0.0 1.0; -10.0 -1.0], B = [0.0; 10.0;;], C = [1.0 0.0], D = [0.0;;]), (x = [0.0, 0.0], p = MTKParameters{Vector{Float64}, Vector{Float64}, Tuple{}, Tuple{}, Tuple{}, Tuple{}}([10.0, 2.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], (), (), (), ()), t = 0.0))
  0.000183 seconds (223 allocations: 15.875 KiB)

Note that linprob above can be interacted with similar to a normal ODEProblem.

julia> prob[x]ERROR: UndefVarError: `prob` not defined
julia> prob[x] = 1.5ERROR: UndefVarError: `prob` not defined
julia> prob[x]ERROR: UndefVarError: `prob` not defined

Symbolic linearization

The function ModelingToolkit.linearize_symbolic works similar to ModelingToolkit.linearize but returns symbolic rather than numeric Jacobians. Symbolic linearization have several limitations and no all systems that can be linearized numerically can be linearized symbolically.

Input derivatives

Physical systems are always proper, i.e., they do not differentiate causal inputs. However, ModelingToolkit allows you to model non-proper systems, such as inverse models, and may sometimes fail to find a realization of a proper system on proper form. In these situations, linearize may throw an error mentioning

Input derivatives appeared in expressions (-g_z\g_u != 0)

This means that to simulate this system, some order of derivatives of the input is required. To allow linearize to proceed in this situation, one may pass the keyword argument allow_input_derivatives = true, in which case the resulting model will have twice as many inputs, $2n_u$, where the last $n_u$ inputs correspond to $\dot u$.

If the modeled system is actually proper (but MTK failed to find a proper realization), further numerical simplification can be applied to the resulting statespace system to obtain a proper form. Such simplification is currently available in the package ControlSystemsMTK.

Tools for linear analysis

ModelingToolkit contains a set of tools for more advanced linear analysis. These can be used to make it easier to work with and analyze causal models, such as control and signal-processing systems.

Also see ControlSystemsMTK.jl for an interface to ControlSystems.jl that contains tools for linear analysis and frequency-domain analysis.

Hybrid systems with clock partitions

linearize accounts for the continuous equations of a model only. A model that contains synchronous (clocked) subsystems, written with ShiftIndex, Sample and Hold or built from components such as those in DiscreteComponents, is linearized with linearize_hybrid. The model is split into its clock partitions, one per periodic clock plus the continuous partition, and every partition is linearized separately. Each signal that crosses a clock boundary becomes an input of the partition it enters and an output of the partition it leaves, in addition to the inputs and outputs requested by the user.

using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D

dt = 0.1
@variables x(t) y(t) u(t) d(t) yd(t) ud(t)
@parameters kp = 2.0
eqs = [
    yd ~ Sample(dt)(y)      # sample the plant output
    ud ~ -kp * yd           # discrete proportional controller
    u ~ Hold(ud)            # hold the controller output
    D(x) ~ -x + u + d       # plant with disturbance input d
    y ~ x
]
@named sys = System(eqs, t)
hl = linearize_hybrid(sys, [d], [y]; op = Dict(x => 0.0, d => 0.0))

The result is a HybridLinearization. The continuous partition comes first, followed by the discrete partitions.

cont, disc = hl.partitions
cont.inputs   # [d, Hold(ud)]: the disturbance and the held controller output
cont.outputs  # [y]: the plant output, which is also sampled by the controller
disc.inputs   # [Sample(dt)(y)]
disc.outputs  # [ud]
disc.Ts       # 0.1
hl.connections

The inputs and outputs of a partition list the user-specified signals first, in the order given by the user; the fields nu_user and ny_user give the number of user-specified inputs and outputs. The remaining signals are the boundary signals, grouped by the partition they come from or go to. The connections state which output of which partition drives which input of which other partition, (; from, output, to, input). clock_boundary collects the connections from one partition to another as index vectors, outputs into the outputs of the partition the signals leave and inputs into the inputs of the partition they enter, which are the index sets required by the advanced interface of ControlSystemsBase.feedback. The variables of the boundary signals can be used as signal names with RobustAndOptimalControl.connect.

For a discrete partition with sample interval Ts, the state consists of the values of the discrete variables at the previous tick, denoted xₜ₋₁ in unknowns, and the matrices describe the update performed at a tick,

\[\begin{aligned} x(k) &= A x(k-1) + B u(k) \\ y(k) &= C x(k-1) + D u(k) \end{aligned}\]

whose transfer function is $C(zI - A)^{-1}B + D$. The continuous partition has the usual form $\dot x = Ax + Bu$, $y = Cx + Du$.

To analyze the sampled-data loop, the partitions are brought to a common time domain and interconnected according to hl.connections. The example below discretizes the continuous partition with zero-order hold, which is the exact description of the loop at the sampling instants when all discrete partitions share one clock, and closes the loop with ControlSystemsBase.feedback.

using ControlSystemsBase
Pd = c2d(ss(cont.A, cont.B, cont.C, cont.D), disc.Ts)
Cd = ss(disc.A, disc.B, disc.C, disc.D, disc.Ts)
plant_to_ctrl = clock_boundary(hl, 1, 2)  # the plant output, sampled by the controller
ctrl_to_plant = clock_boundary(hl, 2, 1)  # the controller output, held and applied to the plant
# The boundary signals close the loop; the user-specified signals of the plant remain external.
G = feedback(
    Pd, Cd; Y1 = plant_to_ctrl.outputs, U2 = plant_to_ctrl.inputs,
    Y2 = ctrl_to_plant.outputs, U1 = ctrl_to_plant.inputs,
    W1 = 1:cont.nu_user, Z1 = 1:cont.ny_user, pos_feedback = true
)

This interconnection is the Redheffer star product of the two partitions over the boundary signals. The functions starprod and lft of ControlSystemsBase compute it when the interconnected signals are the last inputs and outputs of the first system and the first inputs and outputs of the second, and when every output is either external or interconnected. The partitions list the user-specified signals first, and a signal may be both a user-specified output and a boundary output, as y is here, so the index sets are passed to feedback explicitly in general. In the example above, lft(Pd, Cd) is not applicable because y is the only output of the plant, whereas a plant whose sampled output differs from its user-specified output is assembled with lft(Pd, Cd) directly when the controller has no user-specified signals.

The discrete-time model describes the loop at the sampling instants. The content of the sampled signals above the Nyquist frequency of the sampler, $\omega_N = \pi / T_s$, is folded by the sampling and is not represented by the model. Whether such content is present can be checked on the partition that produces the sampled signals. Every signal entering a sampler is an output of the continuous partition, driven by its inputs: the external inputs and the held signals, whose piecewise constant form carries images of the discrete signal at multiples of the sampling frequency. If the gain from all inputs of the continuous partition to the sampled outputs is small above $\omega_N$ compared with the gain below it, the sampled signals carry little content that the sampling folds, and the discrete-time model of the loop is representative.

P = ss(cont.A, cont.B, cont.C, cont.D)
Gb = P[plant_to_ctrl.outputs, :]  # from all inputs of the plant to the sampled signals
ωN = pi / disc.Ts
ω_above = exp10.(range(log10(ωN), log10(1000ωN), length = 200))
ω_below = exp10.(range(log10(ωN) - 3, log10(ωN), length = 200))
gain_above = maximum(abs, freqresp(Gb, ω_above))
gain_below = maximum(abs, freqresp(Gb, ω_below))
gain_above / gain_below

For this plant the ratio is about 0.03, that is, the plant attenuates the content above the Nyquist frequency by a factor of thirty relative to its passband, and the sampled plant output is well described by the discrete-time model. For partitions with several sampled signals or inputs, the singular values (sigma) are the corresponding measure.

In a multi-rate model, a signal leaving a discrete partition for a partition on a slower clock is decimated at the slower clock, which folds the band between the two Nyquist frequencies, $\pi / T_{s,\mathrm{slow}}$ to $\pi / T_{s,\mathrm{fast}}$, onto the slow baseband. The gain of the fast partition alone, from its inputs to that signal and evaluated in this band, is a sufficient but conservative check: it ignores the attenuation the continuous partition provides and rejects a boundary whose fast partition does not filter. The check that accounts for the whole path assembles the composite of the continuous partition, discretized at the fast rate, and the fast partition, and evaluates the gain from all inputs of the composite to the boundary signal in the band. The held outputs of the slow partition have to be among these inputs: the hold at the slow rate produces images of the slow signal at multiples of its sampling frequency, which fall in this band and have to be attenuated by the continuous partition.

dt1 = 0.1  # fast clock
dt2 = 0.3  # slow clock
k1 = ShiftIndex(Clock(dt1))
k2 = ShiftIndex(Clock(dt2))
@variables xc(t) d(t) w(t) z(t)
eqs = [
    D(xc) ~ -xc + Hold(z) + d                       # plant
    w(k1) ~ 0.5w(k1 - 1) + 0.5Sample(dt1)(xc)       # fast filter
    z(k2) ~ 0.9z(k2 - 1) - 0.1Sample(dt2)(Hold(w))  # slow controller
]
@named mr = System(eqs, t)
hlm = linearize_hybrid(mr, [d], [xc]; op = Dict(xc => 0.0, d => 0.0, w => 0.0, z => 0.0))
ic = hlm.continuous_index
ifast = findfirst(p -> p.Ts == dt1, hlm.partitions)
islow = findfirst(p -> p.Ts == dt2, hlm.partitions)
cont, fast = hlm.partitions[ic], hlm.partitions[ifast]
F = ss(fast.A, fast.B, fast.C, fast.D, fast.Ts)
Pf = c2d(ss(cont.A, cont.B, cont.C, cont.D), dt1)  # the plant at the fast rate
cont_to_fast = clock_boundary(hlm, ic, ifast)
fast_to_cont = clock_boundary(hlm, ifast, ic)      # no such signal in this model
fast_to_slow = clock_boundary(hlm, ifast, islow)
# The composite from all inputs of the plant (the disturbance and the held slow output) and
# the user-specified inputs of the fast partition to the signal entering the slow partition.
Gb = feedback(
    Pf, F; Y1 = cont_to_fast.outputs, U2 = cont_to_fast.inputs,
    Y2 = fast_to_cont.outputs, U1 = fast_to_cont.inputs,
    W1 = 1:Pf.nu, Z1 = Int[], W2 = 1:fast.nu_user, Z2 = fast_to_slow.outputs,
    pos_feedback = true
)
band = exp10.(range(log10(pi / dt2), log10(pi / dt1), length = 200))
below = exp10.(range(log10(pi / dt2) - 3, log10(pi / dt2), length = 200))
maximum(abs, freqresp(Gb, band)) / maximum(abs, freqresp(Gb, below))

For this model the ratio is about 0.06, whereas the fast filter alone attenuates the band by less than a factor of two, so the attenuation of the signal entering the slow partition comes from the plant. The content above the Nyquist frequency of the fast sampler is not represented by the composite; it is checked on the continuous partition as above. With more clocks, the signal entering a partition is checked on the composite of the continuous partition and the partitions on faster clocks than the receiving one.

For multi-rate models, each discrete partition carries its own sample interval and the connections span partitions on different clocks. Such loops can be analyzed either by converting the discrete partitions to continuous time with d2c or by lifting them to a common rate. In both cases the result is only meaningful for frequencies well below the Nyquist frequency of every sampler in the loop, since the frequency content above the Nyquist frequency of a sampler is folded by the sampling and is not represented by the individual partition linearizations; the checks above indicate whether this content is small.

The Jacobians of each partition are computed from the generated functions of the compiled partition with the AD backend autodiff (AutoForwardDiff() by default), so models calling arbitrary Julia functions are supported. If differentiation of a partition fails, it is retried with fallback_autodiff (AutoFiniteDiff() by default).

The operating point can be given as a dictionary or as a LinearizationOpPoint wrapping a solution of the model and a time. It provides the values of the state variables of every partition; the history variables of a discrete partition take the value of the variable they are the history of, so the operating point is assumed to be stationary across ticks. The value of a signal crossing a clock boundary is taken from the operating point if present and otherwise evaluated from the operating point of the partition the signal originates from, so that in the example above the held controller output follows from the plant state. The initialization equations of the model that refer to the continuous partition only and determine a value the operating point does not fix take part in the initialization of the continuous partition; parameters bound to missing and constant states that such equations determine therefore take their values from them. Remaining values that are not available default to the guess of the symbol, or to zero, which is reported by a warning. When the operating point is a LinearizationOpPoint, the values of the unknowns and parameters of each partition are taken from the solution; the values the solution holds for observed variables are not, since they would repeat the constraints the unknowns already satisfy.

An operating point that fixes a signal the closed model determines from its state, such as a sampled plant output alongside the plant state it is computed from, makes the initialization of the continuous partition overdetermined. The initialization is then solved in the least-squares sense, and the state at which the partition is linearized can differ from the requested values; linearize_hybrid warns when a requested value of a differential unknown is not retained, and the x0 field of the partition holds the values used. Signals opened by loop_openings are held at the values of the signals that drove them, as in linearize; loop openings are supported at connections of continuous-time signals only.

Only periodic clocks are supported. Partitions on other clocks, as well as continuous and discrete events, assertions and state machines of the model, are not accounted for and produce a warning. Discrete partitions containing an algebraic loop within a single clock cannot be linearized. Linearization is not defined with respect to Boolean-valued variables, such as the state of a relay with hysteresis, and a partition containing them produces an error naming the variables. An equation that is not differentiable at the operating point, such as sqrt(u) at u = 0, gives non-finite entries in the matrices of its partition, which is reported by a warning.

The analysis-point functions get_sensitivity, get_comp_sensitivity and get_looptransfer accept the keyword argument hybrid = true to return a HybridLinearization instead of the continuous linearization, and linearize_hybrid accepts analysis points as inputs and outputs in the same way as linearize.

Docstrings

    ModelingToolkit.linearize — Function
    (; A, B, C, D), simplified_sys, extras = linearize(sys, inputs, outputs;    t=0.0, op = Dict(), allow_input_derivatives = false, zero_dummy_der=false, kwargs...)
    (; A, B, C, D), extras                 = linearize(simplified_sys, lin_fun; t=0.0, op = Dict(), allow_input_derivatives = false, zero_dummy_der=false)

    Linearize sys between inputs and outputs, both vectors of variables. Return a NamedTuple with the matrices of a linear statespace representation on the form

    \[\begin{aligned} ẋ &= Ax + Bu\\ y &= Cx + Du \end{aligned}\]

    The first signature automatically calls linearization_function internally, while the second signature expects the outputs of linearization_function as input.

    op denotes the operating point around which to linearize. If none is provided, the default values of sys are used.

    If allow_input_derivatives = false, an error will be thrown if input derivatives ($u̇$) appear as inputs in the linearized equations. If input derivatives are allowed, the returned B matrix will be of double width, corresponding to the input [u; u̇].

    zero_dummy_der can be set to automatically set the operating point to zero for all dummy derivatives.

    The return value extras is a NamedTuple (; x, p, t) containing the result of the initialization problem that was solved to determine the operating point.

    See also linearization_function which provides a lower-level interface, linearize_symbolic and ModelingToolkit.reorder_unknowns.

    See extended help for an example.

    The implementation and notation follows that of "Linear Analysis Approach for Modelica Models", Allain et al. 2009

    Extended help

    This example builds the following feedback interconnection and linearizes it from the input of F to the output of P.

    
      r ┌─────┐       ┌─────┐     ┌─────┐
    ───►│     ├──────►│     │  u  │     │
        │  F  │       │  C  ├────►│  P  │ y
        └─────┘     ┌►│     │     │     ├─┬─►
                    │ └─────┘     └─────┘ │
                    │                     │
                    └─────────────────────┘
    using ModelingToolkit
    using ModelingToolkit: t_nounits as t, D_nounits as D
    function plant(; name)
        @variables x(t) = 1
        @variables u(t)=0 y(t)=0
        eqs = [D(x) ~ -x + u
               y ~ x]
        System(eqs, t; name = name)
    end
    
    function ref_filt(; name)
        @variables x(t)=0 y(t)=0
        @variables u(t)=0 [input = true]
        eqs = [D(x) ~ -2 * x + u
               y ~ x]
        System(eqs, t, name = name)
    end
    
    function controller(kp; name)
        @variables y(t)=0 r(t)=0 u(t)=0
        @parameters kp = kp
        eqs = [
            u ~ kp * (r - y),
        ]
        System(eqs, t; name = name)
    end
    
    @named f = ref_filt()
    @named c = controller(1)
    @named p = plant()
    
    connections = [f.y ~ c.r # filtered reference to controller reference
                   c.u ~ p.u # controller output to plant input
                   p.y ~ c.y]
    
    @named cl = System(connections, t, systems = [f, c, p])
    
    lsys0, ssys = linearize(cl, [f.u], [p.x])
    desired_order = [f.x, p.x]
    lsys = ModelingToolkit.reorder_unknowns(lsys0, unknowns(ssys), desired_order)
    
    @assert lsys.A == [-2 0; 1 -2]
    @assert lsys.B == [1; 0;;]
    @assert lsys.C == [0 1]
    @assert lsys.D[] == 0
    
    ## Symbolic linearization
    lsys_sym, _ = ModelingToolkit.linearize_symbolic(cl, [f.u], [p.x])
    
    @assert substitute(lsys_sym.A, ModelingToolkit.defaults(cl)) == lsys.A
    source
    ModelingToolkit.linearize_symbolic — Function
    matrices, simplified_sys = linearize_symbolic(sys::AbstractSystem, inputs, outputs;
        simplify = false,
        allow_input_derivatives = false,
        eval_expression = false,
        eval_module = @__MODULE__,
        split = true,
        kwargs...)

    Symbolically linearize sys between inputs and outputs.

    Unlike linearize, this uses Symbolics.jacobian and returns symbolic matrices instead of numerical matrices evaluated at an operating point.

    Arguments

    • sys: the system to linearize. This function calls ModelingToolkitBase.mtkcompile internally.
    • inputs: input variables used as the columns of the B and D matrices.
    • outputs: output variables used as the rows of the C and D matrices.

    Keyword Arguments

    • simplify: whether to run additional symbolic simplification during compilation.
    • allow_input_derivatives: whether differentiated inputs may appear in the linearized equations. If true, B and D include extra columns for those derivatives.
    • eval_expression: whether generated expressions are evaluated directly instead of using runtime-generated functions.
    • eval_module: the module used when eval_expression = true.
    • split: whether generated functions use a tuple of parameters or splatted parameters.
    • kwargs...: additional keyword arguments forwarded to ModelingToolkitBase.mtkcompile.

    Returns

    A pair (matrices, simplified_sys). matrices is a NamedTuple containing A, B, C, and D, plus the symbolic Jacobian blocks f_x, f_z, g_x, g_z, f_u, g_u, h_x, h_z, and h_u of

    \[\begin{aligned} ẋ &= f(x, z, u) \\ 0 &= g(x, z, u) \\ y &= h(x, z, u) \end{aligned}\]

    Here x are differential unknowns, z are algebraic unknowns, u are inputs, and y are outputs.

    Examples

    using ModelingToolkit
    using ModelingToolkit: t_nounits as t, D_nounits as D
    
    @variables x(t) = 1.0 u(t) = 0.0 y(t) = 0.0
    eqs = [D(x) ~ -x + u,
           y ~ x]
    @named sys = System(eqs, t)
    
    matrices, simplified_sys = ModelingToolkit.linearize_symbolic(sys, [u], [y])
    matrices.A

    See also linearize, linearization_function, and reorder_unknowns.

    source
    ModelingToolkit.linearization_function — Function
    lin_fun, simplified_sys = linearization_function(sys::AbstractSystem, inputs, outputs; simplify = false, initialize = true, initialization_solver_alg = nothing, kwargs...)

    Return a function that linearizes the system sys. The function linearize provides a higher-level and easier to use interface.

    lin_fun is a function (variables, p, t) -> (; f_x, f_z, g_x, g_z, f_u, g_u, h_x, h_z, h_u), i.e., it returns a NamedTuple with the Jacobians of f,g,h for the nonlinear sys (technically for simplified_sys) on the form

    \[\begin{aligned} ẋ &= f(x, z, u) \\ 0 &= g(x, z, u) \\ y &= h(x, z, u) \end{aligned}\]

    where x are differential unknown variables, z algebraic variables, u inputs and y outputs. To obtain a linear statespace representation, see linearize. The input argument variables is a vector defining the operating point, corresponding to unknowns(simplified_sys) and p is a vector corresponding to the parameters of simplified_sys. Note: all variables in inputs have been converted to parameters in simplified_sys.

    The simplified_sys has undergone ModelingToolkitBase.mtkcompile and had any occurring input or output variables replaced with the variables provided in arguments inputs and outputs. The unknowns of this system also indicate the order of the unknowns that holds for the linearized matrices.

    Arguments:

    • sys: A System of ODEs. This function will automatically apply simplification passes on sys and return the resulting simplified_sys.
    • inputs: A vector of variables that indicate the inputs of the linearized input-output model.
    • outputs: A vector of variables that indicate the outputs of the linearized input-output model.
    • simplify: Apply simplification in tearing.
    • initialize: If true, a check is performed to ensure that the operating point is consistent (satisfies algebraic equations). If the op is not consistent, initialization is performed.
    • initialization_solver_alg: A NonlinearSolve algorithm to use for solving for a feasible set of state and algebraic variables that satisfies the specified operating point.
    • autodiff: An ADType supported by DifferentiationInterface.jl to use for calculating the necessary jacobians. Defaults to using AutoForwardDiff()
    • op: The operating point, a dictionary or a LinearizationOpPoint. A LinearizationOpPoint determines the operating point and t from its solution at its first time point, and implies ignore_system_initial_conditions = true, as in linearize. This allows passing a LinearizationOpPoint to the functions that build on linearization_function, such as get_sensitivity.
    • ignore_system_initial_conditions: Whether to ignore initial_conditions(sys) and only use op.
    • loop_openings: Analysis points whose connections are removed before linearization, also when inputs and outputs are variables. A signal disconnected by a loop opening is held at the value of the signal that drove it unless op provides a value for it.
    • system_modifier: A function applied to the system after the loop openings and before structural simplification.
    • verbose: An MTKVerbosity, a SciMLLogging preset, or a Bool controlling diagnostic output (the empty_operating_point toggle and the initialization toggles). The deprecated boolean keywords warn_empty_op and warn_initialize_determined remain accepted and override the corresponding toggles when explicitly passed.
    • kwargs: Are passed on to find_solvables!

    See also linearize which provides a higher-level interface.

    source
    ModelingToolkit.LinearizationProblem — Type
    mutable struct LinearizationProblem{F<:ModelingToolkit.LinearizationFunction, T}

    A problem for repeatedly linearizing a ModelingToolkit system at changing operating points.

    Use LinearizationProblem with a system, inputs, and outputs to construct a problem. It supports symbolic indexing, allowing selected state and parameter values to be updated efficiently between calls to CommonSolve.solve. Mutate t to evaluate the linearization at a different value of the system's independent variable.

    Fields

    • f::F: The generated linearization function that evaluates the system and stores its symbolic-indexing data.
    • t::T: The current value of the system's independent variable. This field may be mutated between calls to CommonSolve.solve.
    source
    ModelingToolkit.LinearizationOpPoint — Type
    LinearizationOpPoint(sol, t; op = Dict()) -> LinearizationOpPoint

    Wrap an ODESolution and one or more time points as an operating point for linearize. The operating point contains the values of differential state variables and parameters in sol at t; initialization determines any algebraic variables.

    When t is an AbstractVector, linearize calls linearization_function once and evaluates the linearization at each time point, returning vectors of matrices and extras.

    Arguments

    • sol::SciMLBase.AbstractODESolution: Solution supplying state and parameter values.
    • t: A time point or vector of time points at which to evaluate sol.

    Keywords

    • op::AbstractDict = Dict(): Additional operating-point values that override values from sol. Values may be numbers or symbolic expressions; the latter are evaluated from sol at each time point. Signals disconnected by loop_openings are held at the values they have in the loop-closed solution unless op specifies them, e.g., Dict(opened_signal => 0.0) holds an opened signal at zero.

    Returns

    • LinearizationOpPoint: An operating-point specification accepted by linearize.

    Examples

    op = LinearizationOpPoint(sol, [0.0, 1.0]; op = Dict(opened_signal => 0.0))
    matrices, simplified_sys, extras = linearize(sys, inputs, outputs; op)

    Fields

    • sol::SciMLBase.AbstractODESolution: The solution to extract operating point values from.
    • t::Any: The time point (or vector of time points) at which to evaluate the solution.
    • op::AbstractDict: Additional operating-point values merged into the solution-derived operating point at each time point (takes precedence over solution-derived values).
    source
    ModelingToolkit.linearize_hybrid — Function
    hl = linearize_hybrid(sys, inputs, outputs; op = Dict(), t = 0.0, kwargs...)

    Linearize the hybrid (clocked) system sys partition by partition. The model may contain periodic clock partitions (synchronous subsystems written with ShiftIndex, Sample, Hold and components built on them) alongside the continuous equations. Each clock partition and the continuous partition are linearized separately, and every signal that crosses a clock boundary becomes an input of the partition it enters and an output of the partition it leaves, in addition to the user-specified inputs and outputs. The result is a HybridLinearization holding one ClockPartitionLinearization per partition and the connections between them, from which the sampled-data loop can be assembled with the advanced interface of ControlSystemsBase.feedback or with RobustAndOptimalControl.connect.

    The Jacobians are computed from the generated functions of each compiled partition with autodiff, so models that call arbitrary Julia functions are supported. If differentiation of a partition fails, it is retried with fallback_autodiff.

    Only periodic clocks are supported. Partitions on other clocks, as well as continuous and discrete events, assertions and state machines of the model, are not accounted for and produce a warning. Linearization is not defined with respect to Boolean-valued variables, and a partition containing them produces an error. Non-finite entries in the matrices of a partition, which arise when an equation is not differentiable at the operating point, are reported by a warning.

    Arguments

    • sys: The unsimplified system.
    • inputs: The input variables of the linearization, or analysis points.
    • outputs: The output variables of the linearization, or analysis points.

    Keyword Arguments

    • op: The operating point, a dictionary of variable and parameter values or a LinearizationOpPoint wrapping a solution and a time. The values of the state variables of every partition are taken from op; the history variables of a discrete partition take the value of the variable they are the history of, that is, the operating point is assumed to be stationary across ticks, or the value an initialization equation of the model gives. The value of a signal crossing a clock boundary is taken from op if present and otherwise evaluated from the operating point of the partition the signal originates from, with the boundary signals entering that partition that are not in op set to zero. The initialization equations of the model that refer to symbols of the continuous partition only and determine a value op does not fix take part in the initialization of the continuous partition, so parameters bound to missing and constant states that such equations determine take their values from them. Remaining values that are not available default to the guess of the symbol or to zero. From a LinearizationOpPoint, the values of the unknowns and parameters of each partition are taken; the values the solution holds for observed variables are not, since they would repeat the constraints the unknowns already satisfy.
    • t: The time at which to linearize. Ignored if op is a LinearizationOpPoint.
    • autodiff: The ADTypes.AbstractADType used to compute the Jacobians. Defaults to AutoForwardDiff().
    • fallback_autodiff: The AD type used when autodiff fails for a partition. Defaults to AutoFiniteDiff(); pass nothing to disable the fallback.
    • allow_input_derivatives: See linearize. Applies to the continuous partition.
    • warn_missing_op: Whether to warn about operating-point values that default to zero.
    • warn_zero: Whether to warn about inputs and outputs of a partition whose columns of B and D, or rows of C and D, are zero. Signals disconnected by loop_openings, and the outputs of a partition that such a signal enters, are exempt.
    • warn_unsupported: Whether to warn about constructs that are not accounted for.
    • initialize, initializealg, initialization_abstol, initialization_reltol, initialization_solver_alg, guesses, missing_guess_value, eval_expression, eval_module: See linearization_function. They apply to the continuous partition.
    • loop_openings, system_modifier: See get_sensitivity. The loop openings apply also when inputs and outputs are variables. As in linearization_function, an opened signal without a value in op is held at the value of the signal that drove it. Loop openings are supported at connections of continuous-time signals only.
    • Remaining keyword arguments are forwarded to the structural simplification of each partition.

    See also linearize, HybridLinearization and ClockPartitionLinearization.

    source
    linearize_hybrid(sys, input_aps, output_aps; loop_openings = [], system_modifier = identity, kwargs...)

    Linearize the hybrid system sys between analysis points, see linearize_hybrid and linearization_ap_transform. loop_openings and system_modifier are documented in get_sensitivity.

    source
    ModelingToolkit.HybridLinearization — Type
    struct HybridLinearization

    The result of linearize_hybrid: one ClockPartitionLinearization per clock partition of the model together with the connections between them.

    Each connection (; from, output, to, input) states that partitions[from].outputs[output] drives partitions[to].inputs[input] across a clock boundary. These are the index pairs required to assemble the sampled-data loop with the advanced interface of ControlSystemsBase.feedback, or the signal names required by RobustAndOptimalControl.connect, once each partition has been converted to a common time domain (for example with c2d or d2c). One output may drive several inputs.

    Fields

    • partitions::Vector{ClockPartitionLinearization}: The linearized partitions. The continuous partition, if any, is first.

    • connections::Vector{@NamedTuple{from::Int64, output::Int64, to::Int64, input::Int64}}: The connections across clock boundaries.

    • continuous_index::Union{Nothing, Int64}: The index of the continuous partition in partitions, nothing for a purely discrete model.

    source
    ModelingToolkit.ClockPartitionLinearization — Type
    struct ClockPartitionLinearization

    Linearization of a single clock partition of a hybrid system, as returned in the partitions field of a HybridLinearization.

    For the continuous partition the matrices describe

    \[\begin{aligned} ẋ &= Ax + Bu \\ y &= Cx + Du \end{aligned}\]

    For a discrete partition with sample interval Ts, the state consists of the values of the discrete variables at the previous tick, and the matrices describe the update performed at a tick,

    \[\begin{aligned} x(k) &= A x(k-1) + B u(k) \\ y(k) &= C x(k-1) + D u(k) \end{aligned}\]

    whose transfer function is C(zI - A)⁻¹B + D. The variables in unknowns are the history variables (xₜ₋₁ denotes the value of x at the previous tick).

    The inputs of a partition consist of the user-specified inputs that belong to the partition (first, in the order given by the user) followed by the signals that enter the partition across a clock boundary, grouped by the partition they originate from. The outputs consist of the user-specified outputs that belong to the partition (first) followed by the signals that leave the partition across a clock boundary. Boundary inputs are the operator terms of the model, such as Sample(dt)(y) or Hold(u); boundary outputs are the variables these operators are applied to.

    Fields

    • A::Matrix{Float64}: The state matrix.

    • B::Matrix{Float64}: The input matrix.

    • C::Matrix{Float64}: The output matrix.

    • D::Matrix{Float64}: The feedthrough matrix.

    • unknowns::Vector{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}}: The state variables, in the order of the rows and columns of A.

    • inputs::Vector{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}}: The input variables, in the order of the columns of B and D.

    • outputs::Vector{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}}: The output variables, in the order of the rows of C and D.

    • nu_user::Int64: The number of user-specified inputs; inputs[1:nu_user] is the user input group.

    • ny_user::Int64: The number of user-specified outputs; outputs[1:ny_user] is the user output group.

    • clock::SciMLBase.AbstractClock: The clock of the partition, ContinuousClock() or a PeriodicClock.

    • Ts::Union{Nothing, Float64}: The sample interval of a periodic clock, nothing for the continuous partition or for a clock without a fixed interval.

    • x0::Vector{Float64}: The state at the operating point, in the order of unknowns.

    • sys::System: The compiled system of the partition. Its unknowns and parameters carry the operating point. A boundary term such as Hold(u) is represented in this system by a plain parameter named after the signal and the operator, u_hold.

    source
    ModelingToolkit.clock_boundary — Function
    clock_boundary(hl::HybridLinearization, from::Integer, to::Integer)

    The signals crossing the clock boundary from partition from to partition to of hl, as a named tuple (; from, to, outputs, inputs). outputs[i] is the index into hl.partitions[from].outputs of the i-th signal leaving partition from, and inputs[i] is the index into hl.partitions[to].inputs of the entry it drives. With hl.partitions[from] as the first system and hl.partitions[to] as the second, the keyword arguments Y1 = outputs, U2 = inputs of the advanced interface of ControlSystemsBase.feedback connect these signals. Both index vectors are empty if no signal crosses from from to to.

    source