Skip to main content

lib_jsl_linalg/sparse/
complex.rs

1//! Complex sparse matrices (`scipy.sparse` with `complex128` data): COO and CSR storage with
2//! products, adjoints and conversions; a sparse LU factorisation with partial pivoting and the
3//! fill-reducing orderings of the real code; and the Krylov solvers CG (Hermitian positive
4//! definite), GMRES and BiCGSTAB for any [`ComplexLinearOperator`].
5//!
6//! See the book entry [Sparse matrices and iterative solvers](https://jwkunz.github.io/lib_jsl/book/linear_algebra/sparse.html).
7
8use super::direct::{Ordering, reverse_cuthill_mckee};
9use super::formats::CsrMatrix;
10use super::{colamd, minimum_degree};
11use crate::error::{LinalgError, Result};
12use ndarray::Array2;
13use num_complex::Complex;
14
15type C = Complex<f64>;
16
17/// A complex sparse matrix in coordinate form: duplicate entries are summed on conversion.
18#[derive(Clone, Debug, Default)]
19pub struct ComplexCooMatrix {
20    pub nrows: usize,
21    pub ncols: usize,
22    pub rows: Vec<usize>,
23    pub cols: Vec<usize>,
24    pub values: Vec<C>,
25}
26
27impl ComplexCooMatrix {
28    pub fn new(nrows: usize, ncols: usize) -> Self {
29        ComplexCooMatrix { nrows, ncols, rows: Vec::new(), cols: Vec::new(), values: Vec::new() }
30    }
31
32    /// Adds an entry (`value` is added to any existing entry at `(row, col)` on conversion).
33    pub fn push(&mut self, row: usize, col: usize, value: C) {
34        self.rows.push(row);
35        self.cols.push(col);
36        self.values.push(value);
37    }
38
39    pub fn to_csr(&self) -> Result<ComplexCsrMatrix> {
40        ComplexCsrMatrix::from_triplets(self.nrows, self.ncols, &self.rows, &self.cols, &self.values)
41    }
42}
43
44/// A complex sparse matrix in compressed sparse row form, with the column indices of each row
45/// increasing.
46#[derive(Clone, Debug, PartialEq)]
47pub struct ComplexCsrMatrix {
48    pub nrows: usize,
49    pub ncols: usize,
50    pub indptr: Vec<usize>,
51    pub indices: Vec<usize>,
52    pub data: Vec<C>,
53}
54
55impl ComplexCsrMatrix {
56    /// Builds a matrix from triplets, summing duplicates (SciPy's `coo_array(...).tocsr()`).
57    pub fn from_triplets(nrows: usize, ncols: usize, rows: &[usize], cols: &[usize], values: &[C]) -> Result<Self> {
58        if rows.len() != cols.len() || rows.len() != values.len() {
59            return Err(LinalgError::Shape("triplet arrays of different lengths".into()));
60        }
61        if rows.iter().any(|&r| r >= nrows) || cols.iter().any(|&c| c >= ncols) {
62            return Err(LinalgError::Shape("a triplet lies outside the matrix".into()));
63        }
64        let mut order: Vec<usize> = (0..rows.len()).collect();
65        order.sort_by_key(|&k| (rows[k], cols[k]));
66        let (mut indptr, mut indices, mut data) = (vec![0usize; nrows + 1], Vec::new(), Vec::new());
67        let mut last: Option<(usize, usize)> = None;
68        for &k in &order {
69            if last == Some((rows[k], cols[k])) {
70                *data.last_mut().expect("an entry") += values[k];
71            } else {
72                indices.push(cols[k]);
73                data.push(values[k]);
74                indptr[rows[k] + 1] += 1;
75                last = Some((rows[k], cols[k]));
76            }
77        }
78        for i in 0..nrows {
79            indptr[i + 1] += indptr[i];
80        }
81        Ok(ComplexCsrMatrix { nrows, ncols, indptr, indices, data })
82    }
83
84    /// The matrix `real + i·imag` of two real sparse matrices of the same shape.
85    pub fn from_real_imag(real: &CsrMatrix, imag: &CsrMatrix) -> Result<Self> {
86        if (real.nrows, real.ncols) != (imag.nrows, imag.ncols) {
87            return Err(LinalgError::Shape("real and imaginary parts of different shapes".into()));
88        }
89        let (mut r, mut c, mut v) = (Vec::new(), Vec::new(), Vec::new());
90        for (m, im) in [(real, 0.0), (imag, 1.0)] {
91            for i in 0..m.nrows {
92                for p in m.indptr[i]..m.indptr[i + 1] {
93                    r.push(i);
94                    c.push(m.indices[p]);
95                    v.push(if im == 0.0 { C::new(m.data[p], 0.0) } else { C::new(0.0, m.data[p]) });
96                }
97            }
98        }
99        Self::from_triplets(real.nrows, real.ncols, &r, &c, &v)
100    }
101
102    /// From a dense matrix, keeping the entries of modulus above `tol`.
103    pub fn from_dense(a: &Array2<C>, tol: f64) -> Self {
104        let (mut r, mut c, mut v) = (Vec::new(), Vec::new(), Vec::new());
105        for ((i, j), &x) in a.indexed_iter() {
106            if x.norm() > tol {
107                r.push(i);
108                c.push(j);
109                v.push(x);
110            }
111        }
112        Self::from_triplets(a.nrows(), a.ncols(), &r, &c, &v).expect("indices in range")
113    }
114
115    pub fn nnz(&self) -> usize {
116        self.data.len()
117    }
118
119    pub fn to_dense(&self) -> Array2<C> {
120        let mut d = Array2::from_elem((self.nrows, self.ncols), C::new(0.0, 0.0));
121        for i in 0..self.nrows {
122            for p in self.indptr[i]..self.indptr[i + 1] {
123                d[(i, self.indices[p])] += self.data[p];
124            }
125        }
126        d
127    }
128
129    /// `A x`.
130    pub fn matvec(&self, x: &[C]) -> Vec<C> {
131        (0..self.nrows).map(|i| (self.indptr[i]..self.indptr[i + 1]).map(|p| self.data[p] * x[self.indices[p]]).sum()).collect()
132    }
133
134    /// `Aᴴ x`.
135    pub fn rmatvec(&self, x: &[C]) -> Vec<C> {
136        let mut out = vec![C::new(0.0, 0.0); self.ncols];
137        for i in 0..self.nrows {
138            for p in self.indptr[i]..self.indptr[i + 1] {
139                out[self.indices[p]] += self.data[p].conj() * x[i];
140            }
141        }
142        out
143    }
144
145    fn transposed(&self, conjugate: bool) -> ComplexCsrMatrix {
146        let (mut r, mut c, mut v) = (Vec::with_capacity(self.nnz()), Vec::with_capacity(self.nnz()), Vec::with_capacity(self.nnz()));
147        for i in 0..self.nrows {
148            for p in self.indptr[i]..self.indptr[i + 1] {
149                r.push(self.indices[p]);
150                c.push(i);
151                v.push(if conjugate { self.data[p].conj() } else { self.data[p] });
152            }
153        }
154        Self::from_triplets(self.ncols, self.nrows, &r, &c, &v).expect("indices in range")
155    }
156
157    /// The transpose `Aᵀ`.
158    pub fn transpose(&self) -> ComplexCsrMatrix {
159        self.transposed(false)
160    }
161
162    /// The conjugate transpose `Aᴴ`.
163    pub fn adjoint(&self) -> ComplexCsrMatrix {
164        self.transposed(true)
165    }
166
167    /// The complex conjugate `Ā`.
168    pub fn conj(&self) -> ComplexCsrMatrix {
169        ComplexCsrMatrix { data: self.data.iter().map(|v| v.conj()).collect(), ..self.clone() }
170    }
171
172    /// The diagonal.
173    pub fn diagonal(&self) -> Vec<C> {
174        (0..self.nrows.min(self.ncols))
175            .map(|i| (self.indptr[i]..self.indptr[i + 1]).find(|&p| self.indices[p] == i).map_or(C::new(0.0, 0.0), |p| self.data[p]))
176            .collect()
177    }
178
179    /// `α A + β B` for matrices of the same shape.
180    pub fn add(&self, alpha: C, other: &ComplexCsrMatrix, beta: C) -> Result<ComplexCsrMatrix> {
181        if (self.nrows, self.ncols) != (other.nrows, other.ncols) {
182            return Err(LinalgError::Shape("matrices of different shapes".into()));
183        }
184        let (mut r, mut c, mut v) = (Vec::new(), Vec::new(), Vec::new());
185        for (m, w) in [(self, alpha), (other, beta)] {
186            for i in 0..m.nrows {
187                for p in m.indptr[i]..m.indptr[i + 1] {
188                    r.push(i);
189                    c.push(m.indices[p]);
190                    v.push(w * m.data[p]);
191                }
192            }
193        }
194        Self::from_triplets(self.nrows, self.ncols, &r, &c, &v)
195    }
196
197    /// The product `A B`.
198    pub fn matmul(&self, b: &ComplexCsrMatrix) -> Result<ComplexCsrMatrix> {
199        if self.ncols != b.nrows {
200            return Err(LinalgError::Shape(format!("{} × {} times {} × {}", self.nrows, self.ncols, b.nrows, b.ncols)));
201        }
202        let (mut indptr, mut indices, mut data) = (vec![0usize], Vec::new(), Vec::new());
203        let mut acc = vec![C::new(0.0, 0.0); b.ncols];
204        let mut mark = vec![usize::MAX; b.ncols];
205        for i in 0..self.nrows {
206            let mut cols: Vec<usize> = Vec::new();
207            for p in self.indptr[i]..self.indptr[i + 1] {
208                let (k, a) = (self.indices[p], self.data[p]);
209                for q in b.indptr[k]..b.indptr[k + 1] {
210                    let j = b.indices[q];
211                    if mark[j] != i {
212                        mark[j] = i;
213                        acc[j] = C::new(0.0, 0.0);
214                        cols.push(j);
215                    }
216                    acc[j] += a * b.data[q];
217                }
218            }
219            cols.sort_unstable();
220            for j in cols {
221                indices.push(j);
222                data.push(acc[j]);
223            }
224            indptr.push(indices.len());
225        }
226        Ok(ComplexCsrMatrix { nrows: self.nrows, ncols: b.ncols, indptr, indices, data })
227    }
228
229    /// The pattern as a real matrix of ones, for the orderings.
230    fn pattern(&self) -> CsrMatrix {
231        CsrMatrix { nrows: self.nrows, ncols: self.ncols, indptr: self.indptr.clone(), indices: self.indices.clone(), data: vec![1.0; self.nnz()] }
232    }
233}
234
235// ANCHOR: complex_lu
236/// A sparse LU factorisation `P A Q = L U` of a complex matrix: Gilbert and Peierls' left-looking
237/// algorithm with partial pivoting by modulus, as [`SparseLu`](super::SparseLu), with the column
238/// order `Q` from the pattern of `A`.
239#[derive(Clone, Debug)]
240pub struct ComplexSparseLu {
241    n: usize,
242    l: Vec<Vec<(usize, C)>>,
243    u: Vec<Vec<(usize, C)>>,
244    pivot_row: Vec<usize>,
245    q: Vec<usize>,
246}
247
248impl ComplexSparseLu {
249    /// Factorises with one of the real code's column orderings (applied to the pattern of `A`).
250    pub fn factor(a: &ComplexCsrMatrix, ordering: Ordering) -> Result<ComplexSparseLu> {
251        let n = a.nrows;
252        if a.ncols != n {
253            return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
254        }
255        let q = match ordering {
256            Ordering::Natural => (0..n).collect(),
257            Ordering::ReverseCuthillMcKee => reverse_cuthill_mckee(&a.pattern()),
258            Ordering::MinimumDegree => minimum_degree(&a.pattern()),
259        };
260        Self::factor_with_order(a, &q)
261    }
262
263    /// Factorises with an explicit column order (for example the output of `colamd`).
264    pub fn factor_with_order(a: &ComplexCsrMatrix, q: &[usize]) -> Result<ComplexSparseLu> {
265        let n = a.nrows;
266        if a.ncols != n {
267            return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
268        }
269        let mut seen = vec![false; n];
270        if q.len() != n || q.iter().any(|&c| c >= n || std::mem::replace(&mut seen[c], true)) {
271            return Err(LinalgError::Shape(format!("the column order must be a permutation of 0..{n}")));
272        }
273        // Compressed columns.
274        let t = a.transpose();
275        let scale = a.data.iter().fold(0.0f64, |m, v| m.max(v.norm())).max(f64::MIN_POSITIVE);
276        let mut l: Vec<Vec<(usize, C)>> = Vec::with_capacity(n);
277        let mut u: Vec<Vec<(usize, C)>> = Vec::with_capacity(n);
278        let mut pinv: Vec<Option<usize>> = vec![None; n];
279        let mut pivot_row = Vec::with_capacity(n);
280        let mut x = vec![C::new(0.0, 0.0); n];
281        let mut mark = vec![usize::MAX; n];
282        for (k, &col) in q.iter().enumerate() {
283            // Column `col` of A is row `col` of Aᵀ.
284            let (lo, hi) = (t.indptr[col], t.indptr[col + 1]);
285            let mut topo: Vec<usize> = Vec::new();
286            let mut stack: Vec<(usize, usize)> = Vec::new();
287            for p in lo..hi {
288                let r = t.indices[p];
289                if mark[r] == k {
290                    continue;
291                }
292                mark[r] = k;
293                stack.push((r, 0));
294                while let Some((v, child)) = stack.pop() {
295                    let children = pinv[v].map(|j| &l[j][1..]);
296                    match children.and_then(|c| c.get(child)) {
297                        Some(&(w, _)) => {
298                            stack.push((v, child + 1));
299                            if mark[w] != k {
300                                mark[w] = k;
301                                stack.push((w, 0));
302                            }
303                        }
304                        None => topo.push(v),
305                    }
306                }
307            }
308            for p in lo..hi {
309                x[t.indices[p]] = t.data[p];
310            }
311            for &r in topo.iter().rev() {
312                if let Some(j) = pinv[r] {
313                    let ujk = x[r];
314                    for &(i, lij) in &l[j][1..] {
315                        x[i] -= lij * ujk;
316                    }
317                }
318            }
319            let mut ucol = Vec::new();
320            let mut best: Option<(usize, C)> = None;
321            for &r in &topo {
322                match pinv[r] {
323                    Some(j) => {
324                        if x[r] != C::new(0.0, 0.0) {
325                            ucol.push((j, x[r]));
326                        }
327                    }
328                    None => {
329                        if best.is_none_or(|(_, v)| x[r].norm() > v.norm()) {
330                            best = Some((r, x[r]));
331                        }
332                    }
333                }
334            }
335            let Some((piv, d)) = best.filter(|(_, v)| v.norm() > f64::EPSILON * scale * 1e-3) else {
336                return Err(LinalgError::Singular(k));
337            };
338            ucol.sort_by_key(|e| e.0);
339            ucol.push((k, d));
340            let mut lcol = vec![(piv, C::new(1.0, 0.0))];
341            for &r in &topo {
342                if pinv[r].is_none() && r != piv && x[r] != C::new(0.0, 0.0) {
343                    lcol.push((r, x[r] / d));
344                }
345            }
346            for &r in &topo {
347                x[r] = C::new(0.0, 0.0);
348            }
349            pinv[piv] = Some(k);
350            pivot_row.push(piv);
351            l.push(lcol);
352            u.push(ucol);
353        }
354        Ok(ComplexSparseLu { n, l, u, pivot_row, q: q.to_vec() })
355    }
356
357    /// Solves `A x = b`.
358    pub fn solve(&self, b: &[C]) -> Result<Vec<C>> {
359        if b.len() != self.n {
360            return Err(LinalgError::Shape(format!("right-hand side of length {}, expected {}", b.len(), self.n)));
361        }
362        let mut w = b.to_vec();
363        let mut y = vec![C::new(0.0, 0.0); self.n];
364        for j in 0..self.n {
365            let yj = w[self.pivot_row[j]];
366            y[j] = yj;
367            for &(i, lij) in &self.l[j][1..] {
368                w[i] -= lij * yj;
369            }
370        }
371        for j in (0..self.n).rev() {
372            let (_, ujj) = *self.u[j].last().expect("diagonal");
373            let zj = y[j] / ujj;
374            y[j] = zj;
375            for &(i, uij) in &self.u[j][..self.u[j].len() - 1] {
376                y[i] -= uij * zj;
377            }
378        }
379        let mut x = vec![C::new(0.0, 0.0); self.n];
380        for (k, &col) in self.q.iter().enumerate() {
381            x[col] = y[k];
382        }
383        Ok(x)
384    }
385
386    /// The number of stored entries of `L` and `U` together.
387    pub fn nnz(&self) -> usize {
388        self.l.iter().map(|c| c.len()).sum::<usize>() + self.u.iter().map(|c| c.len()).sum::<usize>()
389    }
390}
391
392/// Solves the complex sparse system `A x = b` (SciPy's `spsolve`) by a sparse LU factorisation
393/// with the minimum-degree column ordering.
394pub fn spsolve_complex(a: &ComplexCsrMatrix, b: &[C]) -> Result<Vec<C>> {
395    ComplexSparseLu::factor(a, Ordering::MinimumDegree)?.solve(b)
396}
397
398/// A complex sparse LU factorisation with the COLAMD column ordering, which does not assume a
399/// symmetric pattern.
400pub fn spsolve_complex_colamd(a: &ComplexCsrMatrix, b: &[C]) -> Result<Vec<C>> {
401    ComplexSparseLu::factor_with_order(a, &colamd(&a.pattern()))?.solve(b)
402}
403// ANCHOR_END: complex_lu
404
405/// A complex linear operator `x ↦ A x`, for the complex Krylov solvers and as a preconditioner.
406pub trait ComplexLinearOperator {
407    /// `(rows, columns)`.
408    fn shape(&self) -> (usize, usize);
409    /// `A x`.
410    fn matvec(&self, x: &[C]) -> Vec<C>;
411}
412
413impl ComplexLinearOperator for ComplexCsrMatrix {
414    fn shape(&self) -> (usize, usize) {
415        (self.nrows, self.ncols)
416    }
417    fn matvec(&self, x: &[C]) -> Vec<C> {
418        ComplexCsrMatrix::matvec(self, x)
419    }
420}
421
422/// The preconditioner `M = diag(A)⁻¹`.
423pub struct ComplexJacobi {
424    inverse_diagonal: Vec<C>,
425}
426
427impl ComplexJacobi {
428    pub fn new(a: &ComplexCsrMatrix) -> Result<Self> {
429        let d = a.diagonal();
430        if d.iter().any(|v| v.norm() == 0.0) {
431            return Err(LinalgError::Singular(d.iter().position(|v| v.norm() == 0.0).unwrap_or(0)));
432        }
433        Ok(ComplexJacobi { inverse_diagonal: d.iter().map(|v| C::new(1.0, 0.0) / v).collect() })
434    }
435}
436
437impl ComplexLinearOperator for ComplexJacobi {
438    fn shape(&self) -> (usize, usize) {
439        (self.inverse_diagonal.len(), self.inverse_diagonal.len())
440    }
441    fn matvec(&self, x: &[C]) -> Vec<C> {
442        self.inverse_diagonal.iter().zip(x).map(|(d, v)| d * v).collect()
443    }
444}
445
446/// The result of a complex iterative solve.
447#[derive(Clone, Debug)]
448#[non_exhaustive]
449pub struct ComplexIterativeResult {
450    pub x: Vec<C>,
451    /// Matrix-vector products with `A` (GMRES counts inner iterations).
452    pub iterations: usize,
453    pub converged: bool,
454    /// The residual norm after each iteration, starting with the initial one.
455    pub residual_history: Vec<f64>,
456}
457
458/// Options of the complex solvers, as the real ones: convergence when `‖b − A x‖ ≤ max(rtol ‖b‖, atol)`.
459pub use super::iterative::IterativeOptions as ComplexIterativeOptions;
460
461fn dotc(a: &[C], b: &[C]) -> C {
462    a.iter().zip(b).map(|(x, y)| x.conj() * y).sum()
463}
464
465fn norm2(a: &[C]) -> f64 {
466    a.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt()
467}
468
469fn axpy(y: &mut [C], a: C, x: &[C]) {
470    y.iter_mut().zip(x).for_each(|(yi, xi)| *yi += a * xi);
471}
472
473fn residual(a: &dyn ComplexLinearOperator, b: &[C], x: &[C]) -> Vec<C> {
474    a.matvec(x).iter().zip(b).map(|(p, q)| q - p).collect()
475}
476
477fn check(a: &dyn ComplexLinearOperator, b: &[C], x0: Option<&[C]>) -> Result<Vec<C>> {
478    let (m, n) = a.shape();
479    if m != n || b.len() != n {
480        return Err(LinalgError::Shape(format!("operator {m} × {n} with right-hand side of length {}", b.len())));
481    }
482    Ok(x0.map_or(vec![C::new(0.0, 0.0); n], |v| v.to_vec()))
483}
484
485fn apply(m: Option<&dyn ComplexLinearOperator>, r: &[C]) -> Vec<C> {
486    m.map_or_else(|| r.to_vec(), |m| m.matvec(r))
487}
488
489// ANCHOR: complex_krylov
490/// Conjugate gradients for Hermitian positive definite `A` (SciPy's `cg` on complex data), with
491/// the inner product `⟨x, y⟩ = xᴴ y`.
492pub fn cg_complex(a: &dyn ComplexLinearOperator, b: &[C], x0: Option<&[C]>, m: Option<&dyn ComplexLinearOperator>, options: ComplexIterativeOptions) -> Result<ComplexIterativeResult> {
493    let mut x = check(a, b, x0)?;
494    let tol = (options.rtol * norm2(b)).max(options.atol);
495    let max_it = options.max_iterations.unwrap_or(10 * b.len());
496    let mut r = residual(a, b, &x);
497    let mut history = vec![norm2(&r)];
498    let mut z = apply(m, &r);
499    let mut p = z.clone();
500    let mut rz = dotc(&r, &z);
501    let mut it = 0;
502    while history[history.len() - 1] > tol && it < max_it {
503        let ap = a.matvec(&p);
504        let alpha = rz / dotc(&p, &ap);
505        axpy(&mut x, alpha, &p);
506        axpy(&mut r, -alpha, &ap);
507        z = apply(m, &r);
508        let rz_new = dotc(&r, &z);
509        let beta = rz_new / rz;
510        rz = rz_new;
511        p.iter_mut().zip(&z).for_each(|(pi, zi)| *pi = zi + beta * *pi);
512        it += 1;
513        history.push(norm2(&r));
514    }
515    let converged = history[history.len() - 1] <= tol;
516    Ok(ComplexIterativeResult { x, iterations: it, converged, residual_history: history })
517}
518
519/// Restarted GMRES (SciPy's `gmres` on complex data): Arnoldi with modified Gram-Schmidt, complex
520/// Givens rotations on the Hessenberg matrix, and right preconditioning.
521pub fn gmres_complex(a: &dyn ComplexLinearOperator, b: &[C], x0: Option<&[C]>, m: Option<&dyn ComplexLinearOperator>, restart: usize, options: ComplexIterativeOptions) -> Result<ComplexIterativeResult> {
522    let mut x = check(a, b, x0)?;
523    let n = b.len();
524    let restart = restart.clamp(1, n.max(1));
525    let tol = (options.rtol * norm2(b)).max(options.atol);
526    let max_it = options.max_iterations.unwrap_or(10 * n);
527    let mut r = residual(a, b, &x);
528    let mut history = vec![norm2(&r)];
529    let mut it = 0;
530    let zero = C::new(0.0, 0.0);
531    while history[history.len() - 1] > tol && it < max_it {
532        let beta = norm2(&r);
533        let mut basis: Vec<Vec<C>> = vec![r.iter().map(|v| v / beta).collect()];
534        let mut h = vec![vec![zero; restart]; restart + 1];
535        let (mut cs, mut sn) = (vec![0.0f64; restart], vec![zero; restart]);
536        let mut g = vec![zero; restart + 1];
537        g[0] = C::new(beta, 0.0);
538        let mut k_done = 0;
539        for k in 0..restart {
540            let mut w = a.matvec(&apply(m, &basis[k]));
541            for (j, vj) in basis.iter().enumerate() {
542                h[j][k] = dotc(vj, &w);
543                let hjk = h[j][k];
544                axpy(&mut w, -hjk, vj);
545            }
546            let hk1 = norm2(&w);
547            h[k + 1][k] = C::new(hk1, 0.0);
548            // Previous rotations on the new column: [c s; −s̄ c] with real c.
549            for j in 0..k {
550                let t = h[j][k] * cs[j] + sn[j] * h[j + 1][k];
551                h[j + 1][k] = -sn[j].conj() * h[j][k] + h[j + 1][k] * cs[j];
552                h[j][k] = t;
553            }
554            let (f, gg) = (h[k][k], h[k + 1][k]);
555            let denom = (f.norm_sqr() + gg.norm_sqr()).sqrt();
556            if f.norm() == 0.0 {
557                cs[k] = 0.0;
558                sn[k] = gg.conj() / gg.norm().max(f64::MIN_POSITIVE);
559                h[k][k] = C::new(gg.norm(), 0.0);
560            } else {
561                let phase = f / f.norm();
562                cs[k] = f.norm() / denom;
563                sn[k] = phase * gg.conj() / denom;
564                h[k][k] = phase * denom;
565            }
566            h[k + 1][k] = zero;
567            g[k + 1] = -sn[k].conj() * g[k];
568            g[k] *= cs[k];
569            it += 1;
570            k_done = k + 1;
571            history.push(g[k + 1].norm());
572            if g[k + 1].norm() <= tol || it >= max_it {
573                break;
574            }
575            if hk1 == 0.0 {
576                break;
577            }
578            basis.push(w.iter().map(|v| v / hk1).collect());
579        }
580        let mut y = vec![zero; k_done];
581        for i in (0..k_done).rev() {
582            let s: C = (i + 1..k_done).map(|j| h[i][j] * y[j]).sum();
583            y[i] = (g[i] - s) / h[i][i];
584        }
585        let mut update = vec![zero; n];
586        for (j, yj) in y.iter().enumerate() {
587            axpy(&mut update, *yj, &basis[j]);
588        }
589        let dx = apply(m, &update);
590        axpy(&mut x, C::new(1.0, 0.0), &dx);
591        r = residual(a, b, &x);
592        let last = history.len() - 1;
593        history[last] = norm2(&r);
594    }
595    let converged = history[history.len() - 1] <= tol;
596    Ok(ComplexIterativeResult { x, iterations: it, converged, residual_history: history })
597}
598
599/// BiCGSTAB (SciPy's `bicgstab` on complex data), left-preconditioned as SciPy's.
600pub fn bicgstab_complex(a: &dyn ComplexLinearOperator, b: &[C], x0: Option<&[C]>, m: Option<&dyn ComplexLinearOperator>, options: ComplexIterativeOptions) -> Result<ComplexIterativeResult> {
601    let mut x = check(a, b, x0)?;
602    let tol = (options.rtol * norm2(b)).max(options.atol);
603    let max_it = options.max_iterations.unwrap_or(10 * b.len());
604    let mut r = residual(a, b, &x);
605    let r_hat = r.clone();
606    let mut history = vec![norm2(&r)];
607    let one = C::new(1.0, 0.0);
608    let zero = C::new(0.0, 0.0);
609    let (mut rho, mut alpha, mut omega) = (one, one, one);
610    let (mut v, mut p) = (vec![zero; b.len()], vec![zero; b.len()]);
611    let mut it = 0;
612    while history[history.len() - 1] > tol && it < max_it {
613        let rho_new = dotc(&r_hat, &r);
614        if rho_new.norm() == 0.0 {
615            break;
616        }
617        let beta = (rho_new / rho) * (alpha / omega);
618        rho = rho_new;
619        p.iter_mut().zip(r.iter().zip(&v)).for_each(|(pi, (ri, vi))| *pi = ri + beta * (*pi - omega * vi));
620        let p_hat = apply(m, &p);
621        v = a.matvec(&p_hat);
622        alpha = rho / dotc(&r_hat, &v);
623        let s: Vec<C> = r.iter().zip(&v).map(|(ri, vi)| ri - alpha * vi).collect();
624        it += 1;
625        if norm2(&s) <= tol {
626            axpy(&mut x, alpha, &p_hat);
627            r = s;
628            history.push(norm2(&r));
629            break;
630        }
631        let s_hat = apply(m, &s);
632        let t = a.matvec(&s_hat);
633        omega = dotc(&t, &s) / dotc(&t, &t);
634        axpy(&mut x, alpha, &p_hat);
635        axpy(&mut x, omega, &s_hat);
636        r = s.iter().zip(&t).map(|(si, ti)| si - omega * ti).collect();
637        history.push(norm2(&r));
638        if omega.norm() == 0.0 {
639            break;
640        }
641    }
642    let converged = history[history.len() - 1] <= tol;
643    Ok(ComplexIterativeResult { x, iterations: it, converged, residual_history: history })
644}
645// ANCHOR_END: complex_krylov