forked from mikerabat/mrmath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinearAlgebraicEquations.pas
2793 lines (2370 loc) · 93.8 KB
/
LinearAlgebraicEquations.pas
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 LinearAlgebraicEquations;
// ############################################
// #### Functions to solve linear algebraic equations
// ############################################
interface
uses SysUtils, Types, MatrixConst, OptimizedFuncs;
// solves the matrix A*X = B where A*x1=b1, A*x2=b2, ... A*xm=bm
// The function stores in A the inverse of A and B stores the result vectors
// A must be a square matrix (width*width) and B must be m*width.
function MatrixGaussJordanInPlace(A : PDouble; const LineWidthA : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; width : TASMNativeInt;
m : TASMNativeInt; const epsilon : double = 1e-20; progress : TLinEquProgress = nil) : TLinEquResult;
function MatrixGaussJordan(A : PDouble; const LineWidthA : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt;
invA : PDouble; const LineWidthInvA : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt;
width : TASMNativeInt; m : TASMNativeInt; const epsilon : double = 1e-20; progress : TLinEquProgress = nil) : TLinEquResult;
// interface functions (used in different parts - don't call them directly)
procedure LUSwap(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; k1, k2 : TASMNativeInt; indx : PIntegerArray; var parity : TASMNativeInt);
procedure LUBacksup(A : PDouble; width, height : TASMNativeInt; B : PDouble; const LineWidth : TASMNativeInt);
// inplace LU decomposition of the matrix A. Diagonal elements of the lower triangular matrix are set to one
// thus the diagonal elements of the resulting matrix A are composed from the upper diagonal elements only.
// The index records the row permutation effected by the partial pivoting.
function MatrixLUDecompInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; indx : PIntegerArray; progress : TLinEquProgress = nil) : TLinEquResult;
function MatrixLUDecomp(A : PDouble; const LineWidthA : TASMNativeInt; LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; indx : PIntegerArray; progress : TLinEquProgress = nil) : TLinEquResult; overload;
function MatrixLUDecomp(A : PDouble; const LineWidthA : TASMNativeInt; LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TLinEquResult; overload;
procedure MatrixLUBackSubst(LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; const indx : PIntegerArray; B : PDouble; const LineWidthB : TASMNativeInt; progress : TLinEquProgress = nil);
// inverse of a matrix by using the LU decomposition
function MatrixInverseInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TLinEquResult;
// Matrix determinant calculated from the LU decomposition. Returns zero in case of a singular matrix. Drawback is a double
// memory usage since the LU decomposition must be stored in a temporary matrix.
function MatrixDeterminant(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : double;
// Matrix Line Equation Solver routines which are based on LU decomposition.
// note these functions use temporarily double the size of A memory.
// The result is stored in X. B and X must have the same size, also B may have
// more than one column.
function MatrixLinEQSolve(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt;
Width2 : TASMNativeInt; const NumRefinments : TASMNativeInt = 0; progress : TLinEquProgress = nil) : TLinEquResult;
// Inplace svd decomposition of a Matrix A
// The output is the computation of A= U*W*V' whereas U is stored in A, and W is a vector 0..Width-1. The matrix V (not V') must be as large as Width*Width!
function MatrixSVDInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; Height : TASMNativeInt; W : PDouble; const LineWidthW : TASMNativeInt;
V : PDouble; const LineWidthV : TASMNativeInt; progress : TLinEquProgress = nil) : TSVDResult;
function MatrixSVD(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; Height : TASMNativeInt;
U : PDouble; const LineWidthU : TASMNativeInt; W : PDouble; const LineWidthW : TASMNativeInt;
V : PDouble; const LineWidthV : TASMNativeInt; progress : TLinEquProgress = nil) : TSVDResult;
// Inplace Cholesky decomposition of the matrix A (A=L*L'). A must be a positive-definite symmetric matrix.
// The cholesky factor L is returned in the lower triangle of a, except for its diagonal elements which are returned in p
function MatrixCholeskyInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; P : PDouble; LineWidthP : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult;
function MatrixCholesky(dest : PDouble; const LineWidthDest : TASMNativeInt; A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt;
P : PDouble; const LineWidthP : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult;
// solves the set of linear equations Ax = b where A is a positive-definite symmetric matrix. A and P are input as the output of
// MatrixCholeskyInPlace. Only the lower triangle is accessed. The result is stored in X, thus the routine can be called multiple
// times. B and X can point to the same memory!
procedure MatrixCholeskySolveLinEq(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; P : PDouble;
const LineWidthP : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt; progress : TLinEquProgress = nil);
// Linpack version of cholesky decomposition
function MatrixCholeskyInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult;
function MatrixCholeskyInPlace3(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult;
function MatrixCholeskyInPlace4(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; pnlSize : TASMNativeInt; progress : TLinEquProgress = nil) : TCholeskyResult;
// original functions from Numerical Recipies:
// In place QR decomposition. Constructs the QR decomposition of A (n*n). The upper triangle matrix R is returned
// in the upper triangle of a, except for the diagonal elements of R which are returned in
// d. The orthogonal matrix Q is represented as a product of n-1 Householder matrices Q1...Qn-1, where
// Qj = 1 - uj*(uj/cj). The ith component of uj is zero for i = 1..j-1 while the nonzero components are returned
// in a[i][j] for i = j...n . False is returned if no singularity was detected
function MatrixQRDecompInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC : TASMNativeInt;
D : PDouble; const LineWidthD : TASMNativeInt; progress : TLinEquProgress = nil) : TQRResult;
function MatrixQRDecomp(dest : PDouble; const LineWidthDest : TASMNativeInt; A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt;
C : PDouble; const LineWidthC : TASMNativeInt; D : PDouble; const LineWidthD : TASMNativeInt; progress : TLinEquProgress = nil) : TQRResult;
// solves the System A*x = b. The input paramaters are the output parameters from the QR decomposition.
// b is the matrix right hand side and will be overwritten by the result x.
procedure MatrixQRSolveLinEq(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; C : PDouble; const LineWidthC : TASMNativeInt;
D : PDouble; const LineWidthD : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; progress : TLinEquProgress = nil);
// implementation of Lapack's blocked QR decomposition
// the upper triangle matrix R is returned in the upper triangle of A. The elements below the
// diagonal with the array TAU, represent the orthogonal matrix Q as a product of elementary reflectors.
// further details: The matrix Q is represented as a product of elementary reflectors
// Q = H(1) H(2) . . . H(k), where k = min(m,n).
// Each H(i) has the form
// H(i) = I - tau * v * v**T
// where tau is a real scalar, and v is a real vector with
// v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i),
// and tau in TAU(i).
// note the matrix above starts with index 1 instead of 0.
// the output is the same as the matlab economy size output on a QR decomposition e.g. dcmp = qr(A, 0);
function MatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; progress : TLinEquProgress = nil) : TQRResult; overload;
function MatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; work : PDouble; pnlSize : TASMNativeInt; progress : TLinEquProgress = nil) : TQRResult; overload;
// implementation of Lapacks dorgqr function: On start the matrix A and Tau contains the result of
// the MatrixQRDecompInPlace2 function (economy size QR Decomposition). On output A is replaced by the full Q
// matrix with orthonormal columns.
procedure MatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; progress : TLinEquProgress = nil); overload;
procedure MatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; BlockSize : TASMNativeInt; work : PDouble; progress : TLinEquProgress = nil); overload;
// Pseudoinversion - implementation taken from matlab
// X = pinv(A) produces a matrix X of the same dimensions
// as A' so that A*X*A = A, X*A*X = X and A*X and X*A
// are Hermitian. The computation is based on SVD(A) and any
// singular values less than a tolerance are treated as zero.
// The default tolerance is MAX(SIZE(A)) * NORM(A) * EPS(class(A))
// Note the Matrix in X is also used in the calculations, thus it's content is destroyed!
// dest must be at least as big as the transposed of X
function MatrixPseudoinverse(dest : PDouble; const LineWidthDest : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt;
width, height : TASMNativeInt; progress : TLinEquProgress = nil) : TSVDResult;
// ######################################################
// #### internaly used objects and definitions
type
TLinearEQProgress = class(TObject)
public
refProgress : TLinEquProgress;
numRefinenmentSteps : TASMNativeInt;
procedure LUDecompSolveProgress(Progress : integer);
procedure RefinementProgress(Progress : integer);
end;
// ###########################################
// #### only for internal use
// ###########################################
type
TRecMtxQRDecompData = record
pWorkMem : PByte;
work : PDouble;
LineWidthWork : TASMNativeInt;
BlkMultMem : PDouble;
Progress : TLinEquProgress;
qrWidth, qrHeight : TASMNativeInt;
actIdx : TASMNativeInt;
pnlSize : TASMNativeInt;
MatrixMultT1 : TMatrixBlockedMultfunc;
MatrixMultT2 : TMatrixBlockedMultfunc;
end;
function InternalMatrixQRDecompInPlace2(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; qrData : TRecMtxQRDecompData) : boolean;
procedure InternalBlkMatrixQFromQRDecomp(A : PDouble; const LineWidthA : TASMNativeInt; width, height : TASMNativeInt; tau : PDouble; qrData : TRecMtxQRDecompData);
function InternalBlkCholeskyInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; pnlSize : TASMNativeInt;
aMatrixMultT2Ex : TMatrixBlockedMultfunc; multMem : PDouble; progress : TLinEquProgress = nil) : TCholeskyResult;
implementation
uses Math, MathUtilFunc, ASMMatrixOperations,
SimpleMatrixOperations, BlockSizeSetup;
function MatrixPseudoinverse(dest : PDouble; const LineWidthDest : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt;
width, height : TASMNativeInt; progress : TLinEquProgress) : TSVDResult;
var doTranspose : boolean;
data : TDoubleDynArray;
UTranspose : TDoubleDynArray;
pData : PDouble;
lineWidthData : TASMNativeInt;
S, V : TDoubleDynArray;
lineWidthV : TASMNativeInt;
tolerance : double;
r : TASMNativeInt;
i : TASMNativeInt;
k, l : TASMNativeInt;
pUTranspose : PDouble;
res : TDoubleDynArray;
pRes : PDouble;
destOffset : TASMNativeInt;
begin
// pseudo inversion of a matrix: pinv(x) = x'*(x*x')^-1
// based on the matlab implementation:
// [u s v] = svd(x, 0)
// s = diag(S);
// tol = max(m,n) * eps(max(s));
// r = sum(s > tol);
// s = diag(ones(r,1)./s(1:r));
// X = V(:,1:r)*s*U(:,1:r)';
assert((width > 0) and (height > 0) and (lineWidthDest >= height*sizeof(double)), 'Dimension error');
doTranspose := width > height;
if doTranspose then
begin
data := MatrixTranspose(X, LineWidthX, width, height);
pData := @data[0];
lineWidthData := height*sizeof(double);
Result := MatrixPseudoinverse(X, LineWidthX, pData, lineWidthData, height, width);
MatrixTranspose(dest, LineWidthDest, x, LineWidthX, width, height);
exit;
end;
SetLength(S, width);
SetLength(V, sqr(width));
lineWidthV := width*sizeof(double);
Result := MatrixSVDInPlace(X, lineWidthX, width, height, @S[0], sizeof(double), @V[0], lineWidthV, progress);
if Result = srNoConvergence then
exit;
tolerance := height*eps(MatrixMax(@S[0], width, 1, width*sizeof(double)));
r := 0;
for i := 0 to width - 1 do
begin
if s[i] > tolerance then
inc(r)
end;
if r = 0 then
begin
// set all to zero
destOffset := LineWidthDest - height*sizeof(double);
for k := 0 to width - 1 do
begin
for l := 0 to height - 1 do
begin
dest^ := 0;
inc(dest);
end;
inc(PByte(dest), destOffset);
end;
end
else
begin
// invert
for i := 0 to width - 1 do
begin
if s[i] > tolerance
then
s[i] := 1/s[i]
else
s[i] := 0;
end;
UTranspose := MatrixTranspose(X, LineWidthX, width, height);
pUTranspose := @UTranspose[0];
for k := 0 to width - 1 do
begin
for l := 0 to height - 1 do
begin
pUTranspose^ := pUTranspose^*s[k];
inc(pUTranspose);
end;
end;
res := MatrixMult(@V[0], @UTranspose[0], width, width, height, width, width*sizeof(double), height*sizeof(double));
V := nil;
UTranspose := nil;
s := nil;
// copy
pRes := @res[0];
for k := 0 to width - 1 do
begin
Move(pRes^, dest^, sizeof(double)*height);
inc(PByte(dest), LineWidthDest);
inc(PByte(pRes), sizeof(double)*height);
end;
end;
end;
function MatrixGaussJordan(A : PDouble; const LineWidthA : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt;
invA : PDouble; const LineWidthInvA : TASMNativeInt; X : PDouble; const LineWidthX : TASMNativeInt;
width : TASMNativeInt; m : TASMNativeInt; const epsilon : double; progress : TLinEquProgress) : TLinEquResult;
var i: TASMNativeInt;
pInvA : PDouble;
PX : PDouble;
begin
Assert(width > 0, 'Dimension Error');
Assert(lineWidthInvA >= width*sizeof(double), 'Dimension error');
Assert(lineWidthX >= sizeof(double), 'Dimension error');
// copy data -> now we can perform an inline gauss elimination procedure
PInvA := invA;
PX := X;
for i := 0 to width - 1 do
begin
Move(A^, PInvA^, sizeof(double)*width);
inc(PByte(PInvA), LineWidthInvA);
inc(PByte(A), LineWidthA);
Move(B^, PX^, sizeof(double)*m);
inc(PByte(B), LineWidthB);
inc(PByte(PX), LineWidthX);
end;
Result := MatrixGaussJordaninPlace(invA, lineWidthInvA, X, LineWidthX, width, m, epsilon, progress);
end;
function MatrixGaussJordanInPlace(A : PDouble; const LineWidthA : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt;
width : TASMNativeInt; m : TASMNativeInt; const epsilon : double; progress : TLinEquProgress) : TLinEquResult;
var i, icol, irow, j, k, l, ll : TASMNativeInt;
big, dum, pivinv : double;
indxc, indxr, ipiv : Array of integer;
pVal1 : PDouble;
pVal2 : PDouble;
begin
assert(LineWidthA >= width*sizeof(double), 'Dimension error');
assert(LineWidthB >= m*sizeof(double), 'Dimension error');
Result := leOk;
SetLength(indxc, width);
SetLength(indxr, width);
SetLength(ipiv, width);
icol := 0;
irow := 0;
if Assigned(progress) then
progress(0);
for j := 0 to width - 1 do
ipiv[j] := 0;
// main loop over the columns to be reduced
for i := 0 to width - 1 do
begin
big := 0;
for j := 0 to width - 1 do
begin
if ipiv[j] <> 1 then
begin
for k := 0 to width - 1 do
begin
if ipiv[k] = 0 then
begin
pVal1 := PDouble(PAnsiChar(A) + j*LineWidthA);
inc(pVal1, k);
if abs(pVal1^) >= big then
begin
big := abs(pVal1^);
irow := j;
icol := k;
end;
end
else if ipiv[k] > 1 then
begin
Result := leSingular;
exit;
end;
end;
end;
end;
inc(ipiv[icol]);
// we now have the pivot element, so we interchange rows, if needed, to put the pivot
// element on the dagonal.
if irow <> icol then
begin
pVal1 := PDouble(PAnsiChar(A) + irow*LineWidthA);
pVal2 := PDouble(PAnsiChar(A) + icol*LineWidthA);
for l := 0 to width - 1 do
begin
DoubleSwap(pVal1^, pVal2^);
inc(pVal1);
inc(pVal2);
end;
pVal1 := PDouble(PAnsiChar(B) + irow*LineWidthB);
pVal2 := PDouble(PAnsiChar(B) + icol*LineWidthB);
for l := 0 to m - 1 do
begin
DoubleSwap(pVal1^, pVal2^);
inc(pVal1);
inc(pVal2);
end;
end;
// we are now ready to divide the pivot row by the pivot element, located in irow and icol
indxr[i] := irow;
indxc[i] := icol;
pVal1 := PDouble(PAnsiChar(A) + icol*LineWidthA);
inc(pVal1, icol);
if abs(pVal1^) < epsilon then
begin
Result := leSingular;
exit;
end;
pivinv := 1/pVal1^;
pVal1^ := 1;
pVal1 := PDouble(PAnsiChar(A) + icol*LineWidthA);
for l := 0 to width - 1 do
begin
pVal1^ := pVal1^*pivinv;
inc(pVal1);
end;
pVal1 := PDouble(PAnsiChar(B) + icol*LineWidthB);
for l := 0 to m - 1 do
begin
pVal1^ := Pivinv*pVal1^;
inc(pVal1);
end;
for ll := 0 to width - 1 do
begin
if ll <> icol then
begin
pVal1 := PDouble(PAnsiChar(A) + ll*LineWidthA);
inc(pVal1, icol);
dum := pVal1^;
pVal1^ := 0;
pVal1 := PDouble(PAnsiChar(A) + ll*LineWidthA);
pVal2 := PDouble(PAnsiChar(A) + icol*LineWidthA);
for l := 0 to width - 1 do
begin
pVal1^ := pVal1^ - pVal2^*dum;
inc(pVal1);
inc(pVal2);
end;
pVal1 := PDouble(PAnsiChar(B) + ll*LineWidthB);
pVal2 := PDouble(PAnsiChar(B) + icol*LineWidthB);
for l := 0 to m - 1 do
begin
pVal1^ := pVal1^ - pVal2^*dum;
inc(pVal1);
inc(pVal2);
end;
end;
end;
if Assigned(progress) then
progress(100*i div width);
end;
for l := width - 1 downto 0 do
begin
if indxr[l] <> indxc[l] then
begin
for k := 0 to width - 1 do
begin
pVal1 := PDouble(PAnsiChar(A) + k*LineWidthA);
pVal2 := pVal1;
inc(pval1, indxr[l]);
inc(pval2, indxc[l]);
DoubleSwap(pVal1^, pVal2^);
end;
end;
end;
if Assigned(progress) then
progress(100);
end;
// LUSWAP performs a series of row interchanges on the matrix A.
// One row interchange is initiated for each of rows K1 through K2 of A.
procedure LUSwap(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; k1, k2 : TASMNativeInt; indx : PIntegerArray; var parity : TASMNativeInt);
var i : TASMNativeInt;
pA1, pA2 : PDouble;
begin
for i := k1 to k2 do
begin
if indx^[i] <> i then
begin
// interchange rows
pA1 := A;
inc(PByte(pA1), i*LineWidthA);
pA2 := A;
inc(PByte(pA2), indx^[i]*LineWidthA);
// swap a complete row at once
MatrixRowSwap(pA1, pA2, width);
parity := -parity;
end;
end;
end;
procedure LUBacksup(A : PDouble; width, height : TASMNativeInt; B : PDouble; const LineWidth : TASMNativeInt);
var j, i, k : TASMNativeInt;
pA, pAi : PDouble;
pB, pBj : PDouble;
pBDest, pBDestj, pBDesti : PDouble;
begin
pA := A;
inc(PByte(pA), LineWidth);
pB := B;
pBDest := B;
inc(PByte(pBDest), LineWidth);
for k := 0 to height - 1 do
begin
pAi := pA;
pBDesti := pBDest;
for i := k + 1 to height - 1 do
begin
pBj := pB;
pBDestj := pBDesti;
for j := 0 to width - 1 do
begin
pBDestj^ := pBDestj^ - pBj^*pAi^;
inc(pBj);
inc(pBDestj);
end;
inc(PByte(pAi), LineWidth);
inc(PByte(pBDesti), LineWidth);
end;
inc(pA);
inc(PByte(pA), LineWidth);
inc(PByte(pB), LineWidth);
inc(PByte(pBDest), LineWidth);
end;
end;
const cBlkMultSize = 48;
type
TRecMtxLUDecompData = record
progress : TLinEquProgress;
numCols,
numCalc : TASMNativeInt;
blkMultMem : Pdouble;
LineWidth : TASMNativeInt;
end;
function InternalRecursiveMatrixLUDecompInPlace(A : PDouble; width, height : TASMNativeInt;
indx : PIntegerArray; var parity : TASMNativeInt; var data : TRecMtxLUDecompData) : TLinEquResult;
var mn : TASMNativeInt;
pA : PDouble;
idx : TASMNativeInt;
maxVal : double;
nleft, nright : TASMNativeInt;
i : TASMNativeInt;
pB, a12, a21 : PDouble;
absMaxVal : double;
begin
mn := min(width, height);
if mn > 1 then
begin
nleft := mn div 2;
nright := width - nleft;
Result := InternalRecursiveMatrixLUDecompInPlace(A, nLeft, height, indx, parity, data);
if Result <> leOk then
exit;
pA := A;
inc(pA, nLeft);
LUSwap(pA, data.LineWidth, nright, 0, nleft - 1, indx, parity);
// lu backsup A12 = L - one*A12
if nRight > 1 then
LUBacksup(A, nRight, nLeft, pA, data.LineWidth);
// matrix mult sub
// A22 = A22 - A21*A12
pB := A;
inc(pB, nleft);
a12 := pB;
inc(PByte(pB), nLeft*data.LineWidth);
a21 := A;
inc(PByte(a21), nleft*data.LineWidth);
// in this case it's faster to have a small block size!
if (nright > cBlkMultSize) or (height - nleft > cBlkMultSize)
then
BlockedMatrixMultiplication(pB, data.LineWidth, a21, a12, nleft, height - nleft, nright, nleft, data.LineWidth, data.LineWidth, cBlkMultSize, doSub, data.blkMultMem)
else
begin
MatrixMult(data.blkMultMem, (nright + nright and $01)*sizeof(double), a21, a12, nleft, height - nleft, nright, nleft, data.LineWidth, data.LineWidth);
MatrixSub(pB, data.LineWidth, pB, data.blkMultMem, nright, height - nleft, data.LineWidth, (nright + nright and $01)*sizeof(double));
end;
// apply recursive LU to A(nleft + 1, nleft + 1);
Result := InternalRecursiveMatrixLUDecompInPlace(pB, nright, height - nleft, @(indx^[nleft]), parity, data);
if Result <> leok then
exit;
for i := nLeft to width - 1 do
indx^[i] := indx^[i] + nLeft;
// dlswap
LUSwap(A, data.LineWidth, nleft, nleft, mn - 1, indx, parity);
end
else
begin
// find maximum element of this column
maxVal := 0;
absMaxVal := 0;
idx := -1;
pA := A;
for i := 0 to Height - 1 do
begin
if Abs(pA^) > absMaxVal then
begin
idx := i;
maxVal := pA^;
absMaxVal := abs(maxVal);
end;
inc(PByte(pA), data.LineWidth);
end;
// now it's time to apply the gauss elimination
indx^[0] := idx;
// check for save invertion of maxVal
if Abs(maxVal) > 10/MaxDouble then
begin
MatrixScaleAndAdd(A, data.LineWidth, 1, Height, 0, 1/maxVal);
pA := A;
inc(PByte(pA), data.LineWidth*idx);
pA^ := A^;
A^ := maxVal;
Result := leOk;
if Assigned(data.progress) then
begin
inc(data.numCalc);
data.progress(data.numCalc*100 div data.numCols);
end;
end
else
Result := leSingular;
end;
end;
function MatrixLUDecompInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; indx : PIntegerArray; progress : TLinEquProgress) : TLinEquResult;
var parity : TASMNativeInt;
mem : Array[0..(4+4*cBlkMultSize*cBlkMultSize)] of double;
rc : TRecMtxLUDecompData;
begin
FillChar(indx^, width*sizeof(integer), 0);
parity := 1;
rc.progress := progress;
rc.numCols := width;
rc.numCalc := 0;
rc.blkMultMem := PDouble(TASMNativeUInt(@mem[0]) + 16 - (TASMNativeUInt(@mem[0]) and $0F));
rc.LineWidth := LineWidthA;
Result := InternalRecursiveMatrixLUDecompInPlace(A, width, width, indx, parity, rc);
end;
function MatrixLUDecomp(A : PDouble; const LineWidthA : TASMNativeInt; LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; indx : PIntegerArray; progress : TLinEquProgress) : TLinEquResult;
begin
Assert(width > 0, 'Dimension Error');
// copy data -> now we can perform an inline LU decomposition
MatrixCopy(LUDecomp, LineWidthLU, A, LineWidthA, width, width);
Result := MatrixLUDecompInPlace(LUDecomp, lineWidthLU, width, indx, progress);
end;
function MatrixLUDecomp(A : PDouble; const LineWidthA : TASMNativeInt; LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress) : TLinEquResult;
var indx : array of integer;
begin
Assert(width > 0, 'Dimension Error');
setLength(indx, width);
Result := MatrixLUDecomp(A, LineWidthA, LUDecomp, LineWidthLU, width, @indx[0], progress);
end;
procedure MatrixLUBackSubst(LUDecomp : PDouble; const LineWidthLU : TASMNativeInt; width : TASMNativeInt; const indx : PIntegerArray;
B : PDouble; const LineWidthB : TASMNativeInt; progress : TLinEquProgress);
var i : TASMNativeInt;
ii : TASMNativeInt;
ip : TASMNativeInt;
j : TASMNativeInt;
sum : double;
pB : PDouble;
pB2 : PDouble;
pVal : PDouble;
pVal2 : PDouble;
begin
assert(width*sizeof(double) <= LineWidthLU, 'Dimension Error');
if Assigned(progress) then
progress(0);
ii := -1;
pB2 := B;
for i := 0 to width - 1 do
begin
ip := indx^[i];
pB := B;
inc(PByte(pB), ip*LineWidthB);
sum := pB^;
pB^ := pB2^;
if ii >= 0 then
begin
pVal := PDouble(PAnsiChar(LUDecomp) + i*LineWidthLU);
inc(pVal, ii);
pB := B;
inc(PByte(pB), LineWidthB*ii);
for j := ii to i - 1 do
begin
sum := sum - pVal^*pB^;
inc(pVal);
inc(PByte(pB), LineWidthB);
end;
end
else if sum <> 0
then
ii := i;
pB2^ := sum;
inc(PByte(pB2), LineWidthB);
end;
if Assigned(progress) then
progress(50);
pB := B;
inc(PByte(pB), LineWidthB*(width - 1));
pVal := PDouble(PAnsiChar(LUDecomp) + (width - 1)*LineWidthLU);
inc(pVal, width - 1);
for i := width - 1 downto 0 do
begin
sum := pB^;
pB2 := pB;
inc(PByte(pB2), LineWidthB);
pVal2 := pVal;
inc(pVal2);
for j := i + 1 to width - 1 do
begin
sum := sum - pVal2^*pB2^;
inc(PByte(pB2), LineWidthB);
inc(pVal2);
end;
pB^ := sum/pVal^;
dec(pVal);
dec(PByte(pVal), LineWidthLU);
dec(PByte(pB), LineWidthB);
end;
if Assigned(progress) then
progress(100);
end;
function MatrixInverseInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress) : TLinEquResult;
var Y : PDouble;
indx : array of integer;
i, j : TASMNativeInt;
pVal : PDouble;
col : TDoubleDynArray;
w : TASMNativeInt;
begin
Assert(lineWidthA >= width*sizeof(double), 'Dimension Error');
Assert(width > 0, 'Dimension error');
w := width + width and $01;
Y := GetMemory(w*w*sizeof(double));
SetLength(indx, width);
SetLength(col, width);
MatrixCopy(Y, sizeof(double)*w, A, LineWidthA, width, width);
Result := MatrixLUDecompInPlace(Y, w*sizeof(double), width, @indx[0], progress);
if Result = leSingular then
begin
FreeMem(Y);
exit;
end;
for j := 0 to width - 1 do
begin
pVal := A;
inc(pVal, j);
for i := 0 to width - 1 do
col[i] := 0;
col[j] := 1;
MatrixLUBackSubst(Y, w*sizeof(double), width, @indx[0], @col[0], sizeof(double));
for i := 0 to width - 1 do
begin
pVal^ := col[i];
inc(PByte(pVal), LineWidthA);
end;
end;
FreeMem(Y);
end;
function MatrixDeterminant(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; progress : TLinEquProgress) : double;
var LUDecomp : PDouble;
indx : Array of Integer;
i : TASMNativeInt;
pVal : PDouble;
parity : TASMNativeInt;
rc : TRecMtxLUDecompData;
w : TASMNativeInt;
mem : Array[0..(4+4*cBlkMultSize*cBlkMultSize)] of double;
begin
assert(width > 0, 'Dimension error');
assert(LineWidthA >= width*sizeof(double), 'Dimension error');
w := width + width and $01;
LUDecomp := GetMemory(w*w*sizeof(double));
SetLength(indx, width);
MatrixCopy(LUDecomp, w*sizeof(double), A, LineWidthA, width, width);
rc.progress := progress;
rc.numCols := width;
rc.numCalc := 0;
rc.blkMultMem := PDouble(TASMNativeUInt(@mem[0]) + 16 - TASMNativeUInt(@mem[0]) and $0F);
rc.LineWidth := w*sizeof(double);
parity := 1;
if InternalRecursiveMatrixLUDecompInPlace(LUDecomp, width, width, @indx[0], parity, rc) = leSingular then
begin
Result := 0;
FreeMem(LUDecomp);
exit;
end;
pVal := LUDecomp;
Result := parity;
for i := 0 to width - 1 do
begin
Result := Result * pVal^;
inc(pVal);
inc(PByte(pVal), w*sizeof(double));
end;
FreeMem(LUDecomp);
end;
{ TLinearEQProgress }
procedure TLinearEQProgress.LUDecompSolveProgress(Progress: integer);
begin
if numRefinenmentSteps > 0
then
refProgress(progress*8 div 10)
else
refProgress(progress);
end;
procedure TLinearEQProgress.RefinementProgress(Progress: integer);
begin
refProgress(80 + 2*progress div 10);
end;
function MatrixLinEQSolve(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; B : PDouble; const LineWidthB : TASMNativeInt; X : PDouble;
const LineWidthX : TASMNativeInt; Width2 : TASMNativeInt; const NumRefinments : TASMNativeInt; progress : TLinEquProgress) : TLinEquResult;
var indx : Array of Integer;
LUDecomp : TDoubleDynArray;
sdp : double;
row : TDoubleDynArray;
pB : PDouble;
i : TASMNativeInt;
pA : PDouble;
j, k : TASMNativeInt;
pX : PDouble;
pVal : PDouble;
refinementCounter : TASMNativeInt;
progObj : TLinearEQProgress;
progRef : TLinEquProgress;
begin
progRef := nil;
progObj := nil;
if Assigned(progress) then
begin
progObj := TLinearEQProgress.Create;
progObj.refProgress := progress;
progObj.numRefinenmentSteps := NumRefinments;
progRef := {$IFDEF FPC}@{$ENDIF}progObj.LUDecompSolveProgress;
end;
// ###########################################
// #### Standard LU Decomposition
SetLength(LUDecomp, width*width);
SetLength(indx, width);
Result := MatrixLUDecomp(A, LineWidthA, @LUDecomp[0], width*sizeof(double), width, @indx[0], progRef);
if Result = leSingular then
begin
progObj.Free;
exit;
end;
for i := 0 to width2 - 1 do
begin
// copy one column
pX := X;
inc(pX, i);
pVal := B;
inc(pVal, i);
for j := 0 to width - 1 do
begin
pX^ := pVal^;
inc(PByte(pX), LineWidthX);
inc(PByte(pVal), LineWidthB);
end;
pX := X;
inc(pX, i);
// calculate vector X
MatrixLUBackSubst(@LUDecomp[0], width*sizeof(double), width, @indx[0], pX, LineWidthX);
end;
// ###########################################
// #### Iterative refinements
if NumRefinments > 0 then
begin
SetLength(row, width);
// for each solution do a separate refinement:
for k := 0 to width2 - 1 do
begin
if Assigned(progobj) then
progObj.RefinementProgress(Int64(k)*100 div Int64(width2));
for refinementCounter := 0 to NumRefinments - 1 do
begin
pb := B;
pA := A;
for i := 0 to width - 1 do
begin
pVal := pA;
sdp := -pB^;
inc(PByte(pB), LineWidthB);
pX := X;
for j := 0 to width - 1 do
begin
sdp := sdp + pX^*pVal^;
inc(pVal);
inc(pX);
end;
inc(PByte(pA), LineWidthA);
row[i] := sdp;
end;
MatrixLUBackSubst(@LUDecomp[0], sizeof(double)*width, width, @indx[0], @row[0], sizeof(double));
pX := X;
for i := 0 to width - 1 do
begin
pX^ := pX^ - row[i];
inc(PByte(pX), LineWidthX);
end;
end;
inc(B);
inc(X);
end;
end;
if Assigned(progObj) then
progObj.Free;
if Assigned(progress) then
progress(100);
end;
function MatrixSVDInPlace(A : PDouble; const LineWidthA : TASMNativeInt; width : TASMNativeInt; Height : TASMNativeInt; W : PDouble; const LineWidthW : TASMNativeInt;
V : PDouble; const LineWidthV : TASMNativeInt; progress : TLinEquProgress) : TSVDResult;
const cMaxNumSVDIter = 75;
var flag : boolean;
i, j, jj, k, l : TASMNativeInt;