-
Notifications
You must be signed in to change notification settings - Fork 32
/
matrix.rs
4822 lines (4468 loc) · 127 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
//! Matrix for Scientific computation
//!
//! ## Declare matrix
//!
//! * You can declare matrix by various ways.
//! * R's way - Default
//! * MATLAB's way
//! * Python's way
//! * Other macro
//!
//! ### R's way
//!
//! * Description: Same as R - `matrix(Vec<f64>, Row, Col, Shape)`
//! * Type: `matrix(Vec<T>, usize, usize, Shape) where T: std::convert::Into<f64> + Copy`
//! * `Shape`: `Enum` for matrix shape - `Row` & `Col`
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix(c!(1,2,3,4), 2, 2, Row);
//! a.print();
//! // c[0] c[1]
//! // r[0] 1 2
//! // r[1] 3 4
//!
//! let b = matrix(c!(1,2,3,4), 2, 2, Col);
//! b.print();
//! // c[0] c[1]
//! // r[0] 1 3
//! // r[1] 2 4
//! }
//! ```
//!
//! ### MATLAB's way
//!
//! * Description: Similar to MATLAB (But should use `&str`)
//! * Type: `ml_matrix(&str)`
//!
//! ```rust
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = ml_matrix("1 2; 3 4");
//! a.print();
//! // c[0] c[1]
//! // r[0] 1 2
//! // r[1] 3 4
//! }
//! ```
//!
//! ### Python's way
//!
//! * Description: Declare matrix as vector of vectors.
//! * Type: `py_matrix(Vec<Vec<T>>) where T: std::convert::Into<f64> + Copy`
//!
//! ```rust
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = py_matrix(vec![vec![1, 2], vec![3, 4]]);
//! a.print();
//! // c[0] c[1]
//! // r[0] 1 2
//! // r[1] 3 4
//! }
//! ```
//!
//! ### Other macro
//!
//! * Description: R-like macro to declare matrix
//! * For `R`,
//!
//! ```R
//! # R
//! a = matrix(1:4, nrow = 2, ncol = 2, byrow = T)
//! print(a)
//! # [,1] [,2]
//! # [1,] 1 2
//! # [2,] 3 4
//! ```
//!
//! * For `Peroxide`,
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix!(1;4;1, 2, 2, Row);
//! a.print();
//! // c[0] c[1]
//! // r[0] 1 2
//! // r[1] 3 4
//! }
//! ```
//!
//! ## Basic Method for Matrix
//!
//! There are some useful methods for `Matrix`
//!
//! * `row(&self, index: usize) -> Vec<f64>` : Extract specific row as `Vec<f64>`
//! * `col(&self, index: usize) -> Vec<f64>` : Extract specific column as `Vec<f64>`
//! * `diag(&self) -> Vec<f64>`: Extract diagonal components as `Vec<f64>`
//! * `swap(&self, usize, usize, Shape)`: Swap two rows or columns (unsafe function)
//! * `subs_col(&mut self, usize, Vec<f64>)`: Substitute column with `Vec<f64>`
//! * `subs_row(&mut self, usize, Vec<f64>)`: Substitute row with `Vec<f64>`
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let mut a = ml_matrix("1 2; 3 4");
//!
//! a.row(0).print(); // [1, 2]
//! a.col(0).print(); // [1, 3]
//! a.diag().print(); // [1, 4]
//! unsafe {
//! a.swap(0, 1, Row);
//! }
//! a.print();
//! // c[0] c[1]
//! // r[0] 3 4
//! // r[1] 1 2
//!
//! let mut b = ml_matrix("1 2;3 4");
//! b.subs_col(0, &c!(5, 6));
//! b.subs_row(1, &c!(7, 8));
//! b.print();
//! // c[0] c[1]
//! // r[0] 5 2
//! // r[1] 7 8
//! }
//! ```
//!
//! ## Read & Write
//!
//! In peroxide, we can write matrix to `csv`
//!
//! ### CSV (Not recommended)
//!
//! * `csv` feature should be required
//! * `write(&self, file_path: &str)`: Write matrix to csv
//! * `write_with_header(&self, file_path, header: Vec<&str>)`: Write with header
//!
//! ```rust
//! use peroxide::fuga::*;
//!
//! fn main() {
//! # #[cfg(feature="csv")]
//! # {
//! let a = ml_matrix("1 2;3 4");
//! a.write("example_data/matrix.csv").expect("Can't write file");
//!
//! let b = ml_matrix("1 2; 3 4; 5 6");
//! b.write_with_header("example_data/header.csv", vec!["odd", "even"])
//! .expect("Can't write header file");
//! # }
//! println!("Complete!")
//! }
//! ```
//!
//! Also, you can read matrix from csv.
//!
//! * Type: `read(&str, bool, char) -> Result<Matrix, Box<Error>>`
//! * Description: `read(file_path, is_header, delimiter)`
//!
//! ```no_run
//! use peroxide::fuga::*;
//!
//! fn main() {
//! # #[cfg(feature="csv")]
//! # {
//! // `csv` feature should be required
//! let a = Matrix::read("example_data/matrix.csv", false, ',')
//! .expect("Can't read matrix.csv file");
//! a.print();
//! # }
//! // c[0] c[1]
//! // r[0] 1 2
//! // r[1] 3 4
//! }
//! ```
//!
//! ### Convert to DataFrame (Recommended)
//!
//! To write columns or rows, `DataFrame` and `nc` feature could be the best choice.
//!
//! * `nc` feature should be required - `netcdf` or `libnetcdf` are prerequisites.
//!
//! ```no_run
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix(c!(1,2,3,4,5,6), 3, 2, Col);
//!
//! // Construct DataFrame
//! let mut df = DataFrame::new(vec![]);
//! df.push("x", Series::new(a.col(0)));
//! df.push("y", Series::new(a.col(1)));
//!
//! // Write nc file (`nc` feature should be required)
//! # #[cfg(feature="nc")]
//! # {
//! df.write_nc("data.nc").expect("Can't write data.nc");
//!
//! // Read nc file (`nc` feature should be required)
//! let dg = DataFrame::read_nc("data.nc").expect("Can't read data.nc");
//! let x: Vec<f64> = dg["x"].to_vec();
//! let y: Vec<f64> = dg["y"].to_vec();
//!
//! assert_eq!(a.col(0), x);
//! assert_eq!(a.col(1), y);
//! # }
//! }
//! ```
//!
//! ## Concatenation
//!
//! There are two options to concatenate matrices.
//!
//! * `cbind`: Concatenate two matrices by column direction.
//! * `rbind`: Concatenate two matrices by row direction.
//!
//! ```rust
//! use peroxide::fuga::*;
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//! let a = ml_matrix("1 2;3 4");
//! let b = ml_matrix("5 6;7 8");
//!
//! cbind(a.clone(), b.clone())?.print();
//! // c[0] c[1] c[2] c[3]
//! // r[0] 1 2 5 7
//! // r[1] 3 4 6 8
//!
//! rbind(a, b)?.print();
//! // c[0] c[1]
//! // r[0] 1 2
//! // r[1] 3 4
//! // r[2] 5 6
//! // r[3] 7 8
//!
//! Ok(())
//! }
//! ```
//!
//! ## Matrix operations
//!
//! * In peroxide, can use basic operations between matrices. I'll show you by examples.
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix!(1;4;1, 2, 2, Row);
//! (a.clone() + 1).print(); // -, *, / are also available
//! // c[0] c[1]
//! // r[0] 2 3
//! // r[1] 4 5
//!
//! let b = matrix!(5;8;1, 2, 2, Row);
//! (a.clone() + b.clone()).print(); // - is also available
//! // c[0] c[1]
//! // r[0] 6 8
//! // r[1] 10 12
//!
//! (a.clone() * b.clone()).print(); // Matrix multiplication
//! // c[0] c[1]
//! // r[0] 19 22
//! // r[1] 43 50
//! }
//! ```
//!
//! * `clone` is too annoying - We can use reference operations!
//!
//! ```rust
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = ml_matrix("1 2;3 4");
//! let b = ml_matrix("5 6;7 8");
//!
//! (&a + 1).print();
//! (&a + &b).print();
//! (&a - &b).print();
//! (&a * &b).print();
//! }
//! ```
//!
//! ## Extract & modify components
//!
//! * In peroxide, matrix data is saved as linear structure.
//! * But you can use two-dimensional index to extract or modify components.
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let mut a = matrix!(1;4;1, 2, 2, Row);
//! a[(0,0)].print(); // 1
//! a[(0,0)] = 2f64; // Modify component
//! a.print();
//! // c[0] c[1]
//! // r[0] 2 2
//! // r[1] 3 4
//! }
//! ```
//!
//! ## Conversion to `Vec<f64>`
//!
//! * Just use `row` or `col` method (I already showed at Basic method section).
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix!(1;4;1, 2, 2, Row);
//! a.row(0).print(); // [1, 2]
//! assert_eq!(a.row(0), vec![1f64, 2f64]);
//! }
//! ```
//!
//! ## Useful constructor
//!
//! * `zeros(usize, usize)`: Construct matrix which elements are all zero
//! * `eye(usize)`: Identity matrix
//! * `rand(usize, usize)`: Construct random uniform matrix (from 0 to 1)
//! * `rand_with_rng(usize, usize, &mut Rng)`: Construct random matrix with user-defined RNG
//!
//! ```rust
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = zeros(2, 2);
//! assert_eq!(a, ml_matrix("0 0;0 0"));
//!
//! let b = eye(2);
//! assert_eq!(b, ml_matrix("1 0;0 1"));
//!
//! let c = rand(2, 2);
//! c.print(); // Random 2x2 matrix
//! }
//! ```
//! # Linear Algebra
//!
//! ## Transpose
//!
//! * Caution: Transpose does not consume the original value.
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix!(1;4;1, 2, 2, Row);
//! a.transpose().print();
//! // Or you can use shorter one
//! a.t().print();
//! // c[0] c[1]
//! // r[0] 1 3
//! // r[1] 2 4
//! }
//! ```
//!
//! ## LU Decomposition
//!
//! * Peroxide uses **complete pivoting** for LU decomposition - Very stable
//! * Since there are lots of causes to generate error, you should use `Option`
//! * `lu` returns `PQLU`
//! * `PQLU` has four field - `p`, `q`, `l` , `u`
//! * `p` means row permutations
//! * `q` means column permutations
//! * `l` means lower triangular matrix
//! * `u` menas upper triangular matrix
//! * The structure of `PQLU` is as follows:
//!
//! ```rust
//! use peroxide::fuga::*;
//!
//! #[derive(Debug, Clone)]
//! pub struct PQLU {
//! pub p: Vec<usize>,
//! pub q: Vec<usize>,
//! pub l: Matrix,
//! pub u: Matrix,
//! }
//! ```
//!
//! * Example of LU decomposition:
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix(c!(1,2,3,4), 2, 2, Row);
//! let pqlu = a.lu();
//! let (p,q,l,u) = (pqlu.p, pqlu.q, pqlu.l, pqlu.u);
//! assert_eq!(p, vec![1]); // swap 0 & 1 (Row)
//! assert_eq!(q, vec![1]); // swap 0 & 1 (Col)
//! assert_eq!(l, matrix(c!(1,0,0.5,1),2,2,Row));
//! // c[0] c[1]
//! // r[0] 1 0
//! // r[1] 0.5 1
//! assert_eq!(u, matrix(c!(4,3,0,-0.5),2,2,Row));
//! // c[0] c[1]
//! // r[0] 4 3
//! // r[1] 0 -0.5
//! }
//! ```
//!
//! ## Determinant
//!
//! * Peroxide uses LU decomposition to obtain determinant ($ \mathcal{O}(n^3) $)
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix!(1;4;1, 2, 2, Row);
//! assert_eq!(a.det(), -2f64);
//! }
//! ```
//!
//! ## Inverse matrix
//!
//! * Peroxide uses LU decomposition (via GECP) to obtain inverse matrix.
//! * It needs two sub functions - `inv_l`, `inv_u`
//! * For inverse of `L, U`, I use block partitioning. For example, for lower triangular matrix :
//! $$ \begin{aligned} L &= \begin{pmatrix} L_1 & \mathbf{0} \\\ L_2 & L_3 \end{pmatrix} \\\ L^{-1} &= \begin{pmatrix} L_1^{-1} & \mathbf{0} \\\ -L_3^{-1}L_2 L_1^{-1} & L_3^{-1} \end{pmatrix} \end{aligned} $$
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix!(1;4;1, 2, 2, Row);
//! a.inv().print();
//! // c[0] c[1]
//! // r[0] -2 1
//! // r[1] 1.5 -0.5
//! }
//! ```
//!
//! ## Tips for LU, Det, Inverse
//!
//! * If you save `self.lu()` rather than the direct use of `self.det()` or `self.lu()` then you can get better performance (via memoization)
//!
//! ```rust
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = ml_matrix("1 2;3 4");
//! let pqlu = a.lu(); // Memoization of LU
//! pqlu.det().print(); // Same as a.det() but do not need an additional LU
//! pqlu.inv().print(); // Same as a.inv() but do not need an additional LU
//! }
//! ```
//!
//! ## QR Decomposition (`O3` feature only)
//!
//! * Use `dgeqrf` of LAPACK
//! * Return `QR` structure.
//!
//! ```ignore
//! pub struct QR {
//! pub q: Matrix,
//! pub r: Matrix,
//! }
//! ```
//!
//! * Example
//!
//! ```ignore
//! use peroxide::fuga::*;
//!
//! let a = ml_matrix("
//! 1 -1 4;
//! 1 4 -2;
//! 1 4 2;
//! 1 -1 0
//! ");
//!
//! // QR decomposition
//! let qr = a.qr();
//!
//! qr.q().print();
//! // c[0] c[1] c[2]
//! // r[0] -0.5 0.5 -0.5
//! // r[1] -0.5 -0.5000 0.5000
//! // r[2] -0.5 -0.5000 -0.5
//! // r[3] -0.5 0.5 0.5000
//!
//! qr.r().print();
//! // c[0] c[1] c[2]
//! // r[0] -2 -3 -2
//! // r[1] 0 -5 2
//! // r[2] 0 0 -4
//! ```
//!
//! ## Singular Value Decomposition (`O3` feature only)
//!
//! * Use `dgesvd` of LAPACK
//! * Return `SVD` structure
//!
//! ```no_run
//! use peroxide::fuga::*;
//!
//! pub struct SVD {
//! pub s: Vec<f64>,
//! pub u: Matrix,
//! pub vt: Matrix,
//! }
//! ```
//!
//! * Example
//!
//! ```
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = ml_matrix("3 2 2;2 3 -2");
//! #[cfg(feature="O3")]
//! {
//! // Full SVD
//! let svd = a.svd();
//! assert!(eq_vec(&vec![5f64, 3f64], &svd.s, 1e-7));
//!
//! // Or Truncated SVD
//! let svd2 = svd.truncated();
//! assert!(eq_vec(&vec![5f64, 3f64], &svd2.s, 1e-7));
//! }
//! a.print();
//! }
//! ```
//!
//! ## Cholesky Decomposition
//!
//! * Use `dpotrf` of LAPACK
//! * Return Matrix (But there can be panic! - Not symmetric or Not positive definite)
//! * Example
//!
//! ```rust
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = ml_matrix("1 2;2 5");
//! #[cfg(feature = "O3")]
//! {
//! let u = a.cholesky(Upper);
//! assert_eq!(u, ml_matrix("1 2;0 1"));
//!
//! let l = a.cholesky(Lower);
//! assert_eq!(l, ml_matrix("1 0;2 1"));
//! }
//! a.print();
//! }
//! ```
//!
//! ## Moore-Penrose Pseudo Inverse
//!
//! * $ X^\dagger = \left(X^T X\right)^{-1} X^T $
//! * For `O3` feature, peroxide use SVD to obtain pseudo inverse
//!
//! ```rust
//! #[macro_use]
//! extern crate peroxide;
//! use peroxide::fuga::*;
//!
//! fn main() {
//! let a = matrix!(1;4;1, 2, 2, Row);
//! let pinv_a = a.pseudo_inv();
//! let inv_a = a.inv();
//!
//! assert_eq!(inv_a, pinv_a); // Nearly equal (not actually equal)
//! }
//! ```
#[cfg(feature = "csv")]
extern crate csv;
#[cfg(feature = "csv")]
use self::csv::{ReaderBuilder, StringRecord, WriterBuilder};
#[cfg(feature = "O3")]
extern crate blas;
#[cfg(feature = "O3")]
extern crate lapack;
#[cfg(feature = "O3")]
use blas::{daxpy, dgemm, dgemv};
#[cfg(feature = "O3")]
use lapack::{dgecon, dgeqrf, dgesvd, dgetrf, dgetri, dgetrs, dorgqr, dpotrf};
#[cfg(feature = "parallel")]
use rayon::iter::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
pub use self::Shape::{Col, Row};
use crate::numerical::eigen::{eigen, EigenMethod};
use crate::structure::dataframe::{Series, TypedVector};
#[cfg(feature = "parallel")]
use crate::traits::math::{ParallelInnerProduct, ParallelNormed};
use crate::traits::sugar::ScalableMut;
use crate::traits::{
fp::{FPMatrix, FPVector},
general::Algorithm,
math::{InnerProduct, LinearOp, MatrixProduct, Norm, Normed, Vector},
matrix::{Form, LinearAlgebra, MatrixTrait, SolveKind, PQLU, QR, SVD, UPLO, WAZD},
mutable::MutMatrix,
};
#[allow(unused_imports)]
use crate::util::{
low_level::{copy_vec_ptr, swap_vec_ptr},
non_macro::{cbind, eye, rbind, zeros},
useful::{nearly_eq, tab},
};
use peroxide_num::{ExpLogOps, Numeric, PowOps, TrigOps};
use std::cmp::{max, min};
pub use std::error::Error;
use std::fmt;
use std::ops::{Add, Div, Index, IndexMut, Mul, Neg, Sub};
pub type Perms = Vec<(usize, usize)>;
/// To select matrices' binding.
///
/// Row - Row binding
/// Col - Column binding
///
/// # Examples
/// ```
/// use peroxide::fuga::*;
///
/// let a = matrix(vec![1,2,3,4], 2, 2, Row);
/// let b = matrix(vec![1,2,3,4], 2, 2, Col);
/// println!("{}", a); // Similar to [[1,2],[3,4]]
/// println!("{}", b); // Similar to [[1,3],[2,4]]
/// ```
#[derive(Default, Debug, PartialEq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Shape {
#[default]
Col,
Row,
}
/// Print for Shape
impl fmt::Display for Shape {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let to_display = match self {
Row => "Row",
Col => "Col",
};
write!(f, "{}", to_display)
}
}
/// R-like matrix structure
///
/// # Examples
///
/// ```
/// use peroxide::fuga::*;
///
/// let a = Matrix {
/// data: vec![1f64,2f64,3f64,4f64],
/// row: 2,
/// col: 2,
/// shape: Row,
/// }; // [[1,2],[3,4]]
/// ```
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Matrix {
pub data: Vec<f64>,
pub row: usize,
pub col: usize,
pub shape: Shape,
}
// =============================================================================
// Various matrix constructor
// =============================================================================
/// R-like matrix constructor
///
/// # Examples
/// ```
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// fn main() {
/// let a = matrix(c!(1,2,3,4), 2, 2, Row);
/// a.print(); // Print matrix
/// }
/// ```
pub fn matrix<T>(v: Vec<T>, r: usize, c: usize, shape: Shape) -> Matrix
where
T: Into<f64>,
{
Matrix {
data: v.into_iter().map(|t| t.into()).collect::<Vec<f64>>(),
row: r,
col: c,
shape,
}
}
/// R-like matrix constructor (Explicit ver.)
pub fn r_matrix<T>(v: Vec<T>, r: usize, c: usize, shape: Shape) -> Matrix
where
T: Into<f64>,
{
matrix(v, r, c, shape)
}
/// Python-like matrix constructor
///
/// # Examples
/// ```
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// fn main() {
/// let a = py_matrix(vec![c!(1,2), c!(3,4)]);
/// let b = matrix(c!(1,2,3,4), 2, 2, Row);
/// assert_eq!(a, b);
/// }
/// ```
pub fn py_matrix<T>(v: Vec<Vec<T>>) -> Matrix
where
T: Into<f64> + Copy,
{
let r = v.len();
let c = v[0].len();
let mut data = vec![0f64; r * c];
for i in 0..r {
for j in 0..c {
let idx = i * c + j;
data[idx] = v[i][j].into();
}
}
matrix(data, r, c, Row)
}
/// Matlab-like matrix constructor
///
/// # Examples
/// ```
/// #[macro_use]
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// fn main() {
/// let a = ml_matrix("1 2; 3 4");
/// let b = matrix(c!(1,2,3,4), 2, 2, Row);
/// assert_eq!(a, b);
/// }
/// ```
pub fn ml_matrix(s: &str) -> Matrix where {
let str_rows: Vec<&str> = s.split(';').collect();
let r = str_rows.len();
let str_data = str_rows
.into_iter()
.map(|x| x.trim().split(' ').collect::<Vec<&str>>())
.collect::<Vec<Vec<&str>>>();
let c = str_data[0].len();
let data = str_data
.into_iter()
.flat_map(|t| {
t.into_iter()
.map(|x| x.parse::<f64>().unwrap())
.collect::<Vec<f64>>()
})
.collect::<Vec<f64>>();
matrix(data, r, c, Row)
}
/// Pretty Print
impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.spread())
}
}
/// PartialEq implements
impl PartialEq for Matrix {
fn eq(&self, other: &Matrix) -> bool {
if self.shape == other.shape {
self.data
.clone()
.into_iter()
.zip(other.data.clone())
.all(|(x, y)| nearly_eq(x, y))
&& self.row == other.row
} else {
self.eq(&other.change_shape())
}
}
}
/// Main matrix structure
#[allow(dead_code)]
impl MatrixTrait for Matrix {
type Scalar = f64;
/// Raw pointer for `self.data`
fn ptr(&self) -> *const f64 {
&self.data[0] as *const f64
}
/// Raw mutable pointer for `self.data`
fn mut_ptr(&mut self) -> *mut f64 {
&mut self.data[0] as *mut f64
}
/// Slice of `self.data`
///
/// # Examples
/// ```
/// use peroxide::fuga::*;
///
/// let a = matrix(vec![1,2,3,4], 2, 2, Col);
/// let b = a.as_slice();
/// assert_eq!(b, &[1f64,2f64,3f64,4f64]);
/// ```
fn as_slice(&self) -> &[f64] {
&self.data[..]
}
/// Mutable slice of `self.data`
///
/// # Examples
/// ```
/// use peroxide::fuga::*;
///
/// let mut a = matrix(vec![1,2,3,4], 2, 2, Col);
/// let mut b = a.as_mut_slice();
/// b[0] = 5f64;
/// assert_eq!(b, &[5f64, 2f64, 3f64, 4f64]);
/// assert_eq!(a, matrix(vec![5,2,3,4], 2, 2, Col));
/// ```
fn as_mut_slice(&mut self) -> &mut [f64] {
&mut self.data[..]
}
/// Change Bindings
///
/// `Row` -> `Col` or `Col` -> `Row`
///
/// # Examples
/// ```
/// use peroxide::fuga::*;
///
/// let a = matrix(vec![1,2,3,4],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<f64> = self.data.clone();
let ref_data = &self.data;
match self.shape {
Row => {
for i in 0..l {
let s = (i * c) % l;
data[i] = ref_data[s];
}
data[l] = ref_data[l];
matrix(data, r, c, Col)
}
Col => {
for i in 0..l {
let s = (i * r) % l;
data[i] = ref_data[s];
}
data[l] = ref_data[l];
matrix(data, r, c, Row)
}
}
}
/// Change Bindings Mutably
///
/// `Row` -> `Col` or `Col` -> `Row`
///
/// # Examples
/// ```
/// use peroxide::fuga::*;
///
/// let a = matrix(vec![1,2,3,4],2,2,Row);
/// assert_eq!(a.shape, Row);
/// let b = a.change_shape();
/// assert_eq!(b.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 {
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 = Col;
}
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 = Row;
}
}
}
/// Spread data(1D vector) to 2D formatted String
///
/// # Examples
/// ```
/// use peroxide::fuga::*;
///
/// let a = matrix(vec![1,2,3,4],2,2,Row);
/// println!("{}", a.spread()); // same as println!("{}", a);
/// // Result:
/// // c[0] c[1]
/// // r[0] 1 3
/// // r[1] 2 4
/// ```
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{}\nonly print {}x{} parts:\n{}",
self.row,
self.col,
key_row,
key_col,
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, max)
+ 1;