Skip to main content

lib_jsl_dsp/discrete/controls/
state_space.rs

1//! Discrete-time state-space models: simulation, poles, stability, controllability and observability.
2//!
3//! See the book entry [Control: state-space models, PID controllers and the Kalman filter](https://jwkunz.github.io/lib_jsl/book/comms/controls.html#state-space-models).
4
5use ndarray::s;
6use lib_jsl_linalg::{Eig, SVD};
7
8use crate::{
9    dsp::discrete::stream_operator::{StreamOperator, StreamOperatorManagement},
10    prelude::{C1D, C2D, ErrorsJSL},
11};
12
13/// When a [`StateSpace`] model reads its output: from the state before or after the update.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum OutputConvention {
16    /// The textbook and SciPy convention, `y[k] = C x[k] + D u[k]`: the output is read from the
17    /// current state, before it is updated. Use [`StateSpace::new_standard`].
18    Standard,
19    /// `y[k] = C x[k+1] + D u[k]`: the state is updated first and the output read from the new
20    /// state, as in the C++ implementation this type mirrors. This is what [`StateSpace::new`]
21    /// builds, and it equals the standard model `(A, B, C A, C B + D)`.
22    Updated,
23}
24
25/// Discrete-time state-space model using complex-valued matrices and vectors.
26///
27/// The state evolves as `x[k+1] = A x[k] + B u[k]`. The output follows one of two conventions
28/// (see [`OutputConvention`]):
29///
30/// - [`new_standard`](Self::new_standard): `y[k] = C x[k] + D u[k]`, the textbook and SciPy model;
31/// - [`new`](Self::new): `y[k] = C x[k+1] + D u[k]`, the state updated before the output is read,
32///   which matches the C++ implementation that this type mirrors.
33///
34/// All matrices use [`C2D`] and all vectors use [`C1D`], so real-valued models
35/// can be represented as purely real complex matrices while still allowing
36/// complex-valued systems when needed.
37pub struct StateSpace {
38    /// State-transition matrix.
39    pub a: C2D,
40    /// Input-to-state matrix.
41    pub b: C2D,
42    /// State-to-output matrix.
43    pub c: C2D,
44    /// Input-to-output feedthrough matrix.
45    pub d: C2D,
46    /// Current state vector.
47    pub x: C1D,
48    initial_x: C1D,
49    convention: OutputConvention,
50}
51
52impl StateSpace {
53    /// Construct a model that reads its output after updating the state,
54    /// `y[k] = C x[k+1] + D u[k]` ([`OutputConvention::Updated`]). For the textbook and SciPy
55    /// convention use [`new_standard`](Self::new_standard).
56    ///
57    /// The dimensions must satisfy:
58    /// - `A` is `n x n`
59    /// - `B` is `n x p`
60    /// - `C` is `m x n`
61    /// - `D` is `m x p`
62    /// - `x` has length `n`
63    pub fn new(a: C2D, b: C2D, c: C2D, d: C2D, x: C1D) -> Result<Self, ErrorsJSL> {
64        Self::with_convention(a, b, c, d, x, OutputConvention::Updated)
65    }
66
67    // ANCHOR: new_standard
68    /// Construct a model in the textbook and SciPy convention,
69    /// `x[k+1] = A x[k] + B u[k]`, `y[k] = C x[k] + D u[k]`: each [`step`](Self::step) reads the
70    /// output from the current state and then updates it. A model given to
71    /// `scipy.signal.dlsim` as `(A, B, C, D)` is entered here unchanged.
72    pub fn new_standard(a: C2D, b: C2D, c: C2D, d: C2D, x: C1D) -> Result<Self, ErrorsJSL> {
73        Self::with_convention(a, b, c, d, x, OutputConvention::Standard)
74    }
75    // ANCHOR_END: new_standard
76
77    /// Construct a model with an explicit [`OutputConvention`]; the dimensions are as for
78    /// [`new`](Self::new).
79    pub fn with_convention(a: C2D, b: C2D, c: C2D, d: C2D, x: C1D, convention: OutputConvention) -> Result<Self, ErrorsJSL> {
80        if a.nrows() == 0 || a.nrows() != a.ncols() {
81            return Err(ErrorsJSL::InvalidInputRange("A must be a non-empty square matrix"));
82        }
83        if a.nrows() != b.nrows() {
84            return Err(ErrorsJSL::InvalidInputRange("A and B are not compatible size"));
85        }
86        if a.nrows() != x.len() {
87            return Err(ErrorsJSL::InvalidInputRange("A and x are not compatible size"));
88        }
89        if c.nrows() != d.nrows() {
90            return Err(ErrorsJSL::InvalidInputRange("C and D are not compatible size"));
91        }
92        if c.ncols() != a.ncols() {
93            return Err(ErrorsJSL::InvalidInputRange("A and C are not compatible size"));
94        }
95        if b.ncols() != d.ncols() {
96            return Err(ErrorsJSL::InvalidInputRange("B and D are not compatible size"));
97        }
98
99        Ok(Self {
100            a,
101            b,
102            c,
103            d,
104            x: x.clone(),
105            initial_x: x,
106            convention,
107        })
108    }
109
110    /// The output convention of this model.
111    pub fn convention(&self) -> OutputConvention {
112        self.convention
113    }
114
115    /// The same system in the standard convention: for an [`Updated`](OutputConvention::Updated)
116    /// model, `(A, B, C A, C B + D)`, which produces identical outputs; a
117    /// [`Standard`](OutputConvention::Standard) model is returned unchanged. The current and
118    /// initial states are kept.
119    pub fn to_standard(&self) -> StateSpace {
120        let (c, d) = match self.convention {
121            OutputConvention::Standard => (self.c.clone(), self.d.clone()),
122            OutputConvention::Updated => (self.c.dot(&self.a), self.c.dot(&self.b) + &self.d),
123        };
124        StateSpace {
125            a: self.a.clone(),
126            b: self.b.clone(),
127            c,
128            d,
129            x: self.x.clone(),
130            initial_x: self.initial_x.clone(),
131            convention: OutputConvention::Standard,
132        }
133    }
134
135    // ANCHOR: step
136    /// Advance the system by one discrete input sample and return the output.
137    ///
138    /// In the standard convention, `y <- C x + D u` and then `x <- A x + B u`; in the updated
139    /// convention (the C++ ordering), `x <- A x + B u` first and then `y <- C x + D u`.
140    pub fn step(&mut self, u: C1D) -> Result<C1D, ErrorsJSL> {
141        if u.len() != self.b.ncols() {
142            return Err(ErrorsJSL::IncompatibleArraySizes((u.len(), self.b.ncols())));
143        }
144
145        match self.convention {
146            OutputConvention::Standard => {
147                let y = self.c.dot(&self.x) + self.d.dot(&u);
148                self.x = self.a.dot(&self.x) + self.b.dot(&u);
149                Ok(y)
150            }
151            OutputConvention::Updated => {
152                self.x = self.a.dot(&self.x) + self.b.dot(&u);
153                Ok(self.c.dot(&self.x) + self.d.dot(&u))
154            }
155        }
156    }
157    // ANCHOR_END: step
158
159    /// Check whether the discrete-time model is observable.
160    ///
161    /// The observability matrix is formed by vertically stacking
162    /// `C, C A, C A^2, ..., C A^(n-1)`.
163    pub fn is_observable(&self) -> Result<bool, ErrorsJSL> {
164        let state_dim = self.a.nrows();
165        let output_dim = self.c.nrows();
166        let mut big_matrix = C2D::zeros((output_dim * state_dim, state_dim));
167        let mut accumulation = self.c.clone();
168
169        for block in 0..state_dim {
170            let row_start = block * output_dim;
171            let row_end = row_start + output_dim;
172            big_matrix
173                .slice_mut(s![row_start..row_end, ..])
174                .assign(&accumulation);
175            accumulation = accumulation.dot(&self.a);
176        }
177
178        Ok(Self::matrix_rank(&big_matrix)? == state_dim)
179    }
180
181    /// Check whether the discrete-time model is controllable.
182    ///
183    /// The controllability matrix is formed by horizontally stacking
184    /// `B, A B, A^2 B, ..., A^(n-1) B`.
185    pub fn is_controllable(&self) -> Result<bool, ErrorsJSL> {
186        let state_dim = self.a.nrows();
187        let input_dim = self.b.ncols();
188        let mut big_matrix = C2D::zeros((state_dim, input_dim * state_dim));
189        let mut accumulation = self.b.clone();
190
191        for block in 0..state_dim {
192            let col_start = block * input_dim;
193            let col_end = col_start + input_dim;
194            big_matrix
195                .slice_mut(s![.., col_start..col_end])
196                .assign(&accumulation);
197            accumulation = self.a.dot(&accumulation);
198        }
199
200        Ok(Self::matrix_rank(&big_matrix)? == state_dim)
201    }
202
203    /// Return the poles of the discrete-time system, which are the eigenvalues
204    /// of the state-transition matrix `A`.
205    pub fn get_poles(&self) -> Result<C1D, ErrorsJSL> {
206        let (eigenvalues, _) = self
207            .a
208            .clone()
209            .eig()
210            .map_err(|_| ErrorsJSL::RuntimeError("failed to compute state-space poles"))?;
211        Ok(eigenvalues)
212    }
213
214    /// Check whether the discrete-time state matrix is stable.
215    ///
216    /// For a discrete-time model this means every pole lies strictly inside the
217    /// unit circle.
218    pub fn is_stable(&self) -> Result<bool, ErrorsJSL> {
219        let poles = self.get_poles()?;
220        Ok(poles.iter().all(|pole| pole.norm() < 1.0))
221    }
222
223    fn matrix_rank(matrix: &C2D) -> Result<usize, ErrorsJSL> {
224        let (_, singular_values, _) = matrix
225            .clone()
226            .svd(false, false)
227            .map_err(|_| ErrorsJSL::RuntimeError("failed to compute matrix rank"))?;
228        let max_sigma = singular_values.iter().copied().fold(0.0_f64, f64::max);
229        let tolerance = if max_sigma == 0.0 {
230            0.0
231        } else {
232            max_sigma * (matrix.nrows().max(matrix.ncols()) as f64) * f64::EPSILON
233        };
234        Ok(singular_values
235            .iter()
236            .filter(|&&sigma| sigma > tolerance)
237            .count())
238    }
239}
240
241impl StreamOperatorManagement for StateSpace {
242    fn reset(&mut self) -> Result<(), ErrorsJSL> {
243        self.x = self.initial_x.clone();
244        Ok(())
245    }
246
247    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
248        Ok(())
249    }
250}
251
252impl StreamOperator<C1D, C1D> for StateSpace {
253    fn process(&mut self, data_in: &[C1D]) -> Result<Option<Vec<C1D>>, ErrorsJSL> {
254        if data_in.is_empty() {
255            return Ok(None);
256        }
257
258        let mut output = Vec::with_capacity(data_in.len());
259        for u in data_in {
260            output.push(self.step(u.clone())?);
261        }
262        Ok(Some(output))
263    }
264
265    fn flush(&mut self) -> Result<Option<Vec<C1D>>, ErrorsJSL> {
266        Ok(None)
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use ndarray::Array1;
274    use num_complex::Complex;
275
276    fn c(re: f64) -> Complex<f64> {
277        Complex::new(re, 0.0)
278    }
279
280    fn vec1(values: &[f64]) -> C1D {
281        Array1::from_iter(values.iter().copied().map(c))
282    }
283
284    fn mat(rows: usize, cols: usize, values: &[f64]) -> C2D {
285        C2D::from_shape_vec((rows, cols), values.iter().copied().map(c).collect()).unwrap()
286    }
287
288    #[test]
289    fn test_state_space_step_matches_reference_update_order() {
290        let mut dut = StateSpace::new(
291            mat(1, 1, &[0.5]),
292            mat(1, 1, &[1.0]),
293            mat(1, 1, &[1.0]),
294            mat(1, 1, &[0.0]),
295            vec1(&[0.0]),
296        )
297        .unwrap();
298
299        let y0 = dut.step(vec1(&[2.0])).unwrap();
300        let y1 = dut.step(vec1(&[0.0])).unwrap();
301
302        assert!((y0[0] - c(2.0)).norm() < 1e-12);
303        assert!((y1[0] - c(1.0)).norm() < 1e-12);
304        assert!((dut.x[0] - c(1.0)).norm() < 1e-12);
305    }
306
307    #[test]
308    fn test_state_space_process_and_reset() {
309        let mut dut = StateSpace::new(
310            mat(1, 1, &[0.5]),
311            mat(1, 1, &[1.0]),
312            mat(1, 1, &[1.0]),
313            mat(1, 1, &[0.0]),
314            vec1(&[0.0]),
315        )
316        .unwrap();
317
318        let output = dut
319            .process(&[vec1(&[1.0]), vec1(&[1.0]), vec1(&[1.0])])
320            .unwrap()
321            .unwrap();
322
323        assert!((output[0][0] - c(1.0)).norm() < 1e-12);
324        assert!((output[1][0] - c(1.5)).norm() < 1e-12);
325        assert!((output[2][0] - c(1.75)).norm() < 1e-12);
326
327        dut.reset().unwrap();
328        assert!((dut.x[0] - c(0.0)).norm() < 1e-12);
329    }
330
331    #[test]
332    fn test_state_space_observable_controllable_and_stable() {
333        let dut = StateSpace::new(
334            mat(2, 2, &[0.5, 0.0, 0.0, 0.25]),
335            mat(2, 1, &[1.0, 1.0]),
336            mat(1, 2, &[1.0, 1.0]),
337            mat(1, 1, &[0.0]),
338            vec1(&[0.0, 0.0]),
339        )
340        .unwrap();
341
342        assert!(dut.is_observable().unwrap());
343        assert!(dut.is_controllable().unwrap());
344        assert!(dut.is_stable().unwrap());
345
346        let poles = dut.get_poles().unwrap();
347        let mut poles = poles.to_vec();
348        poles.sort_by(|a, b| a.re.total_cmp(&b.re));
349        assert!((poles[0] - c(0.25)).norm() < 1e-12);
350        assert!((poles[1] - c(0.5)).norm() < 1e-12);
351    }
352
353    #[test]
354    fn test_state_space_unobservable_and_uncontrollable() {
355        let dut = StateSpace::new(
356            mat(2, 2, &[0.5, 0.0, 0.0, 0.25]),
357            mat(2, 1, &[1.0, 0.0]),
358            mat(1, 2, &[1.0, 0.0]),
359            mat(1, 1, &[0.0]),
360            vec1(&[0.0, 0.0]),
361        )
362        .unwrap();
363
364        assert!(!dut.is_observable().unwrap());
365        assert!(!dut.is_controllable().unwrap());
366    }
367
368    #[test]
369    fn test_standard_convention_reads_the_current_state() {
370        let mut dut = StateSpace::new_standard(
371            mat(1, 1, &[0.5]),
372            mat(1, 1, &[1.0]),
373            mat(1, 1, &[1.0]),
374            mat(1, 1, &[0.0]),
375            vec1(&[0.0]),
376        )
377        .unwrap();
378        assert_eq!(dut.convention(), OutputConvention::Standard);
379        // y[0] = x[0] = 0, then x[1] = 2, y[1] = 2, x[2] = 1, y[2] = 1.
380        let y: Vec<_> = [2.0, 0.0, 0.0].iter().map(|&u| dut.step(vec1(&[u])).unwrap()[0]).collect();
381        assert!((y[0] - c(0.0)).norm() < 1e-12);
382        assert!((y[1] - c(2.0)).norm() < 1e-12);
383        assert!((y[2] - c(1.0)).norm() < 1e-12);
384    }
385
386    #[test]
387    fn test_to_standard_gives_identical_outputs() {
388        let a = mat(2, 2, &[0.9, 0.2, -0.1, 0.8]);
389        let b = mat(2, 1, &[1.0, 0.5]);
390        let cm = mat(1, 2, &[1.0, -1.0]);
391        let d = mat(1, 1, &[0.3]);
392        let mut updated = StateSpace::new(a, b, cm, d, vec1(&[0.5, -0.2])).unwrap();
393        let mut standard = updated.to_standard();
394        assert_eq!(standard.convention(), OutputConvention::Standard);
395        for k in 0..20 {
396            let u = vec1(&[(0.3 * k as f64).sin()]);
397            let (y1, y2) = (updated.step(u.clone()).unwrap(), standard.step(u).unwrap());
398            assert!((y1[0] - y2[0]).norm() < 1e-12);
399        }
400    }
401
402    #[test]
403    fn test_state_space_rejects_incompatible_sizes() {
404        let err = StateSpace::new(
405            mat(2, 2, &[1.0, 0.0, 0.0, 1.0]),
406            mat(1, 1, &[1.0]),
407            mat(1, 2, &[1.0, 0.0]),
408            mat(1, 1, &[0.0]),
409            vec1(&[0.0, 0.0]),
410        );
411        assert!(err.is_err());
412    }
413}