-
Notifications
You must be signed in to change notification settings - Fork 32
/
matrix.rs
2711 lines (2483 loc) · 75.8 KB
/
matrix.rs
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
cmp::{max, min},
fmt,
ops::{Add, Div, Index, IndexMut, Mul, Neg, Sub},
};
use anyhow::{bail, Result};
use matrixmultiply::CGemmOption;
use num_complex::Complex;
use peroxide_num::{ExpLogOps, PowOps, TrigOps};
use rand_distr::num_traits::{One, Zero};
use crate::{
complex::C64,
structure::matrix::Shape,
traits::fp::{FPMatrix, FPVector},
traits::general::Algorithm,
traits::math::{InnerProduct, LinearOp, MatrixProduct, Norm, Normed, Vector},
traits::matrix::{Form, LinearAlgebra, MatrixTrait, SolveKind, PQLU, QR, SVD, WAZD},
traits::mutable::MutMatrix,
util::low_level::{copy_vec_ptr, swap_vec_ptr},
util::non_macro::ConcatenateError,
util::useful::{nearly_eq, tab},
};
/// R-like complex matrix structure
///
/// # Examples
///
/// ```rust
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::ComplexMatrix;
///
/// let v1 = ComplexMatrix {
/// data: vec![
/// C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64),
/// ],
/// row: 2,
/// col: 2,
/// shape: Row,
/// }; // [[1+1i,2+2i],[3+3i,4+4i]]
/// ```
#[derive(Debug, Clone, Default)]
pub struct ComplexMatrix {
pub data: Vec<C64>,
pub row: usize,
pub col: usize,
pub shape: Shape,
}
// =============================================================================
// Various complex matrix constructor
// =============================================================================
/// R-like complex matrix constructor
///
/// # Examples
/// ```rust
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::cmatrix;
///
/// fn main() {
/// let a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// a.col.print(); // Print matrix column
/// }
/// ```
pub fn cmatrix<T>(v: Vec<T>, r: usize, c: usize, shape: Shape) -> ComplexMatrix
where
T: Into<C64>,
{
ComplexMatrix {
data: v.into_iter().map(|t| t.into()).collect::<Vec<C64>>(),
row: r,
col: c,
shape,
}
}
/// R-like complex matrix constructor (Explicit ver.)
pub fn r_cmatrix<T>(v: Vec<T>, r: usize, c: usize, shape: Shape) -> ComplexMatrix
where
T: Into<C64>,
{
cmatrix(v, r, c, shape)
}
/// Python-like complex matrix constructor
///
/// # Examples
/// ```rust
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// fn main() {
/// let a = py_cmatrix(vec![vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64)],
/// vec![C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)]
/// ]);
/// let b = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// assert_eq!(a, b);
/// }
/// ```
pub fn py_cmatrix<T>(v: Vec<Vec<T>>) -> ComplexMatrix
where
T: Into<C64> + Copy,
{
let r = v.len();
let c = v[0].len();
let data: Vec<T> = v.into_iter().flatten().collect();
cmatrix(data, r, c, Shape::Row)
}
/// Matlab-like matrix constructor
///
/// Note that the entries to the `ml_cmatrix`
/// needs to be in the `a+bi` format
/// without any spaces between the real and imaginary
/// parts of the Complex number.
///
/// # Examples
/// ```rust
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// fn main() {
/// let a = ml_cmatrix("1.0+1.0i 2.0+2.0i;
/// 3.0+3.0i 4.0+4.0i");
/// let b = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// assert_eq!(a, b);
/// }
/// ```
pub fn ml_cmatrix(s: &str) -> ComplexMatrix {
let str_row = s.split(";").collect::<Vec<&str>>();
let r = str_row.len();
let str_data = str_row
.iter()
.map(|x| x.trim().split(" ").collect::<Vec<&str>>())
.collect::<Vec<Vec<&str>>>();
let c = str_data[0].len();
let data = str_data
.iter()
.flat_map(|t| {
t.iter()
.map(|x| x.parse::<C64>().unwrap())
.collect::<Vec<C64>>()
})
.collect::<Vec<C64>>();
cmatrix(data, r, c, Shape::Row)
}
/// Pretty Print
impl fmt::Display for ComplexMatrix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.spread())
}
}
/// PartialEq implements
impl PartialEq for ComplexMatrix {
fn eq(&self, other: &ComplexMatrix) -> bool {
if self.shape == other.shape {
self.data
.clone()
.into_iter()
.zip(other.data.clone())
.all(|(x, y)| nearly_eq(x.re, y.re) && nearly_eq(x.im, y.im))
&& self.row == other.row
} else {
self.eq(&other.change_shape())
}
}
}
impl MatrixTrait for ComplexMatrix {
type Scalar = C64;
/// Raw pointer for `self.data`
fn ptr(&self) -> *const C64 {
&self.data[0] as *const C64
}
/// Raw mutable pointer for `self.data`
fn mut_ptr(&mut self) -> *mut C64 {
&mut self.data[0] as *mut C64
}
/// Slice of `self.data`
///
/// # Examples
/// ```rust
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// let a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// let b = a.as_slice();
/// assert_eq!(b, &[C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)]);
/// ```
fn as_slice(&self) -> &[C64] {
&self.data[..]
}
/// Mutable slice of `self.data`
///
/// # Examples
/// ```rust
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// let mut a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// let mut b = a.as_mut_slice();
/// b[1] = C64::new(5f64, 5f64);
/// assert_eq!(b, &[C64::new(1f64, 1f64),
/// C64::new(5f64, 5f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)]);
/// assert_eq!(a, cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(5f64, 5f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row));
/// ```
fn as_mut_slice(&mut self) -> &mut [C64] {
&mut self.data[..]
}
/// Change Bindings
///
/// `Row` -> `Col` or `Col` -> `Row`
///
/// # Examples
/// ```rust
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// let mut a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// assert_eq!(a.shape, Row);
/// let b = a.change_shape();
/// assert_eq!(b.shape, Col);
/// ```
fn change_shape(&self) -> Self {
let r = self.row;
let c = self.col;
assert_eq!(r * c, self.data.len());
let l = r * c - 1;
let mut data: Vec<C64> = self.data.clone();
let ref_data = &self.data;
match self.shape {
Shape::Row => {
for i in 0..l {
let s = (i * c) % l;
data[i] = ref_data[s];
}
data[l] = ref_data[l];
cmatrix(data, r, c, Shape::Col)
}
Shape::Col => {
for i in 0..l {
let s = (i * r) % l;
data[i] = ref_data[s];
}
data[l] = ref_data[l];
cmatrix(data, r, c, Shape::Row)
}
}
}
/// Change Bindings Mutably
///
/// `Row` -> `Col` or `Col` -> `Row`
///
/// # Examples
/// ```rust
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// let mut a = cmatrix(vec![
/// C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)
/// ],
/// 2, 2, Row
/// );
/// assert_eq!(a.shape, Row);
/// a.change_shape_mut();
/// assert_eq!(a.shape, Col);
/// ```
fn change_shape_mut(&mut self) {
let r = self.row;
let c = self.col;
assert_eq!(r * c, self.data.len());
let l = r * c - 1;
let ref_data = self.data.clone();
match self.shape {
Shape::Row => {
for i in 0..l {
let s = (i * c) % l;
self.data[i] = ref_data[s];
}
self.data[l] = ref_data[l];
self.shape = Shape::Col;
}
Shape::Col => {
for i in 0..l {
let s = (i * r) % l;
self.data[i] = ref_data[s];
}
self.data[l] = ref_data[l];
self.shape = Shape::Row;
}
}
}
/// Spread data(1D vector) to 2D formatted String
///
/// # Examples
/// ```rust
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// let a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// println!("{}", a.spread()); // same as println!("{}", a);
/// // Result:
/// // c[0] c[1]
/// // r[0] 1+1i 3+3i
/// // r[1] 2+2i 4+4i
/// ```
fn spread(&self) -> String {
assert_eq!(self.row * self.col, self.data.len());
let r = self.row;
let c = self.col;
let mut key_row = 20usize;
let mut key_col = 20usize;
if r > 100 || c > 100 || (r > 20 && c > 20) {
let part = if r <= 10 {
key_row = r;
key_col = 100;
self.take_col(100)
} else if c <= 10 {
key_row = 100;
key_col = c;
self.take_row(100)
} else {
self.take_row(20).take_col(20)
};
return format!(
"Result is too large to print - {}x{}\n only print {}x{} parts:\n{}",
self.row.to_string(),
self.col.to_string(),
key_row.to_string(),
key_col.to_string(),
part.spread()
);
}
// Find maximum length of data
let sample = self.data.clone();
let mut space: usize = sample
.into_iter()
.map(
|x| min(format!("{:.4}", x).len(), x.to_string().len()), // Choose minimum of approx vs normal
)
.fold(0, |x, y| max(x, y))
+ 1;
if space < 5 {
space = 5;
}
let mut result = String::new();
result.push_str(&tab("", 5));
for i in 0..c {
result.push_str(&tab(&format!("c[{}]", i), space)); // Header
}
result.push('\n');
for i in 0..r {
result.push_str(&tab(&format!("r[{}]", i), 5));
for j in 0..c {
let st1 = format!("{:.4}", self[(i, j)]); // Round at fourth position
let st2 = self[(i, j)].to_string(); // Normal string
let mut st = st2.clone();
// Select more small thing
if st1.len() < st2.len() {
st = st1;
}
result.push_str(&tab(&st, space));
}
if i == (r - 1) {
break;
}
result.push('\n');
}
return result;
}
/// Extract Column
///
/// # Examples
/// ```rust
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// fn main() {
/// let a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// assert_eq!(a.col(0), vec![C64::new(1f64, 1f64), C64::new(3f64, 3f64)]);
/// }
/// ```
fn col(&self, index: usize) -> Vec<C64> {
assert!(index < self.col);
let mut container: Vec<C64> = vec![Complex::zero(); self.row];
for i in 0..self.row {
container[i] = self[(i, index)];
}
container
}
/// Extract Row
///
/// # Examples
/// ```rust
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// fn main() {
/// let a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// assert_eq!(a.row(0), vec![C64::new(1f64, 1f64), C64::new(2f64, 2f64)]);
/// }
/// ```
fn row(&self, index: usize) -> Vec<C64> {
assert!(index < self.row);
let mut container: Vec<C64> = vec![Complex::zero(); self.col];
for i in 0..self.col {
container[i] = self[(index, i)];
}
container
}
/// Extract diagonal components
///
/// # Examples
/// ```rust
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// fn main() {
/// let a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// assert_eq!(a.diag(), vec![C64::new(1f64, 1f64) ,C64::new(4f64, 4f64)]);
/// }
/// ```
fn diag(&self) -> Vec<C64> {
let mut container = vec![Complex::zero(); self.row];
let r = self.row;
let c = self.col;
assert_eq!(r, c);
let c2 = c + 1;
for i in 0..r {
container[i] = self.data[i * c2];
}
container
}
/// Transpose
///
/// # Examples
/// ```rust
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// let a = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row
/// );
/// let a_t = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Col
/// );
///
/// assert_eq!(a.transpose(), a_t);
/// ```
fn transpose(&self) -> Self {
match self.shape {
Shape::Row => cmatrix(self.data.clone(), self.col, self.row, Shape::Col),
Shape::Col => cmatrix(self.data.clone(), self.col, self.row, Shape::Row),
}
}
/// Substitute Col
#[inline]
fn subs_col(&mut self, idx: usize, v: &[C64]) {
for i in 0..self.row {
self[(i, idx)] = v[i];
}
}
/// Substitute Row
#[inline]
fn subs_row(&mut self, idx: usize, v: &[C64]) {
for j in 0..self.col {
self[(idx, j)] = v[j];
}
}
/// From index operations
fn from_index<F, G>(f: F, size: (usize, usize)) -> ComplexMatrix
where
F: Fn(usize, usize) -> G + Copy,
G: Into<C64>,
{
let row = size.0;
let col = size.1;
let mut mat = cmatrix(vec![Complex::zero(); row * col], row, col, Shape::Row);
for i in 0..row {
for j in 0..col {
mat[(i, j)] = f(i, j).into();
}
}
mat
}
/// Matrix to `Vec<Vec<C64>>`
///
/// To send `Matrix` to `inline-python`
fn to_vec(&self) -> Vec<Vec<C64>> {
let mut result = vec![vec![Complex::zero(); self.col]; self.row];
for i in 0..self.row {
result[i] = self.row(i);
}
result
}
fn to_diag(&self) -> ComplexMatrix {
assert_eq!(self.row, self.col, "Should be square matrix");
let mut result = cmatrix(
vec![Complex::zero(); self.row * self.col],
self.row,
self.col,
Shape::Row,
);
let diag = self.diag();
for i in 0..self.row {
result[(i, i)] = diag[i];
}
result
}
/// Submatrix
///
/// # Description
/// Return below elements of complex matrix to a new complex matrix
///
/// $$
/// \begin{pmatrix}
/// \\ddots & & & & \\\\
/// & start & \\cdots & end.1 & \\\\
/// & \\vdots & \\ddots & \\vdots & \\\\
/// & end.0 & \\cdots & end & \\\\
/// & & & & \\ddots
/// \end{pmatrix}
/// $$
///
/// # Examples
/// ```rust
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// fn main() {
/// let a = ml_cmatrix("1.0+1.0i 2.0+2.0i 3.0+3.0i;
/// 4.0+4.0i 5.0+5.0i 6.0+6.0i;
/// 7.0+7.0i 8.0+8.0i 9.0+9.0i");
/// let b = cmatrix(vec![C64::new(5f64, 5f64),
/// C64::new(6f64, 6f64),
/// C64::new(8f64, 8f64),
/// C64::new(9f64, 9f64)],
/// 2, 2, Row
/// );
/// let c = a.submat((1, 1), (2, 2));
/// assert_eq!(b, c);
/// }
/// ```
fn submat(&self, start: (usize, usize), end: (usize, usize)) -> ComplexMatrix {
let row = end.0 - start.0 + 1;
let col = end.1 - start.1 + 1;
let mut result = cmatrix(vec![Complex::zero(); row * col], row, col, self.shape);
for i in 0..row {
for j in 0..col {
result[(i, j)] = self[(start.0 + i, start.1 + j)];
}
}
result
}
/// Substitute complex matrix to specific position
///
/// # Description
/// Substitute below elements of complex matrix
///
/// $$
/// \begin{pmatrix}
/// \\ddots & & & & \\\\
/// & start & \\cdots & end.1 & \\\\
/// & \\vdots & \\ddots & \\vdots & \\\\
/// & end.0 & \\cdots & end & \\\\
/// & & & & \\ddots
/// \end{pmatrix}
/// $$
///
/// # Examples
/// ```
/// extern crate peroxide;
/// use peroxide::fuga::*;
/// use peroxide::complex::matrix::*;
///
/// fn main() {
/// let mut a = ml_cmatrix("1.0+1.0i 2.0+2.0i 3.0+3.0i;
/// 4.0+4.0i 5.0+5.0i 6.0+6.0i;
/// 7.0+7.0i 8.0+8.0i 9.0+9.0i");
/// let b = cmatrix(vec![C64::new(1f64, 1f64),
/// C64::new(2f64, 2f64),
/// C64::new(3f64, 3f64),
/// C64::new(4f64, 4f64)],
/// 2, 2, Row);
/// let c = ml_cmatrix("1.0+1.0i 2.0+2.0i 3.0+3.0i;
/// 4.0+4.0i 1.0+1.0i 2.0+2.0i;
/// 7.0+7.0i 3.0+3.0i 4.0+4.0i");
/// a.subs_mat((1,1), (2,2), &b);
/// assert_eq!(a, c);
/// }
/// ```
fn subs_mat(&mut self, start: (usize, usize), end: (usize, usize), m: &ComplexMatrix) {
let row = end.0 - start.0 + 1;
let col = end.1 - start.1 + 1;
for i in 0..row {
for j in 0..col {
self[(start.0 + i, start.1 + j)] = m[(i, j)];
}
}
}
}
// =============================================================================
// Mathematics for Matrix
// =============================================================================
impl Vector for ComplexMatrix {
type Scalar = C64;
fn add_vec(&self, other: &Self) -> Self {
assert_eq!(self.row, other.row);
assert_eq!(self.col, other.col);
let mut result = cmatrix(self.data.clone(), self.row, self.col, self.shape);
for i in 0..self.row {
for j in 0..self.col {
result[(i, j)] += other[(i, j)];
}
}
result
}
fn sub_vec(&self, other: &Self) -> Self {
assert_eq!(self.row, other.row);
assert_eq!(self.col, other.col);
let mut result = cmatrix(self.data.clone(), self.row, self.col, self.shape);
for i in 0..self.row {
for j in 0..self.col {
result[(i, j)] -= other[(i, j)];
}
}
result
}
fn mul_scalar(&self, other: Self::Scalar) -> Self {
let scalar = other;
self.fmap(|x| x * scalar)
}
}
impl Normed for ComplexMatrix {
type UnsignedScalar = f64;
fn norm(&self, kind: Norm) -> Self::UnsignedScalar {
match kind {
Norm::F => {
let mut s = Complex::zero();
for i in 0..self.data.len() {
s += self.data[i].powi(2);
}
s.sqrt().re
}
Norm::Lpq(p, q) => {
let mut s = Complex::zero();
for j in 0..self.col {
let mut s_row = Complex::zero();
for i in 0..self.row {
s_row += self[(i, j)].powi(p as i32);
}
s += s_row.powf(q / p);
}
s.powf(1f64 / q).re
}
Norm::L1 => {
let mut m = Complex::zero();
match self.shape {
Shape::Row => self.change_shape().norm(Norm::L1),
Shape::Col => {
for c in 0..self.col {
let s: C64 = self.col(c).iter().sum();
if s.re > m.re {
m = s;
}
}
m.re
}
}
}
Norm::LInf => {
let mut m = Complex::zero();
match self.shape {
Shape::Col => self.change_shape().norm(Norm::LInf),
Shape::Row => {
for r in 0..self.row {
let s: C64 = self.row(r).iter().sum();
if s.re > m.re {
m = s;
}
}
m.re
}
}
}
Norm::L2 => {
unimplemented!()
}
Norm::Lp(_) => unimplemented!(),
}
}
fn normalize(&self, _kind: Norm) -> Self
where
Self: Sized,
{
unimplemented!()
}
}
/// Frobenius inner product
impl InnerProduct for ComplexMatrix {
fn dot(&self, rhs: &Self) -> C64 {
if self.shape == rhs.shape {
self.data.dot(&rhs.data)
} else {
self.data.dot(&rhs.change_shape().data)
}
}
}
/// TODO: Transpose
/// Matrix as Linear operator for Vector
#[allow(non_snake_case)]
impl LinearOp<Vec<C64>, Vec<C64>> for ComplexMatrix {
fn apply(&self, other: &Vec<C64>) -> Vec<C64> {
assert_eq!(self.col, other.len());
let mut c = vec![Complex::zero(); self.row];
cgemv(Complex::one(), self, other, Complex::zero(), &mut c);
c
}
}
/// R like cbind - concatenate two comlex matrix by column direction
pub fn complex_cbind(m1: ComplexMatrix, m2: ComplexMatrix) -> Result<ComplexMatrix> {
let mut temp = m1;
if temp.shape != Shape::Col {
temp = temp.change_shape();
}
let mut temp2 = m2;
if temp2.shape != Shape::Col {
temp2 = temp2.change_shape();
}
let mut v = temp.data;
let mut c = temp.col;
let r = temp.row;
if r != temp2.row {
bail!(ConcatenateError::DifferentLength);
}
v.extend_from_slice(&temp2.data[..]);
c += temp2.col;
Ok(cmatrix(v, r, c, Shape::Col))
}
/// R like rbind - concatenate two complex matrix by row direction
/// ```
pub fn complex_rbind(m1: ComplexMatrix, m2: ComplexMatrix) -> Result<ComplexMatrix> {
let mut temp = m1;
if temp.shape != Shape::Row {
temp = temp.change_shape();
}
let mut temp2 = m2;
if temp2.shape != Shape::Row {
temp2 = temp2.change_shape();
}
let mut v = temp.data;
let c = temp.col;
let mut r = temp.row;
if c != temp2.col {
bail!(ConcatenateError::DifferentLength);
}
v.extend_from_slice(&temp2.data[..]);
r += temp2.row;
Ok(cmatrix(v, r, c, Shape::Row))
}
impl MatrixProduct for ComplexMatrix {
fn kronecker(&self, other: &Self) -> Self {
let r1 = self.row;
let c1 = self.col;
let mut result = self[(0, 0)] * other;
for j in 1..c1 {
let n = self[(0, j)] * other;
result = complex_cbind(result, n).unwrap();
}
for i in 1..r1 {
let mut m = self[(i, 0)] * other;
for j in 1..c1 {
let n = self[(i, j)] * other;
m = complex_cbind(m, n).unwrap();
}
result = complex_rbind(result, m).unwrap();
}
result
}
fn hadamard(&self, other: &Self) -> Self {
assert_eq!(self.row, other.row);
assert_eq!(self.col, other.col);
let r = self.row;
let c = self.col;
let mut m = cmatrix(vec![Complex::zero(); r * c], r, c, self.shape);
for i in 0..r {
for j in 0..c {
m[(i, j)] = self[(i, j)] * other[(i, j)]
}
}
m
}
}
// =============================================================================
// Common Properties of Matrix & Vec<f64>
// =============================================================================
/// `Complex Matrix` to `Vec<C64>`
impl Into<Vec<C64>> for ComplexMatrix {
fn into(self) -> Vec<C64> {
self.data
}
}
/// `&ComplexMatrix` to `&Vec<C64>`
impl<'a> Into<&'a Vec<C64>> for &'a ComplexMatrix {
fn into(self) -> &'a Vec<C64> {
&self.data
}
}
/// `Vec<C64>` to `ComplexMatrix`
impl Into<ComplexMatrix> for Vec<C64> {
fn into(self) -> ComplexMatrix {
let l = self.len();
cmatrix(self, l, 1, Shape::Col)
}
}
/// `&Vec<C64>` to `ComplexMatrix`
impl Into<ComplexMatrix> for &Vec<C64> {
fn into(self) -> ComplexMatrix {
let l = self.len();
cmatrix(self.clone(), l, 1, Shape::Col)
}
}
// =============================================================================
// Standard Operation for Complex Matrix (ADD)
// =============================================================================
/// Element-wise addition of Complex Matrix
///
/// # Caution
/// > You should remember ownership.
/// > If you use ComplexMatrix `a,b` then you can't use them after.
impl Add<ComplexMatrix> for ComplexMatrix {
type Output = Self;
fn add(self, other: Self) -> Self {
assert_eq!(&self.row, &other.row);
assert_eq!(&self.col, &other.col);
let mut result = cmatrix(self.data.clone(), self.row, self.col, self.shape);
for i in 0..self.row {
for j in 0..self.col {
result[(i, j)] += other[(i, j)];
}
}