Exported functions and types
Index
ControlSystemsBase.StateSpaceControlSystemsMTK.MultirateLinearizationControlSystemsMTK.MultiratePortModelingToolkitBase.SystemControlSystemsBase.bodeplotControlSystemsBase.isstableControlSystemsBase.loopshapingPIDControlSystemsMTK.GainScheduledStateSpaceControlSystemsMTK.batch_ssControlSystemsMTK.build_quadratic_cost_matrixControlSystemsMTK.build_quadratic_cost_matrixControlSystemsMTK.fundamental_responseControlSystemsMTK.get_named_comp_sensitivityControlSystemsMTK.get_named_looptransferControlSystemsMTK.get_named_sensitivityControlSystemsMTK.harmonic_responseControlSystemsMTK.lifted_ssControlSystemsMTK.multipliersControlSystemsMTK.multirate_linearizationControlSystemsMTK.multirate_marginsControlSystemsMTK.performance_frequency_gainControlSystemsMTK.robust_frequency_gainControlSystemsMTK.single_rate_ssControlSystemsMTK.trajectory_ssModelingToolkit.get_comp_sensitivityModelingToolkit.get_looptransferModelingToolkit.get_sensitivityModelingToolkit.linearization_functionModelingToolkit.linearizeModelingToolkit.linearize_symbolicModelingToolkit.reorder_unknownsModelingToolkitStandardLibrary.Blocks.StateSpaceRobustAndOptimalControl.named_ssRobustAndOptimalControl.named_ssRobustAndOptimalControl.ss2particlesSymbolicControlSystems.ccodeSymbolicControlSystems.print_c_array
Docstrings
ControlSystemsMTK.MultirateLinearization — Type
MultirateLinearizationA linear periodic model of a hybrid system with several clocks, created by multirate_linearization.
The model is defined on the event grid: the sorted set of all instants within one common period Tc at which a clock ticks or a signal of the continuous-time partition is updated or observed. Event k maps the state before the event to the state before the next event,
\[\begin{aligned} x_{k+1} &= A_k x_k + B_k u \\ y_k &= C_k x_k + D_k u \end{aligned}\]
where u contains the lifted inputs of the whole period and y_k the outputs that are observed at event k. The state consists of the state of the continuous-time partition, the state variables of the clocked partitions, one hold variable per clocked signal that is read by another partition, and one hold variable per input of the continuous-time partition. Each partition is represented by one set of Jacobians, evaluated at the operating point and the time of the linearization; a model that depends explicitly on time is not represented.
Fields
A, B, C, D: The matrices of each event.output_channels: The lifted output channels observed at each event.Tc: The common period.t0: The instant at which the period starts.event_times: The instants of the events, in[t0, t0 + Tc).x: The names of the state variables.inputs,outputs: The signals, seeMultiratePort.hl: TheModelingToolkit.HybridLinearizationthe model was created from.
See lifted_ss, multipliers, fundamental_response, harmonic_response, performance_frequency_gain, robust_frequency_gain and multirate_margins.
ControlSystemsMTK.MultiratePort — Type
MultiratePortA signal of a MultirateLinearization.
Fields
name::Symbol: The name of the signal.times::Vector{Float64}: The instants within one period at which the signal has a value. An input is held between these instants, an output is observed at them.channels::Vector{Int}: The indices of the corresponding channels of the lifted system, one per instant.partition::Int: The index of the clock partition of the signal in theHybridLinearization.
ModelingToolkitBase.System — Method
ModelingToolkit.System(sys::AbstractStateSpace; name::Symbol, x0 = zeros(sys.nx), x_names, u_names, y_names)Create an System from sys::StateSpace.
Arguments:
sys: An instance ofStateSpaceorNamedStateSpace.name: A symbol giving the system a unique name.x0: Initial state
The arguments below are automatically set if the system is a NamedStateSpace.
x_names: A vector of symbols with state names.u_names: A vector of symbols with input names.y_names: A vector of symbols with output names.
ControlSystemsMTK.GainScheduledStateSpace — Method
GainScheduledStateSpace(systems, vt; interpolator, x = zeros((systems[1]).nx), name, u0 = zeros((systems[1]).nu), y0 = zeros((systems[1]).ny))A linear parameter-varying (LPV) version of Blocks.StateSpace, implementing the following equations:
\[\begin{aligned} \dot{x} &= A(v) x + B(v) u \\ y &= C(v) x + D(v) u \end{aligned}\]
where v is a scalar scheduling variable.
See example usage in the gain-scheduling example.
Arguments:
systems: A vector ofControlSystemsBase.StateSpaceobjectsvt: A vector of breakpoint values for the scheduling variablev, this has the same length assystems.interpolator: A constructori = interpolator(values, breakpoints)and returns an interpolator object that can be called likei(v)to get the interpolated value atv.LinearInterpolationfrom DataInterpolations.jl is a good choice, but a lookup table can also be used.
Connectors
inputof typeRealInputconnects to $u$.outputof typeRealOutputconnects to $y$.scheduling_inputof typeRealInputconnects to $v$.
ControlSystemsMTK.batch_ss — Method
batch_ss(sys, inputs, outputs, ops::AbstractVector{<:AbstractDict};
t = 0.0,
allow_input_derivatives = false,
kwargs...)Linearize sys in multiple operating points ops::Vector{Dict}. Returns a vector of StateSpace objects and the simplified system.
Example:
using ControlSystemsMTK, ModelingToolkit, RobustAndOptimalControl
using ModelingToolkit: getdefault
unsafe_comparisons(true)
# Create a model
@parameters t k=10 k3=2 c=1
@variables x(t)=0 [bounds = (-2, 2)]
@variables v(t)=0
@variables u(t)=0
@variables y(t)
D = Differential(t)
eqs = [D(x) ~ v
D(v) ~ -k * x - k3 * x^3 - c * v + 10u
y ~ x]
@named duffing = System(eqs, t)
bounds = getbounds(duffing, unknowns(duffing))
sample_within_bounds((l, u)) = (u - l) * rand() + l
# Create a vector of operating points
N = 10
ops = map(1:N) do i
op = Dict(x => sample_within_bounds(bounds[x]) for x in keys(bounds) if isfinite(bounds[x][1]))
end
Ps, ssys = batch_ss(duffing, [u], [y], ops)
w = exp10.(LinRange(-2, 2, 200))
bodeplot(Ps, w)
P = RobustAndOptimalControl.ss2particles(Ps) # convert to a single StateSpace system with `Particles` as coefficients.
bodeplot(P, w) # Should look similar to the one aboveLet's also do some tuning for the linearized models above
function batch_tune(f, Ps)
f.(Ps)
end
Cs = batch_tune(Ps) do P
# C, kp, ki, fig, CF = loopshapingPI(P, 6; phasemargin=45)
C, kp, ki, kd, fig, CF = loopshapingPID(P, 6; Mt=1.3, Tf = 1/100)
ss(CF)
end
P = RobustAndOptimalControl.ss2particles(Ps)
C = RobustAndOptimalControl.ss2particles(Cs)
nyquistplot(P * C,
w,
ylims = (-10, 3),
xlims = (-5, 10),
points = true,
Ms_circles = [1.5, 2],
Mt_circles = [1.5, 2])
# Fit circles that encircle the Nyquist curve for each frequency
centers, radii = fit_complex_perturbations(P * C, w; relative = false, nominal = :center)
nyquistcircles!(w, centers, radii, ylims = (-4, 1), xlims = (-3, 4))See also trajectory_ss.
ControlSystemsMTK.build_quadratic_cost_matrix — Method
build_quadratic_cost_matrix(linear_sys, ssys::System, costs::Vector{Pair})For a system that has been linearized, assemble a quadratic cost matrix (for LQR or Kalman filtering) that penalizes states or outputs of simplified system ssys according to the vector of pairs costs.
The motivation for this function is that ModelingToolkit does not guarantee
- Which states are selected as states after simplification.
- The order of the states.
The second problem above, the ordering of the states, can be worked around using reorder_unknowns, but the first problem cannot be solved by trivial reordering. This function thus accepts an array of costs for a user-selected state realization, and assembles the correct cost matrix for the state realization selected by MTK. To do this, the funciton needs the linearization (linear_sys) as well as the simplified system, both of which are outputs of linearize.
Arguments:
linear_sys: Output oflinearize, an object containing a property calledC. This can be aControlSystemsBase.StateSpaceor aNamedTuplewith a fieldC.ssys: Output oflinearize.costs: A vector of pairs
ControlSystemsMTK.build_quadratic_cost_matrix — Method
build_quadratic_cost_matrix(sys::System, inputs::Vector, costs::Vector{Pair}; kwargs...)Assemble a quadratic cost matrix (for LQR or Kalman filtering) that penalizes states or outputs of system sys according to the vector of pairs costs.
The motivation for this function is that ModelingToolkit does not guarantee
- Which states are selected as states after simplification.
- The order of the states.
The second problem above, the ordering of the states, can be worked around using reorder_unknowns, but the first problem cannot be solved by trivial reordering. This function thus accepts an array of costs for a user-selected state realization, and assembles the correct cost matrix for the state realization selected by MTK. To do this, the funciton performs a linearization between inputs and the cost outputs. The linearization is used to determine the matrix entries belonging to states that are not part of the realization chosen by MTK.
Arguments:
sys: The system to be linearized (not simplified).inputs: A vector of variables that are to be considered controlled inputs for the LQR controller.costs: A vector of pairs.
ControlSystemsMTK.fundamental_response — Method
fundamental_response(ml::MultirateLinearization, u, y, w)The complex amplitude of the component with the angular frequency of the input in the steady-state response of the output y to the input u = exp(im*w*t), for each element of the frequency vector w.
For a time-invariant system this is the frequency response. For a sampled-data system it is one entry of the harmonic response: it is not a transfer function, and neither closed-loop stability nor stability margins can be concluded from it. The result refers to the input held on its grid and the output observed on its grid; with a fine grid for signals of the continuous-time partition (oversample), the result for a sensitivity function approaches the fundamental sensitivity function of Goodwin and Salgado (1994).
See also harmonic_response and performance_frequency_gain.
ControlSystemsMTK.get_named_comp_sensitivity — Function
get_named_comp_sensitivity(sys, ap::AnalysisPoint; kwargs...)
get_named_comp_sensitivity(sys, ap_name::Symbol; kwargs...)Call get_comp_sensitivity while retaining signal names. Returns a NamedStateSpace object (similar to named_ss).
For a model with clocked partitions, the sampled-data system is assembled from the linearizations of the clock partitions and a discrete-time system is returned, see the section on hybrid models in the docstring of named_ss.
ControlSystemsMTK.get_named_looptransfer — Function
get_named_looptransfer(sys, ap::AnalysisPoint; kwargs...)
get_named_looptransfer(sys, ap_name::Symbol; kwargs...)Call get_looptransfer while retaining signal names. Returns a NamedStateSpace object (similar to named_ss).
For a model with clocked partitions, the sampled-data system is assembled from the linearizations of the clock partitions and a discrete-time system is returned, see the section on hybrid models in the docstring of named_ss.
ControlSystemsMTK.get_named_sensitivity — Function
get_named_sensitivity(sys, ap::AnalysisPoint; kwargs...)
get_named_sensitivity(sys, ap_name::Symbol; kwargs...)Call get_sensitivity while retaining signal names. Returns a NamedStateSpace object (similar to named_ss).
For a model with clocked partitions, the sampled-data system is assembled from the linearizations of the clock partitions and a discrete-time system is returned, see the section on hybrid models in the docstring of named_ss.
ControlSystemsMTK.harmonic_response — Method
harmonic_response(ml::MultirateLinearization, u, y, w, k)The complex amplitude of the component with angular frequency w + 2πk/Tc in the steady-state response of the output y to the input u = exp(im*w*t), for each element of the frequency vector w. u and y are names or indices of signals of ml. The signals are required to have uniformly spaced instants.
k = 0 gives the fundamental_response. The components with k ≠ 0 are caused by sampling and holding and are absent in a time-invariant system. An output with n instants per period distinguishes n components, k = 0, …, n - 1; other values of k coincide with one of these.
ControlSystemsMTK.lifted_ss — Method
lifted_ss(ml::MultirateLinearization)The time-invariant system that is equivalent to the periodic model ml, obtained by lifting over one period: a discrete-time NamedStateSpace with the common period as sample interval, in which a signal with n instants per period is represented by the n channels s@1, …, s@n in chronological order. The state is the state of ml before the first event of the period, and the state matrix is the monodromy matrix.
The H∞ norm of the lifted system is the induced ℓ2 norm between the sequences of the sampled signals.
ControlSystemsMTK.multipliers — Method
multipliers(ml::MultirateLinearization)The characteristic multipliers of the periodic model: the eigenvalues of the monodromy matrix. The model is exponentially stable if and only if all multipliers have magnitude smaller than one. Hold variables that are redundant contribute multipliers that are zero.
ControlSystemsMTK.multirate_linearization — Method
multirate_linearization(hl; oversample = 1, t0 = 0.0, continuous_rate = :fastest, inputs = nothing, outputs = nothing, tol = 1e-9)
multirate_linearization(sys, inputs, outputs; oversample, t0, continuous_rate, tol, kwargs...)Create a MultirateLinearization: a linear periodic model of a hybrid system whose clocked partitions are on periodic clocks with commensurate periods and arbitrary phases. hl is a ModelingToolkit.HybridLinearization, the result of ModelingToolkit.linearize_hybrid, or of get_sensitivity, get_comp_sensitivity and get_looptransfer with hybrid = true. The second method calls linearize_hybrid with kwargs.
The operations at an event are, in this order:
- Inputs of the continuous-time partition that are specified by the user take their new values, if the event is an instant of their grid.
- The signals of the continuous-time partition that are sampled are evaluated, with the values that the clocked partitions held before the event. A sampled signal with direct feedthrough from a held signal thus contains the previously held value, and a sampled signal with direct feedthrough from a user input contains its new value.
- The clocked partitions that tick compute their outputs from their state before the event, and then update their state. A clocked signal that is read through
Sample(Hold(x))has the value that was held before the event: ifxis computed at the same instant, the reader obtains its previous value. A clocked signal that is read through another operator, such asLatestof SynchToolkit, has the value computed at the same instant. Outputs that depend directly on each other in a cycle through such operators are rejected. - The held values are updated, and outputs of the continuous-time partition that are specified by the user are observed, if the event is an instant of their grid.
- The continuous-time partition is integrated exactly to the next event with constant inputs.
Keyword arguments
continuous_rate: Inputs and outputs of the continuous-time partition are held and observed on a uniform grid. With:fastest, the interval of the grid is the smallest clock period divided byoversample; with:period, it is the common period.oversample: An integer that refines the grid of the signals of the continuous-time partition, which makes the behavior between the ticks of the clocks visible. The ticks of the clocks are not changed.t0: The instant at which the period starts. The characteristic multipliers do not depend ont0, the input-output behavior does.inputs,outputs: The variables that were used as inputs and outputs of the linearization. They are required to recover the order of the signals if these belong to several clock partitions.tol: Relative tolerance for the recognition of commensurate periods and of coinciding instants: instants closer thantol*Tcare treated as one event.
The linearization is required to be performed in a stationary operating point of the whole model. This is not verified.
ControlSystemsMTK.multirate_margins — Method
multirate_margins(S::MultirateLinearization; σ = 0, N = 400)
multirate_margins(sys, ap; σ = 0, N = 400, kwargs...)Stability margins of a periodic loop at a break point. S is the sensitivity function at the break point, with one signal as input and output, for example created from get_sensitivity(sys, ap; hybrid = true). The second method computes the sensitivity function at the analysis point ap of sys; kwargs are passed to multirate_linearization and to the linearization.
The signal at the break point has n instants per period, and a perturbation of it is classified by its action on the n lifted channels. The result is a named tuple with one margin per class of perturbations:
gain_interval: A numerical estimate of the interval of constant real positive gains at the break point, containing the gain one, for which the loop is stable and well posed. Gains at which the loop is not well posed are computed from the feedthrough matrix; the loss of stability is located by a search with relative step0.002from the gain one, followed by bisection, which can miss an interval of unstable gains that is narrower than the step. A limit of0orInfstates that no boundary was found within the search range(1e-4, 1e4).disk_margin_lti_lower_bound: ARobustAndOptimalControl.Diskmarginfor time-invariant dynamic perturbations at the rate of the signal. Such a perturbation takes values at thenfrequencies that are aliases of each other, which are independent for a complex perturbation without further restrictions, and the margin is computed from an upper bound of the structured singular value withnindependent complex scalars. It is a lower bound of the margin for this class on the grid ofNfrequencies; a peak between the frequencies of the grid is not detected. A perturbation with real coefficients, a fixed order, or the form of a delay belongs to a smaller class.disk_margin_dynamic: ADiskmarginfor arbitrary dynamic perturbations of the lifted signal, with the radius1/‖S + (σ - 1)/2‖∞, whereSis the lifted sensitivity function. This class includes periodically time-varying perturbations, and also perturbations that are not causal within the period. It is conservative for time-invariant perturbations.
For n = 1 the loop at the break point is time invariant and both disk margins are computed from the H∞ norm. Their radius agrees with RobustAndOptimalControl.diskmargin(L, σ) for the loop-transfer function L = 1/S - 1, which is the negative of the loop-transfer function that ModelingToolkit.get_looptransfer returns. S is required to be stable.
All margins refer to the signal as it is represented in S. A signal of the continuous-time partition is represented by its values on the grid selected by continuous_rate and oversample: the perturbation acts between the observation of the signal on the grid and a hold on the grid. The margins then apply to the continuous-time signal itself only if moving the perturbation to the grid changes no value that is sampled from the signal, including the values that are read at an instant that coincides with an instant of the grid.
σ is the skew of the disk.
ControlSystemsMTK.performance_frequency_gain — Method
performance_frequency_gain(ml::MultirateLinearization, u, y, w)The ratio between the root-mean-square value of the steady-state response of the output y and the root-mean-square value of the input u = exp(im*w*t), for each element of the frequency vector w. All harmonic components of the response are included, as opposed to fundamental_response, the magnitude of which is a lower bound.
ControlSystemsMTK.robust_frequency_gain — Method
robust_frequency_gain(ml::MultirateLinearization, u, y, w)The largest singular value of the frequency response of the lifted system between the signals u and y, for each element of the frequency vector w: the largest gain, in terms of the energy of the sequences of sampled values, over all inputs that are composed of the frequencies w + 2πk/Tc. The result is periodic in w with period 2π/Tc, and for a stable model its supremum is the H∞ norm of the lifted system between the two signals, that is, the induced ℓ2 norm between the sequences of their sampled values. For signals with n_u and n_y instants per period, performance_frequency_gain ≤ sqrt(n_u/n_y)*robust_frequency_gain.
ControlSystemsMTK.single_rate_ss — Method
single_rate_ss(hl; Ts, method = :tustin, w_prewarp = 0)
single_rate_ss(sys, inputs, outputs; Ts, method = :tustin, w_prewarp = 0, kwargs...)A time-invariant approximation of a hybrid model with several clocks, obtained by converting all partitions of the ModelingToolkit.HybridLinearization hl to one common rate and closing the connections between them. Ts = 0 gives a continuous-time system, in which each clocked partition is converted with d2c. With Ts > 0, the continuous-time partition is discretized with c2d, a clocked partition with the sample interval Ts is used as it is, and each other clocked partition is converted to continuous time and discretized again. method and w_prewarp are passed to c2d and d2c. The phases of the clocks are not represented.
The result is an approximation: a model with several clocks is periodically time varying, and aliasing between the rates is not represented. In the continuous-time result the holds are not represented either. No stability or robustness property of the model follows from the result. multirate_linearization provides an exact representation for commensurate periods; single_rate_ss is also applicable when the periods are not commensurate.
ControlSystemsMTK.trajectory_ss — Method
linsystems, ssys = trajectory_ss(sys, inputs, outputs, sol; t = _max_100(sol.t), kwargs...)Linearize sys around the trajectory sol at times t. Returns a vector of StateSpace objects and the simplified system.
Operating points are extracted from the solution automatically using ModelingToolkit.LinearizationOpPoint.
Arguments:
inputs: A vector of variables or analysis points.outputs: A vector of variables or analysis points.sol: An ODE solution object.t: Time points along the solution trajectory at which to linearize. The returned array ofStateSpaceobjects will be of the same length ast.loop_openings: A list of analysis points whose connections are broken during the linearization. Each opened signal becomes a parameter that ModelingToolkit holds at the value it has in the loop-closed solutionsolat each time point, such that the linearization is performed around the trajectory also for the opened signals. To linearize around some other value for an opened signal, supply it throughop.op: ADictof operating-point values overriding those obtained fromsol, e.g.op = Dict(sys.opened_signal => 0). Symbolic values are resolved fromsolat every time point. The values are merged into the solution-derived operating point at every time point.kwargs: Are sent to the linearization functions.named: Iftrue, the returned systems will be of typeNamedStateSpace, otherwise they will be of typeStateSpace.
RobustAndOptimalControl.named_ss — Method
RobustAndOptimalControl.named_ss(sys::ModelingToolkit.AbstractSystem, inputs, outputs; descriptor=true, simple_infeigs=true, balance=false, kwargs...)Convert an System to a NamedStateSpace using linearization. inputs, outputs are vectors of variables determining the inputs and outputs respectively. See docstring of ModelingToolkit.linearize for more info on kwargs.
If descriptor = true (default), this method automatically converts systems that MTK has failed to produce a proper form for into a proper linear statespace system using the method described here: https://juliacontrol.github.io/ControlSystemsMTK.jl/dev/#Internals:-Transformation-of-non-proper-models-to-proper-statespace-form If descriptor = false, the system is instead converted to a statespace realization using sys[:,uinds] + sys[:,duinds]*tf('s'), which tends to result in a larger realization on which the user may want to call minreal(sys, tol) with a carefully selected tolerance.
Hybrid models
A model that contains clocked (discrete-time) partitions connected to the continuous-time equations is linearized as a hybrid model if hybrid = true. This is the default if additional_passes contains a discrete compilation pass, such as SynchToolkit.compile_lustre, and also if ModelingToolkit rejects the model as a hybrid model because no such pass was supplied. Each clock partition is then linearized separately with ModelingToolkit.linearize_hybrid and the partitions are assembled into a single discrete-time system: the continuous-time partition is discretized with zero-order hold at the sample interval of the clock and the connections across the clock boundaries are closed. Inputs that belong to the continuous-time partition are consequently assumed to be piecewise constant between the sample instants, and outputs of the continuous-time partition are obtained at the sample instants only. All clocked partitions are required to be on the same periodic clock, and the continuous-time partition must not have direct feedthrough from a held signal to a sampled signal. The HybridLinearization returned by linearize_hybrid is stored in extra[:hybrid_linearization] of the result, and kwargs are forwarded to linearize_hybrid. With hybrid = false, the model is passed to ModelingToolkit.linearize, the result of which does not include the clocked partitions.
See also ModelingToolkit.linearize which is the lower-level function called internally. The functions get_named_sensitivity, get_named_comp_sensitivity, get_named_looptransfer similarily provide convenient ways to compute sensitivity functions while retaining signal names in the same way as named_ss. The corresponding lower-level functions get_sensitivity, get_comp_sensitivity and get_looptransfer are available in ModelingToolkitStandardLibrary.Blocks and are documented in MTKstdlib: Linear analysis.
ControlSystemsBase.isstable — Method
isstable(ml::MultirateLinearization)Return true if the periodic model is exponentially stable, that is, if all characteristic multipliers have a magnitude smaller than one.
ControlSystemsBase.bodeplot — Function
fig = bodeplot(sys, args...)
bodeplot(LTISystem[sys1, sys2...], args...; plotphase=true, balance = true, kwargs...)Create a Bode plot of the LTISystem(s). A frequency vector w can be optionally provided. To change the Magnitude scale see setPlotScale. The default magnitude scale is "log10" (absolute scale).
- If
hz=true, the plot x-axis will be displayed in Hertz, the input frequency vector is still treated as rad/s. balance: Callbalance_statespaceon the system before plotting.adjust_phase_start: If true, the phase will be adjusted so that it starts at -90*intexcess degrees, whereintexcessis the integrator excess of the system.adaptive: If true, an adaptive frequency grid is used in order to keep the number of plotted points low, while resolving features in the frequency response well. If a manually provided frequency vector is used, this may be downsampled before plotting.
kwargs is sent as argument to RecipesBase.plot.
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.AModelingToolkit.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: ASystemof ODEs. This function will automatically apply simplification passes onsysand return the resultingsimplified_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: AnADTypesupported by DifferentiationInterface.jl to use for calculating the necessary jacobians. Defaults to usingAutoForwardDiff()op: The operating point, a dictionary or aLinearizationOpPoint. ALinearizationOpPointdetermines the operating point andtfrom its solution at its first time point, and impliesignore_system_initial_conditions = true, as inlinearize. This allows passing aLinearizationOpPointto the functions that build onlinearization_function, such asget_sensitivity.ignore_system_initial_conditions: Whether to ignoreinitial_conditions(sys)and only useop.loop_openings: Analysis points whose connections are removed before linearization, also wheninputsandoutputsare variables. A signal disconnected by a loop opening is held at the value of the signal that drove it unlessopprovides a value for it.system_modifier: A function applied to the system after the loop openings and before structural simplification.verbose: AnMTKVerbosity, aSciMLLoggingpreset, or aBoolcontrolling diagnostic output (theempty_operating_pointtoggle and the initialization toggles). The deprecated boolean keywordswarn_empty_opandwarn_initialize_determinedremain accepted and override the corresponding toggles when explicitly passed.specialize: TheSciMLBase.AbstractSpecializationof theODEProblembuilt for the system, ornothingforODEProblem's default. WithSciMLBase.FullSpecialize, the system and observed functions are called directly instead of through function wrappers, so the evaluation is fully specialized;eval_expressionandeval_modulealso apply to the system function; and withinitialize = false, a call whoseuandphave the types of the problem's uses them as given, without remaking the problem.kwargs: Are passed on tofind_solvables!
See also linearize which provides a higher-level interface.
ControlSystemsBase.loopshapingPID — Function
C, kp, ki, kd, fig, CF = loopshapingPID(P, ω; Mt = 1.3, ϕt=75, form=:standard, doplot=false, lb=-10, ub=10, Tf = 1/1000ω, F = nothing)Selects the parameters of a PID-controller such that the Nyquist curve of the loop-transfer function $L = PC$ at the frequency ω is tangent to the circle where the magnitude of $T = PC / (1+PC)$ equals Mt. ϕt denotes the positive angle in degrees between the real axis and the tangent point.
The default values for Mt and ϕt are chosen to give a good design for processes with inertia, and may need tuning for simpler processes.
The gain of the resulting controller is generally increasing with increasing ω and Mt.
Arguments:
P: A SISO plant.ω: The specification frequency.Mt: The magnitude of the complementary sensitivity function at the specification frequency, $|T(iω)|$.ϕt: The positive angle in degrees between the real axis and the tangent point.doplot: If true, gang of four and Nyquist plots will be returned infig.lb: log10 of lower bound forkd.ub: log10 of upper bound forkd.Tf: Time constant for second-order measurement noise filter on the formtf(1, [Tf^2, 2*Tf/sqrt(2), 1])to make the controller strictly proper. A practical controller typically sets this time constant slower than the default, e.g.,Tf = 1/100ωorTf = 1/10ωF: A pre-designed filter to use instead of the default second-order filter.
The parameters can be returned as one of several common representations chosen by form, the options are
:standard- $K_p(1 + 1/(T_i s) + T_ds)$:series- $K_c(1 + 1/(τ_i s))(τ_d s + 1)$:parallel- $K_p + K_i/s + K_d s$
See also loopshapingPI, pidplots, stabregionPID and placePI.
Example:
P = tf(1, [1,0,0]) # A double integrator
Mt = 1.3 # Maximum magnitude of complementary sensitivity
ω = 1 # Frequency at which the specification holds
C, kp, ki, kd, fig, CF = loopshapingPID(P, ω; Mt, ϕt = 75, doplot=true)RobustAndOptimalControl.named_ss — Function
RobustAndOptimalControl.named_ss(sys::ModelingToolkit.AbstractSystem, inputs, outputs; descriptor=true, simple_infeigs=true, balance=false, kwargs...)Convert an System to a NamedStateSpace using linearization. inputs, outputs are vectors of variables determining the inputs and outputs respectively. See docstring of ModelingToolkit.linearize for more info on kwargs.
If descriptor = true (default), this method automatically converts systems that MTK has failed to produce a proper form for into a proper linear statespace system using the method described here: https://juliacontrol.github.io/ControlSystemsMTK.jl/dev/#Internals:-Transformation-of-non-proper-models-to-proper-statespace-form If descriptor = false, the system is instead converted to a statespace realization using sys[:,uinds] + sys[:,duinds]*tf('s'), which tends to result in a larger realization on which the user may want to call minreal(sys, tol) with a carefully selected tolerance.
Hybrid models
A model that contains clocked (discrete-time) partitions connected to the continuous-time equations is linearized as a hybrid model if hybrid = true. This is the default if additional_passes contains a discrete compilation pass, such as SynchToolkit.compile_lustre, and also if ModelingToolkit rejects the model as a hybrid model because no such pass was supplied. Each clock partition is then linearized separately with ModelingToolkit.linearize_hybrid and the partitions are assembled into a single discrete-time system: the continuous-time partition is discretized with zero-order hold at the sample interval of the clock and the connections across the clock boundaries are closed. Inputs that belong to the continuous-time partition are consequently assumed to be piecewise constant between the sample instants, and outputs of the continuous-time partition are obtained at the sample instants only. All clocked partitions are required to be on the same periodic clock, and the continuous-time partition must not have direct feedthrough from a held signal to a sampled signal. The HybridLinearization returned by linearize_hybrid is stored in extra[:hybrid_linearization] of the result, and kwargs are forwarded to linearize_hybrid. With hybrid = false, the model is passed to ModelingToolkit.linearize, the result of which does not include the clocked partitions.
See also ModelingToolkit.linearize which is the lower-level function called internally. The functions get_named_sensitivity, get_named_comp_sensitivity, get_named_looptransfer similarily provide convenient ways to compute sensitivity functions while retaining signal names in the same way as named_ss. The corresponding lower-level functions get_sensitivity, get_comp_sensitivity and get_looptransfer are available in ModelingToolkitStandardLibrary.Blocks and are documented in MTKstdlib: Linear analysis.
named_ss(sys::AbstractStateSpace{T}; x, u, y)Create a NamedStateSpace system. This kind of system uses names rather than integer indices to refer to states, inputs and outputs.
- If a single name is provided but a vector of names is expected, this name will be used as prefix followed by a numerical index.
- If no name is provided, default names (
x,y,u) will be used.
Arguments:
sys: A system to add names to.x: A list of symbols with names of the states.u: A list of symbols with names of the inputs.y: A list of symbols with names of the outputs.
Example
G1 = ss(1,1,1,0)
G2 = ss(1,1,1,0)
s1 = named_ss(G1, x = :x, u = :u1, y=:y1)
s2 = named_ss(G2, x = :z, u = :u2, y=:y2)
s1[:y1, :u1] # Index using symbols. Uses prefix matching if no exact match is found.
fb = feedback(s1, s2, r = :r) # named_ss(sys::AbstractStateSpace, name; x, y, u)If a single name of the system is provided, the outputs, inputs and states will be automatically named y,u,x with name as prefix.
named_ss(sys::ExtendedStateSpace; kwargs...)
named_ss(sys::ExtendedStateSpace, name; kwargs...)Assign names to an ExtendedStateSpace. If no specific names are provided for signals z,y,w,u and statesx, names will be generated automatically.
Arguments:
name: Prefix to add to all automatically generated names.xuywz
Missing docstring for get_named_sensitivity. Check Documenter's build log for details.
Missing docstring for get_named_comp_sensitivity. Check Documenter's build log for details.
Missing docstring for get_named_looptransfer. Check Documenter's build log for details.
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 callsModelingToolkitBase.mtkcompileinternally.inputs: input variables used as the columns of theBandDmatrices.outputs: output variables used as the rows of theCandDmatrices.
Keyword Arguments
simplify: whether to run additional symbolic simplification during compilation.allow_input_derivatives: whether differentiated inputs may appear in the linearized equations. Iftrue,BandDinclude extra columns for those derivatives.eval_expression: whether generated expressions are evaluated directly instead of using runtime-generated functions.eval_module: the module used wheneval_expression = true.split: whether generated functions use a tuple of parameters or splatted parameters.kwargs...: additional keyword arguments forwarded toModelingToolkitBase.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.ASee also linearize, linearization_function, and reorder_unknowns.
ModelingToolkit.get_sensitivity — Function
get_sensitivity(sys, ap; loop_openings = [], system_modifier = identity, op = Dict(), kwargs...)Compute the sensitivity transfer matrices at analysis point ap and return (matrices, simplified_system, extras). This introduces an infinitesimal perturbation at the input of ap, linearizes the system, and computes the transfer function from the perturbation to the output of ap.
Arguments
sys: The unsimplified, uncompleted system containing the analysis point. Bothmtkcompileandcompleteremove the analysis points, so neither may have been applied tosys.ap: AnAnalysisPoint, obtained by property access onsys, as inget_sensitivity(sys, sys.plant_input). A point belonging to a subsystem is reached through the hierarchy,sys.inner.plant_input. Passing theSymbolname of the point,get_sensitivity(sys, :plant_input), is the old style and will be deprecated.
Keyword Arguments
loop_openings: connections to open before linearization.system_modifier: transformation applied before linearization.op: operating-point values passed tolinearize, a dictionary or aLinearizationOpPoint.allow_input_derivatives: allow derivatives of input variables in the linearization.t: time at which to evaluate the linearization.hybrid: linearize every clock partition of a system with clocked (discrete-time) equations separately withlinearize_hybrid, and return itsHybridLinearizationinstead of(matrices, simplified_system, extras). The remaining keyword arguments are then forwarded tolinearize_hybrid.kwargs...: forwarded toget_sensitivity_function.
See also get_comp_sensitivity and get_looptransfer.
ModelingToolkit.get_comp_sensitivity — Function
get_comp_sensitivity(sys, ap; loop_openings = [], system_modifier = identity, op = Dict(), kwargs...)Compute the complementary-sensitivity transfer matrices at analysis point ap and return (matrices, simplified_system, extras). This introduces an infinitesimal perturbation at the output of ap, linearizes the system, and computes the transfer function from the perturbation to the input of ap.
Arguments and keyword arguments match get_sensitivity, with kwargs... forwarded to get_comp_sensitivity_function.
See also get_sensitivity and get_looptransfer.
ModelingToolkit.get_looptransfer — Function
get_looptransfer(sys, ap; loop_openings = [], system_modifier = identity, op = Dict(), kwargs...)Compute the loop-transfer matrices at analysis point ap and return (matrices, simplified_system, extras). The transfer is from ap.out to ap.in.
Arguments and keyword arguments match get_sensitivity, with kwargs... forwarded to get_looptransfer_function.
The computed loop transfer includes negative feedback. Negate the result when using an analysis tool that expects a loop-transfer function without the negative gain.
See also get_sensitivity, get_comp_sensitivity, and open_loop.
ModelingToolkitStandardLibrary.Blocks.StateSpace — Function
StateSpace(A, B, C, D = 0; x = zeros(size(A,1)), u0 = zeros(size(B,2)), y0 = zeros(size(C,1)), name)A linear, time-invariant state-space system on the form.
\[\begin{aligned} ẋ &= Ax + Bu \\ y &= Cx + Du \end{aligned}\]
Transfer functions can also be simulated by converting them to a StateSpace form.
y0 and u0 can be used to set an operating point, providing them changes the dynamics from an LTI system to the affine system
\[\begin{aligned} ẋ &= Ax + B(u - u0) \\ y &= Cx + D(u - u0) + y0 \end{aligned}\]
For a nonlinear system
\[\begin{aligned} ẋ &= f(x, u) \\ y &= h(x, u) \end{aligned}\]
linearized around the operating point x₀, u₀, we have y0, u0 = h(x₀, u₀), u₀.
RobustAndOptimalControl.ss2particles — Function
ss2particles(G::Vector{<:AbstractStateSpace})Converts a vector of state space models to a single state space model with coefficient type MonteCarloMeasurements.Particles.
See also sys_from_particles.
ControlSystemsBase.StateSpace — Type
StateSpace{TE, T} <: AbstractStateSpace{TE}An object representing a standard state space system.
See the function ss for a user facing constructor as well as the documentation page creating systems.
Fields:
A::Matrix{T}B::Matrix{T}C::Matrix{T}D::Matrix{T}timeevol::TE
SymbolicControlSystems.ccode — Function
ccode(G; simplify = identity, cse = true, static = true, double = true)Return a string with C-code for filtering a signal u through G.
If G is a transfer function, the system must be SISO, for MIMO systems, use a StateSpace model instead.
With a transfer function as input, the code will return a double corresponding to the single output. With a StateSpace model as input, the code will produce a function that takes a double pointer double *y as the first input argument. Make sure that y points to an array of length G.ny before calling the function.
The state is internally handled by C static variables, so the generated code is thus stateful.
Arguments:
G: A linear systemsimplify: A function for symbolic simplification. You may trySympy.simplify, but for large systems, this will take a long time to compute.cse: Perform common subexpression elimination. This generally improves the performance of the generated code.static: Iftrue, the generated code will use static variables to store the state of the system. Iffalse, the function will take pointers to the state variables as input arguments.double: Iftrue, the generated code will usedoubleas the numeric type. If false, it will usefloat.
SymbolicControlSystems.print_c_array — Function
print_c_array(io, a::Vector{<:AbstractArray}, t::AbstractVector, name = "mat"; cse = false, s = "", print_vector = true, print_logic = true, struct_name::Union{Nothing, String} = nothing, struct_type = nothing, ivecname = name * "_interp_vect")Write C-code for interpolating between arrays a. The array t contains the interpolation points.
print_c_array(io, sys::Vector{<:AbstractStateSpace}, t::AbstractVector, name = "sys"; cse = false, s = "", en = "", struct_name::Union{Nothing, String} = nothing, struct_type = nothing)Write C-code for an interpolated linear system. The interpolation vector t defines the interpolation points, this vector is expected to be of the same length as the vector of linear systems sys.
s, en: are strings that are appended at the start and end of variables names in the C-code.struct_name: If provided, the interpolation matrices will be placed inside a struct with this name.struct_type: If the struct name is used, provide also the C type of the struct.
ModelingToolkit.reorder_unknowns — Function
reorder_unknowns(sys::NamedTuple, old, new)Permute the state ordering of a linearized system.
Arguments
sys: aNamedTuplewith matricesA,B,C, andD, as returned bylinearizeorlinearize_symbolic.old: the current state order, typicallyunknowns(simplified_sys).new: the desired state order. It must contain the same entries asold.
Returns
A NamedTuple (; A, B, C, D) whose state-space matrices use the order new.
Examples
lsys, ssys = linearize(pid, [reference.u, measurement.u], [ctr_output.u])
desired_order = [int.x, der.x] # Unknowns that are present in unknowns(ssys)
lsys = ModelingToolkit.reorder_unknowns(lsys, unknowns(ssys), desired_order)See also similarity_transform.