forked from mikerabat/mrmath
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix.pas
More file actions
2294 lines (1901 loc) · 78.6 KB
/
Matrix.pas
File metadata and controls
2294 lines (1901 loc) · 78.6 KB
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
// ###################################################################
// #### This file is part of the mathematics library project, and is
// #### offered under the licence agreement described on
// #### http://www.mrsoft.org/
// ####
// #### Copyright:(c) 2011, Michael R. . All rights reserved.
// ####
// #### Unless required by applicable law or agreed to in writing, software
// #### distributed under the License is distributed on an "AS IS" BASIS,
// #### WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// #### See the License for the specific language governing permissions and
// #### limitations under the License.
// ###################################################################
unit Matrix;
// ############################################
// #### Base matrix operations
// ############################################
interface
uses SysUtils, Classes, Types, MatrixConst, BaseMathPersistence, RandomEng;
type
TDoubleMatrix = class;
IMatrix = interface(IMathPersistence)
['{8B76CD12-4314-41EB-BD98-302A024AA0EC}']
function StartElement : PDouble;
function LineWidth : integer;
procedure SetLinEQProgress(value : TLinEquProgress);
function GetLinEQProgress : TLinEquProgress;
function GetItems(x, y: integer): double; register;
procedure SetItems(x, y: integer; const Value: double); register;
function GetVecItem(idx: integer): double; register;
procedure SetVecItem(idx: integer; const Value: double); register;
function GetSubWidth : integer;
function GetSubHeight : integer;
procedure SetWidth(const Value : integer);
procedure SetHeight(const Value : integer);
procedure SetWidthHeight(const Width, Height : integer);
property Width : integer read GetSubWidth write SetWidth;
property Height : integer read GetSubHeight write SetHeight;
property LinEQProgress : TLinEquProgress read GetLinEQProgress write SetLinEQProgress;
// general access
property Items[x, y : integer] : double read GetItems write SetItems; default;
property Vec[idx : integer] : double read GetVecItem write SetVecItem; // matrix as vector
procedure Clear;
function GetObjRef : TDoubleMatrix;
function SubMatrix : TDoubleDynArray;
procedure SetSubMatrix(x, y, Subwidth, Subheight : integer);
procedure UseFullMatrix;
procedure SetRow(row : integer; const Values : Array of Double); overload;
procedure SetRow(row : integer; Values : TDoubleMatrix; ValRow : integer = 0); overload;
procedure SetRow(row : integer; Values : IMatrix; ValRow : integer = 0); overload;
procedure SetColumn(col : integer; const Values : Array of Double); overload;
procedure SetColumn(col : integer; Values : TDoubleMatrix; ValCols : integer = 0); overload;
procedure SetColumn(col : integer; Values : IMatrix; ValCols : integer = 0); overload;
procedure SetValue(const initVal : double);
function Reshape(newWidth, newHeight : integer) : TDoubleMatrix;
procedure ReshapeInPlace(newWidth, newHeight : integer);
// ###################################################
// #### Simple matrix utility functions
function Max : double;
function Min : double;
function Abs : TDoubleMatrix;
procedure AbsInPlace;
procedure DiagInPlace(createDiagMtx : boolean);
function Diag(createDiagMtx : boolean) : TDoubleMatrix;
procedure Normalize(RowWise : boolean);
function ElementwiseNorm2 : double;
// ###################################################
// #### Base Matrix operations
procedure TransposeInPlace;
function Transpose : TDoubleMatrix;
procedure AddInplace(Value : TDoubleMatrix); overload;
function Add(Value : TDoubleMatrix) : TDoubleMatrix; overload;
procedure SubInPlace(Value : TDoubleMatrix); overload;
function Sub(Value : TDoubleMatrix) : TDoubleMatrix; overload;
procedure MultInPlace(Value : TDoubleMatrix); overload;
function Mult(Value : TDoubleMatrix) : TDoubleMatrix; overload;
// multT1: dest = mt1' * mt2 mt1' = mt1.transpose
procedure MultInPlaceT1(Value : TDoubleMatrix); overload;
function MultT1(Value : TDoubleMatrix) : TDoubleMatrix; overload;
// multT2: dest = mt1 * mt2' mt2 = mt2.transpose
procedure MultInPlaceT2(Value : TDoubleMatrix); overload;
function MultT2(Value : TDoubleMatrix) : TDoubleMatrix; overload;
procedure AddInplace(Value : IMatrix); overload;
function Add(Value : IMatrix) : TDoubleMatrix; overload;
procedure SubInPlace(Value : IMatrix); overload;
function Sub(Value : IMatrix) : TDoubleMatrix; overload;
procedure MultInPlace(Value : IMatrix); overload;
function Mult(Value : IMatrix) : TDoubleMatrix; overload;
procedure MultInPlaceT1(Value : IMatrix); overload;
function MultT1(Value : IMatrix) : TDoubleMatrix; overload;
procedure MultInPlaceT2(Value : IMatrix); overload;
function MultT2(Value : IMatrix) : TDoubleMatrix; overload;
procedure ElementWiseMultInPlace(Value : TDoubleMatrix); overload;
function ElementWiseMult(Value : TDoubleMatrix) : TDoubleMatrix; overload;
procedure ElementWiseMultInPlace(Value : IMatrix); overload;
function ElementWiseMult(Value : IMatrix) : TDoubleMatrix; overload;
procedure ElementWiseDivInPlace(Value : TDoubleMatrix); overload;
function ElementWiseDiv(Value : TDoubleMatrix) : TDoubleMatrix; overload;
procedure ElementWiseDivInPlace(Value : IMatrix); overload;
function ElementWiseDiv(Value : IMatrix) : TDoubleMatrix; overload;
procedure AddAndScaleInPlace(const Offset, Scale : double);
function AddAndScale(const Offset, Scale : double) : TDoubleMatrix;
function Mean(RowWise : boolean) : TDoubleMatrix;
procedure MeanInPlace(RowWise : boolean);
function Variance(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix;
procedure VarianceInPlace(RowWise : boolean; unbiased : boolean = True);
function Std(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix;
procedure StdInPlace(RowWise : boolean; unbiased : boolean = True);
function Median(RowWise : boolean) : TDoubleMatrix;
procedure MedianInPlace(RowWise : boolean);
procedure SortInPlace(RowWise : boolean);
function Sort(RowWise : boolean) : TDoubleMatrix;
function Sum(RowWise : boolean) : TDoubleMatrix;
procedure SumInPlace(RowWise : boolean);
function Add(const Value : double) : TDoubleMatrix; overload;
procedure AddInPlace(const Value : double); overload;
function Scale(const Value : double) : TDoubleMatrix;
procedure ScaleInPlace(const Value : Double);
function ScaleAndAdd(const aOffset, aScale : double) : TDoubleMatrix;
procedure ScaleAndAddInPlace(const aOffset, aScale : double);
function SQRT : TDoubleMatrix;
procedure SQRTInPlace;
procedure ElementwiseFuncInPlace(func : TMatrixFunc); overload;
function ElementwiseFunc(func : TMatrixFunc) : TDoubleMatrix; overload;
procedure ElementwiseFuncInPlace(func : TMatrixObjFunc); overload;
function ElementwiseFunc(func : TMatrixObjFunc) : TDoubleMatrix; overload;
procedure ElementwiseFuncInPlace(func : TMatrixMtxRefFunc); overload;
function ElementwiseFunc(func : TMatrixMtxRefFunc) : TDoubleMatrix; overload;
procedure ElementwiseFuncInPlace(func : TMatrixMtxRefObjFunc); overload;
function ElementwiseFunc(func : TMatrixMtxRefObjFunc) : TDoubleMatrix; overload;
// ###################################################
// #### Linear System solver A*x = B -> use A.SolveLinEQ(B) -> x
function SolveLinEQ(Value : TDoubleMatrix; numRefinements : integer = 0) : TDoubleMatrix; overload;
function SolveLinEQ(Value : IMatrix; numRefinements : integer = 0) : TDoubleMatrix; overload;
procedure SolveLinEQInPlace(Value : TDoubleMatrix; numRefinements : integer = 0); overload;
procedure SolveLinEQInPlace(Value : IMatrix; numRefinements : integer = 0); overload;
function InvertInPlace : TLinEquResult;
function Invert : TDoubleMatrix;
function PseudoInversionInPlace : TSVDResult;
function PseudoInversion(out Mtx : TDoubleMatrix) : TSVDResult; overload;
function PseudoInversion(out Mtx : IMatrix) : TSVDResult; overload;
function Determinant : double;
// ###################################################
// #### Special functions
procedure MaskedSetValue(const Mask : Array of boolean; const newVal : double);
// ###################################################
// #### Matrix transformations
function SVD(out U, V, W : TDoubleMatrix; onlyDiagElements : boolean = False) : TSVDResult; overload;
function SVD(out U, V, W : IMatrix; onlyDiagElements : boolean = False) : TSVDResult; overload;
function SymEig(out EigVals : TDoubleMatrix; out EigVect : TDoubleMatrix) : TEigenvalueConvergence; overload;
function SymEig(out EigVals : TDoubleMatrix) : TEigenvalueConvergence; overload;
function SymEig(out EigVals : IMatrix; out EigVect : IMatrix) : TEigenvalueConvergence; overload;
function SymEig(out EigVals : IMatrix) : TEigenvalueConvergence; overload;
function Eig(out EigVals : TDoublematrix; out EigVect : TDoubleMatrix; normEigVecs : boolean = False) : TEigenvalueConvergence; overload;
function Eig(out EigVals : TDoublematrix) : TEigenvalueConvergence; overload;
function Eig(out EigVals : IMatrix; out EigVect : IMatrix; normEigVecs : boolean = False) : TEigenvalueConvergence; overload;
function Eig(out EigVals : IMatrix) : TEigenvalueConvergence; overload;
function Cholesky(out Chol : TDoubleMatrix) : TCholeskyResult; overload;
function Cholesky(out Chol : IMatrix) : TCholeskyResult; overload;
function QR(out R : TDoubleMatrix; out tau : TDoubleMatrix) : TQRResult; overload;
function QR(out R : IMatrix; out tau : IMatrix) : TQRResult; overload;
function QRFull(out Q, R : TDoubleMatrix) : TQRResult; overload;
function QRFull(out Q, R : IMatrix) : TQRResult; overload;
// ###################################################
// #### Matrix assignment operations
procedure Assign(Value : TDoubleMatrix); overload;
procedure Assign(Value : IMatrix); overload;
procedure Assign(Value : TDoubleMatrix; OnlySubElements : boolean); overload;
procedure Assign(Value : IMatrix; OnlySubElements : boolean); overload;
procedure Assign(const Mtx : Array of double; W, H : integer); overload;
procedure AssignSubMatrix(Value : TDoubleMatrix; X : integer = 0; Y : integer = 0); overload;
procedure AssignSubMatrix(Value : IMatrix; X : integer = 0; Y : integer = 0); overload;
// moves data from Value to self and clears original object
procedure TakeOver(Value : TDoubleMatrix); overload;
procedure TakeOver(Value : IMatrix); overload;
function Clone : TDoubleMatrix;
end;
// #################################################
// #### Builds base matrix operations
TDoubleMatrixClass = class of TDoubleMatrix;
TDoubleMatrix = class(TBaseMathPersistence, IMatrix)
protected
// used to determine which class type to use as a result
// e.g. the threaded class does not override all standard functions but
// the resulting class type shall always be the threaded class!
class function ResultClass : TDoubleMatrixClass; virtual;
function GetItems(x, y: integer): double; register;
procedure SetItems(x, y: integer; const Value: double); register;
// Access as vector -> same as GetItem(idx mod width, idx div width)
function GetVecItem(idx: integer): double; register;
procedure SetVecItem(idx: integer; const Value: double); register;
// matrix persistence functions
procedure DefineProps; override;
function PropTypeOfName(const Name : string) : TPropType; override;
class function ClassIdentifier : String; override;
procedure OnLoadStringProperty(const Name : String; const Value : String); overload; override;
procedure OnLoadIntProperty(const Name : String; Value : integer); overload; override;
procedure OnLoadDoubleArr(const Name : String; const Value : TDoubleDynArray); override;
procedure SetLinEQProgress(value : TLinEquProgress);
function GetLinEQProgress : TLinEquProgress;
procedure InternalSetWidthHeight(const aWidth, aHeight : integer; AssignMem : boolean = True);
procedure ReserveMem(width, height: integer);
private
fMemory : Pointer;
fData : PConstDoubleArr; // 16 byte aligned pointer:
fLineWidth : integer;
fWidth : integer;
fObj : TObject; // arbitrary object
procedure MtxRandWithEng(var value : double);
procedure MtxRand(var value : double);
protected
fHeight : integer;
fName : String;
fSubWidth : integer;
fSubHeight : integer;
fOffsetX : integer;
fOffsetY : integer;
fLinEQProgress : TLinEquProgress;
procedure CheckAndRaiseError(assertionVal : boolean; const msg : string);
procedure SetData(data : PDouble; srcLineWidth, width, height : integer);
procedure Clear;
procedure SetWidth(const Value : integer);
procedure SetHeight(const Value : integer);
function GetSubWidth : integer;
function GetSubHeight : integer;
function GetObjRef : TDoubleMatrix;
public
property Width : integer read GetSubWidth write SetWidth;
property Height : integer read GetSubHeight write SetHeight;
procedure SetWidthHeight(const aWidth, aHeight : integer);
property Name : string read fName write fName;
property LineEQProgress : TLinEquProgress read GetLinEQProgress write SetLinEQProgress;
// general access
// direct access functionality (use only when you know what you are doing!)
function StartElement : PDouble; {$IFNDEF FPC} {$IF CompilerVersion >= 17.0} inline; {$IFEND} {$ENDIF}
function LineWidth : integer; {$IFNDEF FPC} {$IF CompilerVersion >= 17.0} inline; {$IFEND} {$ENDIF}
property Items[x, y : integer] : double read GetItems write SetItems; default;
property Vec[idx : integer] : double read GetVecItem write SetVecItem; // matrix as vector
function SubMatrix : TDoubleDynArray;
procedure SetSubMatrix(x, y, Subwidth, Subheight : integer);
procedure UseFullMatrix;
procedure SetRow(row : integer; const Values : Array of Double); overload;
procedure SetRow(row : integer; Values : TDoubleMatrix; ValRow : integer = 0); overload;
procedure SetRow(row : integer; Values : IMatrix; ValRow : integer = 0); overload;
procedure SetColumn(col : integer; const Values : Array of Double); overload;
procedure SetColumn(col : integer; Values : TDoubleMatrix; ValCols : integer = 0); overload;
procedure SetColumn(col : integer; Values : IMatrix; ValCols : integer = 0); overload;
procedure SetValue(const initVal : double);
function Reshape(newWidth, newHeight : integer) : TDoubleMatrix;
procedure ReshapeInPlace(newWidth, newHeight : integer);
// ###################################################
// #### Simple matrix utility functions
function Max : double;
function Min : double;
function Abs : TDoubleMatrix;
procedure AbsInPlace;
procedure DiagInPlace(createDiagMtx : boolean);
function Diag(createDiagMtx : boolean) : TDoubleMatrix;
procedure Normalize(RowWise : boolean);
function ElementwiseNorm2 : double;
// ###################################################
// #### Base Matrix operations
procedure TransposeInPlace;
function Transpose : TDoubleMatrix;
procedure AddInplace(Value : TDoubleMatrix); overload; virtual;
function Add(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual;
procedure SubInPlace(Value : TDoubleMatrix); overload; virtual;
function Sub(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual;
procedure MultInPlace(Value : TDoubleMatrix); overload; virtual;
function Mult(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual;
procedure MultInPlaceT1(Value : TDoubleMatrix); overload; virtual;
function MultT1(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual;
procedure MultInPlaceT2(Value : TDoubleMatrix); overload; virtual;
function MultT2(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual;
procedure AddInplace(Value : IMatrix); overload;
function Add(Value : IMatrix) : TDoubleMatrix; overload;
procedure SubInPlace(Value : IMatrix); overload;
function Sub(Value : IMatrix) : TDoubleMatrix; overload;
procedure MultInPlace(Value : IMatrix); overload;
function Mult(Value : IMatrix) : TDoubleMatrix; overload;
procedure MultInPlaceT1(Value : IMatrix); overload;
function MultT1(Value : IMatrix) : TDoubleMatrix; overload;
procedure MultInPlaceT2(Value : IMatrix); overload;
function MultT2(Value : IMatrix) : TDoubleMatrix; overload;
procedure ElementWiseMultInPlace(Value : IMatrix); overload;
function ElementWiseMult(Value : IMatrix) : TDoubleMatrix; overload;
procedure ElementWiseMultInPlace(Value : TDoubleMatrix); overload; virtual;
function ElementWiseMult(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual;
procedure ElementWiseDivInPlace(Value : TDoubleMatrix); overload; virtual;
function ElementWiseDiv(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual;
procedure ElementWiseDivInPlace(Value : IMatrix); overload; virtual;
function ElementWiseDiv(Value : IMatrix) : TDoubleMatrix; overload; virtual;
procedure AddAndScaleInPlace(const Offset, Scale : double); virtual;
function AddAndScale(const Offset, Scale : double) : TDoubleMatrix; virtual;
function Mean(RowWise : boolean) : TDoubleMatrix;
procedure MeanInPlace(RowWise : boolean);
function Variance(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix;
procedure VarianceInPlace(RowWise : boolean; unbiased : boolean = True);
function Std(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix;
procedure StdInPlace(RowWise : boolean; unbiased : boolean = True);
function Median(RowWise : boolean) : TDoubleMatrix; virtual;
procedure MedianInPlace(RowWise : boolean);
procedure SortInPlace(RowWise : boolean); virtual;
function Sort(RowWise : boolean) : TDoubleMatrix;
function Sum(RowWise : boolean) : TDoubleMatrix;
procedure SumInPlace(RowWise : boolean);
function Add(const Value : double) : TDoubleMatrix; overload;
procedure AddInPlace(const Value : double); overload;
function Scale(const Value : double) : TDoubleMatrix;
procedure ScaleInPlace(const Value : Double);
function ScaleAndAdd(const aOffset, aScale : double) : TDoubleMatrix;
procedure ScaleAndAddInPlace(const aOffset, aScale : double);
function SQRT : TDoubleMatrix;
procedure SQRTInPlace;
procedure ElementwiseFuncInPlace(func : TMatrixFunc); overload; virtual;
function ElementwiseFunc(func : TMatrixFunc) : TDoubleMatrix; overload; virtual;
procedure ElementwiseFuncInPlace(func : TMatrixObjFunc); overload; virtual;
function ElementwiseFunc(func : TMatrixObjFunc) : TDoubleMatrix; overload; virtual;
procedure ElementwiseFuncInPlace(func : TMatrixMtxRefFunc); overload; virtual;
function ElementwiseFunc(func : TMatrixMtxRefFunc) : TDoubleMatrix; overload; virtual;
procedure ElementwiseFuncInPlace(func : TMatrixMtxRefObjFunc); overload; virtual;
function ElementwiseFunc(func : TMatrixMtxRefObjFunc) : TDoubleMatrix; overload; virtual;
// ###################################################
// #### Linear System solver A*x = B -> use A.SolveLinEQ(B) -> x
function SolveLinEQ(Value : TDoubleMatrix; numRefinements : integer = 0) : TDoubleMatrix; overload; virtual;
function SolveLinEQ(Value : IMatrix; numRefinements : integer = 0) : TDoubleMatrix; overload;
procedure SolveLinEQInPlace(Value : TDoubleMatrix; numRefinements : integer = 0); overload; virtual;
procedure SolveLinEQInPlace(Value : IMatrix; numRefinements : integer = 0); overload;
function InvertInPlace : TLinEquResult; virtual;
function Invert : TDoubleMatrix; virtual;
function PseudoInversionInPlace : TSVDResult;
function PseudoInversion(out Mtx : TDoubleMatrix) : TSVDResult; overload;
function PseudoInversion(out Mtx : IMatrix) : TSVDResult; overload;
function Determinant : double; virtual;
// ###################################################
// #### Special functions
procedure MaskedSetValue(const Mask : Array of boolean; const newVal : double);
// ###################################################
// #### Matrix transformations
function SVD(out U, V, W : TDoubleMatrix; onlyDiagElements : boolean = False) : TSVDResult; overload;
function SVD(out U, V, W : IMatrix; onlyDiagElements : boolean = False) : TSVDResult; overload;
function SymEig(out EigVals : TDoubleMatrix; out EigVect : TDoubleMatrix) : TEigenvalueConvergence; overload;
function SymEig(out EigVals : TDoubleMatrix) : TEigenvalueConvergence; overload;
function SymEig(out EigVals : IMatrix; out EigVect : IMatrix) : TEigenvalueConvergence; overload;
function SymEig(out EigVals : IMatrix) : TEigenvalueConvergence; overload;
function Eig(out EigVals : TDoublematrix; out EigVect : TDoubleMatrix; normEigVecs : boolean = False) : TEigenvalueConvergence; overload;
function Eig(out EigVals : TDoublematrix) : TEigenvalueConvergence; overload;
function Eig(out EigVals : IMatrix; out EigVect : IMatrix; normEigVecs : boolean = False) : TEigenvalueConvergence; overload;
function Eig(out EigVals : IMatrix) : TEigenvalueConvergence; overload;
function Cholesky(out Chol : TDoubleMatrix) : TCholeskyResult; overload; virtual;
function Cholesky(out Chol : IMatrix) : TCholeskyResult; overload;
function QR(out ecosizeR : TDoubleMatrix; out tau : TDoubleMatrix) : TQRResult; overload; virtual;
function QR(out ecosizeR : IMatrix; out tau : IMatrix) : TQRResult; overload;
function QRFull(out Q, R : TDoubleMatrix) : TQRResult; overload; virtual;
function QRFull(out Q, R : IMatrix) : TQRResult; overload;
// ###################################################
// #### Matrix assignment operations
procedure Assign(Value : TDoubleMatrix); overload;
procedure Assign(Value : IMatrix); overload;
procedure Assign(Value : TDoubleMatrix; OnlySubElements : boolean); overload;
procedure Assign(Value : IMatrix; OnlySubElements : boolean); overload;
procedure Assign(const Mtx : Array of double; W, H : integer); overload;
procedure AssignSubMatrix(Value : TDoubleMatrix; X : integer = 0; Y : integer = 0); overload;
procedure AssignSubMatrix(Value : IMatrix; X : integer = 0; Y : integer = 0); overload;
procedure TakeOver(Value : TDoubleMatrix); overload;
procedure TakeOver(Value : IMatrix); overload;
function Clone : TDoubleMatrix;
constructor Create; overload;
constructor Create(aWidth, aHeight : integer; const initVal : double = 0); overload;
constructor CreateEye(aWidth : integer);
constructor Create(data : PDouble; aLineWidth : integer; aWidth, aHeight : integer); overload;
constructor Create(const Data : TDoubleDynArray; aWidth, aHeight : integer); overload;
constructor CreateRand(aWidth, aHeight : integer; method : TRandomAlgorithm; seed : LongInt); overload; // uses random engine
constructor CreateRand(aWidth, aHeight : integer); overload; // uses system default random
destructor Destroy; override;
end;
type
TDoubleMatrixDynArr = Array of TDoubleMatrix;
implementation
uses Math, OptimizedFuncs, LinearAlgebraicEquations,
Eigensystems;
{$IFNDEF CPUX64}
type
NativeUInt = Cardinal;
{$ENDIF}
{ TDoubleMatrix }
function TDoubleMatrix.Abs: TDoubleMatrix;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'Dimension Error');
Result := ResultClass.Create;
Result.Assign(Self, True);
MatrixAbs(Result.StartElement, Result.LineWidth, Result.Width, Result.Height);
end;
procedure TDoubleMatrix.AbsInPlace;
begin
CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned');
MatrixAbs(StartElement, LineWidth, fSubWidth, fSubHeight);
end;
function TDoubleMatrix.Add(Value: IMatrix): TDoubleMatrix;
begin
Result := Add(Value.GetObjRef);
end;
function TDoubleMatrix.Add(const Value: double): TDoubleMatrix;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'Dimension Error');
Result := ResultClass.Create;
Result.Assign(Self, True);
MatrixAddAndScale(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, Value, 1);
end;
function TDoubleMatrix.AddAndScale(const Offset, Scale: double): TDoubleMatrix;
begin
CheckAndRaiseError((width > 0) and (Height > 0), 'No data assigned');
Result := ResultClass.Create;
Result.Assign(self, True);
Result.AddAndScaleInPlace(Offset, Scale);
end;
procedure TDoubleMatrix.AddAndScaleInPlace(const Offset, Scale: double);
begin
CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned');
MatrixAddAndScale(StartElement, LineWidth, fSubWidth, fSubHeight, Offset, Scale);
end;
procedure TDoubleMatrix.AddInplace(const Value: double);
begin
CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned');
MatrixAddAndScale(StartElement, LineWidth, fSubWidth, fSubHeight, Value, 1);
end;
procedure TDoubleMatrix.AddInplace(Value: IMatrix);
begin
AddInplace(Value.GetObjRef);
end;
procedure TDoubleMatrix.AddInplace(Value: TDoubleMatrix);
begin
CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned');
// inplace matrix addition
CheckAndRaiseError((fSubWidth = Value.fSubWidth) and (fSubHeight = Value.fSubHeight), 'Matrix dimensions do not match');
MatrixAdd(StartElement, LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth);
end;
procedure TDoubleMatrix.Assign(const Mtx: array of double; W, H : integer);
begin
CheckAndRaiseError((W*H > 0) and (Length(Mtx) = W*H), 'Dimension error');
SetWidthHeight(W, H);
MatrixCopy(StartElement, LineWidth, @Mtx[0], W*sizeof(double), W, H);
end;
procedure TDoubleMatrix.AssignSubMatrix(Value: IMatrix; X, Y: integer);
begin
AssignSubMatrix(Value.GetObjRef, X, Y);
end;
procedure TDoubleMatrix.Assign(Value: IMatrix; OnlySubElements: boolean);
begin
Assign(Value.GetObjRef, OnlySubElements);
end;
procedure TDoubleMatrix.Assign(Value: IMatrix);
begin
Assign(Value.GetObjRef);
end;
procedure TDoubleMatrix.AssignSubMatrix(Value: TDoubleMatrix; X, Y: integer);
var pSelf, pValue : PDouble;
begin
CheckAndRaiseError((Value.Width <= Width) and (Value.Height <= Height), 'Dimension error');
if (Value.Width = 0) or (Value.Height = 0) then
exit;
pSelf := StartElement;
inc(PByte(pSelf), Y*LineWidth);
inc(pSelf, X);
pValue := Value.StartElement;
MatrixCopy(pSelf, LineWidth, pValue, Value.LineWidth, Value.Width, Value.Height);
end;
procedure TDoubleMatrix.Assign(Value: TDoubleMatrix; OnlySubElements: boolean);
begin
fName := Value.Name;
if OnlySubElements then
begin
SetWidthHeight(Value.Width, Value.Height);
MatrixCopy(StartElement, LineWidth, Value.StartElement, Value.LineWidth, Value.Width, Value.Height);
end
else
begin
SetWidthHeight(Value.fWidth, Value.fHeight);
MatrixCopy(StartElement, LineWidth, PDouble(Value.fData), Value.LineWidth, Value.fWidth, Value.fHeight);
fSubWidth := Value.fSubWidth;
fSubHeight := Value.fSubHeight;
end;
end;
function TDoubleMatrix.Add(Value : TDoubleMatrix) : TDoubleMatrix;
begin
CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned');
CheckAndRaiseError((Value.fSubWidth = fSubWidth) and (Value.fSubHeight = fSubHeight), 'Dimension error');
Result := ResultClass.Create(fSubWidth, fSubHeight);
MatrixAdd(Result.StartElement, Result.LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth);
end;
procedure TDoubleMatrix.Assign(Value: TDoubleMatrix);
begin
Assign(Value, False);
end;
function TDoubleMatrix.Cholesky(out Chol: TDoubleMatrix): TCholeskyResult;
var x, y : integer;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubWidth = fSubHeight), 'Cholesky decomposition is only allowed on square matrices');
chol := ResultClass.Create;
try
chol.Assign(Self);
// block wise cholesky decomposition
Result := MatrixCholeskyInPlace4(chol.StartElement, chol.LineWidth, chol.Width, 0, fLinEQProgress);
if Result = crOk then
begin
// zero out the upper elements
for y := 0 to fSubWidth - 1 do
begin
for x := y + 1 to fSubWidth - 1 do
Chol[x, y] := 0;
end;
end
else
FreeAndNil(chol);
except
FreeAndNil(chol);
Result := crNoPositiveDefinite;
end;
end;
constructor TDoubleMatrix.Create;
begin
inherited Create;
SetWidthHeight(1, 1);
end;
constructor TDoubleMatrix.Create(data: PDouble; aLineWidth, aWidth,
aHeight: integer);
begin
inherited Create;
fWidth := aWidth;
fHeight := aHeight;
fMemory := data;
fData := PConstDoubleArr(data);
fLineWidth := aLineWidth;
fOffsetX := 0;
fOffsetY := 0;
fSubWidth := fWidth;
fSubHeight := fHeight;
CheckAndRaiseError(width*sizeof(double) <= LineWidth, 'Dimension error');
end;
constructor TDoubleMatrix.Create(aWidth, aHeight: integer; const initVal : double);
var pData : PDouble;
x, y : integer;
begin
inherited Create;
SetWidthHeight(aWidth, aHeight);
if initVal <> 0 then
begin
for y := 0 to height - 1 do
begin
pData := StartElement;
inc(PByte(pData), y*LineWidth);
for x := 0 to Width - 1 do
begin
pData^ := initVal;
inc(pData);
end;
end;
end;
end;
constructor TDoubleMatrix.Create(const Data: TDoubleDynArray; aWidth,
aHeight: integer);
begin
inherited Create;
Assign(Data, aWidth, aHeight);
end;
constructor TDoubleMatrix.CreateEye(aWidth: integer);
var i : integer;
begin
inherited Create;
SetWidthHeight(aWidth, aWidth);
for i := 0 to width - 1 do
Items[i, i] := 1;
end;
constructor TDoubleMatrix.CreateRand(aWidth, aHeight: integer;
method: TRandomAlgorithm; seed: LongInt);
begin
inherited Create;
SetWidthHeight(aWidth, aHeight);
fObj := TRandomGenerator.Create;
TRandomGenerator(fObj).RandMethod := method;
TRandomGenerator(fObj).Init(seed);
ElementwiseFuncInPlace({$IFDEF FPC}@{$ENDIF}MtxRandWithEng);
FreeAndNil(fObj);
end;
procedure TDoubleMatrix.MtxRand(var value: double);
begin
value := Random;
end;
procedure TDoubleMatrix.MtxRandWithEng(var value: double);
begin
value := TRandomGenerator(fObj).Random;
end;
constructor TDoubleMatrix.CreateRand(aWidth, aHeight: integer);
begin
inherited Create;
SetWidthHeight(aWidth, aHeight);
ElementwiseFuncInPlace({$IFDEF FPC}@{$ENDIF}MtxRand);
end;
function TDoubleMatrix.Determinant: double;
begin
CheckAndRaiseError((Width > 0) and (Height = Width), 'Determinant only allowed on square matrices');
Result := MatrixDeterminant(StartElement, LineWidth, fSubWidth);
end;
function TDoubleMatrix.Diag(createDiagMtx : boolean): TDoubleMatrix;
var x : integer;
begin
CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned');
if createDiagMtx then
begin
if (width = 1) then
begin
Result := TDoubleMatrix.Create(height, height);
for x := 0 to Height - 1 do
Result[x, x] := Vec[x];
end
else if height = 1 then
begin
Result := TDoubleMatrix.Create(width, width);
for x := 0 to width - 1 do
Result[x, x] := Vec[x];
end
else
begin
Result := TDoubleMatrix.Create(Math.Min(Width, Height), Math.Min(Width, Height));
for x := 0 to Math.Min(Width, Height) - 1 do
Result[x, x] := Items[x, x];
end;
end
else
begin
Result := TDoubleMatrix.Create(1, Math.Min(Width, Height));
for x := 0 to Result.Height - 1 do
Result[Math.Min(x, Result.width - 1), x] := Items[x, x];
end;
end;
procedure TDoubleMatrix.DiagInPlace(createDiagMtx : boolean);
var dl : IMatrix;
begin
dl := Diag(createDiagMtx);
TakeOver(dl);
end;
function TDoubleMatrix.SolveLinEQ(Value: TDoubleMatrix; numRefinements : integer) : TDoubleMatrix;
begin
// solves the System: A * x = b
// whereas A is the matrix stored in self, and be is the matrix in Value
// The result is a matrix having the size of Value.
CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned');
CheckAndRaiseError((fSubWidth = fSubHeight) and (Value.fSubHeight = fSubHeight), 'Dimension error');
Result := ResultClass.Create(Value.fSubWidth, fSubHeight);
try
if MatrixLinEQSolve(StartElement, LineWidth, fSubWidth, Value.StartElement, Value.LineWidth, Result.StartElement,
Result.LineWidth, Value.fSubWidth, numRefinements, fLinEQProgress) = leSingular
then
raise ELinEQSingularException.Create('Matrix is singular');
except
FreeAndNil(Result);
raise;
end;
end;
function TDoubleMatrix.SolveLinEQ(Value: IMatrix;
numRefinements: integer): TDoubleMatrix;
begin
Result := SolveLinEQ(Value.GetObjRef, numRefinements);
end;
procedure TDoubleMatrix.SolveLinEQInPlace(Value: IMatrix;
numRefinements: integer);
begin
SolveLinEQInPlace(Value.GetObjRef, numRefinements);
end;
procedure TDoubleMatrix.SolveLinEQInPlace(Value: TDoubleMatrix; numRefinements : integer);
var dt : TDoubleMatrix;
begin
// solves the System: A * x = b
// whereas A is the matrix stored in self, and be is the matrix in Value
// The result is a matrix having the size of Value.
CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned');
CheckAndRaiseError((fSubWidth = fSubHeight) and (Value.fSubHeight = fSubHeight), 'Dimension error');
dt := ResultClass.Create(Value.fSubWidth, fSubHeight);
try
if MatrixLinEQSolve(StartElement, LineWidth, fSubWidth, Value.StartElement, Value.LineWidth, dt.StartElement,
dt.LineWidth, Value.fSubWidth, numRefinements, fLinEQProgress) = leSingular
then
raise ELinEQSingularException.Create('Matrix is singular');
TakeOver(dt);
finally
dt.Free;
end;
end;
function TDoubleMatrix.SQRT: TDoubleMatrix;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned');
Result := ResultClass.Create;
Result.Assign(Self, True);
MatrixSQRT(Result.StartElement, Result.LineWidth, Result.Width, Result.Height);
end;
procedure TDoubleMatrix.SQRTInPlace;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned');
MatrixSQRT(StartElement, LineWidth, fSubWidth, fSubHeight);
end;
function TDoubleMatrix.Eig(out EigVals, EigVect: IMatrix; normEigVecs : boolean = False): TEigenvalueConvergence;
var outEigVals, outEigVect : TDoubleMatrix;
begin
Result := Eig(outEigVals, outEigVect, normEigVecs);
EigVals := outEigVals;
EigVect := outEigVect;
end;
function TDoubleMatrix.Eig(out EigVals: IMatrix): TEigenvalueConvergence;
var outEigVals : TDoubleMatrix;
begin
Result := Eig(outEigVals);
EigVals := outEigVals;
end;
function TDoubleMatrix.Eig(out EigVals: TDoublematrix): TEigenvalueConvergence;
var dt : TDoubleMatrix;
pReal, pImag : PDouble;
dummy : TDoubleMatrix;
perm : TIntegerDynArray;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight = fSubWidth), 'Eigenvalues are only defined for square matrices');
EigVals := nil;
dt := ResultClass.Create(2, fSubHeight);
pReal := dt.StartElement;
pImag := pReal;
inc(pImag);
dummy := TDoubleMatrix.Create;
dummy.Assign(self);
SetLength(perm, fSubWidth);
MatrixHessenbergPerm(dummy.StartElement, dummy.LineWidth, StartElement, LineWidth, fSubWidth, @perm[0], sizeof(integer));
Result := MatrixEigHessenbergInPlace(dummy.StartElement, dummy.LineWidth, fSubWidth, pReal, dt.LineWidth, pImag, dt.LineWidth);
dummy.Free;
if Result = qlOk
then
EigVals := dt
else
dt.Free;
end;
function TDoubleMatrix.Eig(out EigVals, EigVect: TDoubleMatrix; normEigVecs : boolean = False): TEigenvalueConvergence;
var dt : TDoubleMatrix;
vecs : TDoubleMatrix;
pReal, pImag : PDouble;
dummy : TDoubleMatrix;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight = fSubWidth), 'Eigenvalues are only defined for square matrices');
EigVals := nil;
EigVect := nil;
dt := nil;
vecs := nil;
try
dt := ResultClass.Create(2, fSubHeight);
pReal := dt.StartElement;
pImag := pReal;
inc(pImag);
vecs := ResultClass.Create(fSubWidth, fSubHeight);
// create a copy since the original content is destroyed!
dummy := TDoubleMatrix.Create;
try
dummy.Assign(self);
Result := MatrixUnsymEigVecInPlace(dummy.StartElement, dummy.LineWidth,
fSubWidth,
pReal, dt.LineWidth, pImag, dt.LineWidth,
vecs.StartElement, vecs.LineWidth,
True);
finally
dummy.Free;
end;
if Result = qlOk then
begin
if normEigVecs then
MatrixNormEivecInPlace(vecs.StartElement, vecs.LineWidth, fSubWidth, pImag, dt.LineWidth);
EigVals := dt;
EigVect := vecs;
end
else
begin
dt.Free;
vecs.Free;
end;
except
dt.Free;
vecs.Free;
raise;
end;
end;
function TDoubleMatrix.ElementwiseFunc(func: TMatrixFunc): TDoubleMatrix;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned');
Result := ResultClass.Create;
Result.Assign(self);
MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func);
end;
procedure TDoubleMatrix.ElementwiseFuncInPlace(func: TMatrixFunc);
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned');
MatrixFunc(StartElement, LineWidth, fSubWidth, fSubHeight, func);
end;
function TDoubleMatrix.ElementwiseFunc(func: TMatrixObjFunc): TDoubleMatrix;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned');
Result := ResultClass.Create;
Result.Assign(self);
MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func);
end;
procedure TDoubleMatrix.ElementwiseFuncInPlace(func: TMatrixObjFunc);
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned');
MatrixFunc(StartElement, LineWidth, fSubWidth, fSubHeight, func);
end;
function TDoubleMatrix.ElementwiseFunc(func: TMatrixMtxRefFunc): TDoubleMatrix;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned');
Result := ResultClass.Create;
Result.Assign(self);
MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func);
end;
function TDoubleMatrix.ElementwiseFunc(func: TMatrixMtxRefObjFunc): TDoubleMatrix;
begin
CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned');
Result := ResultClass.Create;