1use 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#[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 pub dt: Option<f64>,
32}
33
34impl ZerosPolesGain {
35 pub fn new(zeros: Vec<C>, poles: Vec<C>, gain: f64) -> Self {
37 ZerosPolesGain { zeros, poles, gain, dt: None }
38 }
39
40 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 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 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 pub fn to_tf(&self) -> (Vec<f64>, Vec<f64>) {
65 zpk2tf(&self.zeros, &self.poles, self.gain)
66 }
67
68 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 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 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 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 pub fn step(&self, t: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
116 Ok(self.continuous()?.step(t, 0)?.column(0).to_vec())
117 }
118
119 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 let mut bp = vec![0.0; a.len() - b.len()];
134 bp.extend(b);
135 Ok((bp, a))
136 }
137
138 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 pub fn dstep(&self, n: usize) -> Result<Vec<f64>, ErrorsJSL> {
146 self.dlsim(&vec![1.0; n])
147 }
148
149 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 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#[cfg(test)]
170mod tests {
171 use super::*;
172
173 #[test]
174 fn first_order_lag() {
175 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 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}