Skip to main content

lib_jsl_dsp/discrete/
partial_fractions.rs

1//! Partial fractions of rational transfer functions and related polynomial tools, ported from
2//! `scipy.signal`: `residue`/`invres` (positive powers of `s` or `z`), `residuez`/`invresz`
3//! (negative powers of `z`), `unique_roots`, `deconvolve`, and the zero-pole-gain conversions
4//! `tf2zpk`/`zpk2tf`.
5//!
6//! See the book entry [Partial fractions, zoom FFT and waveforms](https://jwkunz.github.io/lib_jsl/book/spectral/partial-fractions-waveforms.html).
7
8use lib_jsl_core::ErrorsJSL;
9use lib_jsl_linalg::EigVals;
10use ndarray::Array2;
11use num_complex::Complex;
12
13type C = Complex<f64>;
14
15/// How [`unique_roots`] represents a group of nearly equal roots.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum RootType {
18    /// The mean of the group (SciPy's `'avg'`, the default of `residue`).
19    Average,
20    /// The smallest, comparing real parts then imaginary parts.
21    Min,
22    /// The largest.
23    Max,
24}
25
26fn reduce(group: &[C], rtype: RootType) -> C {
27    let cmp = |a: &&C, b: &&C| a.re.total_cmp(&b.re).then(a.im.total_cmp(&b.im));
28    match rtype {
29        RootType::Average => group.iter().sum::<C>() / group.len() as f64,
30        RootType::Min => *group.iter().min_by(cmp).expect("non-empty"),
31        RootType::Max => *group.iter().max_by(cmp).expect("non-empty"),
32    }
33}
34
35/// The roots of a polynomial, highest power first (NumPy's `roots`): leading zeros are dropped,
36/// trailing zeros give roots at 0, and the rest are the eigenvalues of the companion matrix.
37/// Complex-conjugate pairs are listed with the positive imaginary part first, as LAPACK does.
38pub fn roots(p: &[f64]) -> Result<Vec<C>, ErrorsJSL> {
39    roots_complex(&p.iter().map(|&v| C::new(v, 0.0)).collect::<Vec<_>>())
40}
41
42fn roots_complex(p: &[C]) -> Result<Vec<C>, ErrorsJSL> {
43    let nz: Vec<usize> = (0..p.len()).filter(|&i| p[i] != C::new(0.0, 0.0)).collect();
44    let (Some(&first), Some(&last)) = (nz.first(), nz.last()) else { return Ok(Vec::new()) };
45    let trailing = p.len() - 1 - last;
46    let q = &p[first..=last];
47    let n = q.len() - 1;
48    let mut out = Vec::with_capacity(n + trailing);
49    if n > 0 {
50        let real = q.iter().all(|c| c.im == 0.0);
51        let mut ev: Vec<C> = if real {
52            // A real companion matrix: the real Schur form gives exact conjugate pairs, as LAPACK.
53            let comp = Array2::from_shape_fn((n, n), |(r, c)| if r == 0 { -q[c + 1].re / q[0].re } else if r == c + 1 { 1.0 } else { 0.0 });
54            comp.eigvals().map_err(|_| ErrorsJSL::RuntimeError("the eigenvalue iteration failed"))?.to_vec()
55        } else {
56            let comp = Array2::from_shape_fn((n, n), |(r, c)| if r == 0 { -q[c + 1] / q[0] } else if r == c + 1 { C::new(1.0, 0.0) } else { C::new(0.0, 0.0) });
57            comp.eigvals().map_err(|_| ErrorsJSL::RuntimeError("the eigenvalue iteration failed"))?.to_vec()
58        };
59        if real {
60            // Make conjugate pairs exact and put the positive imaginary part first.
61            for i in 0..ev.len() {
62                if ev[i].im < 0.0 {
63                    let target = ev[i].conj();
64                    let tol = 1e-8 * ev[i].norm().max(1.0);
65                    if let Some(j) = (i + 1..ev.len()).find(|&j| (ev[j] - target).norm() <= tol) {
66                        let z = ev[j];
67                        ev[i] = z;
68                        ev[j] = z.conj();
69                    }
70                }
71            }
72        }
73        out.extend(ev);
74    }
75    out.extend(std::iter::repeat_n(C::new(0.0, 0.0), trailing));
76    Ok(out)
77}
78
79// ANCHOR: unique_roots
80/// Groups nearly equal roots (SciPy's `unique_roots`): going through `p` in order, each root not
81/// yet used takes every unused root within distance `tol` of it into its group; the group is
82/// represented by its mean, minimum or maximum. Returns the representatives and multiplicities.
83pub fn unique_roots(p: &[C], tol: f64, rtype: RootType) -> (Vec<C>, Vec<usize>) {
84    let mut used = vec![false; p.len()];
85    let (mut unique, mut mult) = (Vec::new(), Vec::new());
86    for i in 0..p.len() {
87        if used[i] {
88            continue;
89        }
90        let group: Vec<usize> = (0..p.len()).filter(|&j| !used[j] && (p[j] - p[i]).norm() <= tol).collect();
91        let values: Vec<C> = group.iter().map(|&j| p[j]).collect();
92        unique.push(reduce(&values, rtype));
93        mult.push(group.len());
94        for j in group {
95            used[j] = true;
96        }
97    }
98    (unique, mult)
99}
100// ANCHOR_END: unique_roots
101
102// --------------------------------------------------------------- polynomial helpers (NumPy's)
103
104fn polymul(a: &[C], b: &[C]) -> Vec<C> {
105    if a.is_empty() || b.is_empty() {
106        return Vec::new();
107    }
108    let mut out = vec![C::new(0.0, 0.0); a.len() + b.len() - 1];
109    for (i, x) in a.iter().enumerate() {
110        for (j, y) in b.iter().enumerate() {
111            out[i + j] += x * y;
112        }
113    }
114    out
115}
116
117fn polyadd(a: &[C], b: &[C]) -> Vec<C> {
118    let n = a.len().max(b.len());
119    let mut out = vec![C::new(0.0, 0.0); n];
120    for (i, x) in a.iter().enumerate() {
121        out[n - a.len() + i] += x;
122    }
123    for (i, x) in b.iter().enumerate() {
124        out[n - b.len() + i] += x;
125    }
126    out
127}
128
129fn polyval(p: &[C], x: C) -> C {
130    p.iter().fold(C::new(0.0, 0.0), |acc, &c| acc * x + c)
131}
132
133/// NumPy's `polydiv`: quotient and remainder, with leading remainder terms within an absolute
134/// `10⁻⁸` of zero stripped (NumPy's `allclose(r[0], 0, rtol=1e-14)`).
135fn polydiv(u: &[C], v: &[C]) -> (Vec<C>, Vec<C>) {
136    let m = u.len() - 1;
137    let n = v.len() - 1;
138    let scale = C::new(1.0, 0.0) / v[0];
139    let mut q = vec![C::new(0.0, 0.0); (m + 1).saturating_sub(n).max(1)];
140    let mut r = u.to_vec();
141    if m >= n {
142        for k in 0..=m - n {
143            let d = scale * r[k];
144            q[k] = d;
145            for (i, vi) in v.iter().enumerate() {
146                r[k + i] -= d * vi;
147            }
148        }
149    }
150    let mut start = 0;
151    while start + 1 < r.len() && r[start].norm() <= 1e-8 {
152        start += 1;
153    }
154    (q, r[start..].to_vec())
155}
156
157fn to_c(p: &[f64]) -> Vec<C> {
158    p.iter().map(|&v| C::new(v, 0.0)).collect()
159}
160
161fn trim_front(p: &[f64]) -> Vec<f64> {
162    p.iter().copied().skip_while(|&v| v == 0.0).collect()
163}
164
165fn trim_back(p: &[f64]) -> Vec<f64> {
166    let mut v = p.to_vec();
167    while v.last() == Some(&0.0) {
168        v.pop();
169    }
170    v
171}
172
173/// Sorts by magnitude, stably (SciPy's `_cmplx_sort`).
174fn cmplx_sort(p: &[C]) -> (Vec<C>, Vec<usize>) {
175    let mut idx: Vec<usize> = (0..p.len()).collect();
176    idx.sort_by(|&a, &b| p[a].norm().total_cmp(&p[b].norm()));
177    (idx.iter().map(|&i| p[i]).collect(), idx)
178}
179
180/// The total product divided by each root's factor (SciPy's `_compute_factors`); with
181/// `include_powers` one entry per power of each repeated root.
182fn compute_factors(roots: &[C], mult: &[usize], include_powers: bool) -> (Vec<Vec<C>>, Vec<C>) {
183    let one = vec![C::new(1.0, 0.0)];
184    let mut current = one.clone();
185    let mut suffixes = vec![current.clone()];
186    for (pole, &m) in roots.iter().zip(mult).skip(1).rev() {
187        let mono = vec![C::new(1.0, 0.0), -pole];
188        for _ in 0..m {
189            current = polymul(&current, &mono);
190        }
191        suffixes.push(current.clone());
192    }
193    suffixes.reverse();
194    let mut factors = Vec::new();
195    let mut current = one;
196    for ((pole, &m), suffix) in roots.iter().zip(mult).zip(&suffixes) {
197        let mono = vec![C::new(1.0, 0.0), -pole];
198        let mut block = Vec::new();
199        for i in 0..m {
200            if i == 0 || include_powers {
201                block.push(polymul(&current, suffix));
202            }
203            current = polymul(&current, &mono);
204        }
205        block.reverse();
206        factors.extend(block);
207    }
208    (factors, current)
209}
210
211// ANCHOR: compute_residues
212/// The residues for poles of given multiplicity (SciPy's `_compute_residues`, "deflation through
213/// subtraction", method 6 of Mahoney and Sivazlian): a simple pole's residue is
214/// `b(p)/∏_{q≠p}(p − q)`; for a repeated pole, divide numerator and the cofactor by `(x − p)`
215/// repeatedly, peeling off one residue per power and subtracting its contribution.
216fn compute_residues(poles: &[C], mult: &[usize], numerator: &[C]) -> Vec<C> {
217    let (factors, _) = compute_factors(poles, mult, false);
218    let mut residues = Vec::new();
219    for ((pole, &m), factor) in poles.iter().zip(mult).zip(&factors) {
220        if m == 1 {
221            residues.push(polyval(numerator, *pole) / polyval(factor, *pole));
222        } else {
223            let mono = vec![C::new(1.0, 0.0), -pole];
224            let (factor, d) = polydiv(factor, &mono);
225            let mut numer = numerator.to_vec();
226            let mut block = Vec::new();
227            for _ in 0..m {
228                let (q, n) = polydiv(&numer, &mono);
229                let r = n[0] / d[0];
230                numer = polyadd(&q, &factor.iter().map(|f| -r * f).collect::<Vec<_>>());
231                block.push(r);
232            }
233            block.reverse();
234            residues.extend(block);
235        }
236    }
237    residues
238}
239// ANCHOR_END: compute_residues
240
241/// The partial-fraction expansion: residues `r`, poles `p` (repeated poles adjacent, ordered by
242/// magnitude) and the direct polynomial term `k` (highest power first for `residue`, increasing
243/// powers of `z⁻¹` for `residuez`).
244#[derive(Clone, Debug, PartialEq)]
245pub struct PartialFractions {
246    pub r: Vec<C>,
247    pub p: Vec<C>,
248    pub k: Vec<f64>,
249}
250
251// ANCHOR: residue
252/// The partial-fraction expansion of `b(s)/a(s)` in positive powers (SciPy's `residue`):
253/// `Σ rᵢ/(s − pᵢ) + k(s)`, with terms `r/(s − p)^j` for poles repeated within `tol`.
254pub fn residue(b: &[f64], a: &[f64], tol: f64, rtype: RootType) -> Result<PartialFractions, ErrorsJSL> {
255    let b = trim_front(b);
256    let a = trim_front(a);
257    if a.is_empty() {
258        return Err(ErrorsJSL::InvalidInputRange("the denominator is zero"));
259    }
260    let mut poles = roots(&a)?;
261    if b.is_empty() {
262        return Ok(PartialFractions { r: vec![C::new(0.0, 0.0); poles.len()], p: cmplx_sort(&poles).0, k: Vec::new() });
263    }
264    let (k, bnum) = if b.len() < a.len() { (Vec::new(), to_c(&b)) } else { polydiv(&to_c(&b), &to_c(&a)) };
265    let (unique, mult) = unique_roots(&poles, tol, rtype);
266    let (unique, order) = cmplx_sort(&unique);
267    let mult: Vec<usize> = order.iter().map(|&i| mult[i]).collect();
268    let residues = compute_residues(&unique, &mult, &bnum);
269    let mut index = 0;
270    for (pole, &m) in unique.iter().zip(&mult) {
271        for slot in poles.iter_mut().skip(index).take(m) {
272            *slot = *pole;
273        }
274        index += m;
275    }
276    Ok(PartialFractions { r: residues.iter().map(|r| r / a[0]).collect(), p: poles, k: k.iter().map(|c| c.re).collect() })
277}
278// ANCHOR_END: residue
279
280/// The partial-fraction expansion of `b(z)/a(z)` in negative powers of `z` (SciPy's `residuez`):
281/// `Σ rᵢ/(1 − pᵢz⁻¹) + k₀ + k₁z⁻¹ + …`.
282pub fn residuez(b: &[f64], a: &[f64], tol: f64, rtype: RootType) -> Result<PartialFractions, ErrorsJSL> {
283    let b = trim_back(b);
284    let a = trim_back(a);
285    if a.is_empty() {
286        return Err(ErrorsJSL::InvalidInputRange("the denominator is zero"));
287    }
288    if a[0] == 0.0 {
289        return Err(ErrorsJSL::InvalidInputRange("the first denominator coefficient must be non-zero"));
290    }
291    let mut poles = roots(&a)?;
292    if b.is_empty() {
293        return Ok(PartialFractions { r: vec![C::new(0.0, 0.0); poles.len()], p: cmplx_sort(&poles).0, k: Vec::new() });
294    }
295    let b_rev: Vec<f64> = b.iter().rev().copied().collect();
296    let a_rev: Vec<f64> = a.iter().rev().copied().collect();
297    let (k_rev, b_rev) = if b_rev.len() < a_rev.len() { (Vec::new(), to_c(&b_rev)) } else { polydiv(&to_c(&b_rev), &to_c(&a_rev)) };
298    let (unique, mult) = unique_roots(&poles, tol, rtype);
299    let (unique, order) = cmplx_sort(&unique);
300    let mult: Vec<usize> = order.iter().map(|&i| mult[i]).collect();
301    let inv: Vec<C> = unique.iter().map(|p| C::new(1.0, 0.0) / p).collect();
302    let mut residues = compute_residues(&inv, &mult, &b_rev);
303    let mut index = 0;
304    let mut powers = vec![0i32; residues.len()];
305    for (pole, &m) in unique.iter().zip(&mult) {
306        for j in 0..m {
307            poles[index + j] = *pole;
308            powers[index + j] = 1 + j as i32;
309        }
310        index += m;
311    }
312    for (i, r) in residues.iter_mut().enumerate() {
313        *r *= (-poles[i]).powi(powers[i]) / a_rev[0];
314    }
315    Ok(PartialFractions { r: residues, p: poles, k: k_rev.iter().rev().map(|c| c.re).collect() })
316}
317
318/// Groups consecutive poles within `tol` of the first of the group (SciPy's `_group_poles`).
319fn group_poles(p: &[C], tol: f64, rtype: RootType) -> (Vec<C>, Vec<usize>) {
320    let (mut unique, mut mult) = (Vec::new(), Vec::new());
321    let mut pole = p[0];
322    let mut block = vec![pole];
323    for &q in &p[1..] {
324        if (q - pole).norm() <= tol {
325            block.push(pole);
326        } else {
327            unique.push(reduce(&block, rtype));
328            mult.push(block.len());
329            pole = q;
330            block = vec![pole];
331        }
332    }
333    unique.push(reduce(&block, rtype));
334    mult.push(block.len());
335    (unique, mult)
336}
337
338/// `b(s)` and `a(s)` from a partial-fraction expansion (SciPy's `invres`); repeated poles must
339/// be adjacent. Complex results whose imaginary parts cancel to rounding are returned as real
340/// parts together with the largest imaginary part dropped.
341pub fn invres(r: &[C], p: &[C], k: &[f64], tol: f64, rtype: RootType) -> (Vec<C>, Vec<C>) {
342    let k = trim_front(k);
343    let (unique, mult) = group_poles(p, tol, rtype);
344    let (factors, denominator) = compute_factors(&unique, &mult, true);
345    let mut numerator = if k.is_empty() { vec![C::new(0.0, 0.0)] } else { polymul(&to_c(&k), &denominator) };
346    for (res, factor) in r.iter().zip(&factors) {
347        numerator = polyadd(&numerator, &factor.iter().map(|f| res * f).collect::<Vec<_>>());
348    }
349    (numerator, denominator)
350}
351
352/// `b(z)` and `a(z)` in negative powers of `z` from a partial-fraction expansion (SciPy's
353/// `invresz`).
354pub fn invresz(r: &[C], p: &[C], k: &[f64], tol: f64, rtype: RootType) -> (Vec<C>, Vec<C>) {
355    let k = trim_back(k);
356    let (unique, mult) = group_poles(p, tol, rtype);
357    let (factors, denominator) = compute_factors(&unique, &mult, true);
358    let rev = |v: &[C]| v.iter().rev().copied().collect::<Vec<_>>();
359    let mut numerator = if k.is_empty() { vec![C::new(0.0, 0.0)] } else { polymul(&rev(&to_c(&k)), &rev(&denominator)) };
360    for (res, factor) in r.iter().zip(&factors) {
361        numerator = polyadd(&numerator, &rev(factor).iter().map(|f| res * f).collect::<Vec<_>>());
362    }
363    (rev(&numerator), denominator)
364}
365
366// ANCHOR: deconvolve
367/// Inverse filtering (SciPy's `deconvolve`): the quotient `q` and remainder `r` with
368/// `signal = divisor ∗ q + r`, `q` being the impulse response of `signal(z)/divisor(z)` for
369/// `len(signal) − len(divisor) + 1` samples. It is polynomial division, so it is unstable when the
370/// divisor has zeros outside the unit circle.
371pub fn deconvolve(signal: &[f64], divisor: &[f64]) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
372    let (n, d) = (signal.len(), divisor.len());
373    if n == 0 || d == 0 {
374        return Err(ErrorsJSL::InvalidInputRange("signal and divisor must be non-empty"));
375    }
376    if divisor[0] == 0.0 {
377        return Err(ErrorsJSL::InvalidInputRange("the divisor's first coefficient must be non-zero"));
378    }
379    if d > n {
380        return Ok((Vec::new(), signal.to_vec()));
381    }
382    let len = n - d + 1;
383    let mut q = vec![0.0; len];
384    for i in 0..len {
385        let s: f64 = (1..d.min(i + 1)).map(|k| divisor[k] * q[i - k]).sum();
386        q[i] = (signal[i] - s) / divisor[0];
387    }
388    let mut rem = signal.to_vec();
389    for (i, qi) in q.iter().enumerate() {
390        for (k, dk) in divisor.iter().enumerate() {
391            rem[i + k] -= dk * qi;
392        }
393    }
394    Ok((q, rem))
395}
396// ANCHOR_END: deconvolve
397
398/// Zeros, poles and gain of `b(s)/a(s)` (SciPy's `tf2zpk`): both are normalised by the leading
399/// denominator coefficient, the gain is the leading numerator coefficient, and the zeros and poles
400/// are the roots of the normalised polynomials.
401pub fn tf2zpk(b: &[f64], a: &[f64]) -> Result<(Vec<C>, Vec<C>, f64), ErrorsJSL> {
402    let a = trim_front(a);
403    if a.is_empty() {
404        return Err(ErrorsJSL::InvalidInputRange("the denominator is zero"));
405    }
406    let b: Vec<f64> = trim_front(b).iter().map(|v| v / a[0]).collect();
407    let a: Vec<f64> = a.iter().map(|v| v / a[0]).collect();
408    let k = b.first().copied().unwrap_or(0.0);
409    let bn: Vec<f64> = if k == 0.0 { Vec::new() } else { b.iter().map(|v| v / k).collect() };
410    Ok((roots(&bn)?, roots(&a)?, k))
411}
412
413/// `b(s)` and `a(s)` from zeros, poles and gain (SciPy's `zpk2tf`), real when the zeros and
414/// poles come in conjugate pairs.
415pub fn zpk2tf(z: &[C], p: &[C], k: f64) -> (Vec<f64>, Vec<f64>) {
416    let b = crate::continuous::lti::poly_from_roots(z).iter().map(|v| v * k).collect();
417    (b, crate::continuous::lti::poly_from_roots(p))
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423
424    fn close(a: C, b: C, tol: f64) -> bool {
425        (a - b).norm() <= tol * b.norm().max(1.0)
426    }
427
428    #[test]
429    fn residue_of_a_simple_rational_function() {
430        // (s + 2)/((s + 1)(s + 3)) = 0.5/(s + 1) + 0.5/(s + 3).
431        let pf = residue(&[1.0, 2.0], &[1.0, 4.0, 3.0], 1e-3, RootType::Average).unwrap();
432        assert!(pf.k.is_empty());
433        for (r, p) in pf.r.iter().zip(&pf.p) {
434            assert!(close(*r, C::new(0.5, 0.0), 1e-14));
435            assert!(close(*p, C::new(-1.0, 0.0), 1e-14) || close(*p, C::new(-3.0, 0.0), 1e-14));
436        }
437        // A double pole: 1/(s + 1)² has r = [0, 1] for powers 1 and 2.
438        let pf = residue(&[1.0], &[1.0, 2.0, 1.0], 1e-3, RootType::Average).unwrap();
439        assert!(close(pf.r[0], C::new(0.0, 0.0), 1e-7) && close(pf.r[1], C::new(1.0, 0.0), 1e-7), "{:?}", pf.r);
440        let (b, a) = invres(&pf.r, &pf.p, &pf.k, 1e-3, RootType::Average);
441        assert!(close(b[b.len() - 1], C::new(1.0, 0.0), 1e-7) && close(a[1], C::new(2.0, 0.0), 1e-7));
442    }
443
444    #[test]
445    fn residuez_round_trips() {
446        let b = [1.0, -0.5, 0.25];
447        let a = [1.0, -0.9, 0.2];
448        let pf = residuez(&b, &a, 1e-3, RootType::Average).unwrap();
449        let (b2, a2) = invresz(&pf.r, &pf.p, &pf.k, 1e-3, RootType::Average);
450        for (x, y) in b2.iter().zip(&b) {
451            assert!(close(*x, C::new(*y, 0.0), 1e-12), "{b2:?}");
452        }
453        for (x, y) in a2.iter().zip(&a) {
454            assert!(close(*x, C::new(*y, 0.0), 1e-12), "{a2:?}");
455        }
456    }
457
458    #[test]
459    fn deconvolve_recovers_the_signal() {
460        let (q, r) = deconvolve(&[0.0, 2.0, 1.0, 0.0, 2.0, 3.0, 1.0, 0.0, 0.0], &[2.0, 1.0]).unwrap();
461        assert_eq!(q, vec![0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0]);
462        assert!(r.iter().all(|v| v.abs() < 1e-15));
463    }
464}