Skip to main content

lib_jsl_dsp/continuous/
lti.rs

1//! Continuous-time linear time-invariant systems, following `scipy.signal`:
2//! `x'(t) = A x(t) + B u(t)`, `y(t) = C x(t) + D u(t)`.
3//!
4//! - Conversions between transfer functions and state space ([`tf2ss`], [`ss2tf`]).
5//! - Simulation with zero-order or linearly interpolated inputs ([`ContinuousStateSpace::lsim`]),
6//!   step and impulse responses, all exact for the held input through the matrix exponential.
7//! - Frequency response and Bode plots ([`ContinuousStateSpace::freqresp`],
8//!   [`ContinuousStateSpace::bode`]).
9//! - Discretisation by zero- and first-order hold, impulse invariance and the generalised
10//!   bilinear transform (Tustin, forward and backward Euler) ([`ContinuousStateSpace::discretize`]).
11//! - Pole placement by state feedback ([`place_poles`]).
12//!
13//! See the book entry [Continuous-time systems](https://jwkunz.github.io/lib_jsl/book/comms/continuous-time.html).
14
15use lib_jsl_core::ErrorsJSL;
16use lib_jsl_linalg::{EigVals, Inverse, SVD, expm};
17use ndarray::{Array1, Array2, s};
18use num_complex::Complex;
19
20type C = Complex<f64>;
21
22fn linalg_error<E>(_: E) -> ErrorsJSL {
23    ErrorsJSL::RuntimeError("a linear-algebra operation failed (singular or non-finite matrix)")
24}
25
26/// A continuous-time state-space model with real matrices (SciPy's `StateSpace` with `dt=None`).
27#[derive(Clone, Debug, PartialEq)]
28pub struct ContinuousStateSpace {
29    pub a: Array2<f64>,
30    pub b: Array2<f64>,
31    pub c: Array2<f64>,
32    pub d: Array2<f64>,
33}
34
35/// How the input is held between samples in [`ContinuousStateSpace::lsim`].
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum InputHold {
38    /// Constant over each step (SciPy's `interp=False`).
39    Zero,
40    /// Linear between samples (SciPy's default, `interp=True`).
41    Linear,
42}
43
44/// Discretisation methods for [`ContinuousStateSpace::discretize`] (SciPy's `cont2discrete`).
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub enum Discretization {
47    /// Zero-order hold: exact for piecewise-constant inputs.
48    ZeroOrderHold,
49    /// First-order hold: exact for piecewise-linear inputs.
50    FirstOrderHold,
51    /// Impulse invariance (strictly proper systems only).
52    Impulse,
53    /// The generalised bilinear transform with parameter `α ∈ [0, 1]`:
54    /// `x[k+1] − x[k] = T (A ((1 − α) x[k] + α x[k+1]) + B u)`.
55    Gbt(f64),
56    /// Tustin's bilinear transform, `Gbt(0.5)`.
57    Bilinear,
58    /// Forward Euler, `Gbt(0)`.
59    ForwardEuler,
60    /// Backward Euler, `Gbt(1)`.
61    BackwardEuler,
62}
63
64/// A discretised system `x[k+1] = A x[k] + B u[k]`, `y[k] = C x[k] + D u[k]` with sample time `dt`.
65#[derive(Clone, Debug, PartialEq)]
66pub struct DiscreteMatrices {
67    pub a: Array2<f64>,
68    pub b: Array2<f64>,
69    pub c: Array2<f64>,
70    pub d: Array2<f64>,
71    pub dt: f64,
72}
73
74/// The result of [`ContinuousStateSpace::lsim`]: outputs and states at each time, one row per time.
75#[derive(Clone, Debug)]
76pub struct Simulation {
77    pub y: Array2<f64>,
78    pub x: Array2<f64>,
79}
80
81/// The coefficients of `∏ (s − rᵢ)`, highest power first (NumPy's `poly`), with the imaginary
82/// parts dropped when the roots come in conjugate pairs.
83pub fn poly_from_roots(roots: &[C]) -> Vec<f64> {
84    let mut p = vec![C::new(1.0, 0.0)];
85    for &r in roots {
86        let mut next = vec![C::new(0.0, 0.0); p.len() + 1];
87        for (i, &c) in p.iter().enumerate() {
88            next[i] += c;
89            next[i + 1] -= c * r;
90        }
91        p = next;
92    }
93    p.iter().map(|z| z.re).collect()
94}
95
96fn normalize(num: &[f64], den: &[f64]) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
97    let den: Vec<f64> = den.iter().copied().skip_while(|&v| v == 0.0).collect();
98    if den.is_empty() {
99        return Err(ErrorsJSL::InvalidInputRange("the denominator must not be zero"));
100    }
101    let lead = den[0];
102    let mut num: Vec<f64> = num.iter().copied().skip_while(|&v| v == 0.0).map(|v| v / lead).collect();
103    if num.is_empty() {
104        num.push(0.0);
105    }
106    Ok((num, den.iter().map(|v| v / lead).collect()))
107}
108
109// ANCHOR: tf2ss
110/// The controllable canonical state-space form of the transfer function
111/// `H(s) = (b₀ sᵐ + … + b_m) / (a₀ sⁿ + … + a_n)` (SciPy's `tf2ss`), for a proper `H` (`m ≤ n`):
112/// `A` has `−a₁/a₀, …, −a_n/a₀` in its first row and ones below the diagonal, `B = e₁`,
113/// `C = b̃₁.. − b̃₀ ã₁..` with `b̃` the numerator padded to length `n + 1`, and `D = b̃₀`.
114pub fn tf2ss(num: &[f64], den: &[f64]) -> Result<ContinuousStateSpace, ErrorsJSL> {
115    let (num, den) = normalize(num, den)?;
116    let k = den.len();
117    if num.len() > k {
118        return Err(ErrorsJSL::InvalidInputRange("the transfer function must be proper (numerator degree ≤ denominator degree)"));
119    }
120    let mut padded = vec![0.0; k - num.len()];
121    padded.extend_from_slice(&num);
122    let n = k - 1;
123    if n == 0 {
124        return Ok(ContinuousStateSpace { a: Array2::zeros((1, 1)), b: Array2::zeros((1, 1)), c: Array2::zeros((1, 1)), d: Array2::from_elem((1, 1), padded[0]) });
125    }
126    let mut a = Array2::<f64>::zeros((n, n));
127    for j in 0..n {
128        a[(0, j)] = -den[j + 1];
129    }
130    for i in 1..n {
131        a[(i, i - 1)] = 1.0;
132    }
133    let mut b = Array2::<f64>::zeros((n, 1));
134    b[(0, 0)] = 1.0;
135    let c = Array2::from_shape_fn((1, n), |(_, j)| padded[j + 1] - padded[0] * den[j + 1]);
136    Ok(ContinuousStateSpace { a, b, c, d: Array2::from_elem((1, 1), padded[0]) })
137}
138// ANCHOR_END: tf2ss
139
140/// The transfer functions from input `input` to every output (SciPy's `ss2tf`): a common
141/// denominator `det(sI − A)` and one numerator row per output, each of length `n + 1`, from
142/// `det(sI − A + B Cₖ) + (Dₖ − 1) det(sI − A)`.
143pub fn ss2tf(sys: &ContinuousStateSpace, input: usize) -> Result<(Array2<f64>, Vec<f64>), ErrorsJSL> {
144    if input >= sys.b.ncols() {
145        return Err(ErrorsJSL::InvalidInputRange("input index out of range"));
146    }
147    let n = sys.a.nrows();
148    let den = poly_from_roots(&sys.a.eigvals().map_err(linalg_error)?.to_vec());
149    let b = sys.b.column(input).to_owned();
150    let p = sys.c.nrows();
151    let mut num = Array2::<f64>::zeros((p, n + 1));
152    for k in 0..p {
153        let ck = sys.c.row(k);
154        let outer = Array2::from_shape_fn((n, n), |(i, j)| b[i] * ck[j]);
155        let pk = poly_from_roots(&(&sys.a - &outer).eigvals().map_err(linalg_error)?.to_vec());
156        for j in 0..=n {
157            num[(k, j)] = pk[j] + (sys.d[(k, input)] - 1.0) * den[j];
158        }
159    }
160    Ok((num, den))
161}
162
163impl ContinuousStateSpace {
164    /// A model from its matrices, checking that the shapes agree.
165    pub fn new(a: Array2<f64>, b: Array2<f64>, c: Array2<f64>, d: Array2<f64>) -> Result<Self, ErrorsJSL> {
166        let n = a.nrows();
167        if a.ncols() != n || b.nrows() != n || c.ncols() != n || d.nrows() != c.nrows() || d.ncols() != b.ncols() {
168            return Err(ErrorsJSL::InvalidInputRange("A (n×n), B (n×m), C (p×n) and D (p×m) must have compatible shapes"));
169        }
170        Ok(ContinuousStateSpace { a, b, c, d })
171    }
172
173    /// The poles, the eigenvalues of `A`.
174    pub fn poles(&self) -> Result<Vec<C>, ErrorsJSL> {
175        Ok(self.a.eigvals().map_err(linalg_error)?.to_vec())
176    }
177
178    // ANCHOR: lsim
179    /// Simulates the response to the input samples `u` (one row per time) at equally spaced
180    /// times `t`, from the initial state `x0` (zero if `None`) (SciPy's `lsim`).
181    ///
182    /// The input is held constant ([`InputHold::Zero`]) or interpolated linearly
183    /// ([`InputHold::Linear`]) between samples, and each step is then exact: with
184    /// `M = [[A T, B T, 0], [0, 0, I], [0, 0, 0]]` and `e^M`'s top blocks `Φ, Γ₁, Γ₂`,
185    /// `x[i+1] = Φ x[i] + (Γ₁ − Γ₂) u[i] + Γ₂ u[i+1]`.
186    pub fn lsim(&self, u: &Array2<f64>, t: &[f64], x0: Option<&[f64]>, hold: InputHold) -> Result<Simulation, ErrorsJSL> {
187        let (n, m) = (self.a.nrows(), self.b.ncols());
188        let steps = t.len();
189        if u.nrows() != steps || u.ncols() != m {
190            return Err(ErrorsJSL::IncompatibleArraySizes((u.nrows(), steps)));
191        }
192        if steps == 0 {
193            return Err(ErrorsJSL::InvalidInputRange("need at least one time"));
194        }
195        let mut x = Array2::<f64>::zeros((steps, n));
196        let x0 = Array1::from(x0.map_or(vec![0.0; n], |v| v.to_vec()));
197        if x0.len() != n {
198            return Err(ErrorsJSL::IncompatibleArraySizes((x0.len(), n)));
199        }
200        if t[0] < 0.0 {
201            return Err(ErrorsJSL::InvalidInputRange("the initial time must be non-negative"));
202        }
203        // Before t[0] the input is zero: x(t₀) = e^{A t₀} x₀.
204        let start = if t[0] == 0.0 { x0 } else { expm(&(&self.a * t[0])).map_err(linalg_error)?.dot(&x0) };
205        x.row_mut(0).assign(&start);
206        if steps > 1 {
207            let dt = t[1] - t[0];
208            if !(dt > 0.0) || t.windows(2).any(|w| ((w[1] - w[0]) - dt).abs() > 1e-8 * dt.abs().max(1e-300) + 1e-12) {
209                return Err(ErrorsJSL::InvalidInputRange("time steps must be positive and equally spaced"));
210            }
211            let size = match hold {
212                InputHold::Zero => n + m,
213                InputHold::Linear => n + 2 * m,
214            };
215            let mut big = Array2::<f64>::zeros((size, size));
216            big.slice_mut(s![..n, ..n]).assign(&(&self.a * dt));
217            big.slice_mut(s![..n, n..n + m]).assign(&(&self.b * dt));
218            if hold == InputHold::Linear {
219                big.slice_mut(s![n..n + m, n + m..]).assign(&Array2::eye(m));
220            }
221            let e = expm(&big).map_err(linalg_error)?;
222            let phi = e.slice(s![..n, ..n]).to_owned();
223            let (g0, g1) = match hold {
224                InputHold::Zero => (e.slice(s![..n, n..n + m]).to_owned(), Array2::zeros((n, m))),
225                InputHold::Linear => {
226                    let g2 = e.slice(s![..n, n + m..]).to_owned();
227                    (&e.slice(s![..n, n..n + m]) - &g2, g2)
228                }
229            };
230            for i in 1..steps {
231                let next = phi.dot(&x.row(i - 1)) + g0.dot(&u.row(i - 1)) + g1.dot(&u.row(i));
232                x.row_mut(i).assign(&next);
233            }
234        }
235        let y = x.dot(&self.c.t()) + u.dot(&self.d.t());
236        Ok(Simulation { y, x })
237    }
238    // ANCHOR_END: lsim
239
240    /// The step response from input `input` at times `t` (SciPy's `step`, with a zero-order hold).
241    pub fn step(&self, t: &[f64], input: usize) -> Result<Array2<f64>, ErrorsJSL> {
242        let m = self.b.ncols();
243        if input >= m {
244            return Err(ErrorsJSL::InvalidInputRange("input index out of range"));
245        }
246        let u = Array2::from_shape_fn((t.len(), m), |(_, j)| if j == input { 1.0 } else { 0.0 });
247        Ok(self.lsim(&u, t, None, InputHold::Zero)?.y)
248    }
249
250    /// The impulse response `C e^{At} B` from input `input` at times `t` (SciPy's `impulse`,
251    /// which leaves out the `D δ(t)` term).
252    pub fn impulse(&self, t: &[f64], input: usize) -> Result<Array2<f64>, ErrorsJSL> {
253        if input >= self.b.ncols() {
254            return Err(ErrorsJSL::InvalidInputRange("input index out of range"));
255        }
256        let x0 = self.b.column(input).to_vec();
257        let u = Array2::zeros((t.len(), self.b.ncols()));
258        let sim = self.lsim(&u, t, Some(&x0), InputHold::Zero)?;
259        Ok(sim.x.dot(&self.c.t()))
260    }
261
262    // ANCHOR: freqresp
263    /// The frequency response `H(iω) = C (iω I − A)⁻¹ B + D` at each angular frequency, one
264    /// `p × m` matrix per frequency.
265    pub fn freqresp(&self, w: &[f64]) -> Result<Vec<Array2<C>>, ErrorsJSL> {
266        let n = self.a.nrows();
267        let a = self.a.mapv(|v| C::new(v, 0.0));
268        let b = self.b.mapv(|v| C::new(v, 0.0));
269        let c = self.c.mapv(|v| C::new(v, 0.0));
270        let d = self.d.mapv(|v| C::new(v, 0.0));
271        w.iter()
272            .map(|&wk| {
273                let m = Array2::from_shape_fn((n, n), |(i, j)| if i == j { C::new(0.0, wk) } else { C::new(0.0, 0.0) }) - &a;
274                let lu = lib_jsl_linalg::Factorize::factorize(&m).map_err(linalg_error)?;
275                let mut x = Array2::<C>::zeros(b.dim());
276                for j in 0..b.ncols() {
277                    x.column_mut(j).assign(&lu.solve(&b.column(j)).map_err(linalg_error)?);
278                }
279                Ok(c.dot(&x) + &d)
280            })
281            .collect()
282    }
283    // ANCHOR_END: freqresp
284
285    /// The Bode diagram from input `input` to output `output` (SciPy's `bode`): the magnitude
286    /// `20 log₁₀ |H(iω)|` in dB and the unwrapped phase in degrees.
287    pub fn bode(&self, w: &[f64], input: usize, output: usize) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
288        if input >= self.b.ncols() || output >= self.c.nrows() {
289            return Err(ErrorsJSL::InvalidInputRange("input or output index out of range"));
290        }
291        let h: Vec<C> = self.freqresp(w)?.iter().map(|m| m[(output, input)]).collect();
292        let mag = h.iter().map(|z| 20.0 * z.norm().log10()).collect();
293        let raw: Vec<f64> = h.iter().map(|z| z.im.atan2(z.re)).collect();
294        Ok((mag, unwrap(&raw).into_iter().map(f64::to_degrees).collect()))
295    }
296
297    // ANCHOR: discretize
298    /// The discrete-time system for sample time `dt` (SciPy's `cont2discrete`).
299    pub fn discretize(&self, dt: f64, method: Discretization) -> Result<DiscreteMatrices, ErrorsJSL> {
300        let (n, m) = (self.a.nrows(), self.b.ncols());
301        let (a, b, c, d) = (&self.a, &self.b, &self.c, &self.d);
302        let gbt = |alpha: f64| -> Result<DiscreteMatrices, ErrorsJSL> {
303            if !(0.0..=1.0).contains(&alpha) {
304                return Err(ErrorsJSL::InvalidInputRange("the bilinear parameter α must lie in [0, 1]"));
305            }
306            let eye = Array2::<f64>::eye(n);
307            let ima = &eye - &(a * (alpha * dt));
308            let inv = ima.inv().map_err(linalg_error)?;
309            let ad = inv.dot(&(&eye + &(a * ((1.0 - alpha) * dt))));
310            let bd = inv.dot(&(b * dt));
311            let cd = c.dot(&inv);
312            let dd = d + &(c.dot(&bd) * alpha);
313            Ok(DiscreteMatrices { a: ad, b: bd, c: cd, d: dd, dt })
314        };
315        match method {
316            Discretization::Gbt(alpha) => gbt(alpha),
317            Discretization::Bilinear => gbt(0.5),
318            Discretization::ForwardEuler => gbt(0.0),
319            Discretization::BackwardEuler => gbt(1.0),
320            Discretization::ZeroOrderHold => {
321                let mut big = Array2::<f64>::zeros((n + m, n + m));
322                big.slice_mut(s![..n, ..n]).assign(&(a * dt));
323                big.slice_mut(s![..n, n..]).assign(&(b * dt));
324                let e = expm(&big).map_err(linalg_error)?;
325                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 })
326            }
327            Discretization::FirstOrderHold => {
328                let mut big = Array2::<f64>::zeros((n + 2 * m, n + 2 * m));
329                big.slice_mut(s![..n, ..n]).assign(&(a * dt));
330                big.slice_mut(s![..n, n..n + m]).assign(&(b * dt));
331                big.slice_mut(s![n..n + m, n + m..]).assign(&Array2::eye(m));
332                let e = expm(&big).map_err(linalg_error)?;
333                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());
334                let bd = &m12 - &m13 + m11.dot(&m13);
335                let dd = d + &c.dot(&m13);
336                Ok(DiscreteMatrices { a: m11, b: bd, c: c.clone(), d: dd, dt })
337            }
338            Discretization::Impulse => {
339                if d.iter().any(|v| v.abs() > 1e-8) {
340                    return Err(ErrorsJSL::InvalidInputRange("impulse invariance needs a strictly proper system (D = 0)"));
341                }
342                let ad = expm(&(a * dt)).map_err(linalg_error)?;
343                let bd = ad.dot(b) * dt;
344                Ok(DiscreteMatrices { a: ad, b: bd, c: c.clone(), d: c.dot(b) * dt, dt })
345            }
346        }
347    }
348    // ANCHOR_END: discretize
349}
350
351/// Removes jumps of more than π between consecutive phases by adding multiples of 2π (NumPy's
352/// `unwrap`).
353pub fn unwrap(phase: &[f64]) -> Vec<f64> {
354    use std::f64::consts::PI;
355    let mut out = phase.to_vec();
356    let mut correction = 0.0;
357    for i in 1..phase.len() {
358        let d = phase[i] - phase[i - 1];
359        let mut dmod = (d + PI).rem_euclid(2.0 * PI) - PI;
360        if dmod == -PI && d > 0.0 {
361            dmod = PI;
362        }
363        if d.abs() >= PI {
364            correction += dmod - d;
365        }
366        out[i] = phase[i] + correction;
367    }
368    out
369}
370
371/// The result of [`place_poles`].
372#[derive(Clone, Debug)]
373pub struct PlacedPoles {
374    /// The gain `K`, such that `A − B K` has the requested poles.
375    pub gain: Array2<f64>,
376    /// The eigenvalues of `A − B K`, as computed.
377    pub computed_poles: Vec<C>,
378    /// The eigenvector matrix `X` of `A − B K` (unit columns).
379    pub transfer_matrix: Array2<C>,
380    /// Sweeps of the orthogonalisation (0 when there is no freedom to optimise).
381    pub iterations: usize,
382}
383
384/// The null space of a complex matrix (as orthonormal columns), from its SVD.
385fn null_space(m: &Array2<C>, dim: usize) -> Result<Array2<C>, ErrorsJSL> {
386    let n = m.ncols();
387    let padded = if m.nrows() < n {
388        let mut p = Array2::<C>::zeros((n, n));
389        p.slice_mut(s![..m.nrows(), ..]).assign(m);
390        p
391    } else {
392        m.clone()
393    };
394    let (_, _, vt) = padded.svd(false, true).map_err(linalg_error)?;
395    let vt = vt.expect("requested");
396    // The last `dim` rows of Vᴴ, conjugated, span the null space.
397    Ok(Array2::from_shape_fn((n, dim), |(i, j)| vt[(n - dim + j, i)].conj()))
398}
399
400// ANCHOR: place_poles
401/// A state-feedback gain `K` that places the eigenvalues of `A − B K` at `poles` (SciPy's
402/// `place_poles`). Complex poles must come in conjugate pairs, and no pole may be repeated more
403/// often than the rank of `B`.
404///
405/// Each closed-loop eigenvector `xⱼ` must lie in the subspace `Sⱼ` where
406/// `U₁ᴴ (A − λⱼ I) x = 0`, with `B = [U₀ U₁] [Z; 0]` the QR factorisation of `B`; then
407/// `K = Z⁻¹ U₀ᴴ (A X − X Λ) X⁻¹`. With one input each `Sⱼ` is a line and `K` is unique. With several,
408/// the vectors are chosen to make `X` as well conditioned as possible by the method of Kautsky,
409/// Nichols and Van Dooren (KNV0): each sweep replaces every `xⱼ` by the projection onto `Sⱼ` of
410/// the direction orthogonal to all the other columns.
411pub fn place_poles(a: &Array2<f64>, b: &Array2<f64>, poles: &[C]) -> Result<PlacedPoles, ErrorsJSL> {
412    let (n, m) = (a.nrows(), b.ncols());
413    if a.ncols() != n || b.nrows() != n || poles.len() != n {
414        return Err(ErrorsJSL::InvalidInputRange("A must be n × n, B n × m, with n poles"));
415    }
416    // Complex poles in conjugate pairs; keep a partner index for each.
417    let mut partner = vec![usize::MAX; n];
418    for i in 0..n {
419        if poles[i].im.abs() > 1e-12 * (1.0 + poles[i].norm()) && partner[i] == usize::MAX {
420            let j = (0..n).find(|&j| j != i && partner[j] == usize::MAX && (poles[j] - poles[i].conj()).norm() <= 1e-10 * (1.0 + poles[i].norm()));
421            let Some(j) = j else { return Err(ErrorsJSL::InvalidInputRange("complex poles must come in conjugate pairs")) };
422            partner[i] = j;
423            partner[j] = i;
424        }
425    }
426    let bc = b.mapv(|v| C::new(v, 0.0));
427    let ac = a.mapv(|v| C::new(v, 0.0));
428    // Full QR of B through the SVD: B = U Σ Vᴴ, U₀ = U[:, ..r], U₁ = U[:, r..].
429    let (u, sv, vt) = bc.svd(true, true).map_err(linalg_error)?;
430    let (u, vt) = (u.expect("requested"), vt.expect("requested"));
431    let rank = sv.iter().filter(|&&v| v > sv[0] * 1e-12 * n as f64).count();
432    if rank == 0 {
433        return Err(ErrorsJSL::InvalidInputRange("B is zero"));
434    }
435    for p in poles {
436        if poles.iter().filter(|q| (*q - p).norm() < 1e-10 * (1.0 + p.norm())).count() > rank {
437            return Err(ErrorsJSL::InvalidInputRange("a pole is repeated more often than the rank of B"));
438        }
439    }
440    let u0 = u.slice(s![.., ..rank]).to_owned();
441    let u1h = u.slice(s![.., rank..]).t().mapv(|v| v.conj());
442    // Bases of the admissible eigenvector spaces.
443    let eye = Array2::<C>::eye(n);
444    let spaces: Vec<Array2<C>> = poles
445        .iter()
446        .map(|&p| if rank == n { Ok(eye.clone()) } else { null_space(&u1h.dot(&(&ac - &(&eye * p))), rank) })
447        .collect::<Result<_, _>>()?;
448    // Start from the first basis vector of each space.
449    let mut x = Array2::<C>::zeros((n, n));
450    for (j, space) in spaces.iter().enumerate() {
451        x.column_mut(j).assign(&space.column(0));
452    }
453    let mut iterations = 0;
454    if rank > 1 {
455        for sweep in 0..30 {
456            let mut change: f64 = 0.0;
457            for j in 0..n {
458                if partner[j] < j {
459                    continue;
460                }
461                // The direction orthogonal to all other columns, projected onto Sⱼ.
462                let mut others = Array2::<C>::zeros((n - 1, n));
463                for (r, k) in (0..n).filter(|&k| k != j).enumerate() {
464                    others.row_mut(r).assign(&x.column(k).mapv(|v| v.conj()));
465                }
466                let y = null_space(&others, 1)?;
467                let sj = &spaces[j];
468                let proj = sj.dot(&sj.t().mapv(|v| v.conj()).dot(&y.column(0)));
469                let norm = proj.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt();
470                if norm < 1e-14 {
471                    continue;
472                }
473                let new = proj.mapv(|v| v / norm);
474                // Compare up to a phase.
475                let overlap = new.iter().zip(x.column(j).iter()).map(|(a, b)| a.conj() * b).sum::<C>().norm();
476                change = change.max(1.0 - overlap);
477                x.column_mut(j).assign(&new);
478                if partner[j] != usize::MAX {
479                    x.column_mut(partner[j]).assign(&new.mapv(|v| v.conj()));
480                }
481            }
482            iterations = sweep + 1;
483            if change < 1e-6 {
484                break;
485            }
486        }
487    }
488    // K = Z⁻¹ U₀ᴴ (A X − X Λ) X⁻¹, with Z = Σ₀ V₀ᴴ the R factor of B in the basis U₀.
489    let lambda = Array2::from_diag(&Array1::from(poles.to_vec()));
490    let xinv = x.inv().map_err(|_| ErrorsJSL::RuntimeError("the eigenvectors are dependent; the poles cannot be placed"))?;
491    let rhs = u0.t().mapv(|v| v.conj()).dot(&(ac.dot(&x) - x.dot(&lambda))).dot(&xinv);
492    let z = Array2::from_shape_fn((rank, m), |(i, j)| vt[(i, j)] * sv[i]);
493    // Minimum-norm solution of Z K = rhs (Z is rank × m with full row rank).
494    let zzh = z.dot(&z.t().mapv(|v| v.conj()));
495    let k = z.t().mapv(|v| v.conj()).dot(&zzh.inv().map_err(linalg_error)?.dot(&rhs));
496    let gain = k.mapv(|v| v.re);
497    let computed_poles = (a - &b.dot(&gain)).eigvals().map_err(linalg_error)?.to_vec();
498    Ok(PlacedPoles { gain, computed_poles, transfer_matrix: x, iterations })
499}
500// ANCHOR_END: place_poles
501
502// ANCHOR: zpk_systems
503/// Zeros, poles and gain from each output of a state-space model for one input (SciPy's
504/// `ss2zpk`), through the transfer function.
505#[allow(clippy::type_complexity)]
506pub fn ss2zpk(sys: &ContinuousStateSpace, input: usize) -> Result<Vec<(Vec<C>, Vec<C>, f64)>, ErrorsJSL> {
507    let (num, den) = ss2tf(sys, input)?;
508    num.rows().into_iter().map(|row| crate::discrete::partial_fractions::tf2zpk(&row.to_vec(), &den)).collect()
509}
510
511/// A state-space model (controllable canonical form) from zeros, poles and gain (SciPy's
512/// `zpk2ss`), through the transfer function.
513pub fn zpk2ss(z: &[C], p: &[C], k: f64) -> Result<ContinuousStateSpace, ErrorsJSL> {
514    let (b, a) = crate::discrete::partial_fractions::zpk2tf(z, p, k);
515    tf2ss(&b, &a)
516}
517// ANCHOR_END: zpk_systems
518
519impl ContinuousStateSpace {
520    /// The time grid SciPy's `step` and `impulse` use when none is given: `n` points from 0 to
521    /// `7/r`, where `r` is the smallest `|Re λ|` over the eigenvalues of `A` (7 time constants of
522    /// the slowest mode; `r = 1` if some mode is undamped).
523    pub fn default_response_times(&self, n: usize) -> Result<Vec<f64>, ErrorsJSL> {
524        let r = if self.a.nrows() == 0 {
525            1.0
526        } else {
527            let ev = self.a.eigvals().map_err(linalg_error)?;
528            let r = ev.iter().map(|z| z.re.abs()).fold(f64::INFINITY, f64::min);
529            if r == 0.0 { 1.0 } else { r }
530        };
531        let tc = 1.0 / r;
532        Ok((0..n).map(|i| if n == 1 { 0.0 } else { 7.0 * tc * i as f64 / (n - 1) as f64 }).collect())
533    }
534}
535
536/// The `[n/n]` Padé approximant of a time delay `e^{−sT}` as a transfer function `(num, den)`,
537/// highest power first: `Σ (−1)^j c_j (sT)^j / Σ c_j (sT)^j` with
538/// `c_j = (2n − j)! n! / ((2n)! j! (n − j)!)`. It is all-pass, `|H(iω)| = 1`, and its phase
539/// matches `−ωT` to order `(ωT)^{2n+1}`; append it to a model with [`tf2ss`] to include a delay.
540pub fn pade_delay(t: f64, n: usize) -> (Vec<f64>, Vec<f64>) {
541    let fact = |k: usize| (1..=k).map(|i| i as f64).product::<f64>();
542    let c: Vec<f64> = (0..=n).map(|j| fact(2 * n - j) * fact(n) / (fact(2 * n) * fact(j) * fact(n - j)) * t.powi(j as i32)).collect();
543    let den: Vec<f64> = c.iter().rev().copied().collect();
544    let num: Vec<f64> = c.iter().enumerate().rev().map(|(j, &v)| if j % 2 == 1 { -v } else { v }).collect();
545    (num, den)
546}
547
548#[cfg(test)]
549mod tests {
550
551    #[test]
552    fn pade_delay_is_all_pass_and_matches_the_phase() {
553        let (num, den) = pade_delay(0.5, 1);
554        assert_eq!((num, den), (vec![-0.25, 1.0], vec![0.25, 1.0]));
555        let (num, den) = pade_delay(0.2, 4);
556        let eval = |p: &[f64], s: C| p.iter().fold(C::new(0.0, 0.0), |acc, &c| acc * s + c);
557        for w in [0.1, 1.0, 5.0] {
558            let h = eval(&num, C::new(0.0, w)) / eval(&den, C::new(0.0, w));
559            assert!((h.norm() - 1.0).abs() < 1e-12);
560            // Phase error about 2 (n!)² / ((2n)! (2n + 1)!) (ωT)^{2n+1}, 7.9e-8 (ωT)⁹ for n = 4.
561            assert!((h.arg() + w * 0.2).abs() < 1e-7 * (w * 0.2f64).powi(9) + 1e-15, "{w}");
562        }
563    }
564
565    #[test]
566    fn default_times_cover_seven_time_constants() {
567        let sys = tf2ss(&[1.0], &[1.0, 3.0, 2.0]).unwrap();
568        let t = sys.default_response_times(100).unwrap();
569        assert!((t[99] - 7.0).abs() < 1e-12, "{}", t[99]);
570    }
571
572    use super::*;
573    use ndarray::array;
574
575    #[test]
576    fn tf2ss_and_back() {
577        let sys = tf2ss(&[1.0, 3.0, 3.0], &[1.0, 2.0, 1.0]).unwrap();
578        assert_eq!(sys.a, array![[-2.0, -1.0], [1.0, 0.0]]);
579        assert_eq!(sys.c, array![[1.0, 2.0]]);
580        assert_eq!(sys.d, array![[1.0]]);
581        let (num, den) = ss2tf(&sys, 0).unwrap();
582        for (got, want) in num.row(0).iter().zip([1.0, 3.0, 3.0]) {
583            assert!((got - want).abs() < 1e-12);
584        }
585        for (got, want) in den.iter().zip([1.0, 2.0, 1.0]) {
586            assert!((got - want).abs() < 1e-12);
587        }
588    }
589
590    #[test]
591    fn first_order_step_response_is_exact() {
592        // H(s) = 1 / (s + 2): y(t) = (1 − e^{−2t}) / 2.
593        let sys = tf2ss(&[1.0], &[1.0, 2.0]).unwrap();
594        let t: Vec<f64> = (0..50).map(|i| i as f64 * 0.1).collect();
595        let y = sys.step(&t, 0).unwrap();
596        for (i, &ti) in t.iter().enumerate() {
597            assert!((y[(i, 0)] - (1.0 - (-2.0 * ti).exp()) / 2.0).abs() < 1e-14);
598        }
599        let h = sys.impulse(&t, 0).unwrap();
600        assert!((h[(10, 0)] - (-2.0f64).exp()).abs() < 1e-14);
601    }
602
603    #[test]
604    fn placed_poles_are_achieved() {
605        let a = array![[0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 11.0, 0.0]];
606        let b1 = array![[0.0], [1.0], [0.0], [-1.0]];
607        let b2 = array![[0.0, 0.0], [1.0, 0.0], [0.0, 0.0], [-1.0, 1.0]];
608        let want = [C::new(-1.0, 1.0), C::new(-1.0, -1.0), C::new(-2.0, 0.0), C::new(-3.0, 0.0)];
609        for b in [b1, b2] {
610            let r = place_poles(&a, &b, &want).unwrap();
611            for p in &want {
612                assert!(r.computed_poles.iter().any(|q| (q - p).norm() < 1e-8), "{p} not in {:?}", r.computed_poles);
613            }
614        }
615    }
616}