Control Systems

A transfer function in Leonardo is an ordinary expression — a Ratio of polynomials in a variable you name. There is no TransferFunction type, no model object, and nothing to construct: 1/(s+1) is one, and so is anything the rest of the library produces that happens to be rational.

That is a deliberate decision, and it has a visible consequence in every signature on this page: the frequency variable is always an explicit argument, because a plain Ratio carries no type to dispatch on. You write poles(g, s), never g.poles.

import it.grypho.scala.leonardo.core.*
import it.grypho.scala.leonardo.control.*
import it.grypho.scala.leonardo.parser.Parser

val env = new Environment()
val s   = _Variable("s")
val t   = _Variable("t")
val z   = _Variable("z")

def tf(src: String): _Expression = Parser.parse(src).get

Why there is no carrier

The argument for a dedicated type is real: it would let the frequency variable be implicit and would give G * H a meaning. The argument against it won, on three counts.

A carrier would be a wall. simplify, derive, integrate, substitute, the exact tier and the parser all operate on expressions; a transfer function that is not one would need each of them taught about it, or would be cut off from all of them. As an expression, a transfer function is differentiable, simplifiable, exactly representable and printable for free.

The one thing a carrier genuinely buys — a result that is a single tidy fraction rather than a nested one — is supplied here instead: every interconnection returns N(s)/D(s) in lowest terms.

And the cost of the decision is paid in documentation, which is what this page is.

Interconnection

Three connections, each returning one normalised rational.

series(tf("1/(s+1)"), tf("2/(s+3)"), s).toString
// res0: String = "(2.0 / ((3.0 + (4.0 * s)) + (s ^ 2.0)))"
parallel(tf("1/(s+1)"), tf("1/(s+2)"), s).toString
// res1: String = "((3.0 + (2.0 * s)) / ((2.0 + (3.0 * s)) + (s ^ 2.0)))"

feedback is negative feedback, G/(1 + G·H):

feedback(tf("1/(s*(s+2))"), _Number(1), s).toString
// res2: String = "(1.0 / ((1.0 + (2.0 * s)) + (s ^ 2.0)))"

The sign convention is stated because it cannot be inferred. Negative feedback is the control convention and what a unity-feedback loop means by default, but a substantial part of the literature writes the positive form G/(1 − G·H). For positive feedback, negate h. This is the same care the spherical polar angle convention needed: choosing silently would make every closed-loop result wrong for half its readers.

Notice what the closed loop above returned: 1/(s² + 2s + 1), not (s² + 2s)/((s² + 2s)(s² + 2s + 1)). The common factor is divided out, because otherwise the poles would come back as {0, −2, −1, −1} — a confident answer to a different question.

Poles, zeros and stability

poles(tf("(s+2)/((s+1)*(s+3))"), s).map(_.mkString(", "))
// res3: Option[String] = Some("-1.0, -3.0")
zeros(tf("(s+2)/((s+1)*(s+3))"), s).map(_.mkString(", "))
// res4: Option[String] = Some("-2.0")
dcgain(tf("5/(s+2)"), s)
// res5: Option[Double] = Some(2.5)

Poles are _Values, not Doubles, because a complex pole is the interesting case — an oscillatory mode is a conjugate pair, and reducing the result to reals would silently drop exactly the systems control theory is about.

poles(tf("1/(s^2 + 1)"), s).map(_.mkString(", "))
// res6: Option[String] = Some("i, -i")

Stability is decided from the poles, strictly:

isStable(tf("1/(s^2 + 3*s + 2)"), s)
// res7: Option[Boolean] = Some(true)
isStable(tf("1/(s - 1)"), s)
// res8: Option[Boolean] = Some(false)
isStable(tf("1/(s^2 + 1)"), s)
// res9: Option[Boolean] = Some(false)

The last one is the marginal case, and it is false. An oscillator that never decays is not a stable system. A Routh array is available as routhTable(g, s) for inspecting a margin by hand, at the prompt too, under that name (routh stays an ordinary variable name, since it shipped unreserved) — but isStable does not consult it: Routh’s degenerate cases (a zero in the first column, an identically zero row) each need their own repair, and a mishandled one yields a wrong verdict rather than a refusal. Root location has neither failure mode.

Time response

stepResponse(tf("1/(s+1)"), s, t).toString
// res10: String = "(1.0 + (-1.0 * exp((-1.0 * t))))"
impulseResponse(tf("2/(s+3)"), s, t).toString
// res11: String = "(2.0 * exp((-3.0 * t)))"

These are the inverse Laplace transform of G(s)/s and of G(s) — almost entirely a re-spelling of machinery that already existed. The response variable t is free in the result, so it can be evaluated, plotted with sample, or differentiated like any other expression.

Frequency response

bode(tf("1/(s+1)"), s, 1.0)
// res12: Option[Tuple2[Double, Double]] = Some(
//   (0.7071067811865476, -0.7853981633974483)
// )
nyquist(tf("1/(s+1)"), s, 1.0)
// res13: Option[Tuple2[Double, Double]] = Some((0.5000000000000001, -0.5))

(magnitude, phase-in-radians) — the data of a Bode plot — and (real, imaginary) — the data of a Nyquist plot — one computation presented two ways. At the corner frequency of a first-order lag the magnitude is 1/√2 (−3 dB) and the phase −45°, as it should be. The whole of the frequency response is a single substitution s → iω riding the existing complex closure; no new arithmetic was written for it.

An integrator has no finite response at ω = 0, and that is reported as absence rather than a fabricated infinity:

bode(tf("1/s"), s, 0.0)
// res14: Option[Tuple2[Double, Double]] = None

Sweeping a band

bode and nyquist answer for one frequency. A diagram needs a vector, and it needs two things that a plain sample cannot give it:

frequencyResponse(tf("1/(s+1)"), s, 0.1, 10.0, 5, new Environment())
// res15: Vector[Tuple3[Double, Double, Double]] = Vector(
//   (0.1, -0.04321373782642559, -5.710593137499643),
//   (0.31622776601683805, -0.41392685158225007, -17.548400613792307),
//   (1.0000000000000004, -3.0102999566398143, -45.00000000000001),
//   (3.162277660168381, -10.413926851582255, -72.45159938620772),
//   (10.0, -20.043213737826427, -84.28940686250037)
// )

(ω, magnitude in dB, phase in degrees) — dB and degrees because that is what a Bode plot is; the raw pair stays available from bode itself.

The grid is geometric, not linear. A frequency response is read across decades, so a linear grid of 200 points over 0.01 .. 100 would put 199 of them in the last decade and none near a corner at 0.1 — the interesting part of the curve is exactly the part it fails to resolve.

The phase is unwrapped, and this is the substance. atan2 has principal value (−π, π], so a swept curve jumps a full turn wherever it crosses the branch cut. That jump is an artefact of the arctangent, not of the plant. A third-order lag tends to −270°:

frequencyResponse(tf("1/(s+1)^3"), s, 1.0, 100.0, 3, new Environment()).map(_._3)
// res16: Vector[Double] = Vector(
//   -135.0,
//   -252.86822058750113,
//   -268.2811839069496
// )

A raw sweep would report the last of those as +90. One caveat worth stating: unwrapping cannot tell a genuine half-turn step from a grid too coarse to resolve a fast one, so a sparse sweep across a lightly damped resonance can unwrap the wrong way — the remedy is points.

nyquistSweep reads the same grid and returns (real, imaginary), the one sweep presented two ways that bode and nyquist already are.

Both take an Environment, so a plant carrying a bound parameter folds — which is what lets the browser REPL draw a diagram from a session where you wrote K := 10 first. There, bode G s 0.01 100 and nyquist G s 0.01 100 draw them.

State space

A state-space model is a 1×4 row of matrices — the same shape lu, qr and eig return — so at(m, 1, k) indexes it and a session :save round-trips it with no new machinery. Controllability asks whether the input can steer every state; observability whether the output can distinguish them:

controllable(tf("[[0, 1], [-2, -3]]"), tf("[[0], [1]]"))
// res17: Option[Boolean] = Some(true)
controllable(tf("[[1, 0], [0, 2]]"), tf("[[1], [0]]"))
// res18: Option[Boolean] = Some(false)

Observability is defined as controllability of the dual pair (Aᵀ, Cᵀ) rather than restated, so the two can never disagree.

Both answers are independent of the units the model is written in, which is less obvious than it sounds. Rank is decided by QR of the transposed controllability matrix, not by det(M·Mᵀ) against a threshold: a determinant scales like ‖M‖^(2n), so with the older test the same plant with B in millivolts rather than volts came back uncontrollable. Scaling B cannot change which states the input can reach, and the tests pin that it does not.

Linearising a nonlinear model

A grey-box plant x' = F(x, u), y = G(x, u) reaches the linear machinery above through its linearisation at an operating point. linearize(F, G, x, u, x0, u0) returns the state-space row [[A, B, C, D]] with A = ∂F/∂x, B = ∂F/∂u, C = ∂G/∂x and D = ∂G/∂u at (x0, u0), so A, B, C, D := linearize(…) binds the four. Here the pendulum at rest:

tf("linearize([[x2], [-sin(x1) + u]], [[x1]], [[x1], [x2]], u, [[0], [0]], 0)").eval(env).toExpression.toString
// res19: String = "[[[[0.0, 1.0], [-1.0, 0.0]], [[0.0], [1.0]], [[1.0, 0.0]], [[0.0]]]]"

The state and input names are an ordered tuple — a column of names, or one bare name — and the column order of A is the order given, never inferred. At a point that is not an equilibrium the model needs its offsets too: linearize(…, affine) appends F0 = F(x0, u0) and G0 = G(x0, u0), giving [[A, B, C, D, F0, G0]] for x' ≈ A·δx + B·δu + F0. A point with a free parameter gives a symbolic linearisation, and exact input stays exact.

It declines rather than linearising where the model is not defined: a point outside the domain of F or G (ln of a negative), and a value or derivative that is not a real number there (abs(x) has no derivative at 0), each with the entry named.

Prediction matrices for MPC

A model-predictive controller writes the outputs over a prediction horizon Np as Y = Φ·x + Γ·U, where U holds the next Nc input moves. mpcMatrices(A, B, C, Np, Nc) returns the row [[Phi, Gamma]] — the lu/stateSpace shape, so Phi, G := mpcMatrices(…) binds both at the prompt:

tf("mpcMatrices(0.5, 1, 1, 3, 2)").eval(env).toExpression.toString
// res20: String = "[[[[0.5], [0.25], [0.125]], [[1.0, 0.0], [0.5, 1.0], [0.25, 1.5]]]]"

Φ stacks C·Aⁱ for i = 1..Np; Γ’s block (i, j) is C·Aⁱ⁻ʲ·B below the diagonal and zero above it. The last column accumulates: past Nc the last move is held, so that column is Σ C·Aᵏ·B — the 1.5 above is 1 + 0.5. That is stated because the other common convention, moves beyond Nc set to zero, gives a different Γ for the same plant. A number is read as a 1×1 matrix, as here; a name with no value yet is never guessed to be one. The matrices are built from ordinary products and the block-matrix words (hcat, vcat, blkdiag, kron, submatrix — see Matrices), so exact input gives exact Φ and Γ.

From a program: the MPC building blocks

A controller running in a loop needs numbers, not expressions, so the library also offers the pieces of an MPC step as Scala functions (no prompt form):

  • mpcPrediction(A, B, C, Np, Nc, limits) gives Φ and Γ as dense matrices, in the convention above; mpcIncrementalPrediction the Δu form y = Φ·x + Ψ·u(k−1) + Θ·Δu, in which the input weight acts on the moves and a constant reference is tracked without offset.
  • mpcQp(prediction, Q, R, reference, x, uPrev, bounds, limits) assembles the quadratic programme with bounds on u, Δu and y; output bounds may be soft, one slack per output with a linear and a quadratic penalty, so a disturbance that makes them unreachable relaxes them instead of leaving no answer. solve(warm, env) runs qpSolve and returns the first input, the moves and the slacks.
  • augmentDisturbance(A, B, C, Bd, Cd, env) — or inputDisturbanceModel / outputDisturbanceModel — adds integrating disturbances, declining an augmentation the outputs cannot observe (an output disturbance on a plant with an integrator, say); disturbanceObserver gives its Kalman gain, and steadyStateTarget the (x_s, u_s) that brings the outputs to the setpoint given the disturbance estimate, or the closest reachable one under input bounds. Together they remove the steady-state offset a mismatched model leaves.
  • mpcQp also takes an MpcWeights record: a weight per step or one for all, a terminal cost on x(k+Np) (its prediction from mpcTerminalPrediction) and, in the absolute form, an input target u_s. Without u_s the absolute form’s R pulls every input towards zero, so a plant that needs a non-zero steady input is tracked with an offset. The stage cost already counts y(k+Np), so the terminal weight that turns an unconstrained MPC into the LQR law is P − CᵀQC, P from dlqr.
  • arx2nmss(model, nk) realises an ARX model with the measured state [y(k), …, u(k−1), …], and arx2nmssIncremental the same in increments with y(k) appended, so a controller on either needs no observer; minreal(A, B, C, D, env) reduces any realisation to the states that reach its input-output map.
  • A model whose input is already an increment — arx2nmssIncremental’s, or any model that keeps u(k−1) in its state — is predicted with mpcAccumulatedPrediction(A, B, C, Np, Nc, limits). Its moves are increments, so mpcQp reads the u bounds as bounds on the actuator position u(k−1) + Δu(k) + … + Δu(k+j) and the Δu bounds as bounds on the moves, exactly as in the incremental form. Do not give such a model to mpcPrediction: that holds the last move over the rest of the horizon, which for an increment is a ramp of the input, and its u bounds would then bound the increments while nothing bounds the position.
  • In the two forms whose moves are increments, R weighs the moves and nothing weighs where the actuator sits. MpcWeights.positionTarget adds Σ ‖u(k+j) − u_s‖²_S on the positions, which settles a plant with more inputs than setpoints: one input as low as possible, say, and the others left to hold the outputs.

Identifying a model from data (ARX)

A black-box model can be learned from recorded inputs and outputs. An ARX model is written here in the predictor form

y[k] = a₁·y[k−1] + … + a_na·y[k−na] + b₁·u[k−nk] + … + b_nb·u[k−nk−nb+1]

and the sign of a is stated because it cannot be inferred: MATLAB’s arx writes A(q) = 1 + a₁q⁻¹ + …, so its coefficients are the negatives of these (a_MATLAB = −a). The predictor sign is the one every recurrence and regression in this library already uses. arx(u, y, na, nb, nk) fits [[a, b]] by least squares; here noise-free data from y[k] = 0.8·y[k−1] + 0.5·u[k−1]:

val u = Vector.tabulate(40)(k => math.sin(0.7 * k) + ((k * 7919) % 11 - 5) / 5.0)
val y = u.indices.foldLeft(Vector.empty[Double]) { (acc, k) =>
  acc :+ (if k == 0 then 0.0 else 0.8 * acc(k - 1) + 0.5 * u(k - 1))
}
arx(_MatrixValue(1, 40, u.toArray), _MatrixValue(1, 40, y.toArray), 1, 1, 1, env)
// res21: Either[ArxFailure, ArxModel] = Right(
//   ArxModel(
//     a = Vector(0.8000000000000003),
//     b = Vector(Vector(0.5000000000000001))
//   )
// )

u is m×N (a row per input) or N×m, so a plant with several inputs fits in one call and b comes back nb×m, a column per input. The delay nk is an argument of the converters, visible where it acts, so b holds exactly what was estimated: arx2tf(a, b, nk, z) gives the discrete transfer function, whose pole is the 0.8 above, and arx2ss(a, b, nk) a state-space row [[A, B, C, D]] (the observer canonical form).

arx2tf(Vector(0.8), Vector(Vector(0.5)), 1, z).map(_.map(_.toString))
// res22: Either[ArxFailure, Vector[String]] = Right(
//   Vector("(0.5 / (-0.8 + z))")
// )
arx2tf(Vector(0.8), Vector(Vector(0.5)), 1, z).toOption.flatMap(gs => poles(gs.head, z))
// res23: Option[Vector[_Value]] = Some(Vector(_Number(0.8)))

It declines data that does not excite the model rather than fitting it. The regressor matrix must have full numerical rank at the session precision — the relative tolerance rank uses — before least squares is asked: QR alone answers a barely varying input with numbers that describe rounding, not the plant. A series too short for the orders declines too, and the REPL says which. With na = 0 there is no a, and arx returns 0 in its place, the absent-group convention of qp.

Several outputs are one model, not one call each. With y p×N (a row per output; the samples run along the longer side, so a row or a column is still one output) each output is regressed on the past of every output, and the model is y[k] = A₁·y[k−1] + … + B₁·u[k−nk] + … with p×p blocks Aᵢ coupling the outputs — what a set of single-output fits cannot see. arx then returns the blocks stacked: a is (na·p)×p = [A₁; A₂; …] and b is (nb·p)×m = [B₁; B₂; …], which at one output are exactly the shapes above; with na = 0, a is zeros(p, p), since a bare 0 would read as one output. The converters recognise a model with several outputs by its a: arx2tf gives the p×m transfer matrix A(z)⁻¹B(z) (up to six outputs, by cofactor expansion), and arx2ss the block observer form, p·max(na, nb + nk − 1) states. That realisation is not minimal — it is exact and simple, simulates identically, and controllable / observable show what is redundant. In Scala the model is arxMimo(u, y, na, nb, nk, env), an ArxMimoModel of blocks, which arx2tf and arx2ss also take. Choosing the orders. arxOrderSelection(u, y, nas, nbs, nks, criterion, validation, env) (Scala only) fits every (na, nb, nk) of a grid and ranks them by AIC, BIC or FPE, named by the caller; given validation data, the loss is measured there. Every candidate is scored on the same samples, so the losses compare; a candidate the data does not excite is skipped and listed with its reason; and an exact fit beats any other, the fewest coefficients winning a tie, so noise-free data from an ARX model returns its true orders. The grid is held to a work budget, Limit.MaxArxOrderWork. A recursive estimate updated each cycle is rlsUpdate over numbers, which answers with the reason when it declines.

Scoring a model on new data. arxPredictionError(model, nk, u, y, env) (Scala only) gives each output’s root-mean-square one-step error and the residual series on any window, the model’s own or one it was not fitted on: every sample is predicted from the measured samples before it, which is the loss the fit minimises and the order selection ranks by. arxSimulationError is the free run: only the first samples are measured and every later output is the model’s own, fed back, so an error the one-step prediction forgets at each sample accumulates. That is the stricter test, and the relevant one for a model that will predict over a horizon; a free run that leaves the finite numbers is declined.

Simulating a discrete model

dlsim(sys, u, x0) runs x[k+1] = A·x[k] + B·u[k], y[k] = C·x[k] + D·u[k] over the inputs u (m×N, column k is u[k]) from x[0] = x0, and returns the outputs p×N — the prediction-error metric a learned model is judged by. sys is the [[A, B, C, D]] row that stateSpace, linearize and arx2ss all build; x0 = 0 starts from rest, and D = 0 means no feedthrough. With the word states it returns [[Y, X]], and X runs from x[0] to x[N]: the final state is the one a simulation continues from, so a long run splits into calls with no gap — where MATLAB’s and scipy’s dlsim stop at x[N−1].

The identity that ties the two halves of this page together: a plant discretised by the zero-order hold and driven by a unit step reproduces the continuous step response at the sample instants.

c2dExact(tf("[[0, 1], [-2, -3]]"), tf("[[0], [1]]"), 0.1).flatMap { (ad, bd) =>
  dlsim(ad, bd, _MatrixValue(1, 2, Array(1.0, 0.0)), _MatrixValue(1, 1, Array(0.0)),
        _MatrixValue(1, 5, Array.fill(5)(1.0)), _MatrixValue(2, 1, Array(0.0, 0.0))).toOption
}.map(_._1.toVector)
// res24: Option[Vector[Double]] = Some(
//   Vector(
//     0.0,
//     0.0045279585030313565,
//     0.016429269939837794,
//     0.03358759736529535,
//     0.05434443602297149
//   )
// )
stepResponse(tf("1/(s^2 + 3*s + 2)"), s, t).eval(env.withBinding("t", _Number(0.4))).toExpression.toString
// res25: String = "0.05434"

An unstable model run long enough leaves the finite numbers; dlsim then declines and names the step, rather than answering with a matrix of Infinity.

LQR and the Kalman filter

dare(A, B, Q, R) solves the discrete algebraic Riccati equation AᵀPA − P − AᵀPB(R + BᵀPB)⁻¹BᵀPA + Q = 0 for its stabilising solution, and dlqr(A, B, Q, R) returns [[K, P]], the gain of the law u = −K·x that minimises Σ xᵀQx + uᵀRu. The sign is stated because the literature also writes u = K·x. The scalar case A = B = Q = R = 1 gives the golden ratio:

tf("dlqr(1, 1, 1, 1)").eval(env).toExpression.toString
// res26: String = "[[[[0.61803]], [[1.61803]]]]"

The solver is structure-preserving doubling, which needs only products and inverses. Its answer is certified twice: the equation’s residual against the = tolerance, and the closed loop A − B·K proved stable. So a problem with no stabilising solution is refused, never answered with one that does not stabilise: (A, B) not stabilisable, or an unstable mode Q does not penalise. R must be symmetric positive definite and Q symmetric positive semidefinite. dlyap(A, Q) solves the Stein equation A·X·Aᵀ − X + Q = 0 for a stable A.

The Kalman filter is the same equation in its dual form. kalmanGain(A, C, Qw, Rv) returns [[M, P]]: the steady-state measurement-update gain and the a priori error covariance. The model is x[k+1] = A·x + B·u + w, y = C·x + D·u + v, with process noise w ~ N(0, Qw) and measurement noise v ~ N(0, Rv). kalmanStep(xhat, P, u, y, sys, Qw, Rv) takes one update, then predict step on the model row and returns [[xhat', P']], the prior for the next step, so its output is its next input. Here a constant state, believed to be 0 with variance 100, is measured as 2.9 with unit noise; one step moves the estimate almost all the way to the measurement and shrinks the variance below one:

val one = tf("kalmanStep(0, 100, 0, 2.9, stateSpace(1, 0, 1, 0), 0, 1)").eval(env).toExpression
// one: _Expression = _Matrix(
//   rows = 1,
//   cols = 2,
//   elems = Vector([[2.87129]], [[0.9901]])
// )
one.toString
// res27: String = "[[[[2.87129]], [[0.9901]]]]"

The covariance update is the Joseph form, which stays symmetric positive semidefinite under rounding where the textbook (I − M·C)·P does not.

Discrete time

Discretisation always names its method — the zero-order hold Zoh or the bilinear (Tustin) transform Tustin. The same plant discretised the two ways has different discrete poles, so a silent default would make two correct-looking answers disagree with no way to see why.

c2d(tf("1/(s+1)"), s, z, 0.1, Tustin).map(_.toString)
// res28: Option[String] = Some("((1.0 + z) / (-19.0 + (21.0 * z)))")

Tustin is exactly invertible, which is what makes the round trip return to where it started. The result below is 2/(s+3) with a factor of -0.2 left in both numerator and denominator — Leonardo does not cancel a common numeric factor out of a fraction, so read the value, not the spelling:

val back = c2d(tf("2/(s+3)"), s, z, 0.05, Tustin).flatMap(d2c(_, z, s, 0.05, Tustin))
back.map(_.toString)
// res29: Option[String] = Some("(-0.4 / (-0.6 + (-0.2 * s)))")
back.map(_.eval(env.withBinding("s", _Number(1.0))))    // 2/(1+3) = 0.5
// res30: Option[Either[_Expression, _Value]] = Some(
//   Right(_Number(0.5000000000000003))
// )

Five more methods cover the rest of the usual menu, each with its convention stated:

Method Rule Note
Foh (z − 1)²/(Ts·z) · Z{L⁻¹[G/s²]}, the triangle hold keeps the DC gain
ImpulseInvariant Ts · Z{g(n·Ts)} aliases: faithful only well below π/Ts; needs no direct feedthrough
MatchedPoleZero roots mapped by e^(s·Ts), all but one zero at infinity to z = −1 gain matched at low frequency, integrators included
ForwardEuler s = (z − 1)/Ts can make a stable plant unstable: pole p goes to 1 + p·Ts
BackwardEuler s = (z − 1)/(Ts·z) keeps a stable plant stable

Prewarped Tustin is not a method of its own but Tustin with a frequency, c2dPrewarped(G, s, z, Ts, w). It matches the continuous response exactly at w, where plain Tustin, which squeezes the whole frequency axis into the Nyquist band, puts a filter’s corner somewhere else. Forward Euler shows its caveat on a fast pole:

c2d(tf("1/(s + 30)"), s, z, 0.1, ForwardEuler).flatMap(isStableDiscrete(_, z))
// res31: Option[Boolean] = Some(false)
c2d(tf("1/(s + 30)"), s, z, 0.1, BackwardEuler).flatMap(isStableDiscrete(_, z))
// res32: Option[Boolean] = Some(true)

d2c inverts the three substitutions — Tustin, both Euler methods — and d2cPrewarped the prewarped one; the response equivalences and matched pole-zero would need a logarithm and are declined.

Discrete stability is the unit circle, not the left half-plane — applying the continuous rule to a z-domain function inverts the answer rather than degrading it:

isStableDiscrete(tf("1/(z - 0.5)"), z)
// res33: Option[Boolean] = Some(true)
isStableDiscrete(tf("1/(z - 1.5)"), z)
// res34: Option[Boolean] = Some(false)

Exact state-space discretisation uses the matrix exponential of the block matrix [[A, B], [0, 0]]·Ts, not B_d = A⁻¹(A_d − I)B. That is a correctness matter: the block form is defined for a singular A, and any system with an integrator has one.

c2dExact(tf("[[0, 1], [0, 0]]"), tf("[[0], [1]]"), 0.5)
// res35: Option[Tuple2[_MatrixValue, _MatrixValue]] = Some(
//   ([[1.0, 0.5], [0.0, 1.0]], [[0.125], [0.5]])
// )

What it declines

The refusals are as much of the design as the features.

A dead-time term is not rational, so it has no poles — and it is not silently Padé-approximated. pade exists, and reaching for it is the user’s decision:

poles(tf("exp(-2*s)/(s+1)"), s).map(_.mkString(", "))
// res36: Option[String] = None

An improper G has a step response containing an impulse at t = 0 that the inverse-transform tier does not represent, so it returns unevaluated rather than handing back only the smooth part:

stepResponse(tf("s^2/(s+1)"), s, t).toString
// res37: String = "step(((s ^ 2.0) / (s + 1.0)), s, t)"

A coefficient whose sign cannot be determined leaves stability undecided, rather than guessed:

isStable(tf("1/(s^2 + a*s + 1)"), s)
// res38: Option[Boolean] = None

The three response equivalences — zoh, foh and impulse — sample the plant’s time response and z-transform it, and the z-transform table has no entry for a damped oscillation e^(an)·cos(bn). A plant with a complex pole pair is therefore declined by those three, not answered in part: tustin, matched and the two Euler methods are substitutions and take it unchanged.

Also absent, deliberately: d2c by zero-order hold (it needs a matrix logarithm), margin plots (the numbers are here), multi-input pole placement (acker is Ackermann’s single-input formula), and a discrete Kronecker delta, which core has no node for. The root locus is rootLocus(G, s, gains) — the closed-loop poles at each gain, matched into continuous branches so a breakaway point does not cross-connect them — and the browser REPL draws it with rlocus.

From the REPL

> feedback(1/(s*(s+2)), 1, s)
> step(1/(s+1), s, t)
> impulse(1/(s+1), s, t)
> a, b := arx(u, y, 1, 1, 1)
> arx2tf(a, b, 1, z)
> A, B, C, D := arx2ss(a, b, 1)
> a2, b2 := arx(u, Y, 1, 1, 1)                 (Y 2 x N, two outputs: stacked blocks)
> arx2tf(a2, b2, 1, z)                          (the 2 x m transfer matrix)
> tfpoles(1/(s^2 + 3*s + 2), s)
> isStable(1/(s^2 + 3*s + 2), s)
> isStableDiscrete(arx2tf(a, b, 1, z), z)
> c2d(1/(s+1), s, z, 0.1, zoh)
> A, B, C, D := stateSpace([[0, 1], [-2, -3]], [[0], [1]], [[1, 0]], [[0]])
> Y, X := dlsim(arx2ss(a, b, 1), u, 0, states)
> routhTable(1/(s^3 + 2*s^2 + 3*s + 4), s)
> controllable([[0, 1], [0, 0]], [[0], [1]])
> ctrb([[0, 1], [0, 0]], [[0], [1]])
> obsv([[0, 1], [0, 0]], [[1, 0]])
> acker([[0, 1], [0, 0]], [[0], [1]], [[-1 + i, -1 - i]])
> rlocus 1/(s*(s + 2)) s 0.1 10            (browser only: draws the locus)

routhTable keeps its Scala name at the prompt: routh shipped as a free variable name and stays one. controllable/observable also take the model row, controllable(sys), and acker answers the gain of u = −K·x only after checking that A − B·K really has the requested eigenvalues — Ackermann’s formula is badly conditioned as the order grows.

The poles and zeros are tfpoles/tfzeros at the prompt, because zeros(r, c) already builds a zero matrix and zeros(G, s) could not be told from zeros(3, n); in Scala they keep the names poles/zeros used above. The roots come back as a row sorted by real part, or false when there are provably none. Every analysis word reads G with the session’s bound parameters but never with a binding of the frequency variable itself, and stays as written with a note when it cannot answer. The c2d method is a word in that slot only — zoh, tustin, foh, impulse, matched, forward and backward — and the first six stay free as names (impulse names the impulse response elsewhere). tustin may be followed by a prewarp frequency: c2d(G, s, z, Ts, tustin, w).

Note that step is arity-overloaded: step(x) is the Heaviside unit step, while step(G, s, t) is the step response of a system.


This site uses Just the Docs, a documentation theme for Jekyll.