/
matrix.zep
3238 lines (2658 loc) · 77.3 KB
/
matrix.zep
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
namespace Tensor;
use Tensor\Reductions\Ref;
use Tensor\Reductions\Rref;
use Tensor\Decompositions\Lu;
use Tensor\Decompositions\Svd;
use Tensor\Decompositions\Eigen;
use Tensor\Decompositions\Cholesky;
use Tensor\Exceptions\InvalidArgumentException;
use Tensor\Exceptions\DimensionalityMismatch;
use Tensor\Exceptions\RuntimeException;
use ArrayIterator;
/**
* Matrix
*
* A two dimensional (rank 2) tensor with integer and/or floating point elements.
*
* @category Scientific Computing
* @package Rubix/Tensor
* @author Andrew DalPino
*/
class Matrix implements Tensor
{
/**
* A 2-dimensional sequential array that holds the values of the matrix.
*
* @var list<list<float>>
*/
protected a;
/**
* The number of rows in the matrix.
*
* @var int
*/
protected m;
/**
* The number of columns in the matrix.
*
* @var int
*/
protected n;
/**
* Factory method to build a new matrix from an array.
*
* @param array[] a
* @return self
*/
public static function build(const array a = []) -> <Matrix>
{
return new self(a, true);
}
/**
* Build a new matrix foregoing any validation for quicker instantiation.
*
* @param array[] a
* @return self
*/
public static function quick(const array a = []) -> <Matrix>
{
return new self(a, false);
}
/**
* Return an identity matrix with dimensionality n x n.
*
* @param int n
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public static function identity(const int n) -> <Matrix>
{
if unlikely n < 1 {
throw new InvalidArgumentException("N must be"
. " greater than 0, " . strval(n) . " given.");
}
int i, j;
array a = [];
array rowA = [];
for i in range(0, n - 1) {
let rowA = [];
for j in range(0, n - 1) {
let rowA[] = i === j ? 1.0 : 0.0;
}
let a[] = rowA;
}
return self::quick(a);
}
/**
* Return a zero matrix with the specified dimensionality.
*
* @param int m
* @param int n
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public static function zeros(const int m, const int n) -> <Matrix>
{
return self::fill(0.0, m, n);
}
/**
* Return a one matrix with the given dimensions.
*
* @param int m
* @param int n
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public static function ones(const int m, const int n) -> <Matrix>
{
return self::fill(1.0, m, n);
}
/**
* Build a matrix with the value of each element along the diagonal
* and zeros everywhere else.
*
* @param float[] elements
* @return self
*/
public static function diagonal(array elements) -> <Matrix>
{
int n = count(elements);
let elements = array_values(elements);
int i, j;
array a = [];
array rowA = [];
for i in range(0, n - 1) {
let rowA = [];
for j in range(0, n - 1) {
let rowA[] = i === j ? elements[i] : 0.0;
}
let a[] = rowA;
}
return self::quick(a);
}
/**
* Fill a matrix with a given value at each element.
*
* @param float value
* @param int m
* @param int n
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public static function fill(const float value, const int m, const int n) -> <Matrix>
{
if unlikely m < 1 {
throw new InvalidArgumentException("M must be"
. " greater than 0, " . strval(m) . " given.");
}
if unlikely n < 1 {
throw new InvalidArgumentException("N must be"
. " greater than 0, " . strval(n) . " given.");
}
return self::quick(array_fill(0, m, array_fill(0, n, value)));
}
/**
* Return a random uniform matrix with values between 0 and 1.
*
* @param int m
* @param int n
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public static function rand(const int m, const int n) -> <Matrix>
{
if unlikely m < 1 {
throw new InvalidArgumentException("M must be"
. " greater than 0, " . strval(m) . " given.");
}
if unlikely n < 1 {
throw new InvalidArgumentException("N must be"
. " greater than 0, " . strval(n) . " given.");
}
array a = [];
array rowA = [];
int max = (int) getrandmax();
while count(a) < m {
let rowA = [];
while count(rowA) < n {
let rowA[] = rand() / max;
}
let a[] = rowA;
}
return self::quick(a);
}
/**
* Return a standard normally (Gaussian( distributed random matrix of specified dimensionality.
*
* @param int m
* @param int n
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public static function gaussian(const int m, const int n) -> <Matrix>
{
if unlikely m < 1 {
throw new InvalidArgumentException("M must be"
. " greater than 0, " . strval(m) . " given.");
}
if unlikely n < 1 {
throw new InvalidArgumentException("N must be"
. " greater than 0, " . strval(n) . " given.");
}
float r, phi;
array a = [];
array rowA = [];
array extras = [];
int max = (int) getrandmax();
while count(a) < m {
let rowA = [];
if !empty extras {
let rowA[] = array_pop(extras);
}
while count(rowA) < n {
let r = sqrt(-2.0 * log(rand() / max));
let phi = rand() / max * self::TWO_PI;
let rowA[] = r * sin(phi);
let rowA[] = r * cos(phi);
}
if count(rowA) > n {
let extras[] = array_pop(rowA);
}
let a[] = rowA;
}
return self::quick(a);
}
/**
* Generate a m x n matrix with elements from a Poisson distribution.
*
* @param int m
* @param int n
* @param float lambda
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public static function poisson(const int m, const int n, const float lambda = 1.0) -> <Matrix>
{
if unlikely m < 1 {
throw new InvalidArgumentException("M must be"
. " greater than 0, " . strval(m) . " given.");
}
if unlikely n < 1 {
throw new InvalidArgumentException("N must be"
. " greater than 0, " . strval(n) . " given.");
}
float l, p, k;
array a = [];
array rowA = [];
let l = (float) exp(-lambda);
int max = (int) getrandmax();
while count(a) < m {
let rowA = [];
while count(rowA) < n {
let k = 0.0;
let p = 1.0;
while p > l {
let k++;
let p *= rand() / max;
}
let rowA[] = k - 1.0;
}
let a[] = rowA;
}
return self::quick(a);
}
/**
* Return a random uniformly distributed matrix with values between -1 and 1.
*
* @param int m
* @param int n
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public static function uniform(const int m, const int n) -> <Matrix>
{
if unlikely m < 1 {
throw new InvalidArgumentException("M must be"
. " greater than 0, " . strval(m) . " given.");
}
if unlikely n < 1 {
throw new InvalidArgumentException("N must be"
. " greater than 0, " . strval(n) . " given.");
}
array a = [];
array rowA = [];
int max = (int) getrandmax();
while count(a) < m {
let rowA = [];
while count(rowA) < n {
let rowA[] = rand(-max, max) / max;
}
let a[] = rowA;
}
return self::quick(a);
}
/**
* @param array[] a
* @param bool validate
* @throws \Tensor\Exceptions\InvalidArgumentException
*/
public function __construct(array a, const bool validate = true)
{
var i, rowA, valueA;
int m = count(a);
int n = count(current(a) ?: []);
if validate {
let a = array_values(a);
for i, rowA in a {
if unlikely count(rowA) !== n {
throw new InvalidArgumentException("The number of columns"
. " must be equal for all rows, " . strval(n)
. " needed but " . count(rowA) . " given"
. " at row offset " . i . ".");
}
for valueA in rowA {
if unlikely !is_float(valueA) {
let valueA = (float) valueA;
}
}
let rowA[] = array_values(rowA);
}
}
let this->a = a;
let this->m = m;
let this->n = n;
}
/**
* Return a tuple with the dimensionality of the tensor.
*
* @return int[]
*/
public function shape() -> array
{
return [this->m, this->n];
}
/**
* Return the shape of the tensor as a string.
*
* @return string
*/
public function shapeString() -> string
{
return (string) this->m . " x " . (string) this->n;
}
/**
* Is this a square matrix?
*
* @return bool
*/
public function isSquare() -> bool
{
return this->m === this->n;
}
/**
* Return the number of elements in the tensor.
*
* @return int
*/
public function size() -> int
{
return this->m * this->n;
}
/**
* Return the number of rows in the matrix.
*
* @return int
*/
public function m() -> int
{
return this->m;
}
/**
* Return the number of columns in the matrix.
*
* @return int
*/
public function n() -> int
{
return this->n;
}
/**
* Return a row as a vector from the matrix.
*
* @param int index
* @return \Tensor\Vector
*/
public function rowAsVector(const int index) -> <Vector>
{
return this->offsetGet(index);
}
/**
* Return a column as a vector from the matrix.
*
* @param int index
* @return \Tensor\ColumnVector
*/
public function columnAsVector(const int index) -> <ColumnVector>
{
return ColumnVector::quick(array_column(this->a, index));
}
/**
* Return the diagonal elements of a square matrix as a vector.
*
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return \Tensor\Vector
*/
public function diagonalAsVector() -> <Vector>
{
if unlikely !this->isSquare() {
throw new InvalidArgumentException("Matrix must be"
. " square, " . this->shapeString() . " given.");
}
var i, rowA;
array b = [];
for i, rowA in this->a {
let b[] = rowA[i];
}
return Vector::quick(b);
}
/**
* Return the elements of the matrix in a 2-d array.
*
* @return list<list<float>>
*/
public function asArray() -> array
{
return this->a;
}
/**
* Return each row as a vector in an array.
*
* @return \Tensor\Vector[]
*/
public function asVectors() -> array
{
return array_map(["Tensor\\Vector", "quick"], this->a);
}
/**
* Return each column as a column vector in an array.
*
* @return \Tensor\ColumnVector[]
*/
public function asColumnVectors() -> array
{
int i;
array vectors = [];
for i in range(0, this->n - 1) {
let vectors[] = this->columnAsVector(i);
}
return vectors;
}
/**
* Flatten i.e unravel the matrix into a vector.
*
* @return \Tensor\Vector
*/
public function flatten() -> <Vector>
{
return Vector::quick(call_user_func_array("array_merge", this->a));
}
/**
* Run a function over all of the elements in the matrix.
*
* @internal
*
* @param callable callback
* @return self
*/
public function map(const var callback) -> <Matrix>
{
var rowA;
array b = [];
for rowA in this->a {
let b[] = array_map(callback, rowA);
}
return self::quick(b);
}
/**
* Reduce the matrix down to a scalar using a callback function.
*
* @internal
*
* @param callable callback
* @param float initial
* @return float
*/
public function reduce(const var callback, float initial = 0.0) -> float
{
var rowA, valueA;
var carry = initial;
for rowA in this->a {
for valueA in rowA {
let carry = {callback}(valueA, carry);
}
}
return carry;
}
/**
* Transpose the matrix i.e row become columns and columns become rows.
*
* @return self
*/
public function transpose() -> <Matrix>
{
int i;
array b = [];
for i in range(0, this->n - 1) {
let b[] = array_column(this->a, i);
}
return self::quick(b);
}
/**
* Compute the inverse of the square matrix.
*
* @return self
*/
public function inverse() -> <Matrix>
{
if unlikely !this->isSquare() {
throw new InvalidArgumentException("Matrix must be"
. " square, " . this->shapeString() . " given.");
}
return self::quick(tensor_inverse(this->a));
}
/**
* Compute the Moore-Penrose pseudoinverse of a general matrix.
*
* @return self
*/
public function pseudoinverse() -> <Matrix>
{
return self::quick(tensor_pseudoinverse(this->a));
}
/**
* Calculate the determinant of the matrix.
*
* @throws \Tensor\Exceptions\RuntimeException
* @return float
*/
public function det() -> float
{
if unlikely !this->isSquare() {
throw new InvalidArgumentException("Matrix must be"
. " square, " . this->shapeString() . " given.");
}
var ref = this->ref();
var pi = ref->a()->diagonalAsVector()->product();
return pi * pow(-1.0, ref->swaps());
}
/**
* Return the trace of the matrix i.e the sum of all diagonal elements of a square matrix.
*
* @return float
*/
public function trace() -> float
{
return this->diagonalAsVector()->sum();
}
/**
* Calculate the rank of the matrix i.e the number of pivots in its reduced row echelon form.
*
* @return int
*/
public function rank() -> int
{
var rowA, valueA;
array a = [];
let a = (array) this->rref()->a()->asArray();
int pivots = 0;
for rowA in a {
for valueA in rowA {
if valueA != 0 {
let pivots++;
continue;
}
}
}
return pivots;
}
/**
* Is the matrix full rank?
*
* @return bool
*/
public function fullRank() -> bool
{
return this->rank() === min(this->shape());
}
/**
* Is the matrix symmetric i.e. is it equal to its transpose.
*
* @return bool
*/
public function symmetric() -> bool
{
if !this->isSquare() {
return false;
}
int i, j;
var rowA;
for i in range(0, this->m - 2) {
let rowA = this->a[i];
for j in range(i + 1, this->n - 1) {
if rowA[j] != this->a[j][i] {
return false;
}
}
}
return true;
}
/**
* Multiply this matrix with another matrix (matrix-matrix product).
*
* @param \Tensor\Matrix b
* @throws \Tensor\Exceptions\DimensionalityMismatch
* @return self
*/
public function matmul(const <Matrix> b) -> <Matrix>
{
if unlikely this->n !== b->m() {
throw new DimensionalityMismatch("Matrix A requires "
. (string) this->n . " rows but Matrix B has "
. (string) b->m() . ".");
}
return self::quick(tensor_matmul(this->a, b->asArray()));
}
/**
* Compute the dot product of this matrix and a vector.
*
* @param \Tensor\Vector b
* @throws \Tensor\Exceptions\DimensionalityMismatch
* @return \Tensor\ColumnVector
*/
public function dot(const <Vector> b) -> <ColumnVector>
{
if unlikely this->n !== b->size() {
throw new DimensionalityMismatch("Matrix A requires "
. (string) this->n . " elements but Vector B has "
. (string) b->size() . ".");
}
return this->matmul(b->asColumnMatrix())->columnAsVector(0);
}
/**
* Return the 2D convolution of this matrix and a kernel matrix with given stride using the "same" method for zero padding.
*
* @param \Tensor\Matrix b
* @param int stride
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return self
*/
public function convolve(const <Matrix> b, const int stride = 1) -> <Matrix>
{
if unlikely b->m() > this->m || b->n() > this->n {
throw new InvalidArgumentException("Matrix B cannot be"
. " larger than Matrix A.");
}
if unlikely stride < 1 {
throw new InvalidArgumentException("Stride cannot be"
. " less than 1, " . strval(stride) . " given.");
}
return self::quick(tensor_convolve_2d(this->a, b->asArray(), stride));
}
/**
* Calculate the row echelon form (REF) of the matrix.
*
* @return \Tensor\Reductions\Ref
*/
public function ref() -> <Ref>
{
return Ref::reduce(this);
}
/**
* Return the reduced row echelon (RREF) form of the matrix.
*
* @return \Tensor\Reductions\Rref
*/
public function rref() -> <Rref>
{
return Rref::reduce(this);
}
/**
* Return the LU decomposition of the matrix in a tuple where l is
* the lower triangular matrix, u is the upper triangular matrix,
* and p is the permutation matrix.
*
* @return \Tensor\Decompositions\Lu
*/
public function lu() -> <Lu>
{
return Lu::decompose(this);
}
/**
* Return the lower triangular matrix of the Cholesky decomposition.
*
* @return \Tensor\Decompositions\Cholesky;
*/
public function cholesky() -> <Cholesky>
{
return Cholesky::decompose(this);
}
/**
* Compute the eigenvalues and eigenvectors of the matrix and return them in a tuple.
*
* @param bool symmetric
* @return \Tensor\Decompositions\Eigen
*/
public function eig(bool symmetric = false) -> <Eigen>
{
return Eigen::decompose(this, symmetric);
}
/**
* Compute the singluar value decomposition of this matrix.
*
* @return \Tensor\Decompositions\Svd
*/
public function svd() -> <Svd>
{
return Svd::decompose(this);
}
/**
* Return the L1 norm of the matrix.
*
* @return float
*/
public function l1Norm() -> float
{
return this->transpose()->abs()->sum()->max();
}
/**
* Return the L2 norm of the matrix.
*
* @return float
*/
public function l2Norm() -> float
{
return sqrt(this->square()->sum()->sum());
}
/**
* Retrn the infinity norm of the matrix.
*
* @return float
*/
public function infinityNorm() -> float
{
return this->abs()->sum()->max();
}
/**
* Return the max norm of the matrix.
*
* @return float
*/
public function maxNorm() -> float
{
return this->abs()->max()->max();
}
/**
* A universal function to multiply this matrix with another tensor element-wise.
*
* @param mixed b
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return mixed
*/
public function multiply(const var b)
{
switch (gettype(b)) {
case "object":
switch true {
case b instanceof Matrix:
return this->multiplyMatrix(b);
case b instanceof ColumnVector:
return this->multiplyColumnVector(b);
case b instanceof Vector:
return this->multiplyVector(b);
}
break;
case "double":
case "integer":
return this->multiplyScalar(b);
}
throw new InvalidArgumentException("Cannot multiply"
. " matrix by the given input.");
}
/**
* A universal function to divide this matrix by another tensor sdfsdfelement-wise.
*
* @param mixed b
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return mixed
*/
public function divide(const var b)
{
switch (gettype(b)) {
case "object":
switch true {
case b instanceof Matrix:
return this->divideMatrix(b);
case b instanceof ColumnVector:
return this->divideColumnVector(b);
case b instanceof Vector:
return this->divideVector(b);
}
break;
case "double":
case "integer":
return this->divideScalar(b);
}
throw new InvalidArgumentException("Cannot divide"
. " matrix by the given input.");
}
/**
* A universal function to add this matrix with another tensor
* element-wise.
*
* @param mixed b
* @throws \Tensor\Exceptions\InvalidArgumentException
* @return mixed
*/
public function add(const var b)
{
switch (gettype(b)) {
case "object":
switch true {
case b instanceof Matrix:
return this->addMatrix(b);
case b instanceof ColumnVector:
return this->addColumnVector(b);
case b instanceof Vector:
return this->addVector(b);
}
break;
case "double":
case "integer":
return this->addScalar(b);
}
throw new InvalidArgumentException("Cannot add"
. " matrix with the given input.");
}