Skip to main content

lib_jsl_linalg/
structured.rs

1//! Structured matrices (SciPy's `scipy.linalg` constructors: `toeplitz`, `hankel`, `circulant`,
2//! `hadamard`, `block_diag`, `companion`, `pascal`, `hilbert`, `leslie`, `dft`,
3//! `convolution_matrix`, `fiedler`) and fast solvers that exploit structure: Levinson recursion
4//! for Toeplitz systems, the FFT for circulant ones, and LU and Cholesky in band storage.
5//!
6//! See the book entry [Generalised eigenproblems and structured matrices](https://jwkunz.github.io/lib_jsl/book/linear_algebra/generalized-structured.html).
7
8use crate::error::{LinalgError, Result};
9use crate::scalar::Scalar;
10use lib_jsl_ffts::{FftDirection, fft_axis};
11use ndarray::{Array1, Array2, ArrayBase, ArrayD, Data, Ix1, Ix2, IxDyn};
12use num_complex::Complex;
13
14type C = Complex<f64>;
15
16fn filled<T: Scalar>(rows: usize, cols: usize) -> Array2<T> {
17    Array2::from_elem((rows, cols), T::zero())
18}
19
20/// The Toeplitz matrix with first column `c` and first row `r` (SciPy's `toeplitz`); `r[0]` is
21/// ignored. Without `r`, the matrix is Hermitian: `r = conj(c)`.
22pub fn toeplitz<T: Scalar>(c: &[T], r: Option<&[T]>) -> Array2<T> {
23    let conj: Vec<T> = c.iter().map(|v| v.conj()).collect();
24    let r = r.unwrap_or(&conj);
25    Array2::from_shape_fn((c.len(), r.len()), |(i, j)| if i >= j { c[i - j] } else { r[j - i] })
26}
27
28/// The Hankel matrix with first column `c` and last row `r` (SciPy's `hankel`); `r[0]` is ignored.
29/// Without `r`, the entries below the anti-diagonal are zero.
30pub fn hankel<T: Scalar>(c: &[T], r: Option<&[T]>) -> Array2<T> {
31    let zeros = vec![T::zero(); c.len()];
32    let r = r.unwrap_or(&zeros);
33    let m = c.len();
34    Array2::from_shape_fn((m, r.len()), |(i, j)| if i + j < m { c[i + j] } else { r[i + j - m + 1] })
35}
36
37/// The circulant matrix with first column `c` (SciPy's `circulant`): `C[i, j] = c[(i − j) mod n]`.
38pub fn circulant<T: Scalar>(c: &[T]) -> Array2<T> {
39    let n = c.len();
40    Array2::from_shape_fn((n, n), |(i, j)| c[(i + n - j) % n])
41}
42
43/// The `n × n` Hadamard matrix of ±1 entries by Sylvester's construction (SciPy's `hadamard`); `n`
44/// must be a power of two. Its rows are orthogonal: `H Hᵀ = n I`.
45pub fn hadamard(n: usize) -> Result<Array2<f64>> {
46    if n == 0 || !n.is_power_of_two() {
47        return Err(LinalgError::Shape(format!("hadamard: n must be a power of 2, got {n}")));
48    }
49    Ok(Array2::from_shape_fn((n, n), |(i, j)| if (i & j).count_ones() % 2 == 0 { 1.0 } else { -1.0 }))
50}
51
52/// The block diagonal matrix with the given blocks (SciPy's `block_diag`).
53pub fn block_diag<T: Scalar>(blocks: &[Array2<T>]) -> Array2<T> {
54    let rows = blocks.iter().map(|b| b.nrows()).sum();
55    let cols = blocks.iter().map(|b| b.ncols()).sum();
56    let mut out = filled(rows, cols);
57    let (mut r0, mut c0) = (0, 0);
58    for b in blocks {
59        for ((i, j), &v) in b.indexed_iter() {
60            out[(r0 + i, c0 + j)] = v;
61        }
62        r0 += b.nrows();
63        c0 += b.ncols();
64    }
65    out
66}
67
68/// The companion matrix of the polynomial `a[0] xⁿ + a[1] xⁿ⁻¹ + … + a[n]` (SciPy's `companion`):
69/// first row `−a[1..]/a[0]`, ones on the subdiagonal. Its eigenvalues are the polynomial's roots.
70pub fn companion<T: Scalar>(a: &[T]) -> Result<Array2<T>> {
71    if a.len() < 2 || a[0] == T::zero() {
72        return Err(LinalgError::Shape("companion: need at least two coefficients and a[0] ≠ 0".into()));
73    }
74    let n = a.len() - 1;
75    Ok(Array2::from_shape_fn((n, n), |(i, j)| if i == 0 { -a[j + 1] / a[0] } else if i == j + 1 { T::one() } else { T::zero() }))
76}
77
78/// Which Pascal matrix (SciPy's `kind`).
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80#[non_exhaustive]
81pub enum PascalKind {
82    /// `binom(i + j, i)`.
83    Symmetric,
84    /// `binom(i, j)`.
85    Lower,
86    /// `binom(j, i)`.
87    Upper,
88}
89
90fn binom(n: usize, k: usize) -> f64 {
91    if k > n {
92        return 0.0;
93    }
94    let k = k.min(n - k);
95    (0..k).fold(1.0, |acc, i| acc * (n - i) as f64 / (i + 1) as f64).round()
96}
97
98/// The Pascal matrix (SciPy's `pascal`, `exact=False`): binomial coefficients, exact while they
99/// are below 2⁵³.
100pub fn pascal(n: usize, kind: PascalKind) -> Array2<f64> {
101    Array2::from_shape_fn((n, n), |(i, j)| match kind {
102        PascalKind::Symmetric => binom(i + j, i),
103        PascalKind::Lower => binom(i, j),
104        PascalKind::Upper => binom(j, i),
105    })
106}
107
108/// The inverse of the Pascal matrix (SciPy's `invpascal`): integer entries,
109/// `(−1)^{i+j} binom(i, j)` for the triangular kinds, and their product for the symmetric one.
110pub fn invpascal(n: usize, kind: PascalKind) -> Array2<f64> {
111    let lower_inv = Array2::from_shape_fn((n, n), |(i, j)| if (i + j) % 2 == 0 { binom(i, j) } else { -binom(i, j) });
112    match kind {
113        PascalKind::Lower => lower_inv,
114        PascalKind::Upper => lower_inv.t().to_owned(),
115        // P = L Lᵀ, so P⁻¹ = L⁻ᵀ L⁻¹.
116        PascalKind::Symmetric => lower_inv.t().dot(&lower_inv),
117    }
118}
119
120/// The Hilbert matrix `1/(i + j + 1)` (SciPy's `hilbert`), a classic ill-conditioned test matrix.
121pub fn hilbert(n: usize) -> Array2<f64> {
122    Array2::from_shape_fn((n, n), |(i, j)| 1.0 / (i + j + 1) as f64)
123}
124
125/// The exact inverse of the Hilbert matrix (SciPy's `invhilbert`), from its closed form
126/// `(−1)^{i+j} (i + j + 1) binom(n+i, n−j−1) binom(n+j, n−i−1) binom(i+j, i)²`; the integer entries
127/// are exact for `n ≤ 14`.
128pub fn invhilbert(n: usize) -> Array2<f64> {
129    Array2::from_shape_fn((n, n), |(i, j)| {
130        let s = if (i + j) % 2 == 0 { 1.0 } else { -1.0 };
131        let b = binom(i + j, i);
132        s * (i + j + 1) as f64 * binom(n + i, n - j - 1) * binom(n + j, n - i - 1) * b * b
133    })
134}
135
136/// The Leslie matrix of a population model (SciPy's `leslie`): fecundities `f` (length `n`) on
137/// the first row, survival rates `s` (length `n − 1`) on the subdiagonal.
138pub fn leslie(f: &[f64], s: &[f64]) -> Result<Array2<f64>> {
139    let n = f.len();
140    if n == 0 || s.len() + 1 != n {
141        return Err(LinalgError::Shape(format!("leslie: need len(s) = len(f) − 1, got {} and {}", s.len(), n)));
142    }
143    Ok(Array2::from_shape_fn((n, n), |(i, j)| if i == 0 { f[j] } else if i == j + 1 { s[j] } else { 0.0 }))
144}
145
146/// How [`dft`] scales its matrix (SciPy's `scale`).
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148#[non_exhaustive]
149pub enum DftScale {
150    /// No scaling.
151    None,
152    /// `1/√n`: unitary.
153    SqrtN,
154    /// `1/n`.
155    N,
156}
157
158/// The discrete Fourier transform matrix `W[j, k] = ω^{jk}`, `ω = e^{−2πi/n}` (SciPy's `dft`).
159pub fn dft(n: usize, scale: DftScale) -> Array2<C> {
160    let s = match scale {
161        DftScale::None => 1.0,
162        DftScale::SqrtN => 1.0 / (n as f64).sqrt(),
163        DftScale::N => 1.0 / n as f64,
164    };
165    Array2::from_shape_fn((n, n), |(j, k)| {
166        let phase = -2.0 * std::f64::consts::PI * ((j * k) % n.max(1)) as f64 / n as f64;
167        C::new(phase.cos(), phase.sin()) * s
168    })
169}
170
171/// Which part of a convolution [`convolution_matrix`] produces (as `numpy.convolve`'s `mode`).
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173#[non_exhaustive]
174pub enum ConvolutionMode {
175    /// All `m + n − 1` outputs.
176    Full,
177    /// `max(m, n)` outputs, centred.
178    Same,
179    /// The `max(m, n) − min(m, n) + 1` outputs computed without padding.
180    Valid,
181}
182
183/// The matrix `M` with `M v = convolve(a, v)` for vectors `v` of length `n` (SciPy's
184/// `convolution_matrix`).
185pub fn convolution_matrix<T: Scalar>(a: &[T], n: usize, mode: ConvolutionMode) -> Result<Array2<T>> {
186    let m = a.len();
187    if m == 0 || n == 0 {
188        return Err(LinalgError::Shape("convolution_matrix: a and n must be non-empty".into()));
189    }
190    let full = Array2::from_shape_fn((m + n - 1, n), |(i, j)| if i >= j && i - j < m { a[i - j] } else { T::zero() });
191    let (start, len) = match mode {
192        ConvolutionMode::Full => (0, m + n - 1),
193        ConvolutionMode::Same => {
194            let len = m.max(n);
195            ((m + n - 1 - len) / 2, len)
196        }
197        ConvolutionMode::Valid => (m.min(n) - 1, m.max(n) - m.min(n) + 1),
198    };
199    Ok(full.slice(ndarray::s![start..start + len, ..]).to_owned())
200}
201
202/// The Fiedler matrix `|a_i − a_j|` (SciPy's `fiedler`).
203pub fn fiedler(a: &[f64]) -> Array2<f64> {
204    let n = a.len();
205    Array2::from_shape_fn((n, n), |(i, j)| (a[i] - a[j]).abs())
206}
207
208// ANCHOR: solve_toeplitz
209/// Solves `T x = b` for the Toeplitz matrix `T` with first column `c` and first row `r` (default
210/// `conj(c)`) by Levinson recursion in `O(n²)` operations (SciPy's `solve_toeplitz`, after the
211/// classic `toeplz`). The recursion builds the solutions for the leading `m × m` sections one size at
212/// a time, together with those of two auxiliary systems for the reversed sections; it needs every
213/// leading principal minor to be non-singular, and is not stable for indefinite or badly
214/// conditioned `T` (then use `solve`).
215pub fn solve_toeplitz<T: Scalar>(c: &[T], r: Option<&[T]>, b: &[T]) -> Result<Array1<T>> {
216    let n = b.len();
217    let conj: Vec<T> = c.iter().map(|v| v.conj()).collect();
218    let r = r.unwrap_or(&conj);
219    if c.len() != n || r.len() != n || n == 0 {
220        return Err(LinalgError::Shape(format!("solve_toeplitz: c, r and b must have one length, got {}, {}, {n}", c.len(), r.len())));
221    }
222    if c.iter().chain(r).chain(b).any(|v| !v.is_finite()) {
223        return Err(LinalgError::NonFinite);
224    }
225    // R[k] (1-based, k = 1..2n−1) with T_ij = R[n + i − j].
226    let mut rr = vec![T::zero(); 2 * n];
227    for k in 1..2 * n {
228        let d = k as isize - n as isize; // i − j
229        rr[k] = if d >= 0 { c[d as usize] } else { r[(-d) as usize] };
230    }
231    let singular = || LinalgError::Shape("solve_toeplitz: a leading principal minor is singular".into());
232    let y: Vec<T> = std::iter::once(T::zero()).chain(b.iter().copied()).collect();
233    let mut x = vec![T::zero(); n + 1];
234    let mut g = vec![T::zero(); n + 1];
235    let mut h = vec![T::zero(); n + 1];
236    if rr[n] == T::zero() {
237        return Err(singular());
238    }
239    x[1] = y[1] / rr[n];
240    if n == 1 {
241        return Ok(Array1::from_vec(x[1..].to_vec()));
242    }
243    g[1] = rr[n - 1] / rr[n];
244    h[1] = rr[n + 1] / rr[n];
245    for m in 1..=n {
246        let m1 = m + 1;
247        let mut sxn = -y[m1];
248        let mut sd = -rr[n];
249        for j in 1..=m {
250            sxn += rr[n + m1 - j] * x[j];
251            sd += rr[n + m1 - j] * g[m - j + 1];
252        }
253        if sd == T::zero() {
254            return Err(singular());
255        }
256        x[m1] = sxn / sd;
257        for j in 1..=m {
258            let t = x[m1] * g[m - j + 1];
259            x[j] -= t;
260        }
261        if m1 == n {
262            break;
263        }
264        let mut sgn = -rr[n - m1];
265        let mut shn = -rr[n + m1];
266        let mut sgd = -rr[n];
267        for j in 1..=m {
268            sgn += rr[n + j - m1] * g[j];
269            shn += rr[n + m1 - j] * h[j];
270            sgd += rr[n + j - m1] * h[m - j + 1];
271        }
272        if sgd == T::zero() {
273            return Err(singular());
274        }
275        g[m1] = sgn / sgd;
276        h[m1] = shn / sd;
277        let (pp, qq) = (g[m1], h[m1]);
278        let mut k = m;
279        for j in 1..=m.div_ceil(2) {
280            let (pt1, pt2, qt1, qt2) = (g[j], g[k], h[j], h[k]);
281            g[j] = pt1 - pp * qt2;
282            g[k] = pt2 - pp * qt1;
283            h[j] = qt1 - qq * pt2;
284            h[k] = qt2 - qq * pt1;
285            k -= 1;
286        }
287    }
288    Ok(Array1::from_vec(x[1..].to_vec()))
289}
290// ANCHOR_END: solve_toeplitz
291
292// ANCHOR: solve_circulant
293/// Solves `C x = b` for the circulant matrix `C` with first column `c` in `O(n log n)` (SciPy's
294/// `solve_circulant`): the DFT diagonalises every circulant matrix, `C = F⁻¹ diag(F c) F`, so
295/// `x = F⁻¹ (F b / F c)`. An error is returned when some `|F c|` is below `tol` (default
296/// `n ε max |F c|`), where `C` is numerically singular.
297pub fn solve_circulant<T: Scalar>(c: &[T], b: &[T], tol: Option<f64>) -> Result<Array1<T>> {
298    let n = c.len();
299    if b.len() != n || n == 0 {
300        return Err(LinalgError::Shape(format!("solve_circulant: c and b must have one length, got {n} and {}", b.len())));
301    }
302    let transform = |v: Vec<C>, direction: FftDirection| -> Result<Vec<C>> {
303        let mut data = ArrayD::from_shape_vec(IxDyn(&[n]), v).expect("shape");
304        fft_axis(&mut data, 0, direction).map_err(|e| LinalgError::Shape(format!("fft: {e:?}")))?;
305        Ok(data.into_iter().collect())
306    };
307    let fc = transform(c.iter().map(|z| z.to_complex()).collect(), FftDirection::Forward)?;
308    let fb = transform(b.iter().map(|z| z.to_complex()).collect(), FftDirection::Forward)?;
309    let largest = fc.iter().fold(0.0f64, |m, v| m.max(v.norm()));
310    let tol = tol.unwrap_or(largest * n as f64 * f64::EPSILON);
311    if fc.iter().any(|v| v.norm() <= tol) {
312        return Err(LinalgError::Shape("solve_circulant: the circulant matrix is singular".into()));
313    }
314    // The quotient stays complex until after the inverse transform.
315    let q: Vec<C> = fb.iter().zip(&fc).map(|(p, d)| p / d).collect();
316    let x = transform(q, FftDirection::Inverse)?;
317    Ok(Array1::from_iter(x.into_iter().map(T::from_complex)))
318}
319// ANCHOR_END: solve_circulant
320
321/// A row of a banded matrix, stored by absolute column from `start`.
322struct BandRow<T> {
323    start: isize,
324    vals: Vec<T>,
325}
326
327impl<T: Scalar> BandRow<T> {
328    fn get(&self, j: usize) -> T {
329        let k = j as isize - self.start;
330        if k >= 0 && (k as usize) < self.vals.len() { self.vals[k as usize] } else { T::zero() }
331    }
332    fn set(&mut self, j: usize, v: T) {
333        let k = (j as isize - self.start) as usize;
334        self.vals[k] = v;
335    }
336}
337
338// ANCHOR: solve_banded
339/// Solves `A x = b` for a banded `A` with `l` subdiagonals and `u` superdiagonals, given in
340/// LAPACK band storage `ab[u + i − j, j] = A[i, j]` (SciPy's `solve_banded((l, u), ab, b)`), by
341/// Gaussian elimination with partial pivoting within the band (LAPACK's `gbsv`): `O(n l (l + u))`
342/// operations. Row interchanges widen the upper band of `U` to `l + u`.
343pub fn solve_banded<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>>(lu: (usize, usize), ab: &ArrayBase<S, Ix2>, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
344    let (l, u) = lu;
345    let n = ab.ncols();
346    if ab.nrows() != l + u + 1 || b.len() != n {
347        return Err(LinalgError::Shape(format!("solve_banded: ab must be {} × n and b of length n = {n}", l + u + 1)));
348    }
349    if ab.iter().chain(b.iter()).any(|v| !v.is_finite()) {
350        return Err(LinalgError::NonFinite);
351    }
352    // The row at position i is stored over columns i − l ..= i + u + l. At step k every candidate
353    // row is non-zero only in columns k ..= k + l + u, so after an interchange each row still fits
354    // the window of its new position, and is moved into it.
355    let width = 2 * l + u + 1;
356    let mut rows: Vec<BandRow<T>> = (0..n)
357        .map(|i| {
358            let start = i as isize - l as isize;
359            let mut row = BandRow { start, vals: vec![T::zero(); width] };
360            for j in i.saturating_sub(l)..=(i + u).min(n - 1) {
361                row.set(j, ab[(u + i - j, j)]);
362            }
363            row
364        })
365        .collect();
366    let mut rhs: Vec<T> = b.to_vec();
367    for k in 0..n {
368        let last = (k + l).min(n - 1);
369        let p = (k..=last).max_by(|&i, &j| rows[i].get(k).abs().total_cmp(&rows[j].get(k).abs()).then(j.cmp(&i))).expect("non-empty");
370        if rows[p].get(k) == T::zero() {
371            return Err(LinalgError::Shape(format!("solve_banded: the matrix is singular (zero pivot in column {k})")));
372        }
373        if p != k {
374            let rewindow = |row: &BandRow<T>, pos: usize| {
375                let mut out = BandRow { start: pos as isize - l as isize, vals: vec![T::zero(); width] };
376                for j in k..=(k + l + u).min(n - 1) {
377                    out.set(j, row.get(j));
378                }
379                out
380            };
381            let (to_k, to_p) = (rewindow(&rows[p], k), rewindow(&rows[k], p));
382            rows[k] = to_k;
383            rows[p] = to_p;
384            rhs.swap(p, k);
385        }
386        let pivot = rows[k].get(k);
387        let end = (k + u + l).min(n - 1);
388        for i in k + 1..=last {
389            let m = rows[i].get(k) / pivot;
390            if m == T::zero() {
391                continue;
392            }
393            for j in k..=end {
394                let v = rows[i].get(j) - m * rows[k].get(j);
395                rows[i].set(j, v);
396            }
397            let t = m * rhs[k];
398            rhs[i] -= t;
399        }
400    }
401    let mut x = vec![T::zero(); n];
402    for i in (0..n).rev() {
403        let end = (i + u + l).min(n - 1);
404        let s = (i + 1..=end).fold(T::zero(), |acc, j| acc + rows[i].get(j) * x[j]);
405        x[i] = (rhs[i] - s) / rows[i].get(i);
406    }
407    Ok(Array1::from_vec(x))
408}
409// ANCHOR_END: solve_banded
410
411// ANCHOR: solveh_banded
412/// Solves `A x = b` for a Hermitian positive definite banded `A` (SciPy's `solveh_banded`, LAPACK's
413/// `pbsv`) by the band Cholesky factorisation `A = L Lᴴ`, which keeps the bandwidth `w`:
414/// `O(n w²)` operations. `ab` has `w + 1` rows; with `lower = false` (SciPy's default) it holds the
415/// upper triangle, `ab[w + i − j, j] = A[i, j]` for `i ≤ j`, and with `lower = true` the lower one,
416/// `ab[i − j, j] = A[i, j]` for `i ≥ j`.
417pub fn solveh_banded<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>>(ab: &ArrayBase<S, Ix2>, b: &ArrayBase<S2, Ix1>, lower: bool) -> Result<Array1<T>> {
418    let n = ab.ncols();
419    let w = ab.nrows().saturating_sub(1);
420    if ab.nrows() == 0 || b.len() != n {
421        return Err(LinalgError::Shape(format!("solveh_banded: ab must have at least one row and b length n = {n}")));
422    }
423    if ab.iter().chain(b.iter()).any(|v| !v.is_finite()) {
424        return Err(LinalgError::NonFinite);
425    }
426    // a(i, j) for i ≥ j within the band, from either storage.
427    let a = |i: usize, j: usize| -> T { if lower { ab[(i - j, j)] } else { ab[(w + j - i, i)].conj() } };
428    // L by rows within the band: lband[i][k] = L[i, i − w + k].
429    let mut lmat = vec![vec![T::zero(); w + 1]; n];
430    let get = |lmat: &Vec<Vec<T>>, i: usize, j: usize| -> T { if j + w >= i && j <= i { lmat[i][j + w - i] } else { T::zero() } };
431    for j in 0..n {
432        let start = j.saturating_sub(w);
433        let d = a(j, j).re() - (start..j).map(|k| get(&lmat, j, k).abs_sqr()).sum::<f64>();
434        if d <= 0.0 || !d.is_finite() {
435            return Err(LinalgError::Shape(format!("solveh_banded: the matrix is not positive definite (leading minor {})", j + 1)));
436        }
437        let ljj = d.sqrt();
438        lmat[j][w] = T::from_real(ljj);
439        for i in j + 1..=(j + w).min(n - 1) {
440            let s = (i.saturating_sub(w).max(start)..j).fold(T::zero(), |acc, k| acc + get(&lmat, i, k) * get(&lmat, j, k).conj());
441            lmat[i][j + w - i] = (a(i, j) - s).scale(1.0 / ljj);
442        }
443    }
444    // L y = b, then Lᴴ x = y.
445    let mut y: Vec<T> = b.to_vec();
446    for i in 0..n {
447        let s = (i.saturating_sub(w)..i).fold(T::zero(), |acc, k| acc + get(&lmat, i, k) * y[k]);
448        y[i] = (y[i] - s) / get(&lmat, i, i);
449    }
450    let mut x = y;
451    for i in (0..n).rev() {
452        let s = (i + 1..=(i + w).min(n - 1)).fold(T::zero(), |acc, k| acc + get(&lmat, k, i).conj() * x[k]);
453        x[i] = (x[i] - s) / get(&lmat, i, i);
454    }
455    Ok(Array1::from_vec(x))
456}
457// ANCHOR_END: solveh_banded
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462    use crate::{Eig, Solve};
463
464    fn close(a: &[f64], b: &[f64], tol: f64) -> bool {
465        a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol * (1.0 + y.abs()))
466    }
467
468    #[test]
469    fn fast_solvers_agree_with_dense_solves() {
470        let n = 9;
471        let c: Vec<f64> = (0..n).map(|k| 4.0 / (1.0 + k as f64) + if k == 0 { 2.0 } else { 0.0 }).collect();
472        let r: Vec<f64> = (0..n).map(|k| if k == 0 { c[0] } else { -0.7 / (1.0 + k as f64 * k as f64) }).collect();
473        let b: Vec<f64> = (0..n).map(|k| (k as f64 * 0.7).sin() + 1.0).collect();
474        let t = toeplitz(&c, Some(&r));
475        let dense = t.solve(&Array1::from_vec(b.clone())).unwrap();
476        let fast = solve_toeplitz(&c, Some(&r), &b).unwrap();
477        assert!(close(fast.as_slice().unwrap(), dense.as_slice().unwrap(), 1e-12));
478        // Complex Hermitian Toeplitz (r defaults to conj(c)).
479        let cc: Vec<C> = c.iter().enumerate().map(|(k, &v)| C::new(v, if k == 0 { 0.0 } else { 0.3 / k as f64 })).collect();
480        let bc: Vec<C> = b.iter().map(|&v| C::new(v, -v)).collect();
481        let xc = solve_toeplitz(&cc, None, &bc).unwrap();
482        let tc = toeplitz(&cc, None);
483        assert!((tc.dot(&xc) - Array1::from_vec(bc.clone())).iter().all(|v| v.norm() < 1e-12));
484        // Circulant.
485        let x = solve_circulant(&c, &b, None).unwrap();
486        let dense = circulant(&c).solve(&Array1::from_vec(b.clone())).unwrap();
487        assert!(close(x.as_slice().unwrap(), dense.as_slice().unwrap(), 1e-12));
488        assert!(solve_circulant(&[1.0, 1.0], &[1.0, 2.0], None).is_err(), "singular");
489        // Banded: l = 2, u = 1, with a small diagonal so that pivoting happens.
490        let (l, u) = (2, 1);
491        let a = Array2::from_shape_fn((n, n), |(i, j)| if i <= j + l && j <= i + u { ((i * 7 + j * 3) as f64 * 0.37).sin() + if i == j { 0.01 } else { 0.0 } } else { 0.0 });
492        let mut ab = Array2::<f64>::zeros((l + u + 1, n));
493        for i in 0..n {
494            for j in 0..n {
495                if i <= j + l && j <= i + u {
496                    ab[(u + i - j, j)] = a[(i, j)];
497                }
498            }
499        }
500        let bb = Array1::from_vec(b.clone());
501        let xb = solve_banded((l, u), &ab, &bb).unwrap();
502        assert!(close(xb.as_slice().unwrap(), a.solve(&bb).unwrap().as_slice().unwrap(), 1e-11));
503        // Repeated interchanges that push a row down several times (l = 3, u = 2, n = 40).
504        let (l, u, n2) = (3, 2, 40);
505        let ab = Array2::from_shape_fn((l + u + 1, n2), |(i, j)| (0.37 * (7 * (i + 1) + 3 * j) as f64).sin() + if i == u { 0.01 } else { 0.0 });
506        let dense = Array2::from_shape_fn((n2, n2), |(i, j)| if i <= j + l && j <= i + u { ab[(u + i - j, j)] } else { 0.0 });
507        let rhs = Array1::from_shape_fn(n2, |k| (0.7 * k as f64).sin() + 1.0);
508        let xb = solve_banded((l, u), &ab, &rhs).unwrap();
509        assert!((dense.dot(&xb) - &rhs).iter().all(|v| v.abs() < 1e-10));
510        // Symmetric positive definite band, both storages.
511        let w = 2;
512        let spd = Array2::from_shape_fn((n, n), |(i, j)| if i.abs_diff(j) <= w { if i == j { 6.0 } else { 1.0 / (1 + i + j) as f64 } } else { 0.0 });
513        let mut upper = Array2::<f64>::zeros((w + 1, n));
514        let mut lower = Array2::<f64>::zeros((w + 1, n));
515        for j in 0..n {
516            for i in j.saturating_sub(w)..=j {
517                upper[(w + i - j, j)] = spd[(i, j)];
518            }
519            for i in j..=(j + w).min(n - 1) {
520                lower[(i - j, j)] = spd[(i, j)];
521            }
522        }
523        let want = spd.solve(&bb).unwrap();
524        for (storage, low) in [(&upper, false), (&lower, true)] {
525            let x = solveh_banded(storage, &bb, low).unwrap();
526            assert!(close(x.as_slice().unwrap(), want.as_slice().unwrap(), 1e-12));
527        }
528    }
529
530    #[test]
531    fn special_matrices() {
532        let h = hadamard(8).unwrap();
533        assert!((h.dot(&h.t()) - Array2::<f64>::eye(8) * 8.0).iter().all(|v| *v == 0.0));
534        assert!(hadamard(6).is_err());
535        let ih = invhilbert(6).dot(&hilbert(6));
536        assert!((ih - Array2::<f64>::eye(6)).iter().all(|v| v.abs() < 1e-8));
537        for kind in [PascalKind::Symmetric, PascalKind::Lower, PascalKind::Upper] {
538            let p = pascal(7, kind).dot(&invpascal(7, kind));
539            assert!((p - Array2::<f64>::eye(7)).iter().all(|v| *v == 0.0), "{kind:?}");
540        }
541        // Roots of (x − 1)(x − 2)(x − 3) = x³ − 6x² + 11x − 6.
542        let (roots, _) = companion(&[1.0, -6.0, 11.0, -6.0]).unwrap().eig().unwrap();
543        let mut re: Vec<f64> = roots.iter().map(|z| z.re).collect();
544        re.sort_by(f64::total_cmp);
545        assert!(close(&re, &[1.0, 2.0, 3.0], 1e-12));
546        // Convolution matrices reproduce numpy.convolve.
547        let a = [1.0, 2.0, 3.0];
548        let v = Array1::from_vec(vec![1.0, -1.0, 0.5, 2.0]);
549        assert_eq!(convolution_matrix(&a, 4, ConvolutionMode::Full).unwrap().dot(&v).to_vec(), vec![1.0, 1.0, 1.5, 0.0, 5.5, 6.0]);
550        assert_eq!(convolution_matrix(&a, 4, ConvolutionMode::Same).unwrap().dot(&v).to_vec(), vec![1.0, 1.5, 0.0, 5.5]);
551        assert_eq!(convolution_matrix(&a, 4, ConvolutionMode::Valid).unwrap().dot(&v).to_vec(), vec![1.5, 0.0]);
552        assert_eq!(hankel(&[1.0, 2.0, 3.0], Some(&[9.0, 4.0, 5.0])), Array2::from_shape_vec((3, 3), vec![1.0, 2.0, 3.0, 2.0, 3.0, 4.0, 3.0, 4.0, 5.0]).unwrap());
553        let bd = block_diag(&[Array2::from_elem((1, 2), 1.0), Array2::from_elem((2, 1), 2.0)]);
554        assert_eq!(bd.dim(), (3, 3));
555        assert_eq!(bd[(1, 2)], 2.0);
556        let f = dft(4, DftScale::SqrtN);
557        let fh = f.t().mapv(|z| z.conj());
558        assert!((f.dot(&fh) - Array2::<C>::eye(4)).iter().all(|v| v.norm() < 1e-15));
559        assert!(leslie(&[0.1, 2.0, 1.0], &[0.2, 0.8]).unwrap()[(2, 1)] == 0.8);
560        assert_eq!(fiedler(&[1.0, 4.0, 2.0])[(1, 2)], 2.0);
561    }
562}