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

Control: state-space models, PID controllers and the Kalman filter

ProblemDescribe a linear dynamic system and test its stability, controllability and observability; drive a plant’s output to a setpoint by feedback; estimate a hidden state from noisy measurements
Devised byRudolf Kálmán (1960), state-space controllability and observability and the Kalman filter; Nicolas Minorsky (1922), PID control; John Ziegler and Nathaniel Nichols (1942), PID tuning
AccuracyThe Kalman filter is the minimum-variance linear estimator when its model is right; on a tracking test it halves the measurement error (below)
Cost per step for a state-space model with states; for PID; per step for a Kalman filter with measurements
Read firstBackground: frequency responses, Preliminaries: probability
APIStateSpace (new_standard, new, step, to_standard, get_poles, is_stable, is_controllable, is_observable), PidController, KalmanFilter

Overview

A state-space model describes a linear system by a state vector that evolves under the input and determines the output . Its eigenvalues decide whether it is stable; the ranks of two matrices built from it decide whether the input can steer every state (controllability) and whether the output reveals every state (observability). A PID controller computes an input from the error between a setpoint and the measured output: in proportion to it, to its integral, and to its rate of change. It is the most common feedback controller in industry. The Kalman filter runs a state-space model alongside the real system, correcting its state with each noisy measurement by just enough to minimise the estimation error. It is the standard way to track, navigate and fuse sensors. All three are stream operators in the library.

Where it is used

Feedback control and state estimation sit under most of the machines that move or regulate something.

  • PID controllers. Thermostats, cruise control, motor speed drives and chemical-process loops are mostly PID loops, tuned by the rules of this entry.
  • Kalman filter. The filter estimates a state from noisy measurements; it was used in the Apollo navigation computers and is now in every GPS receiver, drone autopilot, phone motion tracker and robot localisation stack.
  • Controllability and observability. These tests tell a designer, before any hardware exists, whether the sensors and actuators chosen can actually steer or see the system.

History

Nicolas Minorsky (1922) analysed automatic ship steering and arrived at three-term (PID) control; pneumatic PID controllers spread through process industries in the 1930s, and John Ziegler and Nathaniel Nichols (1942) gave the first tuning rules. Rudolf Kálmán (1960) recast control theory in state-space form, introducing controllability and observability, and in the same year published the discrete-time filter that bears his name. Stanley Schmidt at NASA Ames adapted it for the Apollo navigation computer; it has since become ubiquitous, from GPS receivers to radar trackers.

The idea

State-space models

A dynamic system has memory: its output depends on past inputs as well as the present one. The state is a vector that summarises everything about the past that matters for the future (for a moving object, its position and velocity, say). A linear state-space model says how the state evolves under an input and what output is observed. The standard model is

where describes how the state evolves by itself, how the input acts on it, and and how the state and the input appear in the output. StateSpace::new_standard builds exactly this model: each step reads the output from the current state, then updates it.

The older constructor StateSpace::new keeps the ordering of the C++ code the library grew from: it updates the state first and reads the output from the new one, . Substituting shows that this is the standard model with and , and to_standard performs that conversion. The reverse is not always possible: recovering from needs to be invertible, which is why a model from a textbook or from SciPy should be entered with new_standard. Three questions are asked of such a model.

  • Is it stable? Without input, . Along an eigenvector of the state is multiplied by the eigenvalue at each step, so it decays to zero for every exactly when every eigenvalue of (the poles of the system) lies strictly inside the unit circle: is_stable.
  • Is it controllable? Can the input drive the state anywhere? An input applied now affects the state through ; one step later that effect has become , then , and so on. The reachable states are the combinations of these, so the system is controllable when the controllability matrix has rank , the dimension of the state.
  • Is it observable? Can the state be deduced from the outputs? The output shows the state through now, a step later, and so on, so the system is observable when the stacked observability matrix of has rank . The library computes ranks from the singular values.

PID control

A controller adjusts the input of a system (the “plant”) so that its output follows a desired value, the setpoint . The PID controller is by far the most widely used. It needs no model of the plant, only the error, and combines three responses to it. With error ,

The proportional term acts on the present error. Alone, it leaves a steady-state error: on a plant of unit DC gain, settles at of the setpoint. The integral term accumulates until the error is zero. The derivative term damps the response by anticipating it. The library differentiates the measurement, not the error, so a setpoint step does not produce a spike (derivative kick), and it low-pass filters the measurement first (a Butterworth biquad at 0.1 cycles per sample) to limit the noise the derivative amplifies:

Figure 16.13. PID step responses.

Integrator windup

A real actuator saturates. While it does, the error persists and the integral keeps growing, so when the output finally reaches the setpoint the integral is far too large and drives an overshoot. Anti-windup by conditional integration stops the integral while the output is saturated and the error pushes further into the limit:

Figure 16.14. PID windup.

The Kalman filter

The Kalman filter estimates the state of a system from noisy measurements. It has two sources of information, a model that predicts how the state evolves and measurements that observe it imperfectly, and it combines them, trusting each in proportion to its reliability.

The filter assumes the model , . The process noise , with covariance , represents what the model does not capture; the measurement noise , with covariance , the inaccuracy of the sensor. Both are assumed white and Gaussian. The filter keeps a state estimate and also the covariance of its error, a running account of how uncertain the estimate is. Each step first predicts: the estimate is advanced by the model, and its uncertainty grows, both because the old uncertainty is carried forward and because process noise is added,

and then updates with the measurement,

The innovation is the difference between the measurement and what the prediction said it would be; is its covariance. The estimate is corrected by a fraction of the innovation, the Kalman gain. For a single measured quantity the gain is : close to 1 when the prediction is much less certain than the measurement, so the measurement is believed, and close to 0 in the opposite case, so it is nearly ignored. The last formula records that the measurement has reduced the uncertainty. For a linear Gaussian model, is the exact conditional mean of the state given all the measurements, and for any noise it is the best linear estimate. Estimating a constant (, ) gives the running average, as the example below shows. Tracking a constant-velocity target from position measurements alone recovers the velocity too:

Figure 16.15. Kalman tracking.

After 20 steps the position error is 1.13 RMS against 2.13 for the raw measurements, and the normalised estimation error squared averages 2.27 (2 for a consistent filter with a two-dimensional state). The normalised estimation error squared checks the filter’s honesty: if the model is right, it averages the state dimension. Here the simulation’s discretised acceleration noise differs slightly from the filter’s , hence the small excess.

Checking against SciPy

A model built with new_standard is SciPy’s model with the same matrices; one built with new is SciPy’s model . Simulating both with scipy.signal.dlsim (SciPy 1.17.1, references from book/generator/data/make_controls_refs.py) reproduces the library’s outputs:

Table 16.4. Control and estimation routines against SciPy.

computation (SciPy reference)largest difference
new_standard: response of a 3-state, 2-input, 2-output system to 60 input samples (signal.dlsim with the same (A, B, C, D))2e-15
new: the same matrices, output read after the update (signal.dlsim with (A, B, CA, CB + D))2e-15
its poles, the eigenvalues of A (linalg.eigvals)6e-16

Algorithm

State-space model. step(u) in the standard convention: compute the output from the current state, then update the state (with new, the two are done in the other order). Stability: compute the eigenvalues of and check that all have magnitude below 1. Controllability and observability: build the matrix (or its counterpart from ) column block by column block, and count its singular values above a tolerance.

PID controller, for each sample with setpoint , measurement and time step :

  1. compute the error and the proportional term ;
  2. add to the integral, and form the integral term times it;
  3. pass the measurement through the low-pass filter, and form the derivative term times the difference of the filtered measurement from its previous value, divided by ;
  4. add the three terms, and clip the sum to the actuator’s limits;
  5. anti-windup: if the sum was clipped, and the error has the sign that would push it further beyond the limit, undo the addition made to the integral in step 2.

Kalman filter, for each time step with control and measurement .

  1. Predict: and .
  2. Innovation: , with covariance .
  3. Gain: solve for (a linear solve; is not inverted explicitly).
  4. Update: and .

With states and measurements, a step costs .

Implementation

    /// Advance the system by one discrete input sample and return the output.
    ///
    /// In the standard convention, `y <- C x + D u` and then `x <- A x + B u`; in the updated
    /// convention (the C++ ordering), `x <- A x + B u` first and then `y <- C x + D u`.
    pub fn step(&mut self, u: C1D) -> Result<C1D, ErrorsJSL> {
        if u.len() != self.b.ncols() {
            return Err(ErrorsJSL::IncompatibleArraySizes((u.len(), self.b.ncols())));
        }

        match self.convention {
            OutputConvention::Standard => {
                let y = self.c.dot(&self.x) + self.d.dot(&u);
                self.x = self.a.dot(&self.x) + self.b.dot(&u);
                Ok(y)
            }
            OutputConvention::Updated => {
                self.x = self.a.dot(&self.x) + self.b.dot(&u);
                Ok(self.c.dot(&self.x) + self.d.dot(&u))
            }
        }
    }
    fn step(&mut self, measurement: f64) -> PidOutput {
        let error = self.setpoint - measurement;

        let p_term = self.kp.unwrap_or(0.0) * error;

        let i_prev = self.integral_state;
        self.integral_state += error * self.dt;
        let i_term = self.ki.unwrap_or(0.0) * self.integral_state;

        // Derivative on filtered measurement to reduce noise sensitivity and
        // avoid setpoint-derivative kick.
        let filtered = self.deriv_lpf.step(measurement);
        let d_meas = (filtered - self.prev_filtered_measurement) / self.dt;
        self.prev_filtered_measurement = filtered;
        let d_term = self.kd.unwrap_or(0.0) * (-d_meas);

        let mut control = p_term + i_term + d_term;
        let mut saturated = false;
        if let Some((lo, hi)) = self.output_limits {
            if control < lo {
                control = lo;
                saturated = true;
            } else if control > hi {
                control = hi;
                saturated = true;
            }
        }

        if self.anti_windup.unwrap_or(false) && saturated {
            let pushing_further = if let Some((lo, hi)) = self.output_limits {
                (control >= hi && error > 0.0) || (control <= lo && error < 0.0)
            } else {
                false
            };
            if pushing_further {
                self.integral_state = i_prev;
            }
        }

        PidOutput {
            control,
            error,
        }
    }
    fn predict(&mut self) {
        self.state_estimate = self.state_transition.dot(&self.state_estimate);

        if let (Some(b), Some(u)) = (&self.control_model, &self.control_input) {
            self.state_estimate += &b.dot(u);
        }

        let f_h = Self::conjugate_transpose(&self.state_transition);
        self.estimate_covariance = self
            .state_transition
            .dot(&self.estimate_covariance)
            .dot(&f_h)
            + &self.process_noise;
    }

    fn update(&mut self, measurement: &C1D) -> Result<KalmanResult, ErrorsJSL> {
        let measurement_dim = self.observation_model.nrows();
        if measurement.len() != measurement_dim {
            return Err(ErrorsJSL::IncompatibleArraySizes((
                measurement.len(),
                measurement_dim,
            )));
        }

        let innovation = measurement - &self.observation_model.dot(&self.state_estimate);
        let innovation_covariance = self
            .observation_model
            .dot(&self.estimate_covariance)
            .dot(&self.observation_model_h)
            + &self.measurement_noise;
        let gain_rhs = self.estimate_covariance.dot(&self.observation_model_h);
        let gain_rhs_t = gain_rhs.t().to_owned();
        let mut kalman_gain_t = C2D::zeros(gain_rhs_t.raw_dim());
        for (column_idx, rhs_column) in gain_rhs_t.columns().into_iter().enumerate() {
            let solved_column = innovation_covariance
                .solve_t_into(rhs_column.to_owned())
                .map_err(|_| ErrorsJSL::RuntimeError("failed to solve innovation covariance"))?;
            kalman_gain_t.column_mut(column_idx).assign(&solved_column);
        }
        let kalman_gain = kalman_gain_t.t().to_owned();

        self.state_estimate = &self.state_estimate + &kalman_gain.dot(&innovation);

        let identity = Self::identity(self.state_estimate.len());
        self.estimate_covariance =
            (identity - kalman_gain.dot(&self.observation_model)).dot(&self.estimate_covariance);

        Ok(KalmanResult {
            next_state: self.state_estimate.clone(),
            residual_error: innovation,
        })
    }
  • The matrices are complex (C2D), so the same code handles real and complex systems; the covariance uses conjugate transposes.
  • The gain is found by solving with , not inverting it.
  • The covariance update uses the short form . The longer Joseph form keeps symmetric and positive definite under rounding, and is worth using in long or ill-conditioned runs.
  • The control input is set with set_control_input and held until changed; the observation model can also change between measurements.
  • PID gains, setpoint, limits and anti-windup can all be changed at run time; None disables a term.

In practice

//! State-space models, PID control and a Kalman filter.

use lib_jsl_dsp::discrete::controls::kalman::KalmanFilter;
use lib_jsl_dsp::discrete::controls::pid::PidController;
use lib_jsl_dsp::discrete::controls::state_space::StateSpace;
use lib_jsl_dsp::discrete::stream_operator::StreamOperator;
use ndarray::{Array1, arr2};
use num_complex::Complex;

fn c(m: ndarray::Array2<f64>) -> ndarray::Array2<Complex<f64>> {
    m.mapv(|v| Complex::new(v, 0.0))
}

fn main() {
    // A discretised mass-spring-damper.
    let a = c(arr2(&[[1.0, 0.1], [-0.2, 0.95]]));
    let b = c(arr2(&[[0.0], [0.1]]));
    let cm = c(arr2(&[[1.0, 0.0]]));
    let d = c(arr2(&[[0.0]]));
    let sys = StateSpace::new_standard(a, b, cm, d, Array1::from(vec![Complex::new(0.0, 0.0); 2])).unwrap();
    println!("poles {:.4}, stable {}, controllable {}, observable {}", sys.get_poles().unwrap(), sys.is_stable().unwrap(), sys.is_controllable().unwrap(), sys.is_observable().unwrap());
    // PI control of a first-order plant y' = −y + u.
    let mut pid = PidController::new_with_dt(Some(1.0), Some(2.0), Some(1.0), None, None, None, 0.05).unwrap();
    let mut y = 0.0;
    for _ in 0..400 {
        let u = pid.process(&[y]).unwrap().unwrap()[0].control;
        y += 0.05 * (-y + u);
    }
    println!("PI loop output after 20 s: {y:.4} (setpoint 1)");
    // A Kalman filter estimating a constant from noisy readings is a running average.
    let one = |v: f64| arr2(&[[v]]).mapv(|x| Complex::new(x, 0.0));
    let mut kf = KalmanFilter::new(one(1.0), one(1.0), one(0.0), one(0.25), one(100.0), Array1::from(vec![Complex::new(0.0, 0.0)]), None, None).unwrap();
    let readings = [5.3, 4.6, 5.1, 4.8, 5.4, 4.9, 5.0, 5.2];
    let measurements: Vec<Array1<Complex<f64>>> = readings.iter().map(|&r| Array1::from(vec![Complex::new(r, 0.0)])).collect();
    let out = kf.process(&measurements).unwrap().unwrap();
    println!("Kalman estimate {:.4}, sample mean {:.4}, variance {:.4} (0.25 / 8 = 0.03125)", out.last().unwrap().next_state[0].re, readings.iter().sum::<f64>() / 8.0, kf.estimate_covariance()[[0, 0]].re);
}
poles [0.9750+0.1392i, 0.9750-0.1392i], stable true, controllable true, observable true
PI loop output after 20 s: 0.9999 (setpoint 1)
Kalman estimate 5.0359, sample mean 5.0375, variance 0.0312 (0.25 / 8 = 0.03125)

With a broad prior (), the Kalman estimate of a constant is nearly the sample mean, and its variance is .

Strengths

  • One state-space type for simulation and structural analysis; a PID with derivative filtering, output limits and anti-windup.
  • A general complex Kalman filter with control inputs and time-varying observation models.

Weaknesses

  • Linear models only: no extended or unscented Kalman filter. Continuous-time models, their discretisation and pole placement are in Continuous-time systems.
  • No automatic PID tuning; the derivative filter’s cutoff is fixed relative to the sample rate.

Exercises

  1. Show that decays for every if and only if all eigenvalues of lie inside the unit circle.
  2. Show that a system is controllable if and only if any state can be reached from zero in steps.
  3. For the plant under proportional control, find the closed-loop steady-state error and time constant.
  4. Derive the scalar Kalman filter for a constant observed in noise, and show that with it is the running mean with .
  5. Find the steady-state Kalman gain for the constant-velocity model and compare it with the α-β filter of the pulse tracker.
Hints and answers
  1. Write so , which tends to zero for every initial state iff for all (for a defective matrix use the Jordan form: terms still decay iff ).
  2. By Cayley-Hamilton, for is a combination of , so states reachable in any number of steps are reachable in steps, and the reachable set is the range of .
  3. With and plant the closed loop is : a time constant and a steady-state error of for a unit step, never zero for finite .
  4. For observed as , the Kalman gain is and . With , , so and is the running mean.
  5. Solve the discrete algebraic Riccati equation for the constant-velocity model (with solve_discrete_are); the resulting position and velocity gains play the roles of and in the α-β filter, and the relation depends on the ratio of process to measurement noise.

Further reading

  • K. J. Åström and R. M. Murray, Feedback Systems: An Introduction for Scientists and Engineers, 2nd ed., Princeton University Press, 2021.
  • R. E. Kalman, “A new approach to linear filtering and prediction problems”, Journal of Basic Engineering 82 (1960) 35–45.
  • K. J. Åström and T. Hägglund, Advanced PID Control, ISA, 2006.
  • Y. Bar-Shalom, X. R. Li and T. Kirubarajan, Estimation with Applications to Tracking and Navigation, Wiley, 2001.