1use crate::Complex;
4use mathverse_core::error::{MathError, MathResult};
5use std::ops::{Index, IndexMut};
6
7#[derive(Debug, Clone)]
9pub struct ComplexMatrix {
10 pub data: Vec<Complex>,
12 pub rows: usize,
14 pub cols: usize,
16}
17
18impl ComplexMatrix {
19 pub fn new(rows: usize, cols: usize) -> Self {
21 ComplexMatrix {
22 data: vec![Complex::zero(); rows * cols],
23 rows,
24 cols,
25 }
26 }
27
28 pub fn from_data(data: Vec<Complex>, rows: usize, cols: usize) -> Self {
33 assert_eq!(
34 data.len(),
35 rows * cols,
36 "data length must equal rows * cols"
37 );
38 ComplexMatrix { data, rows, cols }
39 }
40
41 pub fn get(&self, row: usize, col: usize) -> Complex {
47 self.data[row * self.cols + col]
48 }
49
50 pub fn set(&mut self, row: usize, col: usize, value: Complex) {
56 self.data[row * self.cols + col] = value;
57 }
58
59 pub fn try_get(&self, row: usize, col: usize) -> Option<Complex> {
61 if row < self.rows && col < self.cols {
62 Some(self.data[row * self.cols + col])
63 } else {
64 None
65 }
66 }
67
68 pub fn try_set(&mut self, row: usize, col: usize, value: Complex) -> MathResult<()> {
70 if row >= self.rows || col >= self.cols {
71 Err(MathError::OutOfRange)
72 } else {
73 self.data[row * self.cols + col] = value;
74 Ok(())
75 }
76 }
77
78 pub fn zeros(rows: usize, cols: usize) -> Self {
80 ComplexMatrix::new(rows, cols)
81 }
82
83 pub fn identity(n: usize) -> Self {
85 let mut matrix = ComplexMatrix::new(n, n);
86 for i in 0..n {
87 matrix.set(i, i, Complex::one());
88 }
89 matrix
90 }
91
92 pub fn add(&self, other: &ComplexMatrix) -> MathResult<ComplexMatrix> {
97 if self.rows != other.rows || self.cols != other.cols {
98 return Err(MathError::DimensionMismatch);
99 }
100 let mut result = ComplexMatrix::new(self.rows, self.cols);
101 for i in 0..self.data.len() {
102 result.data[i] = self.data[i] + other.data[i];
103 }
104 Ok(result)
105 }
106
107 pub fn sub(&self, other: &ComplexMatrix) -> MathResult<ComplexMatrix> {
112 if self.rows != other.rows || self.cols != other.cols {
113 return Err(MathError::DimensionMismatch);
114 }
115 let mut result = ComplexMatrix::new(self.rows, self.cols);
116 for i in 0..self.data.len() {
117 result.data[i] = self.data[i] - other.data[i];
118 }
119 Ok(result)
120 }
121
122 pub fn scale(&self, scalar: Complex) -> ComplexMatrix {
124 let mut result = ComplexMatrix::new(self.rows, self.cols);
125 for i in 0..self.data.len() {
126 result.data[i] = self.data[i] * scalar;
127 }
128 result
129 }
130
131 pub fn mul(&self, other: &ComplexMatrix) -> MathResult<ComplexMatrix> {
136 if self.cols != other.rows {
137 return Err(MathError::DimensionMismatch);
138 }
139 let mut result = ComplexMatrix::new(self.rows, other.cols);
140 for i in 0..self.rows {
141 for j in 0..other.cols {
142 let mut sum = Complex::zero();
143 for k in 0..self.cols {
144 sum = sum + self.get(i, k) * other.get(k, j);
145 }
146 result.set(i, j, sum);
147 }
148 }
149 Ok(result)
150 }
151
152 pub fn transpose(&self) -> ComplexMatrix {
154 let mut result = ComplexMatrix::new(self.cols, self.rows);
155 for i in 0..self.rows {
156 for j in 0..self.cols {
157 result.set(j, i, self.get(i, j));
158 }
159 }
160 result
161 }
162
163 pub fn hermitian(&self) -> ComplexMatrix {
165 let mut result = ComplexMatrix::new(self.cols, self.rows);
166 for i in 0..self.rows {
167 for j in 0..self.cols {
168 result.set(j, i, self.get(i, j).conjugate());
169 }
170 }
171 result
172 }
173
174 pub fn trace(&self) -> Complex {
179 assert_eq!(self.rows, self.cols, "trace requires a square matrix");
180 let mut sum = Complex::zero();
181 for i in 0..self.rows {
182 sum = sum + self.get(i, i);
183 }
184 sum
185 }
186
187 pub fn determinant(&self) -> Complex {
192 assert_eq!(self.rows, self.cols, "determinant requires a square matrix");
193 match self.rows {
194 1 => self.get(0, 0),
195 2 => {
196 let a = self.get(0, 0);
197 let b = self.get(0, 1);
198 let c = self.get(1, 0);
199 let d = self.get(1, 1);
200 a * d - b * c
201 }
202 3 => {
203 let a = self.get(0, 0);
204 let b = self.get(0, 1);
205 let c = self.get(0, 2);
206 let d = self.get(1, 0);
207 let e = self.get(1, 1);
208 let f = self.get(1, 2);
209 let g = self.get(2, 0);
210 let h = self.get(2, 1);
211 let i = self.get(2, 2);
212 a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
213 }
214 _ => {
215 let (_, u, pivot) = self.lu_decomposition().expect("matrix is singular");
217 let mut det = Complex::one();
218 for i in 0..self.rows {
219 det = det * u.get(i, i);
220 }
221 let mut visited = vec![false; self.rows];
223 let mut cycles = 0;
224 for i in 0..self.rows {
225 if !visited[i] {
226 cycles += 1;
227 let mut j = i;
228 while !visited[j] {
229 visited[j] = true;
230 j = pivot[j];
231 }
232 }
233 }
234 if (self.rows - cycles) % 2 == 1 {
235 det = -det;
236 }
237 det
238 }
239 }
240 }
241
242 pub fn lu_decomposition(&self) -> Option<(ComplexMatrix, ComplexMatrix, Vec<usize>)> {
249 if self.rows != self.cols {
250 return None;
251 }
252 let n = self.rows;
253 let mut l = ComplexMatrix::identity(n);
254 let mut u = self.clone();
255 let mut pivot = (0..n).collect::<Vec<_>>();
256
257 let global_scale = self.data.iter().map(|c| c.norm()).fold(0.0, f64::max);
262 let pivot_tol = 1e-15 * global_scale;
263
264 for k in 0..n {
265 let mut max_row = k;
267 let mut max_val = u.get(k, k).norm();
268 for i in (k + 1)..n {
269 let val = u.get(i, k).norm();
270 if val > max_val {
271 max_val = val;
272 max_row = i;
273 }
274 }
275 if max_val <= pivot_tol {
276 return None; }
278 if max_row != k {
280 pivot.swap(k, max_row);
281 for j in 0..n {
282 let temp = u.get(k, j);
283 u.set(k, j, u.get(max_row, j));
284 u.set(max_row, j, temp);
285 }
286 }
287 for i in (k + 1)..n {
289 let factor = u.get(i, k) / u.get(k, k);
290 l.set(i, k, factor);
291 for j in k..n {
292 let new_val = u.get(i, j) - factor * u.get(k, j);
293 u.set(i, j, new_val);
294 }
295 }
296 }
297 Some((l, u, pivot))
298 }
299
300 pub fn solve(&self, b: &[Complex]) -> Option<Vec<Complex>> {
302 if self.rows != self.cols || b.len() != self.rows {
303 return None;
304 }
305 let (l, u, pivot) = self.lu_decomposition()?;
306 let n = self.rows;
307
308 let mut pb = b.to_vec();
310 for i in 0..n {
311 pb[i] = b[pivot[i]];
312 }
313
314 let mut y = vec![Complex::zero(); n];
316 for i in 0..n {
317 let mut sum = pb[i];
318 for j in 0..i {
319 sum = sum - l.get(i, j) * y[j];
320 }
321 y[i] = sum / l.get(i, i);
322 }
323
324 let mut x = vec![Complex::zero(); n];
326 for i in (0..n).rev() {
327 let mut sum = y[i];
328 for j in (i + 1)..n {
329 sum = sum - u.get(i, j) * x[j];
330 }
331 x[i] = sum / u.get(i, i);
332 }
333 Some(x)
334 }
335
336 pub fn inverse(&self) -> Option<ComplexMatrix> {
338 if self.rows != self.cols {
339 return None;
340 }
341 let n = self.rows;
342 let mut result = ComplexMatrix::new(n, n);
343 for j in 0..n {
344 let mut b = vec![Complex::zero(); n];
345 b[j] = Complex::one();
346 if let Some(col) = self.solve(&b) {
347 for i in 0..n {
348 result.set(i, j, col[i]);
349 }
350 } else {
351 return None;
352 }
353 }
354 Some(result)
355 }
356
357 pub fn is_hermitian(&self, tolerance: f64) -> bool {
359 if self.rows != self.cols {
360 return false;
361 }
362 let hermitian = self.hermitian();
363 for i in 0..self.rows {
364 for j in 0..self.cols {
365 let diff = (self.get(i, j) - hermitian.get(i, j)).norm();
366 if diff > tolerance {
367 return false;
368 }
369 }
370 }
371 true
372 }
373
374 pub fn is_unitary(&self, tolerance: f64) -> bool {
376 if self.rows != self.cols {
377 return false;
378 }
379 let product = self
380 .mul(&self.hermitian())
381 .expect("unitary check on square matrix");
382 let identity = ComplexMatrix::identity(self.rows);
383 for i in 0..self.rows {
384 for j in 0..self.cols {
385 let diff = (product.get(i, j) - identity.get(i, j)).norm();
386 if diff > tolerance {
387 return false;
388 }
389 }
390 }
391 true
392 }
393
394 pub fn frobenius_norm(&self) -> f64 {
396 self.data.iter().map(|c| c.norm_sq()).sum::<f64>().sqrt()
397 }
398
399 pub fn power(&self, n: usize) -> ComplexMatrix {
404 assert_eq!(self.rows, self.cols, "power requires a square matrix");
405 if n == 0 {
406 return ComplexMatrix::identity(self.rows);
407 }
408 let mut result = ComplexMatrix::identity(self.rows);
409 let mut base = self.clone();
410 let mut exp = n;
411 while exp > 0 {
412 if exp % 2 == 1 {
413 result = result
414 .mul(&base)
415 .expect("internal: square matrix dimensions");
416 }
417 base = base.mul(&base).expect("internal: square matrix dimensions");
418 exp /= 2;
419 }
420 result
421 }
422
423 pub fn exp(&self, iterations: usize) -> ComplexMatrix {
431 assert_eq!(self.rows, self.cols, "exp requires a square matrix");
432 let norm = self.frobenius_norm();
433 let mut scale_pow = 0;
434 if norm > 1.0 {
435 scale_pow = norm.log2().ceil() as usize;
436 }
437 let scaled = self.scale(Complex::real(1.0 / 2.0_f64.powi(scale_pow as i32)));
438
439 let mut result = ComplexMatrix::identity(self.rows);
440 let mut term = ComplexMatrix::identity(self.rows);
441 let mut factorial: f64 = 1.0;
442
443 for n in 1..=iterations {
444 factorial *= n as f64;
445 term = term
446 .mul(&scaled)
447 .expect("internal: square matrix dimensions");
448 let factor = 1.0 / factorial;
449 if term.frobenius_norm() * factor < 1e-20 {
453 break;
454 }
455 for i in 0..term.data.len() {
456 result.data[i] = result.data[i] + term.data[i] * Complex::real(factor);
457 }
458 }
459
460 for _ in 0..scale_pow {
461 result = result
462 .mul(&result)
463 .expect("internal: square matrix dimensions");
464 }
465 result
466 }
467
468 pub fn ln(&self, iterations: usize) -> Option<ComplexMatrix> {
476 assert_eq!(self.rows, self.cols, "ln requires a square matrix");
477 let identity = ComplexMatrix::identity(self.rows);
478 let a_minus_i = self
479 .sub(&identity)
480 .expect("internal: square matrix dimensions");
481
482 if a_minus_i.frobenius_norm() >= 1.0 {
484 return None;
485 }
486
487 let mut result = ComplexMatrix::zeros(self.rows, self.cols);
488 let mut term = a_minus_i.clone();
489 for n in 1..=iterations {
490 let sign = if n % 2 == 0 {
491 -Complex::one()
492 } else {
493 Complex::one()
494 };
495 let scalar = sign / Complex::real(n as f64);
496 for i in 0..result.data.len() {
497 result.data[i] = result.data[i] + term.data[i] * scalar;
498 }
499 term = term
500 .mul(&a_minus_i)
501 .expect("internal: square matrix dimensions");
502 }
503 Some(result)
504 }
505
506 pub fn qr_decomposition(&self) -> MathResult<(ComplexMatrix, ComplexMatrix)> {
514 if self.rows != self.cols {
515 return Err(MathError::DimensionMismatch);
516 }
517 let n = self.rows;
518 if n == 0 {
519 return Ok((ComplexMatrix::new(0, 0), ComplexMatrix::new(0, 0)));
520 }
521 let mut q = ComplexMatrix::new(n, n);
522 let mut r = ComplexMatrix::new(n, n);
523 for j in 0..n {
524 let mut v: Vec<Complex> = (0..n).map(|i| self.get(i, j)).collect();
525 for k in 0..j {
526 let mut dot = Complex::zero();
527 for i in 0..n {
528 dot = dot + q.get(i, k).conjugate() * v[i];
529 }
530 r.set(k, j, dot);
531 for i in 0..n {
532 v[i] = v[i] - dot * q.get(i, k);
533 }
534 }
535 let mut norm_sq = 0.0;
536 for i in 0..n {
537 norm_sq += v[i].norm_sq();
538 }
539 let norm = norm_sq.sqrt();
540 if norm <= 1e-300 {
541 let mut completed = false;
546 for k in 0..n {
547 let mut cand = vec![Complex::zero(); n];
548 cand[k] = Complex::one();
549 for m in 0..j {
550 let mut dot = Complex::zero();
551 for i in 0..n {
552 dot = dot + q.get(i, m).conjugate() * cand[i];
553 }
554 for i in 0..n {
555 cand[i] = cand[i] - dot * q.get(i, m);
556 }
557 }
558 let mut cnorm_sq = 0.0;
559 for i in 0..n {
560 cnorm_sq += cand[i].norm_sq();
561 }
562 if cnorm_sq > 1e-300 {
563 let cnorm = cnorm_sq.sqrt();
564 for i in 0..n {
565 q.set(i, j, cand[i] / Complex::real(cnorm));
566 }
567 completed = true;
568 break;
569 }
570 }
571 if !completed {
572 return Err(MathError::Singular);
573 }
574 r.set(j, j, Complex::zero());
575 continue;
576 }
577 r.set(j, j, Complex::real(norm));
578 for i in 0..n {
579 q.set(i, j, v[i] / Complex::real(norm));
580 }
581 }
582 Ok((q, r))
583 }
584
585 pub fn eigenvalues(&self, max_iterations: usize, tolerance: f64) -> MathResult<Vec<Complex>> {
603 if self.rows != self.cols {
604 return Err(MathError::DimensionMismatch);
605 }
606 let n = self.rows;
607 if n == 0 {
608 return Ok(Vec::new());
609 }
610 let mut a = self.clone();
611 for _ in 0..max_iterations {
612 let mut converged = true;
613 for i in 0..n.saturating_sub(1) {
614 if a.get(i + 1, i).norm() > tolerance {
615 converged = false;
616 break;
617 }
618 }
619 if converged {
620 return Ok((0..n).map(|i| a.get(i, i)).collect());
621 }
622 let shift = if n >= 2 {
626 Self::wilkinson_shift(
627 a.get(n - 2, n - 2),
628 a.get(n - 2, n - 1),
629 a.get(n - 1, n - 2),
630 a.get(n - 1, n - 1),
631 )
632 } else {
633 a.get(0, 0)
634 };
635 let shifted = a.sub(&ComplexMatrix::identity(n).scale(shift))?;
636 let (q, r) = shifted.qr_decomposition()?;
637 a = r.mul(&q)?.add(&ComplexMatrix::identity(n).scale(shift))?;
638 }
639 Err(MathError::NotConverged("eigenvalues: QR iteration"))
640 }
641
642 fn wilkinson_shift(a: Complex, b: Complex, c: Complex, d: Complex) -> Complex {
645 let m = (a + d) / Complex::real(2.0);
646 let disc = ((a - d) / Complex::real(2.0)).powf(2.0) + b * c;
647 let s = disc.sqrt();
648 let l1 = m + s;
649 let l2 = m - s;
650 if (l1 - d).norm() < (l2 - d).norm() {
651 l1
652 } else {
653 l2
654 }
655 }
656}
657
658impl Index<(usize, usize)> for ComplexMatrix {
659 type Output = Complex;
660 fn index(&self, (row, col): (usize, usize)) -> &Complex {
661 assert!(
662 row < self.rows && col < self.cols,
663 "index out of bounds: ({row}, {col}) for {}×{} matrix",
664 self.rows,
665 self.cols
666 );
667 &self.data[row * self.cols + col]
668 }
669}
670
671impl IndexMut<(usize, usize)> for ComplexMatrix {
672 fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut Complex {
673 assert!(
674 row < self.rows && col < self.cols,
675 "index out of bounds: ({row}, {col}) for {}×{} matrix",
676 self.rows,
677 self.cols
678 );
679 &mut self.data[row * self.cols + col]
680 }
681}
682
683pub mod linalg {
685 use super::*;
686
687 pub fn expm(a: &ComplexMatrix) -> ComplexMatrix {
689 a.exp(50)
690 }
691
692 pub fn logm(a: &ComplexMatrix) -> MathResult<ComplexMatrix> {
698 a.ln(50).ok_or(MathError::NotConverged("logm"))
699 }
700
701 pub fn eig(a: &ComplexMatrix) -> MathResult<Vec<Complex>> {
706 a.eigenvalues(1000, 1e-12)
707 }
708}
709
710#[cfg(test)]
711mod tests {
712 use super::*;
713
714 #[test]
715 fn test_matrix_creation() {
716 let m = ComplexMatrix::new(2, 3);
717 assert_eq!(m.rows, 2);
718 assert_eq!(m.cols, 3);
719 assert_eq!(m.data.len(), 6);
720 }
721
722 #[test]
723 fn test_identity() {
724 let i = ComplexMatrix::identity(3);
725 assert_eq!(i.get(0, 0), Complex::one());
726 assert_eq!(i.get(1, 1), Complex::one());
727 assert_eq!(i.get(2, 2), Complex::one());
728 assert_eq!(i.get(0, 1), Complex::zero());
729 }
730
731 #[test]
732 fn test_matrix_addition() {
733 let mut m1 = ComplexMatrix::new(2, 2);
734 m1.set(0, 0, Complex::real(1.0));
735 m1.set(0, 1, Complex::real(2.0));
736
737 let mut m2 = ComplexMatrix::new(2, 2);
738 m2.set(0, 0, Complex::real(3.0));
739 m2.set(0, 1, Complex::real(4.0));
740
741 let result = m1.add(&m2).unwrap();
742 assert_eq!(result.get(0, 0), Complex::real(4.0));
743 assert_eq!(result.get(0, 1), Complex::real(6.0));
744
745 let bad = ComplexMatrix::new(2, 3);
747 assert!(matches!(m1.add(&bad), Err(MathError::DimensionMismatch)));
748 }
749
750 #[test]
751 fn test_matrix_multiplication() {
752 let mut m1 = ComplexMatrix::new(2, 2);
753 m1.set(0, 0, Complex::real(1.0));
754 m1.set(0, 1, Complex::real(2.0));
755 m1.set(1, 0, Complex::real(3.0));
756 m1.set(1, 1, Complex::real(4.0));
757
758 let mut m2 = ComplexMatrix::new(2, 2);
759 m2.set(0, 0, Complex::real(5.0));
760 m2.set(0, 1, Complex::real(6.0));
761 m2.set(1, 0, Complex::real(7.0));
762 m2.set(1, 1, Complex::real(8.0));
763
764 let result = m1.mul(&m2).unwrap();
765 assert_eq!(result.get(0, 0), Complex::real(19.0)); assert_eq!(result.get(0, 1), Complex::real(22.0)); assert_eq!(result.get(1, 0), Complex::real(43.0)); assert_eq!(result.get(1, 1), Complex::real(50.0)); let bad = ComplexMatrix::new(3, 2);
771 assert!(matches!(m1.mul(&bad), Err(MathError::DimensionMismatch)));
772 }
773
774 #[test]
775 fn test_determinant_2x2() {
776 let mut m = ComplexMatrix::new(2, 2);
777 m.set(0, 0, Complex::real(1.0));
778 m.set(0, 1, Complex::real(2.0));
779 m.set(1, 0, Complex::real(3.0));
780 m.set(1, 1, Complex::real(4.0));
781
782 let det = m.determinant();
783 assert_eq!(det, Complex::real(-2.0)); }
785
786 #[test]
787 fn test_transpose() {
788 let mut m = ComplexMatrix::new(2, 3);
789 m.set(0, 0, Complex::real(1.0));
790 m.set(0, 1, Complex::real(2.0));
791 m.set(0, 2, Complex::real(3.0));
792 m.set(1, 0, Complex::real(4.0));
793 m.set(1, 1, Complex::real(5.0));
794 m.set(1, 2, Complex::real(6.0));
795
796 let t = m.transpose();
797 assert_eq!(t.rows, 3);
798 assert_eq!(t.cols, 2);
799 assert_eq!(t.get(0, 0), Complex::real(1.0));
800 assert_eq!(t.get(1, 0), Complex::real(2.0));
801 assert_eq!(t.get(0, 1), Complex::real(4.0));
802 }
803
804 #[test]
805 fn test_hermitian() {
806 let mut m = ComplexMatrix::new(2, 2);
807 m.set(0, 0, Complex::real(1.0));
808 m.set(0, 1, Complex::new(1.0, 2.0));
809 m.set(1, 0, Complex::new(1.0, -2.0));
810 m.set(1, 1, Complex::real(3.0));
811
812 assert!(m.is_hermitian(1e-10));
813 }
814
815 #[test]
816 fn test_solve() {
817 let mut m = ComplexMatrix::new(2, 2);
818 m.set(0, 0, Complex::real(2.0));
819 m.set(0, 1, Complex::real(1.0));
820 m.set(1, 0, Complex::real(1.0));
821 m.set(1, 1, Complex::real(1.0));
822
823 let b = vec![Complex::real(3.0), Complex::real(2.0)];
824 let x = m.solve(&b).unwrap();
825 assert!((x[0].re - 1.0).abs() < 1e-10);
826 assert!((x[1].re - 1.0).abs() < 1e-10);
827 }
828
829 #[test]
830 fn test_inverse() {
831 let mut m = ComplexMatrix::new(2, 2);
832 m.set(0, 0, Complex::real(2.0));
833 m.set(0, 1, Complex::real(1.0));
834 m.set(1, 0, Complex::real(1.0));
835 m.set(1, 1, Complex::real(1.0));
836
837 let inv = m.inverse().unwrap();
838 let product = m.mul(&inv).unwrap();
839 assert!((product.get(0, 0) - Complex::one()).norm() < 1e-10);
840 assert!((product.get(1, 1) - Complex::one()).norm() < 1e-10);
841 }
842
843 #[test]
844 fn test_power() {
845 let mut m = ComplexMatrix::new(2, 2);
846 m.set(0, 0, Complex::real(1.0));
847 m.set(0, 1, Complex::real(1.0));
848 m.set(1, 0, Complex::real(0.0));
849 m.set(1, 1, Complex::real(1.0));
850
851 let m2 = m.power(2);
852 assert_eq!(m2.get(0, 0), Complex::real(1.0));
853 assert_eq!(m2.get(0, 1), Complex::real(2.0));
854 assert_eq!(m2.get(1, 0), Complex::zero());
855 assert_eq!(m2.get(1, 1), Complex::real(1.0));
856 }
857
858 #[test]
859 fn test_determinant_permutation_sign() {
860 let mut m = ComplexMatrix::identity(4);
861 for j in 0..4 {
862 let t = m.get(0, j);
863 m.set(0, j, m.get(1, j));
864 m.set(1, j, t);
865 }
866 let det = m.determinant();
867 assert!((det.re + 1.0).abs() < 1e-12);
868 assert!(det.im.abs() < 1e-12);
869
870 let mut m2 = ComplexMatrix::new(4, 4);
871 m2.set(0, 0, Complex::real(1.0));
872 m2.set(1, 1, Complex::real(2.0));
873 m2.set(2, 2, Complex::real(3.0));
874 m2.set(3, 3, Complex::real(4.0));
875 for j in 0..4 {
876 let t = m2.get(0, j);
877 m2.set(0, j, m2.get(1, j));
878 m2.set(1, j, t);
879 }
880 let det2 = m2.determinant();
881 assert!((det2.re + 24.0).abs() < 1e-10);
882 }
883
884 #[test]
885 fn test_matrix_exp() {
886 let zero = ComplexMatrix::new(2, 2);
888 let e0 = zero.exp(20);
889 assert!((e0.get(0, 0) - Complex::one()).norm() < 1e-10);
890 assert!((e0.get(1, 1) - Complex::one()).norm() < 1e-10);
891
892 let mut m = ComplexMatrix::new(2, 2);
894 m.set(0, 1, Complex::one());
895 let em = m.exp(20);
896 assert!((em.get(0, 0) - Complex::one()).norm() < 1e-10);
897 assert!((em.get(0, 1) - Complex::one()).norm() < 1e-10);
898 assert!((em.get(1, 0) - Complex::zero()).norm() < 1e-10);
899 assert!((em.get(1, 1) - Complex::one()).norm() < 1e-10);
900
901 let mut big = ComplexMatrix::new(2, 2);
903 big.set(0, 0, Complex::real(10.0));
904 big.set(1, 1, Complex::real(10.0));
905 let ebig = big.exp(30);
906 let e10 = 10.0_f64.exp();
907 assert!((ebig.get(0, 0).re - e10).abs() < 1e-6 * e10);
908 assert!((ebig.get(1, 1).re - e10).abs() < 1e-6 * e10);
909 assert!((ebig.get(0, 1) - Complex::zero()).norm() < 1e-6 * e10);
910 }
911
912 #[test]
913 fn test_matrix_exp_large_norm_does_not_overflow() {
914 let mut big = ComplexMatrix::new(2, 2);
916 big.set(0, 0, Complex::real(600.0));
917 big.set(1, 1, Complex::real(600.0));
918 let ebig = big.exp(30);
919 let e600 = 600.0_f64.exp();
920 assert!(ebig.get(0, 0).re.is_finite());
921 assert!((ebig.get(0, 0).re - e600).abs() < 1e-6 * e600);
922 }
923
924 #[test]
925 fn test_matrix_ln() {
926 let i = ComplexMatrix::identity(2);
928 let ln_i = i.ln(20).unwrap();
929 assert!((ln_i.get(0, 0) - Complex::zero()).norm() < 1e-10);
930
931 let mut a = ComplexMatrix::new(2, 2);
933 a.set(0, 0, Complex::real(1.2));
934 a.set(0, 1, Complex::real(0.1));
935 a.set(1, 0, Complex::real(-0.2));
936 a.set(1, 1, Complex::real(0.8));
937 let ln_a = a.ln(40).unwrap();
938 let round = ln_a.exp(40);
939 for i in 0..2 {
940 for j in 0..2 {
941 assert!((round.get(i, j) - a.get(i, j)).norm() < 1e-8);
942 }
943 }
944
945 let mut big = ComplexMatrix::new(2, 2);
947 big.set(0, 0, Complex::real(10.0));
948 big.set(1, 1, Complex::real(10.0));
949 assert!(big.ln(20).is_none());
950 }
951
952 #[test]
953 fn test_lu_ill_conditioned_scale_invariance() {
954 let mut m = ComplexMatrix::new(2, 2);
957 m.set(0, 0, Complex::real(1e-20));
958 m.set(0, 1, Complex::real(2e-20));
959 m.set(1, 0, Complex::real(3e-20));
960 m.set(1, 1, Complex::real(4e-20));
961 let (l, u, pivot) = m
962 .lu_decomposition()
963 .expect("scaled matrix must not be singular");
964 assert_eq!(pivot.len(), 2);
965 let lu = l.mul(&u).unwrap();
967 for k in 0..2 {
968 for j in 0..2 {
969 assert!(
970 (lu.get(k, j) - m.get(pivot[k], j)).norm() < 1e-30,
971 "L·U row {k} col {j} mismatch"
972 );
973 }
974 }
975
976 let mut s = ComplexMatrix::new(2, 2);
978 s.set(0, 0, Complex::real(1.0));
979 s.set(1, 0, Complex::real(2.0));
980 assert!(s.lu_decomposition().is_none());
981 }
982
983 #[test]
984 fn test_indexing_and_checked_access() {
985 let mut m = ComplexMatrix::new(2, 2);
986 m[(0, 1)] = Complex::real(7.0);
987 assert_eq!(m[(0, 1)], Complex::real(7.0));
988 assert_eq!(m.try_get(0, 1), Some(Complex::real(7.0)));
989 assert_eq!(m.try_get(5, 5), None);
990 assert!(m.try_set(5, 5, Complex::one()).is_err());
991 assert!(m.try_set(1, 1, Complex::real(3.0)).is_ok());
992 assert_eq!(m.get(1, 1), Complex::real(3.0));
993 }
994
995 #[test]
996 fn test_qr_decomposition() {
997 let mut m = ComplexMatrix::new(2, 2);
998 m.set(0, 0, Complex::real(1.0));
999 m.set(0, 1, Complex::real(2.0));
1000 m.set(1, 0, Complex::real(3.0));
1001 m.set(1, 1, Complex::real(4.0));
1002 let (q, r) = m.qr_decomposition().unwrap();
1003 assert!(q.is_unitary(1e-12));
1005 let qr = q.mul(&r).unwrap();
1007 for i in 0..2 {
1008 for j in 0..2 {
1009 assert!((qr.get(i, j) - m.get(i, j)).norm() < 1e-12);
1010 }
1011 }
1012 assert!((r.get(1, 0) - Complex::zero()).norm() < 1e-12);
1014 }
1015
1016 #[test]
1017 fn test_eigenvalues_diagonal() {
1018 let mut m = ComplexMatrix::new(3, 3);
1019 m.set(0, 0, Complex::real(1.0));
1020 m.set(1, 1, Complex::real(2.0));
1021 m.set(2, 2, Complex::real(3.0));
1022 let e = m.eigenvalues(100, 1e-12).unwrap();
1023 let mut vals: Vec<f64> = e.iter().map(|c| c.re).collect();
1024 vals.sort_by(|a, b| a.partial_cmp(b).unwrap());
1025 assert!((vals[0] - 1.0).abs() < 1e-10);
1026 assert!((vals[1] - 2.0).abs() < 1e-10);
1027 assert!((vals[2] - 3.0).abs() < 1e-10);
1028 }
1029
1030 #[test]
1031 fn test_eigenvalues_complex_pair() {
1032 let mut m = ComplexMatrix::new(2, 2);
1034 m.set(0, 1, Complex::real(-1.0));
1035 m.set(1, 0, Complex::real(1.0));
1036 let e = m.eigenvalues(2000, 1e-10).unwrap();
1037 let d_i = |c: &Complex| (*c - Complex::i()).norm();
1038 let d_ni = |c: &Complex| (*c + Complex::i()).norm();
1039 assert!(e.iter().map(d_i).fold(f64::MAX, f64::min) < 1e-6);
1040 assert!(e.iter().map(d_ni).fold(f64::MAX, f64::min) < 1e-6);
1041 }
1042
1043 #[test]
1044 fn test_eigenvalues_2x2_real() {
1045 let mut m = ComplexMatrix::new(2, 2);
1047 m.set(0, 0, Complex::real(2.0));
1048 m.set(0, 1, Complex::real(1.0));
1049 m.set(1, 0, Complex::real(1.0));
1050 m.set(1, 1, Complex::real(2.0));
1051 let e = m.eigenvalues(2000, 1e-10).unwrap();
1052 let mut vals: Vec<f64> = e.iter().map(|c| c.re).collect();
1053 vals.sort_by(|a, b| a.partial_cmp(b).unwrap());
1054 assert!((vals[0] - 1.0).abs() < 1e-6);
1055 assert!((vals[1] - 3.0).abs() < 1e-6);
1056 }
1057
1058 #[test]
1059 fn test_linalg_wrappers() {
1060 use crate::matrix::linalg;
1061 let mut m = ComplexMatrix::new(2, 2);
1063 m.set(0, 1, Complex::one());
1064 let em = linalg::expm(&m);
1065 assert!((em.get(0, 1) - Complex::one()).norm() < 1e-10);
1066 let e = linalg::eig(&m).unwrap();
1067 assert_eq!(e.len(), 2);
1068 let mut a = ComplexMatrix::new(2, 2);
1070 a.set(0, 0, Complex::real(1.1));
1071 a.set(0, 1, Complex::real(0.05));
1072 a.set(1, 0, Complex::real(-0.05));
1073 a.set(1, 1, Complex::real(0.9));
1074 let ln = linalg::logm(&a).unwrap();
1075 let round = ln.exp(40);
1076 for i in 0..2 {
1077 for j in 0..2 {
1078 assert!((round.get(i, j) - a.get(i, j)).norm() < 1e-8);
1079 }
1080 }
1081 assert!(linalg::logm(&m).is_err());
1083 }
1084}