1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
//! To find Eigenvalue & Eigenvector
//!
//! * Reference : Press, William H., and William T. Vetterling. *Numerical Recipes.* Cambridge: Cambridge Univ. Press, 2007.

#[cfg(feature = "O3")]
use lapack::{dorgtr, dsteqr, dsytrd};

pub use self::EigenMethod::*;
use crate::structure::matrix::Matrix;
use crate::util::non_macro::eye_shape;
use std::f64::EPSILON;

#[derive(Debug, Copy, Clone)]
pub enum EigenMethod {
    Jacobi,
}

#[derive(Debug, Clone)]
pub struct Eigen {
    pub eigenvalue: Vec<f64>,
    pub eigenvector: Matrix,
}

impl Eigen {
    pub fn extract(self) -> (Vec<f64>, Matrix) {
        (self.eigenvalue, self.eigenvector)
    }
}

pub fn eigen(m: &Matrix, em: EigenMethod) -> Eigen {
    match em {
        Jacobi => {
            let mat = m.clone();
            let mut j = jacobi(mat);
            j.iter();
            j.extract()
        }
    }
}

// =============================================================================
// Jacobi Method
// =============================================================================
/// To do Jacobi method
///
/// * Reference : Press, William H., and William T. Vetterling. *Numerical Recipes.* Cambridge: Cambridge Univ. Press, 2007.
#[derive(Debug)]
pub struct JacobiTemp {
    pub n: usize,
    pub a: Matrix,
    pub v: Matrix,
    pub d: Vec<f64>,
    pub n_rot: usize,
}

pub fn jacobi(m: Matrix) -> JacobiTemp {
    let n = m.row;
    let v = eye_shape(n, m.shape);
    let d = m.diag();
    let a = m;

    JacobiTemp {
        n,
        a,
        v,
        d,
        n_rot: 0,
    }
}

impl JacobiTemp {
    pub fn new(m: Matrix) -> Self {
        jacobi(m)
    }

    pub fn extract(self) -> Eigen {
        let v = self.v;
        let d = self.d;
        Eigen {
            eigenvalue: d,
            eigenvector: v,
        }
    }

    /// Main Jacobi traits
    ///
    /// * Reference : Press, William H., and William T. Vetterling. *Numerical Recipes.* Cambridge: Cambridge Univ. Press, 2007.
    pub fn iter(&mut self) {
        let a = &mut self.a;
        let n = self.n;
        let v = &mut self.v;
        let mut b = a.diag();
        let d = &mut self.d;
        let mut z = vec![0f64; n];
        let mut h: f64;
        let mut _n_rot = self.n_rot;

        for i in 1..51 {
            let mut sm = 0f64;
            for ip in 0..n - 1 {
                for iq in ip + 1..n {
                    sm += a[(ip, iq)].abs();
                }
            }
            if sm == 0f64 {
                eigsrt(d, v);
                return ();
            }
            let tresh = if i < 4 {
                0.2 * sm / (n.pow(2) as f64)
            } else {
                0f64
            };
            for ip in 0..n - 1 {
                for iq in ip + 1..n {
                    let g = 100f64 * a[(ip, iq)].abs();
                    if i > 4 && g <= EPSILON * d[ip].abs() && g <= EPSILON * d[iq].abs() {
                        a[(ip, iq)] = 0f64;
                    } else if a[(ip, iq)].abs() > tresh {
                        h = d[iq] - d[ip];
                        let t = if g <= EPSILON * h.abs() {
                            a[(ip, iq)] / h
                        } else {
                            let theta = 0.5 * h / a[(ip, iq)];
                            let mut temp = 1f64 / (theta.abs() + (1f64 + theta.powi(2)).sqrt());
                            if theta < 0f64 {
                                temp = -temp;
                            }
                            temp
                        };
                        let c = 1f64 / (1f64 + t.powi(2)).sqrt();
                        let s = t * c;
                        let tau = s / (1f64 + c);
                        h = t * a[(ip, iq)];
                        z[ip] -= h;
                        z[iq] += h;
                        d[ip] -= h;
                        d[iq] += h;
                        a[(ip, iq)] = 0f64;
                        for j in 0..ip {
                            rot(a, s, tau, j, ip, j, iq);
                        }
                        for j in ip + 1..iq {
                            rot(a, s, tau, ip, j, j, iq);
                        }
                        for j in iq + 1..n {
                            rot(a, s, tau, ip, j, iq, j);
                        }
                        for j in 0..n {
                            rot(v, s, tau, j, ip, j, iq);
                        }
                        _n_rot += 1;
                    }
                }
            }
            for ip in 0..n {
                b[ip] += z[ip];
                d[ip] = b[ip];
                z[ip] = 0f64;
            }
        }
        assert!(false, "Too many iterations in routine jacobi");
    }
}

fn rot(a: &mut Matrix, s: f64, tau: f64, i: usize, j: usize, k: usize, l: usize) {
    let g = a[(i, j)];
    let h = a[(k, l)];
    a[(i, j)] = g - s * (h + g * tau);
    a[(k, l)] = h + s * (g - h * tau);
}

/// Given eigenvalue & eigenvector, sorts thod eigenvalues into descending order
///
/// * Reference : Press, William H., and William T. Vetterling. *Numerical Recipes.* Cambridge: Cambridge Univ. Press, 2007.
fn eigsrt(d: &mut Vec<f64>, v: &mut Matrix) {
    let mut k: usize;
    let n = d.len();
    for i in 0..n - 1 {
        k = i;
        let mut p = d[k];
        for j in i..n {
            if d[j] >= p {
                k = j;
                p = d[k];
            }
        }
        if k != i {
            d[k] = d[i];
            d[i] = p;
            for j in 0..n {
                p = v[(j, i)];
                v[(j, i)] = v[(j, k)];
                v[(j, k)] = p;
            }
        }
    }
}