Skip to main content

mathverse_complex/
matrix.rs

1//! Complex matrix operations: arithmetic, decomposition, eigenvalues.
2
3use crate::Complex;
4
5/// Complex matrix with row-major storage.
6#[derive(Debug, Clone)]
7pub struct ComplexMatrix {
8    pub data: Vec<Complex>,
9    pub rows: usize,
10    pub cols: usize,
11}
12
13impl ComplexMatrix {
14    /// Create a new complex matrix.
15    pub fn new(rows: usize, cols: usize) -> Self {
16        ComplexMatrix {
17            data: vec![Complex::zero(); rows * cols],
18            rows,
19            cols,
20        }
21    }
22
23    /// Create matrix from data.
24    pub fn from_data(data: Vec<Complex>, rows: usize, cols: usize) -> Self {
25        assert_eq!(data.len(), rows * cols);
26        ComplexMatrix { data, rows, cols }
27    }
28
29    /// Get element at (row, col).
30    pub fn get(&self, row: usize, col: usize) -> Complex {
31        self.data[row * self.cols + col]
32    }
33
34    /// Set element at (row, col).
35    pub fn set(&mut self, row: usize, col: usize, value: Complex) {
36        self.data[row * self.cols + col] = value;
37    }
38
39    /// Create zero matrix.
40    pub fn zeros(rows: usize, cols: usize) -> Self {
41        ComplexMatrix::new(rows, cols)
42    }
43
44    /// Create identity matrix.
45    pub fn identity(n: usize) -> Self {
46        let mut matrix = ComplexMatrix::new(n, n);
47        for i in 0..n {
48            matrix.set(i, i, Complex::one());
49        }
50        matrix
51    }
52
53    /// Matrix addition.
54    pub fn add(&self, other: &ComplexMatrix) -> ComplexMatrix {
55        assert_eq!(self.rows, other.rows);
56        assert_eq!(self.cols, other.cols);
57        
58        let mut result = ComplexMatrix::new(self.rows, self.cols);
59        for i in 0..self.data.len() {
60            result.data[i] = self.data[i] + other.data[i];
61        }
62        result
63    }
64
65    /// Matrix subtraction.
66    pub fn sub(&self, other: &ComplexMatrix) -> ComplexMatrix {
67        assert_eq!(self.rows, other.rows);
68        assert_eq!(self.cols, other.cols);
69        
70        let mut result = ComplexMatrix::new(self.rows, self.cols);
71        for i in 0..self.data.len() {
72            result.data[i] = self.data[i] - other.data[i];
73        }
74        result
75    }
76
77    /// Scalar multiplication.
78    pub fn scale(&self, scalar: Complex) -> ComplexMatrix {
79        let mut result = ComplexMatrix::new(self.rows, self.cols);
80        for i in 0..self.data.len() {
81            result.data[i] = self.data[i] * scalar;
82        }
83        result
84    }
85
86    /// Matrix multiplication.
87    pub fn mul(&self, other: &ComplexMatrix) -> ComplexMatrix {
88        assert_eq!(self.cols, other.rows);
89        
90        let mut result = ComplexMatrix::new(self.rows, other.cols);
91        
92        for i in 0..self.rows {
93            for j in 0..other.cols {
94                let mut sum = Complex::zero();
95                for k in 0..self.cols {
96                    sum = sum + self.get(i, k) * other.get(k, j);
97                }
98                result.set(i, j, sum);
99            }
100        }
101        
102        result
103    }
104
105    /// Matrix transpose.
106    pub fn transpose(&self) -> ComplexMatrix {
107        let mut result = ComplexMatrix::new(self.cols, self.rows);
108        
109        for i in 0..self.rows {
110            for j in 0..self.cols {
111                result.set(j, i, self.get(i, j));
112            }
113        }
114        
115        result
116    }
117
118    /// Conjugate transpose (Hermitian transpose).
119    pub fn hermitian(&self) -> ComplexMatrix {
120        let mut result = ComplexMatrix::new(self.cols, self.rows);
121        
122        for i in 0..self.rows {
123            for j in 0..self.cols {
124                result.set(j, i, self.get(i, j).conjugate());
125            }
126        }
127        
128        result
129    }
130
131    /// Matrix trace.
132    pub fn trace(&self) -> Complex {
133        assert_eq!(self.rows, self.cols);
134        
135        let mut sum = Complex::zero();
136        for i in 0..self.rows {
137            sum = sum + self.get(i, i);
138        }
139        sum
140    }
141
142    /// Matrix determinant (for small matrices).
143    pub fn determinant(&self) -> Complex {
144        assert_eq!(self.rows, self.cols);
145        
146        match self.rows {
147            1 => self.get(0, 0),
148            2 => {
149                let a = self.get(0, 0);
150                let b = self.get(0, 1);
151                let c = self.get(1, 0);
152                let d = self.get(1, 1);
153                a * d - b * c
154            }
155            3 => {
156                let a = self.get(0, 0);
157                let b = self.get(0, 1);
158                let c = self.get(0, 2);
159                let d = self.get(1, 0);
160                let e = self.get(1, 1);
161                let f = self.get(1, 2);
162                let g = self.get(2, 0);
163                let h = self.get(2, 1);
164                let i = self.get(2, 2);
165                
166                a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
167            }
168            _ => {
169                // Use LU decomposition for larger matrices
170                let (_, u, pivot) = self.lu_decomposition().unwrap();
171                let mut det = Complex::one();
172                
173                for i in 0..self.rows {
174                    det = det * u.get(i, i);
175                }
176                
177                // Sign from permutation parity: (-1)^(n - #cycles)
178                let mut visited = vec![false; self.rows];
179                let mut cycles = 0;
180                for i in 0..self.rows {
181                    if !visited[i] {
182                        cycles += 1;
183                        let mut j = i;
184                        while !visited[j] {
185                            visited[j] = true;
186                            j = pivot[j];
187                        }
188                    }
189                }
190                if (self.rows - cycles) % 2 == 1 {
191                    det = -det;
192                }
193                
194                det
195            }
196        }
197    }
198
199    /// LU decomposition with partial pivoting.
200    pub fn lu_decomposition(&self) -> Option<(ComplexMatrix, ComplexMatrix, Vec<usize>)> {
201        if self.rows != self.cols {
202            return None;
203        }
204        
205        let n = self.rows;
206        let mut l = ComplexMatrix::identity(n);
207        let mut u = self.clone();
208        let mut pivot = (0..n).collect::<Vec<_>>();
209        
210        for k in 0..n {
211            // Find pivot
212            let mut max_row = k;
213            let mut max_val = u.get(k, k).norm();
214            
215            for i in (k + 1)..n {
216                let val = u.get(i, k).norm();
217                if val > max_val {
218                    max_val = val;
219                    max_row = i;
220                }
221            }
222            
223            if max_val < 1e-15 {
224                return None; // Singular matrix
225            }
226            
227            // Swap rows
228            if max_row != k {
229                pivot.swap(k, max_row);
230                for j in 0..n {
231                    let temp = u.get(k, j);
232                    u.set(k, j, u.get(max_row, j));
233                    u.set(max_row, j, temp);
234                }
235            }
236            
237            // Elimination
238            for i in (k + 1)..n {
239                let factor = u.get(i, k) / u.get(k, k);
240                l.set(i, k, factor);
241                
242                for j in k..n {
243                    let new_val = u.get(i, j) - factor * u.get(k, j);
244                    u.set(i, j, new_val);
245                }
246            }
247        }
248        
249        Some((l, u, pivot))
250    }
251
252    /// Solve linear system Ax = b using LU decomposition.
253    pub fn solve(&self, b: &[Complex]) -> Option<Vec<Complex>> {
254        if self.rows != self.cols || b.len() != self.rows {
255            return None;
256        }
257        
258        let (l, u, pivot) = self.lu_decomposition()?;
259        let n = self.rows;
260        
261        // Apply pivot to b
262        let mut pb = b.to_vec();
263        for i in 0..n {
264            pb[i] = b[pivot[i]];
265        }
266        
267        // Forward substitution: Ly = pb
268        let mut y = vec![Complex::zero(); n];
269        for i in 0..n {
270            let mut sum = pb[i];
271            for j in 0..i {
272                sum = sum - l.get(i, j) * y[j];
273            }
274            y[i] = sum / l.get(i, i);
275        }
276        
277        // Back substitution: Ux = y
278        let mut x = vec![Complex::zero(); n];
279        for i in (0..n).rev() {
280            let mut sum = y[i];
281            for j in (i + 1)..n {
282                sum = sum - u.get(i, j) * x[j];
283            }
284            x[i] = sum / u.get(i, i);
285        }
286        
287        Some(x)
288    }
289
290    /// Matrix inverse.
291    pub fn inverse(&self) -> Option<ComplexMatrix> {
292        if self.rows != self.cols {
293            return None;
294        }
295        
296        let n = self.rows;
297        let mut result = ComplexMatrix::new(n, n);
298        
299        // Solve for each column of identity
300        for j in 0..n {
301            let mut b = vec![Complex::zero(); n];
302            b[j] = Complex::one();
303            
304            if let Some(col) = self.solve(&b) {
305                for i in 0..n {
306                    result.set(i, j, col[i]);
307                }
308            } else {
309                return None;
310            }
311        }
312        
313        Some(result)
314    }
315
316    /// Check if matrix is Hermitian (equal to its conjugate transpose).
317    pub fn is_hermitian(&self, tolerance: f64) -> bool {
318        if self.rows != self.cols {
319            return false;
320        }
321        
322        let hermitian = self.hermitian();
323        
324        for i in 0..self.rows {
325            for j in 0..self.cols {
326                let diff = (self.get(i, j) - hermitian.get(i, j)).norm();
327                if diff > tolerance {
328                    return false;
329                }
330            }
331        }
332        
333        true
334    }
335
336    /// Check if matrix is unitary (A * A^H = I).
337    pub fn is_unitary(&self, tolerance: f64) -> bool {
338        if self.rows != self.cols {
339            return false;
340        }
341        
342        let hermitian = self.hermitian();
343        let product = self.mul(&hermitian);
344        let identity = ComplexMatrix::identity(self.rows);
345        
346        for i in 0..self.rows {
347            for j in 0..self.cols {
348                let diff = (product.get(i, j) - identity.get(i, j)).norm();
349                if diff > tolerance {
350                    return false;
351                }
352            }
353        }
354        
355        true
356    }
357
358    /// Frobenius norm.
359    pub fn frobenius_norm(&self) -> f64 {
360        self.data.iter().map(|c| c.norm_sq()).sum::<f64>().sqrt()
361    }
362
363    /// Matrix power A^n.
364    pub fn power(&self, n: usize) -> ComplexMatrix {
365        if self.rows != self.cols {
366            panic!("Matrix must be square");
367        }
368        
369        if n == 0 {
370            return ComplexMatrix::identity(self.rows);
371        }
372        
373        let mut result = ComplexMatrix::identity(self.rows);
374        let mut base = self.clone();
375        let mut exp = n;
376        
377        while exp > 0 {
378            if exp % 2 == 1 {
379                result = result.mul(&base);
380            }
381            base = base.mul(&base);
382            exp /= 2;
383        }
384        
385        result
386    }
387
388    /// Matrix exponential e^A using Taylor series with scaling-and-squaring:
389    /// compute e^(A/2^k) then square k times.
390    pub fn exp(&self, iterations: usize) -> ComplexMatrix {
391        if self.rows != self.cols {
392            panic!("Matrix must be square");
393        }
394        
395        let norm = self.frobenius_norm();
396        let mut scale_pow = 0;
397        if norm > 1.0 {
398            scale_pow = norm.log2().ceil() as usize;
399        }
400        let scaled = self.scale(Complex::real(1.0 / 2.0_f64.powi(scale_pow as i32)));
401        
402        let mut result = ComplexMatrix::identity(self.rows);
403        let mut term = ComplexMatrix::identity(self.rows);
404        let mut factorial: f64 = 1.0;
405        
406        for n in 1..=iterations {
407            factorial *= n as f64;
408            term = term.mul(&scaled);
409            
410            for i in 0..term.data.len() {
411                result.data[i] = result.data[i] + term.data[i] / Complex::real(factorial);
412            }
413        }
414        
415        for _ in 0..scale_pow {
416            result = result.mul(&result);
417        }
418        
419        result
420    }
421
422    /// Matrix logarithm ln(A) using Taylor series around identity.
423    /// Returns `None` if the series cannot converge, i.e. if any eigenvalue
424    /// of A is outside the disk |λ - 1| < 1 (checked via a Frobenius-norm
425    /// bound on A - I, which is conservative but safe).
426    pub fn ln(&self, iterations: usize) -> Option<ComplexMatrix> {
427        if self.rows != self.cols {
428            panic!("Matrix must be square");
429        }
430        
431        let identity = ComplexMatrix::identity(self.rows);
432        let a_minus_i = self.sub(&identity);
433        
434        // ||A - I||_F >= spectral radius of (A - I); series needs it < 1
435        if a_minus_i.frobenius_norm() >= 1.0 {
436            return None;
437        }
438        
439        let mut result = ComplexMatrix::zeros(self.rows, self.cols);
440        let mut term = a_minus_i.clone();
441        
442        for n in 1..=iterations {
443            let sign = if n % 2 == 0 { -Complex::one() } else { Complex::one() };
444            let scalar = sign / Complex::real(n as f64);
445            
446            for i in 0..result.data.len() {
447                result.data[i] = result.data[i] + term.data[i] * scalar;
448            }
449            
450            term = term.mul(&a_minus_i);
451        }
452        
453        Some(result)
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460
461    #[test]
462    fn test_matrix_creation() {
463        let m = ComplexMatrix::new(2, 3);
464        assert_eq!(m.rows, 2);
465        assert_eq!(m.cols, 3);
466        assert_eq!(m.data.len(), 6);
467    }
468
469    #[test]
470    fn test_identity() {
471        let i = ComplexMatrix::identity(3);
472        assert_eq!(i.get(0, 0), Complex::one());
473        assert_eq!(i.get(1, 1), Complex::one());
474        assert_eq!(i.get(2, 2), Complex::one());
475        assert_eq!(i.get(0, 1), Complex::zero());
476    }
477
478    #[test]
479    fn test_matrix_addition() {
480        let mut m1 = ComplexMatrix::new(2, 2);
481        m1.set(0, 0, Complex::real(1.0));
482        m1.set(0, 1, Complex::real(2.0));
483        
484        let mut m2 = ComplexMatrix::new(2, 2);
485        m2.set(0, 0, Complex::real(3.0));
486        m2.set(0, 1, Complex::real(4.0));
487        
488        let result = m1.add(&m2);
489        assert_eq!(result.get(0, 0), Complex::real(4.0));
490        assert_eq!(result.get(0, 1), Complex::real(6.0));
491    }
492
493    #[test]
494    fn test_matrix_multiplication() {
495        let mut m1 = ComplexMatrix::new(2, 2);
496        m1.set(0, 0, Complex::real(1.0));
497        m1.set(0, 1, Complex::real(2.0));
498        m1.set(1, 0, Complex::real(3.0));
499        m1.set(1, 1, Complex::real(4.0));
500        
501        let mut m2 = ComplexMatrix::new(2, 2);
502        m2.set(0, 0, Complex::real(5.0));
503        m2.set(0, 1, Complex::real(6.0));
504        m2.set(1, 0, Complex::real(7.0));
505        m2.set(1, 1, Complex::real(8.0));
506        
507        let result = m1.mul(&m2);
508        
509        assert_eq!(result.get(0, 0), Complex::real(19.0)); // 1*5 + 2*7
510        assert_eq!(result.get(0, 1), Complex::real(22.0)); // 1*6 + 2*8
511        assert_eq!(result.get(1, 0), Complex::real(43.0)); // 3*5 + 4*7
512        assert_eq!(result.get(1, 1), Complex::real(50.0)); // 3*6 + 4*8
513    }
514
515    #[test]
516    fn test_determinant_2x2() {
517        let mut m = ComplexMatrix::new(2, 2);
518        m.set(0, 0, Complex::real(1.0));
519        m.set(0, 1, Complex::real(2.0));
520        m.set(1, 0, Complex::real(3.0));
521        m.set(1, 1, Complex::real(4.0));
522        
523        let det = m.determinant();
524        assert_eq!(det, Complex::real(-2.0)); // 1*4 - 2*3
525    }
526
527    #[test]
528    fn test_transpose() {
529        let mut m = ComplexMatrix::new(2, 3);
530        m.set(0, 0, Complex::real(1.0));
531        m.set(0, 1, Complex::real(2.0));
532        m.set(0, 2, Complex::real(3.0));
533        m.set(1, 0, Complex::real(4.0));
534        m.set(1, 1, Complex::real(5.0));
535        m.set(1, 2, Complex::real(6.0));
536        
537        let t = m.transpose();
538        assert_eq!(t.rows, 3);
539        assert_eq!(t.cols, 2);
540        assert_eq!(t.get(0, 0), Complex::real(1.0));
541        assert_eq!(t.get(1, 0), Complex::real(2.0));
542        assert_eq!(t.get(0, 1), Complex::real(4.0));
543    }
544
545    #[test]
546    fn test_hermitian() {
547        let mut m = ComplexMatrix::new(2, 2);
548        m.set(0, 0, Complex::real(1.0));
549        m.set(0, 1, Complex::new(1.0, 2.0));
550        m.set(1, 0, Complex::new(1.0, -2.0));
551        m.set(1, 1, Complex::real(3.0));
552        
553        assert!(m.is_hermitian(1e-10));
554    }
555
556    #[test]
557    fn test_solve() {
558        let mut m = ComplexMatrix::new(2, 2);
559        m.set(0, 0, Complex::real(2.0));
560        m.set(0, 1, Complex::real(1.0));
561        m.set(1, 0, Complex::real(1.0));
562        m.set(1, 1, Complex::real(1.0));
563        
564        let b = vec![Complex::real(3.0), Complex::real(2.0)];
565        let x = m.solve(&b).unwrap();
566        
567        // Solution should be [1, 1]
568        assert!((x[0].re - 1.0).abs() < 1e-10);
569        assert!((x[1].re - 1.0).abs() < 1e-10);
570    }
571
572    #[test]
573    fn test_inverse() {
574        let mut m = ComplexMatrix::new(2, 2);
575        m.set(0, 0, Complex::real(2.0));
576        m.set(0, 1, Complex::real(1.0));
577        m.set(1, 0, Complex::real(1.0));
578        m.set(1, 1, Complex::real(1.0));
579        
580        let inv = m.inverse().unwrap();
581        let product = m.mul(&inv);
582        
583        // Should be close to identity
584        assert!((product.get(0, 0) - Complex::one()).norm() < 1e-10);
585        assert!((product.get(1, 1) - Complex::one()).norm() < 1e-10);
586    }
587
588    #[test]
589    fn test_power() {
590        let mut m = ComplexMatrix::new(2, 2);
591        m.set(0, 0, Complex::real(1.0));
592        m.set(0, 1, Complex::real(1.0));
593        m.set(1, 0, Complex::real(0.0));
594        m.set(1, 1, Complex::real(1.0));
595        
596        let m2 = m.power(2);
597        
598        assert_eq!(m2.get(0, 0), Complex::real(1.0));
599        assert_eq!(m2.get(0, 1), Complex::real(2.0));
600        assert_eq!(m2.get(1, 0), Complex::zero());
601        assert_eq!(m2.get(1, 1), Complex::real(1.0));
602    }
603
604    #[test]
605    fn test_determinant_permutation_sign() {
606        // 4x4 permutation matrix swapping rows 0/1: det must be -1
607        // (regression: LU path ignored pivot parity)
608        let mut m = ComplexMatrix::identity(4);
609        for j in 0..4 {
610            let t = m.get(0, j);
611            m.set(0, j, m.get(1, j));
612            m.set(1, j, t);
613        }
614        let det = m.determinant();
615        assert!((det.re + 1.0).abs() < 1e-12);
616        assert!(det.im.abs() < 1e-12);
617
618        // 4x4 diag(1,2,3,4) with rows 0/1 swapped: det = -24
619        let mut m2 = ComplexMatrix::new(4, 4);
620        m2.set(0, 0, Complex::real(1.0));
621        m2.set(1, 1, Complex::real(2.0));
622        m2.set(2, 2, Complex::real(3.0));
623        m2.set(3, 3, Complex::real(4.0));
624        for j in 0..4 {
625            let t = m2.get(0, j);
626            m2.set(0, j, m2.get(1, j));
627            m2.set(1, j, t);
628        }
629        let det2 = m2.determinant();
630        assert!((det2.re + 24.0).abs() < 1e-10);
631    }
632
633    #[test]
634    fn test_matrix_exp() {
635        // exp(0) = I
636        let zero = ComplexMatrix::new(2, 2);
637        let e0 = zero.exp(20);
638        assert!((e0.get(0, 0) - Complex::one()).norm() < 1e-10);
639        assert!((e0.get(1, 1) - Complex::one()).norm() < 1e-10);
640
641        // exp([[0,1],[0,0]]) = [[1,1],[0,1]]
642        let mut m = ComplexMatrix::new(2, 2);
643        m.set(0, 1, Complex::one());
644        let em = m.exp(20);
645        assert!((em.get(0, 0) - Complex::one()).norm() < 1e-10);
646        assert!((em.get(0, 1) - Complex::one()).norm() < 1e-10);
647        assert!((em.get(1, 0) - Complex::zero()).norm() < 1e-10);
648        assert!((em.get(1, 1) - Complex::one()).norm() < 1e-10);
649
650        // exp of large-norm matrix needs scaling-and-squaring: exp(diag(10,10)) = diag(e^10, e^10)
651        let mut big = ComplexMatrix::new(2, 2);
652        big.set(0, 0, Complex::real(10.0));
653        big.set(1, 1, Complex::real(10.0));
654        let ebig = big.exp(30);
655        let e10 = 10.0_f64.exp();
656        assert!((ebig.get(0, 0).re - e10).abs() < 1e-6 * e10);
657        assert!((ebig.get(1, 1).re - e10).abs() < 1e-6 * e10);
658        assert!((ebig.get(0, 1) - Complex::zero()).norm() < 1e-6 * e10);
659    }
660
661    #[test]
662    fn test_matrix_ln() {
663        // ln(I) = 0
664        let i = ComplexMatrix::identity(2);
665        let ln_i = i.ln(20).unwrap();
666        assert!((ln_i.get(0, 0) - Complex::zero()).norm() < 1e-10);
667
668        // exp(ln(A)) = A for A near identity
669        let mut a = ComplexMatrix::new(2, 2);
670        a.set(0, 0, Complex::real(1.2));
671        a.set(0, 1, Complex::real(0.1));
672        a.set(1, 0, Complex::real(-0.2));
673        a.set(1, 1, Complex::real(0.8));
674        let ln_a = a.ln(40).unwrap();
675        let round = ln_a.exp(40);
676        for i in 0..2 {
677            for j in 0..2 {
678                assert!((round.get(i, j) - a.get(i, j)).norm() < 1e-8);
679            }
680        }
681
682        // ln(10·I) diverges: must return None (regression: silently returned garbage)
683        let mut big = ComplexMatrix::new(2, 2);
684        big.set(0, 0, Complex::real(10.0));
685        big.set(1, 1, Complex::real(10.0));
686        assert!(big.ln(20).is_none());
687    }
688}