Learn/Numerics/Control Design

Control Design

Build models, analyze them in time and frequency, and design controllers and estimators, with two worked examples on a real plant and the Luau and Rune calls for the routines scripts reach.

Time62 min readLevelAdvancedUpdatedUpdated Nov 2026
Script language

01Overview

What Control Design Is

A controller reads what a system is doing and decides what to push on it. Control design is choosing that rule so the system settles where you want, quickly, without oscillating or becoming unstable.

The control routines build models of linear systems, analyze them in time and in frequency, design state-feedback gains, estimator gains and PID controllers, and reduce a model to fewer states. Their names follow MATLAB's Control System Toolbox, so the mapping is direct, and every result is checked against an independent reference: NumPy, SciPy and python-control. The library behind them is finished and passes all 119 of its tests.

Work in four steps: build the model, check it, design the controller, then verify the closed loop. Both worked examples at the end of this page follow that order. The check step is where the open-loop poles, the controllability rank or the stability margins are read before any design is done.

Scripts reach the library in three ways. Luau and Rune both call 10 of the routines on this page: lqr, lqr_with, dlqr, dlqr_with, care, care_with, dare, dare_with, c2d and c2d_with. They are the Riccati solvers, the two LQR gain designs and the continuous-to-discrete conversion.

Rune alone calls 51 more function names: 49 control functions (the conversions, the time and frequency responses, the analysis and the design routines) and lyap and dlyap. Rune also has 9 types: Tf, TfMatrix, Ss, Zpk, Pid, DiscreteStepper, DiscretePid, IirFilter and FftPlan. In all, Rune calls 61 function names on this page and Luau calls 10.

Everything else is Rust only: the grid helpers logspace and linspace, the lqr that takes a model (a script passes the matrices A and B instead), and the Rust enums PidType and RiccatiMethod, which a script spells as strings. The page documents the whole library so that the routines scripts reach sit in context; the Scripts column in the table under Names and Status gives the reach of each routine.

Luau and Rune scripts in Studio and in the Player call the library. The conventions every numerics routine shares in scripts are in the Numerics overview. The subsection Calling the Library from a Script, below the names table, gives what a control call needs.

The Feedback Loop

The loop used on this page has a reference, a controller, a plant and a measured output that is fed back with a negative sign. The DC motor example also adds a disturbance at the plant input.

rreference+-econtroller CPID, LQR gain+ddisturbanceplant Pmotor, pendulumyoutputnegative feedback of the measured output
The loop used on this page. The feedback routines take the sign as an argument, -1 for negative feedback; a sensor model would sit in the return path.

Names and Status

Each row lists a MATLAB name, the library's name for it, the script names that reach it, and its status. The Scripts column gives the reach: Luau and Rune, Rune only (a function under numerics:: or a method of a Rune type), or Rust only (part of the Rust crate and not callable from scripts). Done means the routine is covered with no stated limit. Partial means it works, with the limit written in the last column. A gap is a routine the library does not have; those are listed under What Is Not Covered. In the Riccati and Lyapunov rows, S is the cross-weighting term between state and input, and E is the descriptor matrix of a generalized form.

MATLABEustressScriptsStatus and limit
tf, ss, zpkTf, TfMatrix, Ss, ZpkRune onlyDone; no time delays, no descriptor (E) form
tf2ss, ss2tf, tf2zp, zp2tf, ss2zp, zp2sstf2ss, ss2tf, tf2zpk, zpk2tf, ss2zpk, zpk2ssRune onlyDone
minrealminrealRune onlyDone, for transfer function, zero-pole-gain and state-space models
series, parallel, feedbackseries, parallel, feedbackRune onlyDone, as methods on transfer functions (SISO only) and on state-space models (SISO and MIMO); connect, append and lft are gaps
pole, zero, tzero, dcgain, evalfr, freqresp, isstablepoles, zeros, dcgain, eval, freqresp, is_stableRune onlyDone; the zeros of a state-space model need a square system (as many inputs as outputs)
step, impulse, initial, lsimstep, impulse, initial, lsimRune onlyDone (MIMO)
stepinfostepinfo, stepinfo_sysRune onlyDone
bode, nyquistbode, bode_ss, nyquistRune onlyDone: data only, SISO; there is no plotting
margin, allmarginmargin, allmarginRune onlyDone (SISO)
c2dc2d, c2d_tf, c2d_matchedLuau and Rune: c2d, c2d_withDone for zoh, foh, tustin, prewarp and matched; the impulse and least-squares methods are gaps; matched is SISO. In Luau a script reaches the state-space form only. In Rune the same two names also take a Tf, an Ss or a Zpk: a Tf goes through c2d_tf, and a Zpk with the matched method through c2d_matched
d2cd2cRune onlyDone (zoh, tustin, prewarp)
ctrb, obsvctrb, obsv, ctrb_rank, obsv_rankRune onlyDone
gram, norm(sys, 2), hsvdgram, h2norm, hsvdRune onlyDone for stable models
MATLABEustressScriptsStatus and limit
lyap, dlyaplyap, dlyapRune onlyDone; the generalized forms with E are gaps
care / icarecare, care_withLuau and Rune: care, care_withDone, with S; no E
dare / idaredare, dare_withLuau and Rune: dare, dare_withDone, with S; no E
lqr, dlqr, lqilqr, lqr_matrices, dlqr, lqiLuau and Rune: lqr, lqr_with, dlqr, dlqr_with. Rune only: lqi, lqi_withDone. Scripts take the matrices A and B for lqr and dlqr; lqi takes a model and is Rune only
place, ackerplace, ackerRune onlyDone
kalman, lqe, dlqekalman, lqe, dlqeRune onlyPartial: steady-state gains and covariance only; no assembled estimator model, no correlated noise term N
balreal, balredbalreal, balred (truncate, match DC)Rune onlyDone for stable models
rlocusrlocusRune onlyDone: points only; there is no plot
pidtune, pidpidtune, PidRune onlyPartial: P, PI, PD and PID from a target crossover and phase margin; the gains differ from MATLAB's proprietary rule for the same targets
dampdampRune onlyDone
real-time blocksDiscreteStepper, DiscretePid, IirFilter, FftPlanRune onlyBeyond MATLAB: the per-sample step in Rust does not allocate
logspace, linspacelogspace, linspaceRust onlyDone; a script passes its own array of frequencies

Every row above is checked by named tests against fixtures produced by NumPy 2.5.5, SciPy 1.18.1 and python-control 0.10.2. The control fixture holds 30 cases. A mutation run breaks one line at a time and expects the named test to fail; the mutations in the control code that it breaks (the Riccati residual, the Tustin factor, the phase margin, the gain-crossover polynomial and the discrete Riccati gain) were caught. Across the whole library the run covers 43 mutations, of which 41 were caught and 2 survived by design: one in the discrete Riccati doubling step that the Newton correction repairs, and one in a stiff ODE coefficient that gives plain BDF2, a valid method. For timings, see Performance.

Calling the Library from a Script

The library is a read-only global table named Numerics. Both Numerics.lqr(A, B, Q, R) and Numerics:lqr(A, B, Q, R) work.

The library is a module: use eustress::realism::numerics; and then numerics::lqr(a, b, q, r)?.

The two languages reach different parts of the library:

ReachNames on this page
Luau and Rune (10)lqr, lqr_with, dlqr, dlqr_with, care, care_with, dare, dare_with, c2d, c2d_with
Rune only: conversions (6)tf2ss, ss2tf, tf2zpk, zpk2tf, ss2zpk, zpk2ss
Rune only: responses (22)step, step_with, impulse, impulse_with, initial, initial_with, lsim, lsim_with, stepinfo, stepinfo_with, stepinfo_sys, stepinfo_sys_with, bode, bode_with, bode_ss, nyquist, nyquist_with, margin, allmargin, rlocus, rlocus_with, damp
Rune only: analysis and design (21)d2c, d2c_with, ctrb, ctrb_rank, obsv, obsv_rank, gram, h2norm, hsvd, lqi, lqi_with, place, acker, kalman, lqe, dlqe, balreal, balred, balred_with, pidtune, pidtune_with
Rune only: Lyapunov (2)lyap, dlyap
Rune only: types (9)Tf, TfMatrix, Ss, Zpk, Pid, DiscreteStepper, DiscretePid, IirFilter, FftPlan
Rust onlylogspace, linspace, the model form of lqr, PidType and RiccatiMethod

On this page Luau reaches only the first row, and it has no model types, so a Luau script passes matrices and tables of rows. In Rune a model is a value of a type, built with a constructor and used through methods. A method returns a new model and never changes the one it is called on; a free function that takes a model accepts a Tf, an Ss, a Zpk or an object #{a, b, c, d, ts} (c, d and ts optional). The frequency-domain routines bode, nyquist, margin, allmargin, rlocus and pidtune need a single-input single-output model. The Rune types:

TypeBuilt withMethodsFields
TfTf::new(num, den), Tf::discrete(num, den, ts), Tf::gain(k)is_discrete, order, is_proper, poles, zeros, eval(re, im), freq_point(w), freqresp(w), dcgain, series(h), parallel(h), feedback(h, sign), feedback_unity, scale(k), minreal, minreal_with(opts), to_zpk, to_ssnum, den, ts
SsSs::new(a, b, c, d), Ss::discrete(a, b, c, d, ts), Ss::from_gain(d), Ss::from_gain_with(d, opts)n_states, n_inputs, n_outputs, is_discrete, is_siso, poles, is_stable, zeros, dcgain, eval(re, im), freqresp(w), channel(o, i), to_tf(o, i), to_zpk(o, i), series(h), parallel(h), feedback(h, sign), transform(t), minreal, minreal_with(opts)a, b, c, d, ts
ZpkZpk::new(z, p, k), Zpk::discrete(z, p, k, ts)to_tf, to_ss, eval(re, im), minreal, minreal_with(opts)z, p, k, ts
TfMatrixTfMatrix::new(rows), TfMatrix::from_ss(sys)n_outputs, n_inputs, get(i, j), eval(re, im), to_ssnone
PidPid::new(kp, ki, kd, tf)to_tf, freq_point(w)kp, ki, kd, tf (read and set)
DiscreteStepperDiscreteStepper::new(sys)step(u), state, set_state(x), resetnone
DiscretePidDiscretePid::new(gains, ts)with_limits(min, max), step(error), resetnone
IirFilterIirFilter::new(b, a)step(x), state, set_state(z), resetnone
FftPlanFftPlan::new(n), FftPlan::with_engine(n, engine)fft(x), ifft(x), len, enginenone

Methods do not exist on every type. is_stable exists on Ss only. poles, zeros, dcgain, freqresp, series, parallel and feedback exist on Tf and Ss; Zpk has none of them, so convert it with to_tf or to_ss first. eval exists on Tf, Ss, Zpk and TfMatrix, and minreal on Tf, Ss and Zpk. dcgain returns a number on a Tf and a matrix on an Ss. In an Ss method that names a channel, outputs and inputs count from 0. Complex results are objects #{re, im} of two arrays.

A Rune snippet on this page is either a whole script, with its use lines and a function such as on_init, or, where its label says so, the body of such a function. The call shapes differ only where the languages differ:

TopicLuauRune
OptionsAn optional last table: {n = N}. Each _with name is the same function as its base nameNo optional arguments. The _with form takes the options object last: #{n: N}
MatrixA table of rows: {{1, 2}, {3, 4}}An array of rows: [[1.0, 2.0], [3.0, 4.0]]
VectorAn array: {1, 2}An array: [1.0, 2.0]
NumbersAny Luau numberA float, or an integer wherever a number is expected
Complex values{re = {...}, im = {...}}#{re: [...], im: [...]}
A modelA table of rows, or a table with the keys a, b, c, dA Tf, Ss or Zpk value, or an object #{a: ..., b: ...}
Index base10
Reading a result fieldctl.k[1][2]ctl["k"][0][1]
Calling a methodNot availableg.series(h)?; a constructor is numerics::Tf::new(num, den)?
FailureA Luau error that pcall catches; the text begins runtime error: Numerics.<name>: An Err holding a string that starts numerics::<name>:; ? turns it into a script error. A constructor failure starts numerics::Tf::new: and a method failure starts numerics::Tf::series:

A matrix is an array of rows, and every row has the same length; ragged rows are an error. A plain number is read as a 1 by 1 matrix, so 1 stands for {{1}} as the input weight of a single-input system. A complex value is two arrays of the same length. An option name the routine does not have is an error that lists the names it does have.

As a first call, the double integrator, a mass pushed by a force, with the state weight on its position only, has the optimal gain 1 and the square root of 2 (about 1.4142). It is the check the binding tests run in both languages:

Luau
local A = {{0, 1}, {0, 0}}
local B = {{0}, {1}}
local Q = {{1, 0}, {0, 0}}
local ctl = Numerics.lqr(A, B, Q, 1)
print(ctl.k[1][1], ctl.k[1][2])   -- about 1 and 1.4142
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let a = [[0.0, 1.0], [0.0, 0.0]];
    let b = [[0.0], [1.0]];
    let q = [[1.0, 0.0], [0.0, 0.0]];
    let ctl = numerics::lqr(a, b, q, 1.0)?;
    let k = ctl["k"][0];
    log_info(`K = ${k[0]}, ${k[1]}`);   // about 1 and 1.4142
}

Units, Conventions and Errors

QuantityConvention
Polynomial coefficientsHighest power first, as in MATLAB
Continuous or discreteA model carries a sample time. With none it is continuous; with a sample time it is discrete with that sample time
AnglesRadians
Phase and phase marginDegrees, as in MATLAB. Phase from the Bode routines is unwrapped along the frequency grid
Gain marginAn absolute factor, not decibels
Bode magnitudeBoth absolute magnitude and decibels are returned
FrequencyAngular frequency in rad per time unit, never hertz
Everything elseUnit-free: the routines work in whatever consistent units the model uses, and the examples below use SI units

Bad input returns an error and nothing panics on bad input. There are eight error kinds, and each message names the routine: dimension mismatch, not square, singular, not positive definite, invalid argument, no convergence, no solution and unsupported. Examples of the text: unsupported: c2d: the matched method needs a SISO model, dimension mismatch: solve: A is (3, 3), B is (2, 1). With one thread, every routine returns the same bits on every run.

In a script an error is a message string. The message names the routine and the crate text follows it, and that text begins with the error type, for example dimension mismatch: ... or singular matrix: .... A failure is a Luau error that pcall catches. A script builds matrices as tables of rows and reads results from the returned table with indexes from 1. A failure is an Err value. A script uses arrays and indexes from 0. The table under Calling the Library from a Script has the shapes.

What Is Not Covered

These control items are not in the library: time delays, descriptor systems, nichols, sigma, norm(sys, inf), bandwidth, lqg, lqgreg, reg, estim, lqry, connect, d2d, frd, diskmargin, sisotool, plotting, and the Robust Control, MPC and System Identification toolboxes. For the ones with a close substitute, the nearest alternative is:

MissingUse instead
Time delaysA Pade approximant written as a transfer function, or extra delay states in a discrete state-space model
nichols, sigmaThe Bode data; the singular values of the state-space model evaluated at jw
norm(sys, inf), bandwidthThe peak of the Bode magnitude on a fine grid
lqg, lqgreg, reg, estimAssemble the regulator from the lqr and kalman gains with a state-space constructor
connect, appendseries, parallel and feedback, or build the block matrices directly
d2dd2c, then c2d
modred, canonbalred; a change of state basis of your own choosing
PlottingEvery routine returns the series; draw them with the host application

Descriptor systems, lqry, frd, diskmargin, sisotool and the three other toolboxes have no equivalent.

02Models

Rune builds and converts the models in this section; Luau does not. The types and their methods are in the table under Calling the Library from a Script. A function that takes a model accepts a Tf, an Ss, a Zpk or an object #{a, b, c, d, ts}.

Rune callReturnsNotes
tf2ss(g)an SsController canonical form
ss2tf(sys)a TfSingle input, single output
tf2zpk(g), zpk2tf(z)a Zpk, a TfAny model in, as for every call here
ss2zpk(sys), zpk2ss(z)a Zpk, an SsSingle input, single output for ss2zpk
g.to_ss(), g.to_zpk()an Ss, a ZpkMethods on a Tf; a Zpk has to_tf() and to_ss()
sys.to_tf(o, i), sys.to_zpk(o, i)a Tf, a ZpkOne channel of an Ss, output o and input i from 0
TfMatrix::from_ss(sys), m.to_ss()a TfMatrix, an SsA matrix of transfer functions and back
g.minreal(), g.minreal_with(#{tol: x})the same typeOn a Tf, an Ss and a Zpk
damp(sys)#{poles, wn, zeta}Sorted by natural frequency; poles is #{re, im}

Transfer Functions

A transfer function is a numerator and a denominator polynomial, highest power first, for a single-input single-output system. Built with a sample time it is discrete, in powers of z; built without one it is continuous, in powers of s. Construction fails with an error when the numerator or denominator is empty, when a coefficient is not finite, when the denominator is zero, or when the sample time is not positive and finite.

A transfer function reports its order, whether it is proper, its poles and zeros, its value at a complex frequency, its frequency response over a grid, and its steady-state gain. The steady-state gain is infinite when the model has an integrator. A pure gain is a transfer function with a numerator of one coefficient and a denominator of one.

A matrix of transfer functions covers the multi-input multi-output case: its elements are laid out by output (rows) and input (columns), and all of them share one sample time.

State-Space Models

A state-space model is four matrices: A (states by states), B (states by inputs), C (outputs by states) and D (outputs by inputs, the feedthrough term). D is part of the model, so a direct path from input to output is allowed. With a sample time the model is a difference equation; without one it is a differential equation.

Construction fails with an error when A is not square, when the matrix sizes do not agree, or when any entry is not finite. A model with no states and only a gain matrix is allowed. Poles are the eigenvalues of A. A continuous model is stable when every pole has a negative real part; a discrete model is stable when every pole has magnitude below one.

Zero-Pole-Gain Models

A zero-pole-gain model is a list of complex zeros, a list of complex poles, a real gain, and an optional sample time. Its value at a point is the gain times the product of the distances to the zeros over the product of the distances to the poles. It converts to a transfer function or a state-space model, and can cancel zeros against poles that sit close together.

Converting Between Forms

Every pair of forms converts. A transfer function becomes a state-space model in controller canonical form, and the conversion fails for an improper transfer function with the message tf2ss: the transfer function is improper. A state-space model becomes a transfer function or a zero-pole-gain model one input and one output at a time, so the conversion names the output and the input. A zero-pole-gain model becomes a transfer function or a state-space model. A matrix of transfer functions converts to and from a state-space model. The MATLAB names tf2ss, ss2tf, tf2zpk, zpk2tf, ss2zpk and zpk2ss are the routines for each direction.

minreal cancels pole-zero pairs of a transfer function or a zero-pole-gain model that are closer together than a tolerance, relative to their size, and removes the uncontrollable and unobservable states of a state-space model. The default tolerance is the square root of machine epsilon.

In Rune the whole chain is calls on values: a Tf becomes an Ss, a Zpk and a Tf again. The example shows the controller canonical state matrix, which is exactly [[-3, -2], [1, 0]] for this transfer function:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let g = numerics::Tf::new([1.0], [1.0, 3.0, 2.0])?;   // 1 / (s^2 + 3 s + 2)
    let s = g.to_ss()?;                                   // controller canonical form
    let z = numerics::tf2zpk(g)?;
    let back = numerics::zpk2tf(z)?;
    let h = s.to_tf(0, 0)?;                               // output 0, input 0

    let a = s.a;                                          // [[-3, -2], [1, 0]]
    log_info(`states ${s.n_states()}, A row 0 = ${a[0][0]}, ${a[0][1]}`);
    log_info(`dc gain of g ${g.dcgain()}, gain k of z ${z.k}`);   // 1/2 and 1
    log_info(`round trip den ${back.den[1]}, ${back.den[2]}, order of h ${h.order()}`);
}

Poles, Damping and Natural Frequency

damp takes a state-space model and returns its poles sorted by natural frequency, the natural frequency of each (rad per time unit) and the damping ratio of each. Discrete poles are first mapped to continuous time through s = ln(z) / Ts. A pole at the origin reports a damping ratio of -1. A real pole at -2 reports a damping ratio of 1; a negative damping ratio marks an unstable pole.

03Interconnection

Rune closes loops with methods on a Tf or an Ss; Luau does not have them. g.series(h), g.parallel(h) and g.feedback(h, sign) take another model or a number (a number is a gain), and return a model of the same type as g. feedback_unity() on a Tf is the loop g / (1 + g), and scale(k) multiplies by a constant. The sign is -1.0 for negative feedback.

Closing a Loop

feedback puts one model in the forward path and another in the return path, with a sign argument: -1 is negative feedback and +1 is positive feedback. The return path is where a sensor model goes. A transfer function can also be closed with unity negative feedback in one call, which gives the loop transfer function over one plus the loop transfer function. Both models must have the same sample time, or the call fails with an error.

series passes the signal through the first model and then the second. parallel adds the outputs of two models. All three exist as methods on transfer functions, which are SISO only, and on state-space models, which are SISO and MIMO and check that the input and output counts agree. A state-space feedback loop whose direct terms make it algebraic and singular fails with an error that says so.

connect, append and lft are not covered; build the block matrices directly, or use series, parallel and feedback.

In Rune the loop closes with one method call and the result answers poles and dcgain:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let g = numerics::Tf::new([1.0], [1.0, 3.0, 2.0])?;
    let closed = g.feedback(1.0, -1.0)?;       // g / (1 + g) = 1 / (s^2 + 3 s + 3)
    let p = closed.poles()?;                   // #{re, im}
    let dc = closed.dcgain();                  // 1/3
    log_info(`dc gain ${dc}, pole real parts ${p["re"][0]} and ${p["re"][1]}`);   // both -1.5
}

04Time Response

Rune calls the routines in this section; Luau does not. A model argument is any model, so a Tf needs no conversion first. The result of a response routine is an object #{t, y, x} with one row of y (outputs) and x (states) per time sample.

Rune callOptionsReturns
step(sys), step_with(sys, opts)input (from 0), t (the time grid)#{t, y, x}
impulse(sys), impulse_with(sys, opts)input, t#{t, y, x}
initial(sys, x0), initial_with(sys, x0, opts)t#{t, y, x}
lsim(sys, u, t), lsim_with(sys, u, t, opts)x0, hold ("zoh" or "foh")#{t, y, x}; u has one row per sample, or is a plain array for one input
stepinfo(t, y), stepinfo_with(t, y, opts)y_final, settling_threshold, rise_limits (two numbers)the nine measures below
stepinfo_sys(sys), stepinfo_sys_with(sys, opts)settling_threshold, rise_limitsthe nine measures below

The nine measures are the fields rise_time, settling_time, settling_min, settling_max, overshoot, undershoot, peak, peak_time and final_value.

Step and Impulse

step gives the unit step response of a state-space model from one chosen input. impulse gives the impulse response from one chosen input; in continuous time that is the response to a Dirac impulse, and a direct feedthrough term is not shown, as in MATLAB. In discrete time it is the response to a pulse of height 1 / Ts lasting one sample. initial gives the free response from an initial state. Each returns the time samples, the outputs (one row per sample, one column per output) and the states.

When no time vector is given, the routines pick a grid that shows the transient: about seven time constants of the slowest stable mode, resolved for the fastest one, with at least 1000 samples in continuous time. In Rust the step routines take a state-space model, so a transfer function is converted first; in Rune they take any model.

Arbitrary Inputs and Initial Conditions

lsim simulates a model for any input signal and an optional initial state. The input has one row per time sample and one column per input. The time samples must be at least two, increasing and evenly spaced. For a continuous model the propagation between samples is exact for the chosen hold: piecewise constant (zero-order hold) or piecewise linear (first-order hold, the choice for smooth signals). For a discrete model the time step must equal the sample time. Wrong sizes, a non-finite input or an initial state of the wrong length fail with an error.

Measuring a Step Response

stepinfo measures a sampled step response. It returns the rise time (10 % to 90 % of the final value), the settling time (the time after which the response stays within 2 % of the final value), the minimum and maximum of the response once it has risen, the overshoot above the final value in percent, the undershoot in percent, the peak absolute value and its time, and the final value used for the percentages. The 2 % band and the 10 % and 90 % limits are the defaults and can be changed. Crossing times are interpolated linearly between samples, as in MATLAB. When no final value is given, the last sample is used. stepinfo_sys does the same for a SISO state-space model on an automatic grid, with the true steady-state gain as the final value.

As a worked reading, take a second-order system with natural frequency 2 rad/s and damping ratio 0.3, that is wn^2 / (s^2 + 2 zeta wn s + wn^2). Stepped over 0 to 10 s in 2001 samples and measured against a final value of 1, it has a rise time of 0.6607 s, a settling time of 5.615 s, an overshoot of 37.23 %, a peak of 1.3723 at 1.645 s, a settling minimum of 0.8614 and a settling maximum of 1.3723. The plot marks each one on the curve.

01234567800.511.5outputtime (s)rise time 0.6607 s (10 % to 90 %)peak 1.3723 at 1.645 s, overshoot 37.23 %settling time 5.615 s (2 % band)final value 1
A second-order step response with its stepinfo measurements marked, drawn from control_step.csv and control_step_marks.csv, the series the library wrote on its real run (2001 samples, 0 to 10 s; the plot shows 0 to 8 s). The system is wn^2 / (s^2 + 2 zeta wn s + wn^2) with wn = 2 rad/s and zeta = 0.3. Dashed lines mark the rise-time crossings, the settling time and the final value; dotted lines mark the 10 %, 90 % and 2 % levels.

In Rune stepinfo_sys measures a model directly. The sampled form stepinfo(t, y) takes the time array and one output as a plain array of numbers, not the rows that step returns, so take one column of y first. The example measures a first-order lag:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let lag = numerics::Tf::new([1.0], [1.0, 1.0])?;                         // 1 / (s + 1)
    let info = numerics::stepinfo_sys(lag)?;
    let band = numerics::stepinfo_sys_with(lag, #{settling_threshold: 0.05})?;
    log_info(`rise ${info["rise_time"]}, settling ${info["settling_time"]}, final ${info["final_value"]}`);
    log_info(`settling in a 5 % band ${band["settling_time"]}`);
    // rise time is close to ln 9; settling is close to -ln 0.02 and -ln 0.05; the final value is 1
}

05Frequency Response

Rune calls the routines in this section; Luau does not. They take a single-input single-output model, which may be a Tf, an Ss or a Zpk.

Rune callOptionsReturns
bode(sys), bode_with(sys, opts)w (the frequencies)#{w, mag, mag_db, phase_deg}
bode_ss(sys, w)none#{w, mag, mag_db, phase_deg} from the state-space form
nyquist(sys), nyquist_with(sys, opts)w#{w, re, im}
margin(sys)none#{gm, pm, wcg, wcp}
allmargin(sys)none#{gain_margins, gm_freqs, phase_margins, pm_freqs, delay_margins}
g.freqresp(w), g.eval(re, im), g.freq_point(w)nonemethods on a Tf; the result is #{re, im}

Bode

bode returns the frequencies, the magnitude (absolute), the magnitude in decibels and the phase in degrees, unwrapped along the grid, for a SISO transfer function. bode_ss does the same for a SISO state-space model. When no frequency grid is given, the routine covers every pole and zero with a decade to spare. Frequencies are angular, in rad per time unit. logspace and linspace build grids.

Nyquist

nyquist returns the curve of a SISO system for positive frequencies as three series: the frequencies, the real parts and the imaginary parts. It does not count encirclements of the critical point; read the stability from the margins or the closed-loop poles.

The example loop is L(s) = 10 / ((s + 1)(s + 2)(s + 3)), evaluated at 400 frequencies spaced logarithmically from 0.01 to 100 rad/s. The curve is drawn for positive frequencies only, because that is all the routine returns; the mirror image for negative frequencies is neither returned nor drawn. The margin routine on the same loop gives a gain margin of 6 (an absolute factor), a phase margin of 90 degrees, a phase crossover at 3.3166 rad/s and a gain crossover at 1 rad/s. At the phase crossover the curve meets the negative real axis at -1/6, which is -0.1667, so the loop gain can rise by a factor of 6 before the curve reaches the critical point at -1. At the gain crossover the curve sits on the unit circle at -j, which is a phase margin of 90 degrees.

-1012-1-0.50imaginary partreal partcritical point -1121 phase crossover 3.3166 rad/sgain margin 6 (curve at -1/6)2 gain crossover 1 rad/sphase margin 90 degw = 0.01 rad/spositive frequencies only
The Nyquist curve of L(s) = 10 / ((s + 1)(s + 2)(s + 3)) for positive frequencies only, drawn from control_nyquist.csv, the series the library wrote on its real run (400 points, 0.01 to 100 rad/s). The negative-frequency half is not returned and not drawn. The dashed arc is the unit circle; the cross is the critical point at -1. The margins are the figures the library printed.

Stability Margins

margin takes the open-loop transfer function of a SISO loop under unity negative feedback and returns the gain margin, the phase margin and the two frequencies they are measured at. The gain margin is an absolute factor, not decibels, and is infinite when the phase never crosses -180 degrees. The phase margin is in degrees and is infinite when the gain never crosses 1. The frequency of the gain margin is where the phase crosses -180 degrees, and the frequency of the phase margin is where the gain crosses 1; either is not a number when there is no crossing. When several crossings exist, the margin closest to instability of each kind is returned.

allmargin returns every crossover: all gain margins and the frequencies where the phase is -180 degrees, all phase margins and the frequencies where the gain is 1, and the delay margins in time units. In continuous time the crossovers are the exact roots of polynomials in the frequency. In discrete time the routine searches a dense grid up to the Nyquist frequency and refines each crossing by Brent's method.

In Rune margin and bode_with take the loop as a Tf. The loop in the example is 2 / (s + 1)^3, for which the answers are exact by hand:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let l = numerics::Tf::new([2.0], [1.0, 3.0, 3.0, 1.0])?;   // 2 / (s + 1)^3
    let m = numerics::margin(l)?;                              // #{gm, pm, wcg, wcp}
    let b = numerics::bode_with(l, #{w: [1.0, 10.0]})?;        // #{w, mag, mag_db, phase_deg}
    log_info(`gain margin ${m["gm"]} at ${m["wcg"]} rad/s, phase margin ${m["pm"]} degrees`);
    log_info(`at 1 rad/s: ${b["mag_db"][0]} dB, ${b["phase_deg"][0]} degrees`);
    // gm is 4 at w = sqrt(3); at 1 rad/s the magnitude is 1 / sqrt(2) and the phase is -135 degrees
}

06Discretization

c2d and c2d_with are callable from Luau and Rune, for state-space models; Rune also takes a Tf or a Zpk. d2c and d2c_with are callable from Rune only. The Rust names c2d_tf and c2d_matched are reached in Rune through c2d on a Tf and on a Zpk with the matched method.

Continuous to Discrete

c2d converts a continuous state-space model to discrete time at a sample time. The methods are: zero-order hold on the inputs (zoh), triangle or first-order hold (foh), the bilinear Tustin approximation (tustin), Tustin with frequency prewarping at an angular frequency you give (prewarp), and matched pole-zero mapping (matched, SISO only). c2d_tf does the same for a transfer function and c2d_matched for a zero-pole-gain model. The impulse and least-squares methods are not covered.

Matched mapping sends each finite pole and zero through z = exp(s Ts), sends all but one of the zeros at infinity to z = -1, and matches the gain at DC, or at s = j 0.1 / Ts when the model has a pole or zero at the origin. The conversion fails with an error when the model is already discrete, when the prewarp frequency is not positive and below the Nyquist frequency, when Tustin is singular (a pole sits at 2 / Ts), and when the matched method is given a model that is not SISO or not proper. The sample time must be positive and finite.

From a script, c2d takes a model, the sample time and the method. The model is a tablean object with the keys a, b, c and d: a and b are required, a missing c is the identity matrix, a missing d is zeros, and upper-case keys work as well. The result has the same four keys and ts, the sample time. A script reaches the state-space form only. A Tf, an Ss or a Zpk is also accepted and the result has the same type. The matched method is chosen by name.

TopicLuauRune
Default methodZero-order hold: c2d(sys, ts)None in c2d, which takes the method as its third argument. c2d_with with no method uses zero-order hold
Choose a methodA string as the third argument, or {method = ...}c2d(sys, ts, "foh") or c2d_with(sys, ts, #{method: "foh"})
Method nameszoh, foh, tustin and matched (single input, single output). Tustin with prewarping is chosen by giving a prewarp frequencyzoh, foh, tustin and matched (single input, single output). Tustin with prewarping is chosen by giving a prewarp frequency
Prewarpc2d(sys, ts, {prewarp = w})c2d_with(sys, ts, #{prewarp: w})

The prewarp frequency is in rad per time unit. A prewarp frequency on its own selects Tustin with prewarping, and the method name prewarp without a frequency is an error. A prewarp frequency together with zoh, foh, tustin or matched is an error, and so is any other method name; the message lists the valid ones. The failure conditions listed for the crate apply to scripts as well: a prewarp frequency must be positive and below the Nyquist frequency, and the sample time must be positive and finite.

Luau
local sys = {a = {{-1}}, b = {{1}}}
local zoh = Numerics.c2d(sys, 0.1)
local warped = Numerics.c2d(sys, 0.1, {prewarp = 5})
print(zoh.a[1][1], zoh.ts, warped.a[1][1])
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let zoh = numerics::c2d(#{a: [[-1.0]], b: [[1.0]]}, 0.1, "zoh")?;
    let warped = numerics::c2d_with(#{a: [[-1.0]], b: [[1.0]]}, 0.1, #{prewarp: 5.0})?;
    log_info(`ts ${zoh["ts"]}, a ${zoh["a"][0][0]}, warped a ${warped["a"][0][0]}`);
}

Discrete to Continuous

d2c converts a discrete state-space model back to continuous time with the inverse of zero-order hold, the inverse bilinear transform, or the inverse of Tustin with prewarping. It fails when the model is already continuous, when zero-order hold has no real continuous equivalent (a pole at zero or on the negative real axis), and when Tustin is singular (a pole at z = -1). The test that d2c inverts c2d passes.

In Rune d2c(sys, method) takes "zoh" or "tustin", and d2c_with(sys, #{method: m, prewarp: w}) adds Tustin with prewarping; a prewarp frequency alone selects it, as for c2d. The result has the type of the input. The example discretizes a Tf and converts it back:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let g = numerics::Tf::new([1.0], [1.0, 3.0, 2.0])?;
    let gd = numerics::c2d(g, 0.1, "zoh")?;     // a discrete Tf with ts = 0.1
    let gc = numerics::d2c(gd, "zoh")?;         // back to continuous time
    let d = gd.dcgain();
    let c = gc.dcgain();
    log_info(`ts ${gd.ts}, dc gain ${d}, after d2c ${c}`);   // zero-order hold keeps the dc gain 1/2
}

07Controllability and Observability

Rune calls the routines in this section; Luau does not. The first two rows take matrices, and the last three take a model.

Rune callReturns
ctrb(a, b), ctrb_rank(a, b)the controllability matrix, its rank
obsv(a, c), obsv_rank(a, c)the observability matrix, its rank
gram(sys, kind)the Gramian matrix; kind is "c" or "o"
h2norm(sys)a number
hsvd(sys)an array, largest first

ctrb and obsv

A system is controllable when inputs can steer the state anywhere, and observable when the outputs reveal the whole state. Both are rank tests on a matrix built from the model.

ctrb builds the controllability matrix [B, AB, ..., A^(n-1) B] and obsv builds the observability matrix with the rows C, CA, ..., C A^(n-1). ctrb_rank and obsv_rank return the rank of each. The system is controllable when the controllability rank equals the number of states, and observable when the observability rank does. The rank is the number of singular values above the default tolerance, max(m, n) times machine epsilon times the largest singular value, so a system that is nearly uncontrollable can still report full rank.

Gramians and Norms

gram returns the controllability or observability Gramian of a stable model, h2norm its H2 norm, and hsvd its Hankel singular values, largest first. All three require a stable model; gram on an unstable model fails with the message gram: the model must be stable. The H-infinity norm is not covered; use the peak of the Bode magnitude on a fine grid.

08Lyapunov and Riccati Equations

care, care_with, dare and dare_with are callable from Luau and Rune. lyap and dlyap are callable from Rune only.

Lyapunov

lyap solves the continuous Lyapunov equation A X + X A' + Q = 0, and dlyap solves the discrete one, A X A' - X + Q = 0. Q must have the size of A. The generalized forms with a descriptor matrix E are not covered. Both are checked against SciPy.

In Rune lyap(a, q) and dlyap(a, q) return X as a matrix.

Luau does not have lyap or dlyap.

Algebraic Riccati

care solves the continuous equation A'X + XA - (XB + S) R^-1 (B'X + S') + Q = 0 and dare solves the discrete equation A'XA - X - (A'XB + S)(R + B'XB)^-1 (B'XA + S') + Q = 0, each for the stabilizing solution. S is optional. The result carries four things: the symmetric solution X, the state-feedback gain K (the closed loop is A - B K), the closed-loop eigenvalues, and the residual, which is the Frobenius norm of the equation residual divided by the norm of X.

The default method is automatic: the fast path first (the matrix sign function for the continuous equation, structured doubling for the discrete one), and the ordered Schur method if that fails or leaves a large residual. The Schur method, or the iterative method alone, can be forced with care_with and dare_with; the options are RiccatiMethod Auto, Schur and Iterative, and the Schur method for the discrete equation needs an invertible A. Every method finishes with Newton corrections while they lower the residual.

Failure is an error, not a bad answer. R must be invertible. When no stabilizing solution exists the continuous routine returns care: no stabilising solution exists for this problem (the no-solution error kind), and the discrete routine reports that the doubling iteration did not converge or that the solution found is not stabilizing. Measured accuracy, as the scaled residual of the equation: on a problem with 100 states and 10 inputs the care solution has a residual of 1.12e-13, against 1.02e-10 for SciPy 1.18.1 on the same problem; for lqr on 50 states and 5 inputs it is 7.73e-16 against 9.73e-15. The tests cover a problem with a cross term, an ill-conditioned problem whose residual is no worse than SciPy's, a problem with no stabilizing solution, and a discrete problem with a singular state matrix.

Scripts call four routines: care, dare, lqr and dlqr. All four take the matrices A, B, Q and R, in that order, and return the same result. care and lqr solve the continuous equation, dare and dlqr the discrete one. The pairs differ in the name of the optional cross term: care and dare read it from the option s, lqr and dlqr from the option n (the N of the LQR section). Every call also reads the option method: auto (the default), schur or iterative. Any other method name is an error.

The result has four fields. x is the stabilizing solution X, a matrix. k is the gain K, a matrix with one row per input, so the closed loop is A - B K. eigenvalues holds the closed-loop eigenvalues as a complex value, two arrays re and im. residual is a number, the relative residual described above. The options are an optional fifth argument, and care_with and dare_with are the same functions as care and dare. The options go in the care_with and dare_with forms as an object in the fifth argument. A failure, such as an R that is not invertible or a problem with no stabilizing solution, is an error.

Luau
local A = {{0, 1}, {0, 0}}
local B = {{0}, {1}}
local Q = {{1, 0}, {0, 0}}
local R = {{1}}

local plain = Numerics.care(A, B, Q, R)
local cross = Numerics.care(A, B, Q, R, {s = {{0}, {0}}, method = "schur"})
print(plain.residual, cross.k[1][1])
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let a = [[0.0, 1.0], [0.0, 0.0]];
    let b = [[0.0], [1.0]];
    let q = [[1.0, 0.0], [0.0, 0.0]];
    let r = [[1.0]];

    let plain = numerics::care(a, b, q, r)?;
    let cross = numerics::care_with(a, b, q, r, #{s: [[0.0], [0.0]], method: "schur"})?;
    log_info(`residual ${plain["residual"]}, gain ${cross["k"][0][0]}`);
}

09Feedback Design

lqr, lqr_with, dlqr and dlqr_with are callable from Luau and Rune, and they take the matrices A and B, not a model. lqi, lqi_with, place and acker are callable from Rune only.

LQR and Discrete LQR

A linear quadratic regulator picks the feedback gain that minimizes a cost made of state error and control effort, weighted by two matrices you choose.

lqr takes a state-space model, the state weight Q, the input weight R and an optional cross term N, and minimizes the integral of x'Qx + u'Ru + 2x'Nu (the sum, for a discrete model). It follows the model's sample time, so it solves the continuous equation for a continuous model and the discrete equation for a discrete one. lqr_matrices and dlqr do the continuous and discrete cases from the matrices A and B directly. The result is the same as for the Riccati routines: the gain K, the solution, the closed-loop eigenvalues and the relative residual. The control law is u = -K x, and the closed loop is A - B K.

Use a state weight Q that is positive semidefinite and an input weight R that is positive definite, as in the example below (Q diagonal with a zero on each velocity, R equal to 1). The library checks that R is invertible and that the matrix sizes agree; a problem with no stabilizing solution returns an error.

Scripts pass the matrices instead of a model: lqr(A, B, Q, R) solves the continuous problem and dlqr(A, B, Q, R) the discrete one, so the name chooses the time domain. The cross term N is the option n and the method is the option method, as described under Algebraic Riccati. The result fields are x, k, eigenvalues and residual. The gain is the matrix k with one row per input; a single-input system has the one row k[1]k[0], and the control law is u = -K x.

A discrete design chains two script calls: discretize the plant with c2d, then pass the discrete a and b to dlqr. The design calls belong outside the frame loop; keep the gain and apply u = -K x with ordinary arithmetic at each step, as the last section describes.

Luau
local plant = {a = {{0, 1}, {0, 0}}, b = {{0}, {1}}}
local d = Numerics.c2d(plant, 0.02)
local ctl = Numerics.dlqr(d.a, d.b, {{1, 0}, {0, 0}}, {{1}})
local K = ctl.k[1]
-- each sample: u = -(K[1] * x1 + K[2] * x2)
Rune
use eustress::realism::numerics;

pub fn on_init() {
    let plant = #{a: [[0.0, 1.0], [0.0, 0.0]], b: [[0.0], [1.0]]};
    let d = numerics::c2d(plant, 0.02, "zoh")?;
    let ctl = numerics::dlqr(d["a"], d["b"], [[1.0, 0.0], [0.0, 0.0]], [[1.0]])?;
    let k = ctl["k"][0];
    // each sample: u = -(k[0] * x1 + k[1] * x2)
}

LQI: Integral Action

lqi designs an LQR with integral action on the outputs. The returned gain acts on the state vector extended with one integrator state per output, [x; xi], where xi integrates the reference minus the output. The weights Q and R are sized for the extended system, that is, the number of states plus the number of outputs. The routine works in continuous and in discrete time.

In Rune lqi(sys, q, r) takes a model and the weights, and lqi_with(sys, q, r, #{n: m}) adds the cross term. The result is #{x, k, eigenvalues, residual}, like the other design routines, and each row of k acts on the extended state [x; xi].

Pole Placement

place returns the gain K so that A - B K has the requested poles, for single-input and multi-input systems. It chooses the closed-loop eigenvectors to be as well conditioned as the pole locations allow. Complex poles must come in conjugate pairs, you must give exactly as many poles as states, and a pole may not repeat more often than the rank of B. It fails when A and B are not controllable. acker uses Ackermann's formula for a single input; it is numerically fragile beyond small orders, so prefer place except for small single-input systems.

In Rune place(a, b, p) and acker(a, b, p) return the gain K as a matrix with one row per input. The poles p are an array of reals or an object #{re: [...], im: [...]}, with complex poles in conjugate pairs. For the double integrator, the gain that puts the poles at -1 and -2 is [2, 3], and the gain for -1 plus or minus j is [2, 2]:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let a = [[0.0, 1.0], [0.0, 0.0]];          // double integrator
    let b = [[0.0], [1.0]];
    let k = numerics::place(a, b, [-1.0, -2.0])?;
    let ka = numerics::acker(a, b, #{re: [-1.0, -1.0], im: [1.0, -1.0]})?;
    log_info(`place K = ${k[0][0]}, ${k[0][1]}`);      // 2 and 3: A - B K has s^2 + 3 s + 2
    log_info(`acker K = ${ka[0][0]}, ${ka[0][1]}`);    // 2 and 2: poles -1 plus or minus j, s^2 + 2 s + 2
}

10State Estimation

Rune calls the routines in this section; Luau does not. Each returns an object #{l, p, m, eigenvalues}: the gain L, the covariance P, the innovation gain M and the estimator poles as #{re, im}.

Rune callArguments
kalman(sys, qn, rn)a model whose inputs are all process noise, then Qn and Rn
lqe(a, g, c, qn, rn)continuous time
dlqe(a, g, c, qn, rn)discrete time

Kalman Filter Design

lqe computes the continuous steady-state Kalman gain for x' = Ax + Bu + Gw, y = Cx + v, from the process-noise covariance Qn and the measurement-noise covariance Rn. dlqe does the discrete case. kalman takes a state-space model whose inputs are all process-noise channels entering through B, with measurement noise on every output, and follows the model's sample time.

The result carries the estimator gain L, the steady-state error covariance P, the innovation gain M, and the estimator poles (the eigenvalues of A - L C). In continuous time M equals L. In discrete time L is the one-step predictor gain, P is the prediction covariance, and M is the innovation gain of the filter that corrects a prediction with the measurement. This is a partial implementation: it gives steady-state gains and covariance only. It does not assemble an estimator model, and it does not take correlated noise (the N term). To build a regulator with an estimator, assemble it from the lqr and kalman gains.

The example is a first-order plant with unit noise covariances. The Riccati equation -2 P + 1 - P^2 = 0 gives P = sqrt(2) - 1, and L equals P:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    // x' = -x + w, y = x + v, with unit noise covariances: A, G, C, Qn, Rn
    let est = numerics::lqe([[-1.0]], [[1.0]], [[1.0]], [[1.0]], [[1.0]])?;
    let lag = numerics::Ss::new([[-1.0]], [[1.0]], [[1.0]], [[0.0]])?;
    let same = numerics::kalman(lag, [[1.0]], [[1.0]])?;
    log_info(`L ${est["l"][0][0]}, P ${est["p"][0][0]}, kalman L ${same["l"][0][0]}`);   // sqrt(2) - 1 each
}

11Model Reduction

Rune calls the routines in this section; Luau does not. balreal(sys) returns #{sys, hsv, t, t_inv} with sys the balanced Ss. balred(sys, order) returns an Ss with order states, and balred_with(sys, order, #{method: m}) takes "truncate" (the default) or "match_dc".

Balanced Reduction

balreal returns a balanced realization of a stable, minimal model: a model whose two Gramians are equal and diagonal, the Hankel singular values (largest first) and the state transformation with its inverse. balred reduces a stable model to a requested number of states by dropping the states with the weakest Hankel singular values. Two methods: truncate drops them, and match DC residualizes them so the steady-state gain is preserved. Both fail for an unstable model, and a request for more states than the model has fails with an error. A model that is not minimal fails in balreal with the advice to use minreal first.

Use the Hankel singular values from hsvd to see how many states carry the response before choosing the order. This page states no error bound for the reduced model.

12Classical Tools

Rune calls the routines in this section; Luau does not. rlocus(sys) and rlocus_with(sys, #{gains: g}) return #{k, roots}, where roots holds one #{re, im} per gain. pidtune(plant, type, phase_margin) and pidtune_with(plant, type, phase_margin, #{crossover: w}) take a type of "p", "pi", "pd" or "pid" and a phase margin in degrees, and return #{pid, crossover, phase_margin} with pid a Pid.

Root Locus

rlocus returns the closed-loop poles of 1 + k G = 0 for a transfer function G over a set of gains k: the gains, and for each gain the list of roots, ordered so that each branch is continuous across gains. When no gains are given, it sweeps zero and then 400 logarithmically spaced gains from 1e-4 to 1e4. It returns points; there is no plot. Gains must be finite.

The example plant is 1 / ((s + 1)(s + 2)(s + 3)), swept with the default gains: the data holds 401 gains, from 0 to 10000, and three branches. The branches start at the plant poles -1, -2 and -3. The chosen gain is 10, where the closed-loop poles are -4.3089 and -0.8455 plus or minus 1.7316 j. The gain at the stability limit is 60: there the two complex branches cross the imaginary axis, and for larger gains they are in the right half-plane. The chosen gain 10 times 6 is 60, matching the gain margin of 6 of the Nyquist loop above, which is 10 times this plant.

-8-6-4-20246-4-2024imaginary part (rad/s)real part (1/s)gain 10gain 60: stability limit, poles on the imaginary axispoles at gain 0poles at gain 10gain 60 (limit)gain 0 to 10000,401 points per branch
Root locus of the plant 1 / ((s + 1)(s + 2)(s + 3)), drawn from control_rlocus.csv and control_rlocus_chosen_gain.csv, the series the library wrote on its real run (401 gains, 3 branches). Axes are limited to -8 to 6 and -5 to 5, and branches are cut at the plot edge. The circles are the poles at the chosen gain 10; the dots are where the branches cross the imaginary axis at gain 60, the stability limit.

PID Tuning

pidtune tunes a P, PI, PD or PID controller for a continuous SISO plant so that the open loop crosses unity gain at a crossover frequency with a phase margin you state. The gains are the closed-form solution of two loop-shaping equations: the controller times the plant has magnitude 1 at the crossover, and its phase there is -180 degrees plus the margin. The PID form has the integral time equal to four times the derivative time. The controller types are PidType P, Pi, Pd and Pid. The phase margin must be between 0 and 90 degrees, and the plant must be continuous.

When no crossover is given, the routine picks the frequency where the plant phase leaves room for the controller type, and asks for an explicit one if none is found. It fails when the controller type cannot supply the phase the crossover needs. For type P only the crossover can be met; the margin is whatever the plant gives there. The result carries the gains Kp, Ki and Kd in a PID description (with a derivative filter time constant of 0, an ideal derivative), the crossover and the phase margin. The gains differ from MATLAB's for the same targets, because MATLAB's tuning rule is proprietary; the crossover and the margin match.

The PID form is C(s) = Kp + Ki / s + Kd s / (Tf s + 1), where Tf is the derivative filter time constant. The description converts to a transfer function.

In Rune pidtune returns the gains as a Pid with the fields kp, ki, kd and tf, and to_tf() turns it into a transfer function. The example tunes a PI controller for 1 / (s + 1)^2 and checks the loop margin, which is the target of 60 degrees:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let plant = numerics::Tf::new([1.0], [1.0, 2.0, 1.0])?;     // 1 / (s + 1)^2
    let tuned = numerics::pidtune(plant, "pi", 60.0)?;         // #{pid, crossover, phase_margin}
    let c = tuned["pid"];                                      // a Pid
    let loop_tf = c.to_tf()?.series(plant)?;
    let m = numerics::margin(loop_tf)?;
    log_info(`kp ${c.kp}, ki ${c.ki}, crossover ${tuned["crossover"]}`);
    log_info(`phase margin of the loop ${m["pm"]}`);              // 60, the target
}

13Worked Example: LQR on an Inverted Pendulum on a Cart

The plant and the weights are the ones in the University of Michigan Control Tutorials for MATLAB and Simulink (CTMS), Inverted Pendulum, State-Space Methods for Controller Design. That choice lets the gain be checked against the published MATLAB result. Everything below is from a real run of the example; the numbers in the tables are the lines the run printed.

The run is a Rust program on the library. A script reaches the design step, lqr, and an ODE solver, ode45, so the steps below show the script calls for the model, the gain and the closed-loop simulation.

The controllability rank, the lsim step response and the stepinfo measurements are Rune calls (ctrb_rank, lsim, stepinfo) that Luau does not have. The script snippets in the steps form one script. In Rune they sit in the body of one function such as on_init, below the lines use eustress::log_info; and use eustress::realism::numerics;.

Step 1: The Model

A pendulum balanced upright on a cart that a horizontal force pushes. The state is the cart position and speed and the pendulum angle and angular speed; the input is the force.

ParameterMeaningValue
MCart mass0.5 kg
mPendulum mass0.2 kg
bCart friction0.1 N s/m
IPendulum inertia about its center0.006 kg m^2
lLength to the pendulum center0.3 m
gGravity9.8 m/s^2

The example linearizes the equations of motion about the upright position, with the angle measured from the upward vertical. The state is x (cart position), its rate, phi (pendulum angle) and its rate; the input is the force on the cart; the two outputs are the cart position and the angle, and there is no feedthrough. With the parameters above the model works out to a state matrix whose second row is about [0, -0.1818, 2.6727, 0] and whose fourth row is about [0, -0.4545, 31.18, 0], and an input matrix of about [0, 1.818, 0, 4.545]. The first and third rows are the two kinematic identities (position rate and angle rate).

In a script lqr takes the matrices, not a model. The script builds A and B from the parameters with the formulas the example uses, as tables of rowsarrays of rows:

Luau
local mc, mp, bf, inertia, l, g = 0.5, 0.2, 0.1, 0.006, 0.3, 9.8
local p = inertia * (mc + mp) + mc * mp * l * l
local A = {
    {0, 1, 0, 0},
    {0, -(inertia + mp * l * l) * bf / p, mp * mp * g * l * l / p, 0},
    {0, 0, 0, 1},
    {0, -mp * l * bf / p, mp * g * l * (mc + mp) / p, 0},
}
local B = {{0}, {(inertia + mp * l * l) / p}, {0}, {mp * l / p}}
Rune (inside a function)
let mc = 0.5;
let mp = 0.2;
let bf = 0.1;
let inertia = 0.006;
let l = 0.3;
let g = 9.8;
let p = inertia * (mc + mp) + mc * mp * l * l;
let a = [
    [0.0, 1.0, 0.0, 0.0],
    [0.0, -(inertia + mp * l * l) * bf / p, mp * mp * g * l * l / p, 0.0],
    [0.0, 0.0, 0.0, 1.0],
    [0.0, -mp * l * bf / p, mp * g * l * (mc + mp) / p, 0.0],
];
let b = [[0.0], [(inertia + mp * l * l) / p], [0.0], [mp * l / p]];

Step 2: Check the Open Loop

The open-loop poles are the eigenvalues of the state matrix:

PoleValue (1/s)Reading
10The cart position: pushing the cart leaves it wherever it stops
2-0.1428Slow decay
3-5.604Fast decay
4+5.565Unstable: the pendulum falls

One pole is in the right half-plane. A tilt of the upright pendulum grows by a factor of e about every 0.18 s (1 / 5.565) until the pendulum falls. Whether the cart can hold it up is a controllability question. ctrb_rank gives a rank of 4 of 4, so the force on the cart can steer all four states and a stabilizing gain exists.

A script reads the same poles with Numerics.eigvals(A)numerics::eigvals(a)?, which returns them as a complex value with re and im arrays. The call numerics::ctrb_rank(a, b)? returns the controllability rank, 4 here.Luau does not have ctrb_rank.

The open-loop response is the linearized model released from 0.1 rad with no control. The angle grows to 13.1 rad at 1 s. That number is far outside the range where a linear model means anything: the linear model keeps growing where a real pendulum would have fallen over, so read the curve only for its direction and its rate at small angles. The plot limits its upper panel to 0.5 rad so that the closed-loop trace stays readable; the open-loop trace leaves that panel at about 0.41 s (read from the series). The lower panel shows the same series on the full range.

-0.100.10.20.30.40.5pendulum angle (rad)open loop, linearized modelclosed loop with the LQR gainopen loop leaves the plot at 0.41 s00.20.40.60.81051013.1pendulum angle (rad)time (s)13.1 rad at 1 ssame series, full range: a linear model has no meaning at these angles
The pendulum released from 0.1 rad, open loop against closed loop, drawn from control_pendulum_open_loop_initial.csv and lqr_cart_pendulum_initial.csv, series the library wrote on real runs. The open-loop series is the linearized model with no control; it reaches 13.1 rad at 1 s, far outside the range where a linear model means anything. The upper panel limits the axis to 0.5 rad so the closed-loop trace stays readable; the lower panel shows the full range.

Step 3: Design the Gain

The weights are Q = diag(5000, 0, 100, 0) and R = 1. Q penalizes the cart position (5000) and the pendulum angle (100) and leaves the two velocities free; R is 1 on the force. The example source gives the reason: position is weighted 50 times the angle because the cart has to track its reference while the angle only has to stay small. The angle does not stay negligible. For the 0.2 m cart step below, the pendulum swings to 0.16 rad (9.3 degrees), because the cart must first move the wrong way to tip it. These are the CTMS weights.

Calling lqr on the state-space model with Q and R returns the gain, and the example compares it with the published CTMS gain:

EntryCart positionCart speedAngleAngular speed
K from lqr-70.71067811865464-37.83445399345578105.5297819160366520.923843749209908
Published MATLAB K-70.7107-37.8345105.529820.9238

The largest difference is 4.60e-5. The published values have four decimals, so a difference of that size is rounding in the published numbers. The example asserts that the gain is within 1e-4 of the published one. The relative Riccati residual is 6.97e-15, which is how well the computed solution satisfies the equation.

The script call is one line after the weights. The gain it returns is the row ctl.k[1]ctl["k"][0]. The script lqr runs the same continuous Riccati solver with the same default method as the call the example makes, on the same A, B, Q and R, so the four numbers match the table above:

Luau
local Q = {{5000, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 100, 0}, {0, 0, 0, 0}}
local ctl = Numerics.lqr(A, B, Q, {{1}})
local K = ctl.k[1]
print(K[1], K[2], K[3], K[4])   -- about -70.7107, -37.8345, 105.5298, 20.9238
Rune (inside a function)
let q = [
    [5000.0, 0.0, 0.0, 0.0],
    [0.0, 0.0, 0.0, 0.0],
    [0.0, 0.0, 100.0, 0.0],
    [0.0, 0.0, 0.0, 0.0],
];
let ctl = numerics::lqr(a, b, q, [[1.0]])?;
let k = ctl["k"][0];
log_info(`K = ${k[0]}, ${k[1]}, ${k[2]}, ${k[3]}`);   // about -70.7107, -37.8345, 105.5298, 20.9238

Step 4: Close the Loop and Simulate

With u = -K x the closed loop is A - B K. Its poles, from the same run, are two complex pairs: -8.491 plus or minus 7.928 j and -4.759 plus or minus 0.831 j. All four are in the left half-plane, and the unstable pole of the open loop has moved from +5.565 to a stable position. The map below shows the open-loop poles as crosses and the closed-loop poles as circles. A script reads the closed-loop poles from the field eigenvalues of the lqr result, a complex value with re and im arrays.

-10-8-6-4-22460-8-4048real part (1/s)imaginary part (rad/s)unstable, +5.565open loop0-0.1428-5.604+5.565 (unstable)closed loop-8.491 +/- 7.928 j-4.759 +/- 0.831 jall four in the left half-plane
Open-loop poles (crosses) and closed-loop poles (circles) of the pendulum on a cart, from the pole lists the LQR example printed on its real run. The unstable open-loop pole at +5.565 is ringed. Both axes use the same scale.

To move the cart to a position, the example scales the reference with a gain Nbar, so that the closed loop is x' = (A - B K) x + B Nbar r. Nbar is the reciprocal of the closed-loop steady-state gain from reference to cart position, and it comes out at -70.7107, the CTMS value as well. The example then simulates a 0.2 m step of the cart position with lsim over 0 to 5 s at a step of 0.01 s (501 samples, zero-order hold on the input), and measures the cart position with stepinfo against a final value of 0.2:

MeasureValue
Rise time (10 % to 90 %)0.412 s
Settling time (2 %)1.038 s
Overshoot0.00 %
Undershoot29.05 %
Peak pendulum angle (magnitude)0.1623 rad
-0.100.10.2cart position (m)target 0.2 mfirst moves back (undershoot)-0.2-0.100.1pendulum angle (rad)peak -0.1623 rad012345-15-10-505force (N)time (s)first sample -14.14 N
The closed-loop response to a 0.2 m cart step, drawn from lqr_cart_pendulum_step.csv, the series the LQR worked example wrote on its real run (501 samples, 0 to 5 s). Each trace is thinned to at most 200 points with the peaks kept. Top: cart position. Middle: pendulum angle. Bottom: the force from u = -K x plus the reference term.

A script simulates the closed loop with an ODE solver. The derivative callback applies u = -K x and returns the derivative of the state: it takes the time and the state array, and returns an array with one value per state. The snippet below integrates the linear closed loop x' = A x + B u written out term by term, from the pendulum released at 0.1 rad, over 0 to 5 s; the options are the tolerances the example used. The result has the fields t, y, nfev, accepted and rejected, and y[k] is the state at t[k]. The option t_eval asks for the output at times you choose.

Luau
local function closedLoop(t, y)
    local u = -(K[1] * y[1] + K[2] * y[2] + K[3] * y[3] + K[4] * y[4])
    local dy = {}
    for i = 1, 4 do
        dy[i] = A[i][1] * y[1] + A[i][2] * y[2] + A[i][3] * y[3] + A[i][4] * y[4] + B[i][1] * u
    end
    return dy
end

local sol = Numerics.ode45(closedLoop, {0, 5}, {0, 0, 0.1, 0}, {rtol = 1e-8, atol = 1e-10})
local last = sol.y[#sol.y]   -- the state at t = 5
Rune (inside a function)
let closed_loop = |t, y| {
    let u = -(k[0] * y[0] + k[1] * y[1] + k[2] * y[2] + k[3] * y[3]);
    let row = |i| a[i][0] * y[0] + a[i][1] * y[1] + a[i][2] * y[2] + a[i][3] * y[3] + b[i][0] * u;
    [row(0), row(1), row(2), row(3)]
};

let sol = numerics::ode45_with(closed_loop, [0.0, 5.0], [0.0, 0.0, 0.1, 0.0], #{rtol: 1e-8, atol: 1e-10})?;
let ys = sol["y"];
let last = ys[ys.len() - 1];   // the state at t = 5

In Rune the closed loop can also be built as a model and checked with the control routines. The block continues the script above: it forms A - B K as a state-space model with the cart position and the angle as outputs, asks whether it is stable, and releases it from 0.1 rad. The closed-loop poles are the ones listed earlier in this step, all in the left half-plane, so is_stable is true and the angle decays toward zero.

Rune (inside a function)
// closed loop A - B K, with the cart position and the angle as outputs
let acl = [
    [a[0][0] - b[0][0] * k[0], a[0][1] - b[0][0] * k[1], a[0][2] - b[0][0] * k[2], a[0][3] - b[0][0] * k[3]],
    [a[1][0] - b[1][0] * k[0], a[1][1] - b[1][0] * k[1], a[1][2] - b[1][0] * k[2], a[1][3] - b[1][0] * k[3]],
    [a[2][0] - b[2][0] * k[0], a[2][1] - b[2][0] * k[1], a[2][2] - b[2][0] * k[2], a[2][3] - b[2][0] * k[3]],
    [a[3][0] - b[3][0] * k[0], a[3][1] - b[3][0] * k[1], a[3][2] - b[3][0] * k[2], a[3][3] - b[3][0] * k[3]],
];
let cl = numerics::Ss::new(acl, b, [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], [[0.0], [0.0]])?;
let stable = cl.is_stable()?;                                  // true: all four poles in the left half-plane
let free = numerics::initial(cl, [0.0, 0.0, 0.1, 0.0])?;       // released from 0.1 rad, #{t, y, x}
let ys = free["y"];
let last_row = ys[ys.len() - 1];                                  // [cart position, angle] at the last sample
log_info(`stable ${stable}, angle at the end ${last_row[1]}`);

The nonlinear check in the example puts the full equations of motion of the pendulum, with the sine and cosine of the angle, in the same callback and leaves the call as it is. A Luau script cannot pass event functions or a Jacobian to the solver; Rune has the ode45_events family of solvers for events, and the stiff ones also take a user Jacobian.

Step 5: What to Look At

The cart does not move straight to the target. The undershoot of 29.05 % means it first moves away from the target, to about -0.058 m in the position series, and only then moves toward 0.2 m. The example source gives the reason: the cart must first move the wrong way to tip the pendulum. The first sample of the force is -14.14 N, the reference gain times the 0.2 m step, and the force swings positive to about 5.06 N before settling (these two force figures are read from the force series, not from the log). The example places no limit on the force.

The gain is designed on the linear model. The nonlinear check releases the pendulum from 0.1 rad with the gain in the loop, once on the linear model (with initial) and once on the full nonlinear equations of motion (with the ode45 solver, relative tolerance 1e-8 and absolute tolerance 1e-10, 175 steps and 1058 right-hand-side evaluations). The two angles differ by at most 1.16e-3 rad, and the nonlinear state at the end of the run is of the order of 1e-10 in every component, so the linear gain brings the nonlinear plant to rest as well.

-0.08-0.0400.040.080.12pendulum angle (rad)linear modelnonlinear plant012345-101nonlinear minus linear (mrad)time (s)largest 1.16 mrad at 0.21 s
The pendulum released from 0.1 rad with the LQR gain, drawn from lqr_cart_pendulum_initial.csv, the series the worked example wrote on its real run. The linear model and the nonlinear plant overlap; the lower plot is their difference in milliradians.

How far from upright the linear gain still works was checked on a grid. The example releases the nonlinear plant from 0.1 rad, 0.2 rad and so on up to 1.5 rad, simulates 10 s with the same gain, and counts a release as recovered when every state is below 1e-3 in magnitude at the end. It stops at the first release that fails. The largest release angle on that grid that the linear gain recovers is 0.5 rad.

14Worked Example: PID on a DC Motor

The motor is the one in the University of Michigan Control Tutorials for MATLAB and Simulink (CTMS), DC Motor Speed. Everything below is from a real run of the example.

The example uses the transfer function type, pidtune, step, stepinfo, the Bode data and DiscretePid. Rune calls all of them, so each step below has a Rune block that follows the example. Luau has none of them, so there is no Luau block. The blocks form one script: the first opens on_init, each next one continues it, and the last closes it. Each call shape is one the binding tests run or the binding source defines.

Step 1: The Model

A brushed DC motor driven by a voltage, with speed as the output. The electrical side (resistance and inductance) and the mechanical side (inertia and friction) combine into a second-order transfer function.

ParameterMeaningValue
JRotor inertia0.01 kg m^2
bViscous friction0.1 N m s
KMotor constant (N m/A and V s/rad)0.01
RArmature resistance1 ohm
LArmature inductance0.5 H

From armature voltage to speed the transfer function is P(s) = K / ((J s + b)(L s + R) + K^2). Expanded, the numerator is 0.01 and the denominator is 0.005 s^2 + 0.06 s + 0.1001, with coefficients in the order highest power first. The example builds the transfer function and converts it to state space for the simulations.

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    // P(s) = 0.01 / (0.005 s^2 + 0.06 s + 0.1001)
    let plant = numerics::Tf::new([0.01], [0.005, 0.06, 0.1001])?;

Step 2: Check the Open Loop

The plant poles are -9.9975 and -2.0025 (1/s): two real, stable poles. The steady-state gain is 0.0999 rad/s per volt. The plant margins are an infinite gain margin and an infinite phase margin, because the plant gain never reaches 1.

CaseRise timeSettling time (2 %)OvershootFinal value
Open loop, 1 V step1.1350 s2.0652 s0.000 %0.09990 rad/s
Unity feedback, no controller, 1 rad/s step1.0160 s1.8470 s0.000 %0.09083 rad/s

Closing the loop around the bare plant does not fix it. With a reference of 1 rad/s the speed settles at 0.09083 rad/s, a steady-state error of 90.9 %. A controller has to add gain and an integrator.

Rune (continues the function)
    let poles = plant.poles()?;
    let gain = plant.dcgain();
    let pm = numerics::margin(plant)?;
    log_info(`plant pole real parts ${poles["re"][0]} and ${poles["re"][1]}, dc gain ${gain}`);
    log_info(`plant gain margin ${pm["gm"]}, phase margin ${pm["pm"]}`);   // both infinite

Step 3: Tune the Controller

pidtune is called for a PID controller with a target crossover of 20 rad/s and a phase margin of 60 degrees. It returns Kp = 198.918048, Ki = 1201.774293 and Kd = 8.231244. With the ideal PID (no derivative filter) the loop has an infinite gain margin and a phase margin of 60.000000 degrees at 20.000000 rad/s, exactly the target.

The example then adds a derivative filter, because a real controller filters the derivative, with a time constant of 0.005 s (1 / (10 times the crossover)). The loop margin becomes 58.5598 degrees at 20.9705 rad/s, still an infinite gain margin. Everything after this point uses the filtered controller.

In Rune pidtune_with takes the crossover as an option, the result holds a Pid, and a new Pid with the filter constant 0.005 s gives the filtered controller. Pid::new reads the three gains from the fields of the tuned Pid:

Rune (continues the function)
    let tuned = numerics::pidtune_with(plant, "pid", 60.0, #{crossover: 20.0})?;
    let ideal = tuned["pid"];
    let pid = numerics::Pid::new(ideal.kp, ideal.ki, ideal.kd, 0.005)?;   // add the derivative filter
    let loop_tf = pid.to_tf()?.series(plant)?;
    let lm = numerics::margin(loop_tf)?;
    log_info(`Kp ${pid.kp}, Ki ${pid.ki}, Kd ${pid.kd}`);
    log_info(`filtered loop: phase margin ${lm["pm"]} at ${lm["wcp"]} rad/s`);

Step 4: Close the Loop and Measure

The closed-loop poles are -180.7436, -9.9817 plus or minus 11.6566 j, and -11.2930, all stable. The 1 rad/s step response, measured with stepinfo against a final value of 1:

LoopRise timeSettling time (2 %)OvershootPeakFinal value
PID, continuous0.0579 s0.3105 s21.353 %1.21353 at 0.152 s1.00000
PID, sampled at 1 kHz0.0553 s0.3053 s22.247 %1.22247 at 0.148 s1.00000

The overshoot is 21.353 %: the speed rises to 1.21353 rad/s before settling at 1. The tuning targets name a crossover and a phase margin only. Overshoot was not a target, and the example does not reduce it. The final value is 1.00000, so the integral action removes the 90.9 % error.

For the load disturbance the example adds a unit step to the plant input, a load in volts, and takes the response from the disturbance to the speed. The peak speed error is 0.00400 rad/s at 0.144 s, and 2.45e-14 rad/s is left at 3 s. The controller rejects the disturbance.

00.511.522.5300.51speed (rad/s)time (s)no controller (unity feedback)PID, continuous00.10.20.30.40.50.600.51speed (rad/s)time (s)continuoussampled at 1 kHzsampled, limited to 24 Vpeak 1.2135 at 0.152 slimited peak 1.0266 at 0.482 s (dot)00.20.40.60.8100.0020.004speed error (rad/s)time (s)peak 0.00400 at 0.144 s00.10.20.30.40.50.6050010001500voltage command (V)time (s)unlimited: first command 1571.4 Vno limitlimited to 24 V00.10.20.30.40.50.6-24024voltage command (V)time (s)limit +24 V and -24 V
Step responses of the motor speed loop, drawn from pid_dc_motor_step.csv, the series the PID worked example wrote on its real run (3001 samples, 0 to 3 s). Top: unity feedback without a controller against the PID loop, for a 1 rad/s reference. Second: the first 0.6 s of the PID loop, continuous, sampled at 1 kHz, and sampled with the voltage limited to plus or minus 24 V, with the 2 % band. Third: the speed error after a unit voltage disturbance at the plant input. Fourth: the voltage command at 1 kHz with no limit and with the 24 V limit. Bottom: the same command zoomed to plus or minus 30 V, where the unlimited command leaves the plot at the top. The open-loop 1 V step (0.0999 rad/s final value, a different input) is left out; its figures are in the table above.
Rune (continues the function)
    let closed = loop_tf.feedback(1.0, -1.0)?;
    let info = numerics::stepinfo_sys(closed)?;
    log_info(`rise ${info["rise_time"]}, settling ${info["settling_time"]}, overshoot ${info["overshoot"]} %`);
    log_info(`peak ${info["peak"]} at ${info["peak_time"]}, final ${info["final_value"]}`);

Step 5: Limit the Supply Voltage

The unlimited sampled loop asks for 1571.4 V on its first command. The example's log says why: it is the derivative term reacting to the step in the reference, and that first command is also the largest. The command then falls, swings to about -26 V, and settles to about 10.0 V at 3 s, the voltage that holds 1 rad/s on the plant (1 / 0.0999); the swing and the final value are read from the series, not the log. A real supply cannot deliver 1571.4 V.

The example therefore runs the 1 kHz loop again with the controller output limited to plus or minus 24 V. The sampled PID block takes the limits as an option, and while its output is saturated it holds the integrator (conditional integration), which is the anti-windup. The example does not state why it uses 24 V. Both sampled runs, measured against a final value of 1:

Sampled loop at 1 kHzRise timeSettling time (2 %)OvershootPeakFinal value
No voltage limit0.0553 s0.3053 s22.247 %1.22247 at 0.148 s1.00000
Limited to plus or minus 24 V0.2694 s0.5375 s2.660 %1.02660 at 0.482 s1.00000

The limit is active for 292 of 3001 samples, which is 0.292 s, and the final speed is 1.00000 rad/s. The loop still settles on the reference, so the integrator did not wind up. The limit makes the start slower: the rise time grows from 0.0553 s to 0.2694 s and the settling time from 0.3053 s to 0.5375 s. The overshoot is 2.660 % against 22.247 %. In the figure under Step 4, the second panel draws the limited speed beside the other two, and the bottom two panels draw the voltage command with and without the limit; the limited command is 24 V on the first sample.

The sampled loop in Rune puts the plant in a DiscreteStepper and the controller in a DiscretePid with limits. c2d on the Tf gives a discrete Tf, which DiscreteStepper::new accepts, and with_limits(min, max) returns a copy whose output is clamped, with anti-windup:

Rune (ends the function)
    // the sampled loop at 1 kHz: the plant in a DiscreteStepper, the controller a DiscretePid
    let ts = 0.001;
    let sim = numerics::DiscreteStepper::new(numerics::c2d(plant, ts, "zoh")?)?;
    let ctrl = numerics::DiscretePid::new(pid, ts)?.with_limits(-24.0, 24.0)?;   // drop with_limits for the unlimited run
    let y = 0.0;
    for k in 0..3001 {                          // 3001 samples, 0 to 3 s
        let u = ctrl.step(1.0 - y)?;            // error = reference - speed
        y = sim.step(u)?[0];                    // the command reaches the plant on the next sample
    }
    log_info(`speed after 3 s ${y}`);
}

Step 6: What to Look At

The margins come from the Bode data of the loop (the controller with its derivative filter times the plant). The phase margin of 58.5598 degrees is measured at the gain crossover of 20.9705 rad/s; the plot marks both.

-60-40-20020406080magnitude (dB)gain crossover 20.9705 rad/s (0 dB)0.11101001000-180-150-120-90-60phase (deg)angular frequency (rad/s)-180 degphase margin 58.5598 deg
Bode magnitude and phase of the open loop (PID with derivative filter times the motor), drawn from pid_dc_motor_loop_bode.csv, the series the PID worked example wrote on its real run (400 points, 0.1 to 1000 rad/s). The gain crossover (20.9705 rad/s) and the phase margin (58.5598 degrees) are the figures the example printed, marked on the curve.

The example discretizes the loop at 1 kHz. The plant is converted with c2d using zero-order hold and run in a DiscreteStepper, and the controller is a DiscretePid with the same gains and filter. As the example orders the calls, a command computed at one sample reaches the plant at the next. The sampled step is in the table above: a rise time of 0.0553 s, 22.247 % overshoot, and the largest difference from the continuous closed-loop step is 0.0198 rad/s. At 1 kHz the sampled loop follows the continuous design closely.

15In a Space

Running a Controller Each Frame

Three blocks are built to run once per sample inside a loop: DiscreteStepper, DiscretePid and IirFilter. Each keeps its own state between calls, and in Rust it does not allocate when it steps. A DiscreteStepper advances a discrete state-space model one sample, taking an input and writing an output; it can report, set and zero its state. A DiscretePid takes the error (setpoint minus measurement) and returns the control output, using a Tustin integrator, a filtered backward-Euler derivative, an optional output clamp and conditional-integration anti-windup. An IirFilter processes one sample of a digital filter. The motor example above runs its sampled loop with the first two.

In Rune the three blocks are types, built with DiscreteStepper::new(sys), DiscretePid::new(gains, ts) and IirFilter::new(b, a), and each has a step method (the type table under Calling the Library from a Script lists the rest). A Rune call returns a new number or array on every step.

Luau does not have these three blocks.

Design calls do not belong in the frame loop. A 200 by 200 eigenproblem takes about 18 ms and a 100-state Riccati solve about 60 ms, which is too long for a frame at 60 Hz. Design the controller outside the loop (at load, or when a parameter changes), and run only the per-sample blocks inside it. For timings, see Performance.

A script applies a state-feedback controller with ordinary arithmetic. Compute the gain once, with lqr for a continuous design or with c2d and dlqr for a discrete one, keep the row k in a variable, and apply u = -K x with plain multiplication and addition each step. For where per-frame code runs and where it keeps its state between frames, see Scripting.

The times quoted above are of the Rust routines called directly. A script call adds the cost of converting tables to matrices and back, and a script callback runs once per evaluation. That cost is not measured on this page.

16What's Next

Related Pages

The dense linear algebra behind these routines, the eigenvalue and Schur factorizations that the Riccati solvers use, is in Linear Algebra and Polynomials. Simulating a model that is not linear, as the pendulum check does, uses the solvers in Differential Equations. Filters and sample-by-sample processing are in Calculus and Signal. Timings and the accuracy tables are in Performance. The conventions for calling the library from Luau and Rune are in the Numerics overview.

Model it, check it, design it, then verify the closed loop.

Loading Eustress Engine...