Skip to main content

lib_jsl_dsp/continuous/
zpk.rs

1//! Linear time-invariant systems held as zeros, poles and gain (SciPy's `ZerosPolesGain`), in
2//! continuous or discrete time.
3//!
4//! The factored form `H(s) = k ∏(s − zᵢ) / ∏(s − pⱼ)` is the natural output of filter design
5//! and the numerically safe one: the frequency response is evaluated factor by factor, without
6//! forming polynomial coefficients whose roots are ill-conditioned for high orders.
7//!
8//! See the book entry [Continuous-time systems](https://jwkunz.github.io/lib_jsl/book/comms/continuous-time.html#zeros-poles-and-gain-as-a-system).
9
10use super::lti::{ContinuousStateSpace, Discretization, InputHold, ss2zpk, tf2ss, unwrap};
11use crate::discrete::filters::iir::zero_phase::lfilter;
12use crate::discrete::partial_fractions::{tf2zpk, zpk2tf};
13use lib_jsl_core::ErrorsJSL;
14use ndarray::Array2;
15use num_complex::Complex;
16
17type C = Complex<f64>;
18
19// ANCHOR: zpk
20/// A single-input, single-output system `H = k ∏(x − zᵢ) / ∏(x − pⱼ)` with `x = s` in
21/// continuous time (`dt = None`) or `x = z` in discrete time with sample time `dt` (SciPy's
22/// `ZerosPolesGain` and `lti(z, p, k)` / `dlti(z, p, k, dt=dt)`). Complex zeros and poles must
23/// come in conjugate pairs for the real-coefficient conversions.
24#[derive(Clone, Debug, PartialEq)]
25#[non_exhaustive]
26pub struct ZerosPolesGain {
27    pub zeros: Vec<C>,
28    pub poles: Vec<C>,
29    pub gain: f64,
30    /// The sample time of a discrete-time system; `None` in continuous time.
31    pub dt: Option<f64>,
32}
33
34impl ZerosPolesGain {
35    /// A continuous-time system.
36    pub fn new(zeros: Vec<C>, poles: Vec<C>, gain: f64) -> Self {
37        ZerosPolesGain { zeros, poles, gain, dt: None }
38    }
39
40    /// A discrete-time system with sample time `dt > 0`.
41    pub fn new_discrete(zeros: Vec<C>, poles: Vec<C>, gain: f64, dt: f64) -> Result<Self, ErrorsJSL> {
42        if !(dt > 0.0 && dt.is_finite()) {
43            return Err(ErrorsJSL::InvalidInputRange("the sample time must be positive"));
44        }
45        Ok(ZerosPolesGain { zeros, poles, gain, dt: Some(dt) })
46    }
47
48    /// From a transfer function `num/den` (highest power first), through [`tf2zpk`].
49    pub fn from_tf(num: &[f64], den: &[f64], dt: Option<f64>) -> Result<Self, ErrorsJSL> {
50        let (z, p, k) = tf2zpk(num, den)?;
51        Ok(ZerosPolesGain { zeros: z, poles: p, gain: k, dt })
52    }
53
54    /// From a single-input, single-output state-space model.
55    pub fn from_ss(sys: &ContinuousStateSpace, dt: Option<f64>) -> Result<Self, ErrorsJSL> {
56        if sys.b.ncols() != 1 || sys.c.nrows() != 1 {
57            return Err(ErrorsJSL::InvalidInputRange("a ZerosPolesGain system has one input and one output"));
58        }
59        let (z, p, k) = ss2zpk(sys, 0)?.remove(0);
60        Ok(ZerosPolesGain { zeros: z, poles: p, gain: k, dt })
61    }
62
63    /// The transfer function `(num, den)`, highest power first (SciPy's `to_tf`).
64    pub fn to_tf(&self) -> (Vec<f64>, Vec<f64>) {
65        zpk2tf(&self.zeros, &self.poles, self.gain)
66    }
67
68    /// A state-space realisation in controllable canonical form (SciPy's `to_ss`). For a
69    /// discrete-time system the matrices are those of `x[k+1] = A x[k] + B u[k]`.
70    pub fn to_ss(&self) -> Result<ContinuousStateSpace, ErrorsJSL> {
71        let (b, a) = self.to_tf();
72        tf2ss(&b, &a)
73    }
74
75    fn eval(&self, x: C) -> C {
76        let num = self.zeros.iter().fold(C::new(self.gain, 0.0), |acc, z| acc * (x - z));
77        self.poles.iter().fold(num, |acc, p| acc / (x - p))
78    }
79
80    /// The frequency response at the angular frequencies `w`: `H(iω)` in continuous time
81    /// (rad/s), `H(e^{iω})` in discrete time (rad/sample, as SciPy's `dfreqresp`), evaluated
82    /// factor by factor.
83    pub fn freqresp(&self, w: &[f64]) -> Vec<C> {
84        match self.dt {
85            None => w.iter().map(|&w| self.eval(C::new(0.0, w))).collect(),
86            Some(_) => w.iter().map(|&w| self.eval(C::from_polar(1.0, w))).collect(),
87        }
88    }
89
90    /// The Bode diagram: `20 log₁₀|H|` in dB and the unwrapped phase in degrees (SciPy's `bode`
91    /// and `dbode`; in discrete time `w` is in rad/sample).
92    pub fn bode(&self, w: &[f64]) -> (Vec<f64>, Vec<f64>) {
93        let h = self.freqresp(w);
94        let mag = h.iter().map(|v| 20.0 * v.norm().log10()).collect();
95        let phase = unwrap(&h.iter().map(|v| v.arg()).collect::<Vec<_>>()).iter().map(|p| p.to_degrees()).collect();
96        (mag, phase)
97    }
98
99    fn continuous(&self) -> Result<ContinuousStateSpace, ErrorsJSL> {
100        if self.dt.is_some() {
101            return Err(ErrorsJSL::InvalidInputRange("this is a discrete-time system: use dlsim, dstep or dimpulse"));
102        }
103        self.to_ss()
104    }
105
106    /// The response to the input samples `u` at equally spaced times `t` from rest, with the
107    /// input held or interpolated between samples (SciPy's `lsim`). Continuous time only.
108    pub fn lsim(&self, u: &[f64], t: &[f64], hold: InputHold) -> Result<Vec<f64>, ErrorsJSL> {
109        let ss = self.continuous()?;
110        let u = Array2::from_shape_vec((u.len(), 1), u.to_vec()).map_err(|_| ErrorsJSL::InvalidInputRange("bad input"))?;
111        Ok(ss.lsim(&u, t, None, hold)?.y.column(0).to_vec())
112    }
113
114    /// The step response at times `t` (SciPy's `step`). Continuous time only.
115    pub fn step(&self, t: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
116        Ok(self.continuous()?.step(t, 0)?.column(0).to_vec())
117    }
118
119    /// The impulse response at times `t` (SciPy's `impulse`). Continuous time only.
120    pub fn impulse(&self, t: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
121        Ok(self.continuous()?.impulse(t, 0)?.column(0).to_vec())
122    }
123
124    fn discrete_tf(&self) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
125        if self.dt.is_none() {
126            return Err(ErrorsJSL::InvalidInputRange("this is a continuous-time system: use lsim, step or impulse"));
127        }
128        if self.zeros.len() > self.poles.len() {
129            return Err(ErrorsJSL::InvalidInputRange("a causal discrete-time system has no more zeros than poles"));
130        }
131        let (b, a) = self.to_tf();
132        // Positive powers of z to the delay form b(z⁻¹)/a(z⁻¹): pad the numerator in front.
133        let mut bp = vec![0.0; a.len() - b.len()];
134        bp.extend(b);
135        Ok((bp, a))
136    }
137
138    /// The response to the samples `u` from rest (SciPy's `dlsim`). Discrete time only.
139    pub fn dlsim(&self, u: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
140        let (b, a) = self.discrete_tf()?;
141        Ok(lfilter(&b, &a, u, None)?.0)
142    }
143
144    /// The first `n` samples of the step response (SciPy's `dstep`). Discrete time only.
145    pub fn dstep(&self, n: usize) -> Result<Vec<f64>, ErrorsJSL> {
146        self.dlsim(&vec![1.0; n])
147    }
148
149    /// The first `n` samples of the response to a unit pulse at `k = 0` (SciPy's `dimpulse`).
150    /// Discrete time only.
151    pub fn dimpulse(&self, n: usize) -> Result<Vec<f64>, ErrorsJSL> {
152        let mut u = vec![0.0; n];
153        if n > 0 {
154            u[0] = 1.0;
155        }
156        self.dlsim(&u)
157    }
158
159    /// The discrete-time system for sample time `dt` (SciPy's `to_discrete`, i.e.
160    /// `cont2discrete` on the state-space form and back).
161    pub fn to_discrete(&self, dt: f64, method: Discretization) -> Result<ZerosPolesGain, ErrorsJSL> {
162        let d = self.continuous()?.discretize(dt, method)?;
163        let ss = ContinuousStateSpace::new(d.a, d.b, d.c, d.d)?;
164        ZerosPolesGain::from_ss(&ss, Some(dt))
165    }
166}
167// ANCHOR_END: zpk
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn first_order_lag() {
175        // H(s) = 2/(s + 1).
176        let h = ZerosPolesGain::new(vec![], vec![C::new(-1.0, 0.0)], 2.0);
177        let r = h.freqresp(&[0.0, 1.0]);
178        assert!((r[0] - C::new(2.0, 0.0)).norm() < 1e-15);
179        assert!((r[1] - C::new(1.0, -1.0)).norm() < 1e-15);
180        let (mag, ph) = h.bode(&[1.0]);
181        assert!((mag[0] - 20.0 * 2f64.sqrt().log10()).abs() < 1e-12 && (ph[0] + 45.0).abs() < 1e-12);
182        let t: Vec<f64> = (0..50).map(|i| i as f64 * 0.1).collect();
183        let s = h.step(&t).unwrap();
184        assert!(t.iter().zip(&s).all(|(t, y)| (y - 2.0 * (1.0 - (-t).exp())).abs() < 1e-10));
185        assert_eq!(h.to_tf(), (vec![2.0], vec![1.0, 1.0]));
186        let back = ZerosPolesGain::from_tf(&[2.0], &[1.0, 1.0], None).unwrap();
187        assert_eq!(back, h);
188        assert!(h.dstep(3).is_err());
189        // Zero-order hold: pole e^{−dt}, gain 2(1 − e^{−dt}).
190        let d = h.to_discrete(0.5, Discretization::ZeroOrderHold).unwrap();
191        assert!((d.poles[0].re - (-0.5f64).exp()).abs() < 1e-14);
192        let y = d.dstep(20).unwrap();
193        assert!(y.iter().enumerate().all(|(k, y)| (y - 2.0 * (1.0 - (-0.5 * k as f64).exp())).abs() < 1e-12));
194        assert!(d.step(&t).is_err());
195    }
196}