ndarray_linalg/krylov/
mgs.rs

1//! Modified Gram-Schmit orthogonalizer
2
3use super::*;
4use crate::{generate::*, inner::*, norm::Norm};
5
6/// Iterative orthogonalizer using modified Gram-Schmit procedure
7#[derive(Debug, Clone)]
8pub struct MGS<A: Scalar> {
9    /// Dimension of base space
10    dim: usize,
11
12    /// Basis of spanned space
13    q: Vec<Array1<A>>,
14
15    /// Tolerance
16    tol: A::Real,
17}
18
19impl<A: Scalar + Lapack> MGS<A> {
20    /// Create an empty orthogonalizer
21    pub fn new(dim: usize, tol: A::Real) -> Self {
22        Self {
23            dim,
24            q: Vec::new(),
25            tol,
26        }
27    }
28}
29
30impl<A: Scalar + Lapack> Orthogonalizer for MGS<A> {
31    type Elem = A;
32
33    fn dim(&self) -> usize {
34        self.dim
35    }
36
37    fn len(&self) -> usize {
38        self.q.len()
39    }
40
41    fn tolerance(&self) -> A::Real {
42        self.tol
43    }
44
45    fn decompose(&self, a: &mut ArrayRef<A, Ix1>) -> Array1<A> {
46        assert_eq!(a.len(), self.dim());
47        let mut coef = Array1::zeros(self.len() + 1);
48        for i in 0..self.len() {
49            let q = &self.q[i];
50            let c = q.inner(a);
51            azip!((a in &mut *a, &q in q) *a -= c * q);
52            coef[i] = c;
53        }
54        let nrm = a.norm_l2();
55        coef[self.len()] = A::from_real(nrm);
56        coef
57    }
58
59    fn coeff<S>(&self, a: ArrayBase<S, Ix1>) -> Array1<A>
60    where
61        A: Lapack,
62        S: Data<Elem = A>,
63    {
64        let mut a = a.into_owned();
65        self.decompose(&mut a)
66    }
67
68    fn append<S>(&mut self, a: ArrayBase<S, Ix1>) -> AppendResult<A>
69    where
70        A: Lapack,
71        S: Data<Elem = A>,
72    {
73        let mut a = a.into_owned();
74        self.div_append(&mut a)
75    }
76
77    fn div_append(&mut self, a: &mut ArrayRef<A, Ix1>) -> AppendResult<A>
78    where
79        A: Lapack,
80    {
81        let coef = self.decompose(a);
82        let nrm = coef[coef.len() - 1].re();
83        if nrm < self.tol {
84            // Linearly dependent
85            return AppendResult::Dependent(coef);
86        }
87        azip!((a in &mut *a) *a /= A::from_real(nrm));
88        self.q.push(a.to_owned());
89        AppendResult::Added(coef)
90    }
91
92    fn get_q(&self) -> Q<A> {
93        hstack(&self.q).unwrap()
94    }
95}
96
97/// Online QR decomposition using modified Gram-Schmit algorithm
98pub fn mgs<A, S>(
99    iter: impl Iterator<Item = ArrayBase<S, Ix1>>,
100    dim: usize,
101    rtol: A::Real,
102    strategy: Strategy,
103) -> (Q<A>, R<A>)
104where
105    A: Scalar + Lapack,
106    S: Data<Elem = A>,
107{
108    let mgs = MGS::new(dim, rtol);
109    qr(iter, mgs, strategy)
110}