Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Continuous-time systems

ProblemModel a linear system , in continuous time: convert between transfer functions and state space, simulate its response to sampled inputs, compute its frequency response, discretise it for a digital controller, and place its poles by state feedback
Devised byOliver Heaviside (1880s), operational calculus; Hendrik Bode (1940), frequency-response plots; Rudolf Kálmán (1960), state space; Arnold Tustin (1947), the bilinear transform; Jan Kautsky, Nancy Nichols and Paul Van Dooren (1985), robust pole placement
AccuracySimulation is exact for inputs held constant or linear between samples; agrees with scipy.signal to or better
CostSimulation: one matrix exponential of size , then per step. Frequency response: one solve per frequency. Pole placement: per sweep
Read firstControl: state-space models, PID controllers and the Kalman filter, Matrix functions and matrix equations
APIContinuousStateSpace (lsim, step, impulse, freqresp, bode, discretize, poles), tf2ss, ss2tf, place_poles, Discretization, InputHold; ZerosPolesGain

Overview

Physical systems evolve in continuous time: a motor, a circuit or a vehicle obeys differential equations. The previous entry worked with discrete-time models, which a computer runs one sample at a time. This one connects them to the continuous world. A linear time-invariant system has two standard descriptions:

  • a transfer function , the Laplace transform of its impulse response, which describes one input and one output;
  • a state-space model , , which describes any number of inputs and outputs, and from which .

The library provides SciPy’s operations on them: conversions (tf2ss, ss2tf), simulation (lsim, step, impulse), the frequency response (freqresp, bode), discretisation (cont2discrete) and pole placement (place_poles).

Where it is used

State-space models describe almost every physical system with inputs and outputs, and this entry is where the analogue world meets the digital one.

  • Circuits and mechanics. An RLC circuit, a mass-spring-damper, a DC motor and a suspension are all with a small ; the eigenvalues of tell you at once whether the response rings, decays or blows up.
  • Control design. Pole placement, stability analysis and the discretisation used to run a controller on a microprocessor all start from this model.
  • Simulation. Computing the step response, impulse response or Bode plot of a plant before building it is how engineers check a design on a laptop first.

History

Oliver Heaviside’s operational calculus of the 1880s, later justified by the Laplace transform, turned linear differential equations into algebra and gave engineers the transfer function. At Bell Labs, Harry Nyquist (1932) and Hendrik Bode (1940) analysed feedback amplifiers through their frequency response, and Bode’s plots of gain and phase against log frequency remain the standard way to read a system. Arnold Tustin (1947) proposed the bilinear substitution that maps continuous designs to sampled ones. Rudolf Kálmán’s state-space theory (1960) showed that with full state feedback the poles of a controllable system can be placed anywhere. Jan Kautsky, Nancy Nichols and Paul Van Dooren (1985) showed how to use the remaining freedom with several inputs to make the placement robust. André Tits and Yaguang Yang (1996) improved their method, and theirs is SciPy’s default.

The idea

Transfer functions and state space

A transfer function of order has many state-space forms. The controllable canonical form (SciPy’s tf2ss) writes the denominator into the first row of :

with and the numerator padded to coefficients. In the other direction (ss2tf), the denominator is , the characteristic polynomial. A numerator follows from the determinant identity : it is . Both polynomials are formed from eigenvalues.

Exact simulation

Between samples, the solution of is

If the input is held constant over the step (a zero-order hold) or varies linearly between samples, the integral has a closed form, and one matrix exponential of an augmented matrix gives all its pieces at once. For a linear input:

The simulation is then a recurrence, exact up to rounding for inputs of that shape and with no step-size error to control. The step response holds a constant input. The impulse response starts from with no input.

Figure 16.16. Step responses.

Frequency response

A sinusoidal input produces, once transients have decayed, the output , with . The Bode diagram plots in decibels and the phase against . On these axes each pole and zero contributes a straight-line asymptote, and the resonance of a lightly damped pair stands out as a peak of height about dB:

Figure 16.17. Bode magnitude.

Figure 16.18. Bode phase.

The phase is unwrapped, so that it falls continuously from 0 to instead of jumping by .

Discretisation

A digital controller sees the system only at the samples , through a converter that holds its output between them. The discrete model depends on that hold:

  • Zero-order hold (zoh): and , exact when the input is piecewise constant, as from a digital-to-analogue converter.
  • First-order hold (foh): exact for piecewise-linear inputs. The state is redefined to absorb the ramp, which changes and .
  • Impulse invariance: the discrete impulse response equals the continuous one sampled, times .
  • The generalised bilinear transform approximates by a difference that mixes the two ends of the step: . Here is forward Euler, backward Euler, and Tustin’s method, which maps . It keeps stable systems stable and preserves the frequency response up to a warping of the frequency axis.

They differ in how well the discrete frequency response matches below the Nyquist frequency , here for :

Table 16.5. Frequency-response error of each discretisation.

Tmethoderror at a tenth of the Nyquist frequencylargest error up to half the Nyquist frequency
0.1zero-order hold1.7e-28.2e-2
0.1first-order hold9.0e-41.4e-3
0.1bilinear (Tustin)2.0e-34.7e-3
0.1forward Euler3.9e-23.1e-1
0.1backward Euler3.7e-22.3e-1
0.5zero-order hold2.2e-14.1e-1
0.5first-order hold1.2e-23.6e-2
0.5bilinear (Tustin)1.4e-21.3e-1
0.5forward Euler3.0e-18.1e0
0.5backward Euler2.3e-18.2e-1

The zero-order hold is exact at the samples for held inputs, but it adds an average delay of half a sample, which shows as a phase error that grows with frequency. The first-order hold and Tustin’s method are second order in , and the Euler methods only first order. Forward Euler can also turn a stable system unstable when is large.

Pole placement

With every state measured, the feedback makes the closed loop . If is controllable, any set of poles closed under conjugation can be placed. Each closed-loop eigenvector must satisfy , so it lies in the subspace where is in the range of . Writing , these are the vectors with . Given eigenvectors and poles ,

With one input each is a line, so and are unique. With inputs each has dimension , and the choice of decides how sensitive the placed poles are to errors in the model, through the condition number of . The method of Kautsky, Nichols and Van Dooren sweeps over the columns, replacing each by the unit vector in most nearly orthogonal to the others.

An inverted pendulum on a cart is unstable (a pole at ). Placing the poles at , and balances it from an initial tilt of 0.2 rad:

Figure 16.19. Inverted pendulum.

The gain is . The cart first moves under the pendulum to catch it, then returns to the origin.

Algorithm

lsim(u, t, x0, hold): check that the times are equally spaced with step . If , advance the initial state by . Form the augmented matrix ( square for a zero-order hold, for a linear input), exponentiate it once, read off , and , and run the recurrence; then .

bode(w): for each frequency, solve by LU, form , and return and the unwrapped phase in degrees.

discretize(T, method): zero- and first-order hold and impulse invariance through one matrix exponential each; the bilinear family through one inverse of .

place_poles(A, B, poles):

  1. Factor through its SVD, which gives , and .
  2. For each pole, compute an orthonormal basis of as the null space of .
  3. Start each at the first basis vector.
  4. With several inputs, sweep: replace by the normalised projection onto of the direction orthogonal to the other columns, and keep conjugate poles’ vectors conjugate. Stop when no column changes.
  5. Return from the formula above.

Implementation

    /// Simulates the response to the input samples `u` (one row per time) at equally spaced
    /// times `t`, from the initial state `x0` (zero if `None`) (SciPy's `lsim`).
    ///
    /// The input is held constant ([`InputHold::Zero`]) or interpolated linearly
    /// ([`InputHold::Linear`]) between samples, and each step is then exact: with
    /// `M = [[A T, B T, 0], [0, 0, I], [0, 0, 0]]` and `e^M`'s top blocks `Φ, Γ₁, Γ₂`,
    /// `x[i+1] = Φ x[i] + (Γ₁ − Γ₂) u[i] + Γ₂ u[i+1]`.
    pub fn lsim(&self, u: &Array2<f64>, t: &[f64], x0: Option<&[f64]>, hold: InputHold) -> Result<Simulation, ErrorsJSL> {
        let (n, m) = (self.a.nrows(), self.b.ncols());
        let steps = t.len();
        if u.nrows() != steps || u.ncols() != m {
            return Err(ErrorsJSL::IncompatibleArraySizes((u.nrows(), steps)));
        }
        if steps == 0 {
            return Err(ErrorsJSL::InvalidInputRange("need at least one time"));
        }
        let mut x = Array2::<f64>::zeros((steps, n));
        let x0 = Array1::from(x0.map_or(vec![0.0; n], |v| v.to_vec()));
        if x0.len() != n {
            return Err(ErrorsJSL::IncompatibleArraySizes((x0.len(), n)));
        }
        if t[0] < 0.0 {
            return Err(ErrorsJSL::InvalidInputRange("the initial time must be non-negative"));
        }
        // Before t[0] the input is zero: x(t₀) = e^{A t₀} x₀.
        let start = if t[0] == 0.0 { x0 } else { expm(&(&self.a * t[0])).map_err(linalg_error)?.dot(&x0) };
        x.row_mut(0).assign(&start);
        if steps > 1 {
            let dt = t[1] - t[0];
            if !(dt > 0.0) || t.windows(2).any(|w| ((w[1] - w[0]) - dt).abs() > 1e-8 * dt.abs().max(1e-300) + 1e-12) {
                return Err(ErrorsJSL::InvalidInputRange("time steps must be positive and equally spaced"));
            }
            let size = match hold {
                InputHold::Zero => n + m,
                InputHold::Linear => n + 2 * m,
            };
            let mut big = Array2::<f64>::zeros((size, size));
            big.slice_mut(s![..n, ..n]).assign(&(&self.a * dt));
            big.slice_mut(s![..n, n..n + m]).assign(&(&self.b * dt));
            if hold == InputHold::Linear {
                big.slice_mut(s![n..n + m, n + m..]).assign(&Array2::eye(m));
            }
            let e = expm(&big).map_err(linalg_error)?;
            let phi = e.slice(s![..n, ..n]).to_owned();
            let (g0, g1) = match hold {
                InputHold::Zero => (e.slice(s![..n, n..n + m]).to_owned(), Array2::zeros((n, m))),
                InputHold::Linear => {
                    let g2 = e.slice(s![..n, n + m..]).to_owned();
                    (&e.slice(s![..n, n..n + m]) - &g2, g2)
                }
            };
            for i in 1..steps {
                let next = phi.dot(&x.row(i - 1)) + g0.dot(&u.row(i - 1)) + g1.dot(&u.row(i));
                x.row_mut(i).assign(&next);
            }
        }
        let y = x.dot(&self.c.t()) + u.dot(&self.d.t());
        Ok(Simulation { y, x })
    }
    /// The discrete-time system for sample time `dt` (SciPy's `cont2discrete`).
    pub fn discretize(&self, dt: f64, method: Discretization) -> Result<DiscreteMatrices, ErrorsJSL> {
        let (n, m) = (self.a.nrows(), self.b.ncols());
        let (a, b, c, d) = (&self.a, &self.b, &self.c, &self.d);
        let gbt = |alpha: f64| -> Result<DiscreteMatrices, ErrorsJSL> {
            if !(0.0..=1.0).contains(&alpha) {
                return Err(ErrorsJSL::InvalidInputRange("the bilinear parameter α must lie in [0, 1]"));
            }
            let eye = Array2::<f64>::eye(n);
            let ima = &eye - &(a * (alpha * dt));
            let inv = ima.inv().map_err(linalg_error)?;
            let ad = inv.dot(&(&eye + &(a * ((1.0 - alpha) * dt))));
            let bd = inv.dot(&(b * dt));
            let cd = c.dot(&inv);
            let dd = d + &(c.dot(&bd) * alpha);
            Ok(DiscreteMatrices { a: ad, b: bd, c: cd, d: dd, dt })
        };
        match method {
            Discretization::Gbt(alpha) => gbt(alpha),
            Discretization::Bilinear => gbt(0.5),
            Discretization::ForwardEuler => gbt(0.0),
            Discretization::BackwardEuler => gbt(1.0),
            Discretization::ZeroOrderHold => {
                let mut big = Array2::<f64>::zeros((n + m, n + m));
                big.slice_mut(s![..n, ..n]).assign(&(a * dt));
                big.slice_mut(s![..n, n..]).assign(&(b * dt));
                let e = expm(&big).map_err(linalg_error)?;
                Ok(DiscreteMatrices { a: e.slice(s![..n, ..n]).to_owned(), b: e.slice(s![..n, n..]).to_owned(), c: c.clone(), d: d.clone(), dt })
            }
            Discretization::FirstOrderHold => {
                let mut big = Array2::<f64>::zeros((n + 2 * m, n + 2 * m));
                big.slice_mut(s![..n, ..n]).assign(&(a * dt));
                big.slice_mut(s![..n, n..n + m]).assign(&(b * dt));
                big.slice_mut(s![n..n + m, n + m..]).assign(&Array2::eye(m));
                let e = expm(&big).map_err(linalg_error)?;
                let (m11, m12, m13) = (e.slice(s![..n, ..n]).to_owned(), e.slice(s![..n, n..n + m]).to_owned(), e.slice(s![..n, n + m..]).to_owned());
                let bd = &m12 - &m13 + m11.dot(&m13);
                let dd = d + &c.dot(&m13);
                Ok(DiscreteMatrices { a: m11, b: bd, c: c.clone(), d: dd, dt })
            }
            Discretization::Impulse => {
                if d.iter().any(|v| v.abs() > 1e-8) {
                    return Err(ErrorsJSL::InvalidInputRange("impulse invariance needs a strictly proper system (D = 0)"));
                }
                let ad = expm(&(a * dt)).map_err(linalg_error)?;
                let bd = ad.dot(b) * dt;
                Ok(DiscreteMatrices { a: ad, b: bd, c: c.clone(), d: c.dot(b) * dt, dt })
            }
        }
    }
  • ContinuousStateSpace uses real matrices. discretize returns DiscreteMatrices, whose output convention is that of StateSpace::new_standard.
  • impulse follows SciPy in leaving out the term of the impulse response.
  • place_poles uses Kautsky, Nichols and Van Dooren’s first method (KNV0) rather than SciPy’s default Tits-Yang method. With one input the two give the same gain; with several they give different gains that place the same poles.

In practice

Every function is compared with scipy.signal from SciPy 1.17.1 (references from book/generator/data/make_lti_refs.py) on a third-order transfer function and a system with 3 states, 2 inputs and 2 outputs:

Table 16.6. Continuous-time routines against SciPy.

computation (SciPy reference)largest difference
tf2ss, third order with a second-order numerator0
ss2tf, 3 states, input 04e-15
ss2tf, 3 states, input 17e-15
lsim, 3 states, 2 inputs, 201 steps, zero-order hold1e-15
lsim, 3 states, 2 inputs, 201 steps, linear interpolation2e-15
lsim starting at t = 0.52e-15
step4e-15
impulse4e-15
bode, magnitude in dB2e-14
bode, phase in degrees1e-13
cont2discrete, zoh1e-16
cont2discrete, foh1e-16
cont2discrete, bilinear1e-16
cont2discrete, euler0
cont2discrete, backward_diff6e-17
cont2discrete, gbt1e-16
cont2discrete, impulse1e-16
place_poles, one input: the gain1e-13
place_poles, two inputs: the achieved poles6e-15

With two inputs the gain is not unique. After 2 sweeps the library’s eigenvector matrix has condition number 26.04, against 10.50 for SciPy’s (whose default method, by Tits and Yang, maximises a different measure); the gains differ, but both place the poles to . With one input, the eigenvector matrix is fixed, with condition number 347.

Zeros, poles and gain as a system

ZerosPolesGain holds a single-input, single-output system in factored form, with in continuous time or in discrete time with a sample time dt. It is SciPy’s ZerosPolesGain (lti(z, p, k) and dlti(z, p, k, dt=...)).

Filter design produces this form, and it is the accurate one to evaluate. freqresp and bode multiply the factors and divide by one at a time, so each factor contributes a relative error of order . Expanding the factors into polynomial coefficients first gives coefficients of very different sizes, and evaluating the polynomials near the passband edge cancels them. Figure 16.20 shows the cost for Butterworth filters: the expanded form loses one digit for every few orders.

Time responses and discretisation go through the state-space form, as in SciPy:

  • lsim, step and impulse for continuous-time systems;
  • dlsim, dstep and dimpulse for discrete-time ones;
  • to_discrete for converting one to the other.
/// A single-input, single-output system `H = k ∏(x − zᵢ) / ∏(x − pⱼ)` with `x = s` in
/// continuous time (`dt = None`) or `x = z` in discrete time with sample time `dt` (SciPy's
/// `ZerosPolesGain` and `lti(z, p, k)` / `dlti(z, p, k, dt=dt)`). Complex zeros and poles must
/// come in conjugate pairs for the real-coefficient conversions.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ZerosPolesGain {
    pub zeros: Vec<C>,
    pub poles: Vec<C>,
    pub gain: f64,
    /// The sample time of a discrete-time system; `None` in continuous time.
    pub dt: Option<f64>,
}

impl ZerosPolesGain {
    /// A continuous-time system.
    pub fn new(zeros: Vec<C>, poles: Vec<C>, gain: f64) -> Self {
        ZerosPolesGain { zeros, poles, gain, dt: None }
    }

    /// A discrete-time system with sample time `dt > 0`.
    pub fn new_discrete(zeros: Vec<C>, poles: Vec<C>, gain: f64, dt: f64) -> Result<Self, ErrorsJSL> {
        if !(dt > 0.0 && dt.is_finite()) {
            return Err(ErrorsJSL::InvalidInputRange("the sample time must be positive"));
        }
        Ok(ZerosPolesGain { zeros, poles, gain, dt: Some(dt) })
    }

    /// From a transfer function `num/den` (highest power first), through [`tf2zpk`].
    pub fn from_tf(num: &[f64], den: &[f64], dt: Option<f64>) -> Result<Self, ErrorsJSL> {
        let (z, p, k) = tf2zpk(num, den)?;
        Ok(ZerosPolesGain { zeros: z, poles: p, gain: k, dt })
    }

    /// From a single-input, single-output state-space model.
    pub fn from_ss(sys: &ContinuousStateSpace, dt: Option<f64>) -> Result<Self, ErrorsJSL> {
        if sys.b.ncols() != 1 || sys.c.nrows() != 1 {
            return Err(ErrorsJSL::InvalidInputRange("a ZerosPolesGain system has one input and one output"));
        }
        let (z, p, k) = ss2zpk(sys, 0)?.remove(0);
        Ok(ZerosPolesGain { zeros: z, poles: p, gain: k, dt })
    }

    /// The transfer function `(num, den)`, highest power first (SciPy's `to_tf`).
    pub fn to_tf(&self) -> (Vec<f64>, Vec<f64>) {
        zpk2tf(&self.zeros, &self.poles, self.gain)
    }

    /// A state-space realisation in controllable canonical form (SciPy's `to_ss`). For a
    /// discrete-time system the matrices are those of `x[k+1] = A x[k] + B u[k]`.
    pub fn to_ss(&self) -> Result<ContinuousStateSpace, ErrorsJSL> {
        let (b, a) = self.to_tf();
        tf2ss(&b, &a)
    }

    fn eval(&self, x: C) -> C {
        let num = self.zeros.iter().fold(C::new(self.gain, 0.0), |acc, z| acc * (x - z));
        self.poles.iter().fold(num, |acc, p| acc / (x - p))
    }

    /// The frequency response at the angular frequencies `w`: `H(iω)` in continuous time
    /// (rad/s), `H(e^{iω})` in discrete time (rad/sample, as SciPy's `dfreqresp`), evaluated
    /// factor by factor.
    pub fn freqresp(&self, w: &[f64]) -> Vec<C> {
        match self.dt {
            None => w.iter().map(|&w| self.eval(C::new(0.0, w))).collect(),
            Some(_) => w.iter().map(|&w| self.eval(C::from_polar(1.0, w))).collect(),
        }
    }

    /// The Bode diagram: `20 log₁₀|H|` in dB and the unwrapped phase in degrees (SciPy's `bode`
    /// and `dbode`; in discrete time `w` is in rad/sample).
    pub fn bode(&self, w: &[f64]) -> (Vec<f64>, Vec<f64>) {
        let h = self.freqresp(w);
        let mag = h.iter().map(|v| 20.0 * v.norm().log10()).collect();
        let phase = unwrap(&h.iter().map(|v| v.arg()).collect::<Vec<_>>()).iter().map(|p| p.to_degrees()).collect();
        (mag, phase)
    }

    fn continuous(&self) -> Result<ContinuousStateSpace, ErrorsJSL> {
        if self.dt.is_some() {
            return Err(ErrorsJSL::InvalidInputRange("this is a discrete-time system: use dlsim, dstep or dimpulse"));
        }
        self.to_ss()
    }

    /// The response to the input samples `u` at equally spaced times `t` from rest, with the
    /// input held or interpolated between samples (SciPy's `lsim`). Continuous time only.
    pub fn lsim(&self, u: &[f64], t: &[f64], hold: InputHold) -> Result<Vec<f64>, ErrorsJSL> {
        let ss = self.continuous()?;
        let u = Array2::from_shape_vec((u.len(), 1), u.to_vec()).map_err(|_| ErrorsJSL::InvalidInputRange("bad input"))?;
        Ok(ss.lsim(&u, t, None, hold)?.y.column(0).to_vec())
    }

    /// The step response at times `t` (SciPy's `step`). Continuous time only.
    pub fn step(&self, t: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
        Ok(self.continuous()?.step(t, 0)?.column(0).to_vec())
    }

    /// The impulse response at times `t` (SciPy's `impulse`). Continuous time only.
    pub fn impulse(&self, t: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
        Ok(self.continuous()?.impulse(t, 0)?.column(0).to_vec())
    }

    fn discrete_tf(&self) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
        if self.dt.is_none() {
            return Err(ErrorsJSL::InvalidInputRange("this is a continuous-time system: use lsim, step or impulse"));
        }
        if self.zeros.len() > self.poles.len() {
            return Err(ErrorsJSL::InvalidInputRange("a causal discrete-time system has no more zeros than poles"));
        }
        let (b, a) = self.to_tf();
        // Positive powers of z to the delay form b(z⁻¹)/a(z⁻¹): pad the numerator in front.
        let mut bp = vec![0.0; a.len() - b.len()];
        bp.extend(b);
        Ok((bp, a))
    }

    /// The response to the samples `u` from rest (SciPy's `dlsim`). Discrete time only.
    pub fn dlsim(&self, u: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
        let (b, a) = self.discrete_tf()?;
        Ok(lfilter(&b, &a, u, None)?.0)
    }

    /// The first `n` samples of the step response (SciPy's `dstep`). Discrete time only.
    pub fn dstep(&self, n: usize) -> Result<Vec<f64>, ErrorsJSL> {
        self.dlsim(&vec![1.0; n])
    }

    /// The first `n` samples of the response to a unit pulse at `k = 0` (SciPy's `dimpulse`).
    /// Discrete time only.
    pub fn dimpulse(&self, n: usize) -> Result<Vec<f64>, ErrorsJSL> {
        let mut u = vec![0.0; n];
        if n > 0 {
            u[0] = 1.0;
        }
        self.dlsim(&u)
    }

    /// The discrete-time system for sample time `dt` (SciPy's `to_discrete`, i.e.
    /// `cont2discrete` on the state-space form and back).
    pub fn to_discrete(&self, dt: f64, method: Discretization) -> Result<ZerosPolesGain, ErrorsJSL> {
        let d = self.continuous()?.discretize(dt, method)?;
        let ss = ContinuousStateSpace::new(d.a, d.b, d.c, d.d)?;
        ZerosPolesGain::from_ss(&ss, Some(dt))
    }
}

Table 16.7. ZerosPolesGain against SciPy.

System and operationDifference from SciPy (relative where scaled)
Butterworth, order 6, low-pass: freqresp; bode (dB, degrees); step, impulse4e-16; 3e-14 / 1e-13; 1e-14 / 2e-14
… to_discrete(0.1, zoh): poles; zeros; gain; dstep, dimpulse; dfreqresp3e-11; 1e-6; 2e-8; 6e-11 / 6e-11; 4e-11
… to_discrete(0.1, bilinear): poles; zeros; gain; dstep, dimpulse; dfreqresp3e-12; 3e-2; 0; 9e-11 / 7e-11; 8e-11 (zeros exactly at -1: library off by 4e-2, SciPy by 6e-2)
… to_discrete(0.1, foh): poles; zeros; gain; dstep, dimpulse; dfreqresp7e-12; 2e-6; 2e-8; 9e-11 / 6e-11; 5e-11
Chebyshev I, order 5, high-pass: freqresp; bode (dB, degrees); step, impulse6e-16; 3e-14 / 6e-14; 1e-14 / 3e-15
… to_discrete(0.1, zoh): poles; zeros; gain; dstep, dimpulse; dfreqresp3e-14; 2e-13; 0; 4e-13 / 4e-14; 7e-13
… to_discrete(0.1, bilinear): poles; zeros; gain; dstep, dimpulse; dfreqresp3e-14; 7e-4; 0; 1e-12 / 1e-13; 6e-13 (zeros exactly at 1: library off by 1e-3, SciPy by 1e-3)
… to_discrete(0.1, foh): poles; zeros; gain; dstep, dimpulse; dfreqresp3e-14; 2e-6; 2e-15; 1e-12 / 2e-13; 1e-12

Responses agree to or better. The zeros of the discretised systems differ by up to , because both libraries compute them as roots of the numerator polynomial. The bilinear transform maps all six zeros at infinity of the Butterworth filter to , and a six-fold root moves by about under rounding. Both libraries are off by a few hundredths, while the responses, which depend on the polynomial and not on its roots, agree.

Figure 16.20. The largest relative error of for Butterworth filters of order , against the exact . Factor by factor the error stays near ; from expanded coefficients it grows to about at order 40.

Strengths

  • Simulation is exact for held or linearly interpolated inputs, with no step-size error to control. Stiff systems cost the same as any other.
  • One state-space type serves any number of inputs and outputs, with discretisation by all of SciPy’s methods.
  • Pole placement handles complex poles and several inputs, and reports the achieved poles and the eigenvector matrix.

Weaknesses

  • Time steps must be equal; for irregular sampling, call lsim piecewise.
  • tf2ss and ss2tf go through polynomial coefficients and eigenvalues, which lose accuracy for high orders. Prefer state space throughout.
  • Time delays only through Padé approximants (pade_delay).

Exercises

  1. Derive from the Laplace transform of the state equations, and check that the controllable canonical form of has this transfer function.
  2. Show that the zero-order hold gives and when is invertible, and verify it from the block exponential.
  3. Show that the bilinear transform maps the left half of the -plane onto the inside of the unit circle, and find where it maps the frequency (frequency warping).
  4. For the double integrator , place both poles at by hand and compare with place_poles.
  5. Find the height of the resonant peak of for small , and check it against the Bode figure for .
Hints and answers
  1. Transforming gives (zero initial state), so and . For the example, , , , and .
  2. . Expanding the exponential of as a series gives the same top-right block, .
  3. With , exactly when . The imaginary axis maps onto the unit circle, with going to the angle .
  4. , , so has characteristic polynomial . Matching gives .
  5. peaks near at , or 14 dB for , as in the figure.

Further reading

  • K. J. Åström and R. M. Murray, Feedback Systems: An Introduction for Scientists and Engineers, 2nd ed., Princeton University Press, 2021.
  • G. F. Franklin, J. D. Powell and M. Workman, Digital Control of Dynamic Systems, 3rd ed., Addison-Wesley, 1998.
  • J. Kautsky, N. K. Nichols and P. Van Dooren, “Robust pole assignment in linear state feedback”, International Journal of Control 41 (1985) 1129–1155.
  • A. L. Tits and Y. Yang, “Globally convergent algorithms for robust pole assignment by state feedback”, IEEE Transactions on Automatic Control 41 (1996) 1432–1452.
  • C. Moler and C. Van Loan, “Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later”, SIAM Review 45 (2003) 3–49.