-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLSODA4cc.pas
4961 lines (4428 loc) · 135 KB
/
LSODA4cc.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
unit LSODA4cc;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
// LSODA reconstructed for ChainCalculator
// The same as original but has pointer to OBJECT function - TChainCalculator.DoChainCalc
{ Routines painfully converted from 'C' BLAS routines }
{ H M Sauro, December 1996 }
interface
uses Classes, SysUtils, EuLibMin;
//type
// double=double;
{Unit Vector}
{ Implements dynamic vector type, integer and Double, Summer 1996 H M Sauro
Copyright 1996/97 Future Skill Software }
// September 1997
{ Available functions for Double vector:
EnlargeBy Enlarge vector by n elements
ReduceBy Reduce vector by n elements
Enlarge Enlarge by one element (top element)
Reduce Reduce by one element (top element)
Zero Set all elemenets to 0.0
Clear Same as Zero
Size Get size of vector
Assign Assigns one vector to another (Copy function)
Add, Sub Add or subract two vectors to give Self
Dot Form the dot product
CrossU Form the cross product (self overwritten)
Cross Form the cross product
Sum Form sum of elements
Mean Form mean of elements
SumofSquares Form sum of squares of elements
StdDev Form sample standard deviation
Scale Scale vector by factor }
{ Example of use:
v : TVector;
v := TVector.Create (5);
for i := 1 to 5 do v[i] := i*2.3;
m := v.mean;
v.free; }
const
MaxIniVectorSize=1000;
type
EVectorSizeError=class(Exception);
{ The MaxIniVectorSize in the array types below does not impose a limit a runtime!
If you compile with range checking on then the compiled code will impose
an effective limit of MaxIniVectorSize, but with range checking off the size of
vector is limited to 64K under 16bit OS or *much* greater under 32bit OS }
TArrayd=array[1..MaxIniVectorSize] of Double; pTArrayd=^TArrayd;
TArrayi=array[1..MaxIniVectorSize] of integer; pTArrayi=^TArrayi;
{ Define a dynamic array type for holding integers }
TVectori=class(TObject)
private
s: integer; { size of vector }
vx: pTArrayi; { pointer to the data }
private
procedure SetSize(NewSize: integer);
public
constructor create(i: integer); virtual;
constructor CreateFromLongIntList(const Src: TLongIntList);
destructor destroy; override;
procedure EnlargeBy(n: integer);
procedure ReduceBy(n: integer);
procedure Enlarge;
procedure Reduce;
procedure Zero;
procedure Clear;
procedure Assign(v: TVectori);
procedure Setval(i: integer; v: integer);
function Getval(ii: integer): integer;
function GetSize: integer;
property Elem[x: Integer]: integer read GetVal write SetVal; default;
property Size: integer read s;
end;
{ Define a dynamic array type for holding Doubles }
TVector=class(TObject)
private
s: integer; { size of vector }
vx: pTArrayd; { pointer to the data }
Tmp: boolean; { set to true if temporary }
public
{ Declare as a class method, saves having a self variable }
class function Dot(u, v: TVector): Double;
constructor CreateFromFloatList(const Src: TFloatList);
constructor create(i: integer); virtual;
constructor createTmp(i: integer);
destructor destroy; override;
procedure FreeSpace;
procedure SetSize(i: integer);
procedure EnlargeBy(n: integer);
procedure ReduceBy(n: integer);
procedure Enlarge;
procedure Reduce;
procedure Zero;
procedure Clear;
procedure Setval(i: integer; v: Double);
function Getval(ii: integer): Double;
property Elem[x: Integer]: Double read GetVal write SetVal; default;
property Size: integer read s;
procedure Assign(v: TVector);
function Add(v, u: TVector): TVector;
function Sub(v, u: TVector): TVector;
class function xAdd(v, u: TVector): TVector;
class function xSub(v, u: TVector): TVector;
function DotU(v: TVector): Double;
function CrossU(v: TVector): TVector;
function Cross(v1, v2: TVector): TVector;
function Sum: Double;
function Mean: Double;
function SumofSquares: Double;
function StdDev: Double;
procedure Scale(factor: Double);
end;
{Unit Mat}
const
MaxIniMatrixSize=50000; // Eu was 5000
type
EMatrixError=class(Exception);
EMatrixSizeError=class(EMatrixError);
ESingularMatrix=class(EMatrixError);
ENonSquareMatrix=class(EMatrixError);
TMatError=(Singular, NonSingular, NonSquare);
TMatElement=Double;
{ A Matrix is made up of a set of rows of type TRow, pTRow is
a pointer to a single row and a matrix is a row of pTRows, this
allows arrays larger then 65K to be built, the max size of
a matrix is roughly 4096 MBytes }
TRow=array[0..MaxIniMatrixSize] of TMatElement; pTRow=^TRow;
{ The TRows are collected together into a RowList }
TRowList=array[0..MaxIniMatrixSize] of pTRow;
{ Finally, pTRowList points to a RowList }
pTRowList=^TRowList;
{ forward declare the Matrix class }
TMatrix=class;
{ Used by svdfit, supplies basis functions at x }
BasisProc=procedure(x: TMatElement; var BasisFunc: TVector);
{ Define a dynamic matrix type for holding Doubles }
TMatrix=class(TObject)
private
nr, nc: integer;
mx: pTRowList; { pointer to a list of rows }
FRowNames, FColumnNames: TStringList;
procedure SetSize(ri, ci: integer);
procedure FreeSpace;
public
constructor create(r, c: integer); virtual;
constructor createI(n: integer); virtual;
constructor createLit(c: integer; d: array of TMatElement); virtual;
destructor destroy; override;
procedure CreateNameLists(ri, ci: integer);
procedure DestroyNameLists;
procedure Setval(ri, ci: integer; v: TMatElement);
function Getval(ri, ci: integer): TMatElement;
property M[x, y: Integer]: TMatElement read GetVal write SetVal; default;
procedure SetRowName(ri: integer; name: string);
function GetRowName(ri: integer): string;
procedure SetColumnName(ci: integer; name: string);
function GetColumnName(ci: integer): string;
property rName[ri: integer]: string read GetRowName write SetRowname;
property cName[ci: integer]: string read GetColumnName write SetColumnname;
property r: integer read nr;
property c: integer read nc;
function IsSquare(m: TMatrix): boolean;
function SameDimensions(m1, m2: TMatrix): boolean;
procedure AddRow;
function Identity: TMatrix;
function Diagonal(k: TMatElement): TMatrix;
function DiagonalV(v: TVector): TMatrix;
function Zero: TMatrix;
function L(ci: integer; d: array of TMatElement): TMatrix;
function transposeSelf: TMatrix;
function transpose(m: TMatrix): TMatrix;
function add(m1, m2: TMatrix): TMatrix;
function addU(m: TMatrix): TMatrix;
function sub(m1, m2: TMatrix): TMatrix;
function subU(m: TMatrix): TMatrix;
function multk(m: TMatrix; k: TMatElement): TMatrix;
function multkU(k: TMatElement): TMatrix;
function mult(m1, m2: TMatrix): TMatrix;
function copy(m: TMatrix): TMatrix;
procedure ExtractColumn(var v: TVector; cc: integer);
procedure ExtractRow(var v: TVector; rr: integer);
function ExchangeRows(r1, r2: integer): TMatrix;
function ExchangeCols(c1, c2: integer): TMatrix;
function Rank(echelon: TMatrix; eps: Double): integer;
procedure Invert(inv: TMatrix);
procedure InvertSelf;
procedure SolveLinear(v, b: TVector; SelfToInv: boolean);
procedure LUSolve(index: TVectori; b: TVector);
procedure LUDecomp(m: TMatrix; index: TVectori);
function Det: Double;
procedure NullSpace(NullVectors: TMatrix; var BasisSize: integer;
Echelon: TMatrix; var TheRank: integer);
procedure svd(var u: TMatrix; var w: TVector; var v: TMatrix);
procedure svd2(var u: TMatrix; var w: TVector; var v: TMatrix);
procedure svdSolve(var u: TMatrix; var w: TVector; var v: TMatrix;
b: TVector; var x: TVector);
function svdfit(x, y, yerr: TVector; var fit: TVector;
var u, v: TMatrix; var w: TVector; funcs: BasisProc): TMatElement;
procedure svdCovar(v: TMatrix; w: TVector; alpha: TMatrix);
end;
{ ------------------------------------------------------------------------- }
{Unit Lsodamat}
procedure LUfactor(a: TMatrix; pivots: TVectori);
procedure LUsolve(a: TMatrix; pivots: TVectori; b: TVector);
{unit adamsbdf.pas}
{ Lsoda differential equation solver Delphied. H M Sauro Dec 1996
Original Pascal translation by Joao Pedro Monij-Barreto and Ronny Shuster.
Original FORTRAN (version march30, 1987) to C translation by
From tam@dragonfly.wri.com Wed Apr 24 01:35:52 1991
Return-Path: <tam>
Date: Wed, 24 Apr 91 03:35:24 CDT
From: tam@dragonfly.wri.com
To: whitbeck@wheeler.wrc.unr.edu
Subject: lsoda.c
Cc: augenbau@sparc0.brc.uconn.edu
I'm told by Steve Nichols at Georgia Tech that you are interested in
a stiff integrator. Here's a translation of the fortran code LSODA.
Please note that there is no comment. The interface is the same as the FORTRAN
code and I believe the documentation in LSODA will suffice.
As usual, a free software comes with no guarantee.
Hon Wah Tam
Wolfram Research, Inc.
tam@wri.com
I have done some additions to lsoda.c . These were mainly to fill the
gap of some features that were available in the fortran code and were
missing in the C version.
Changes are: all messages printed by lsoda routines will start with
a '\n' (instead of ending with one); xsetf() was added so that user
can control printing of messages by lsoda. xsetf should be called before
calling lsoda: xsetf(0) switches printing off xsetf(1) swithces printing
on (default) this implies one new global variable prfl (print flag).
xsetf(0) will stop *any* printing by lsoda functions.
Turning printing off means losing valuable information but will not scramble
your stderr output ;-) This function is part of the original FORTRAN version.
xsetf() and intdy() are now callable from outside the library as assumed
in the FORTRAN version; created lsoda.h that should be included in blocks
calling functions in lsoda's library. iwork5 can now have an extra value:
0 - no extra printing (default), 1 - print data on each method switch,
-> 2 - print useful information at *each* stoda step (one lsoda call
has performs many stoda calls) and also data on each method switch
note that a xsetf(0) call will prevent any printing even if iwork5 > 0;
hu, tn were made available as extern variables.
eMail: INTERNET: prm@aber.ac.uk
Pedro Mendes, Dept. of Biological Sciences, University College of Wales,
Aberystwyth, Dyfed, SY23 3DA, United Kingdom.
Further minor changes: 10 June 1992 by H Sauro and Pedro Mendes }
{ This version in a Delphi compatible object by H M Sauro Dec 1996 }
{ -------------------------------------------------------------------------- }
{ Quick usage instructions:
1. Create Lsoda object specifying dimension of problem
2. Initialise rtol and atol arrays (error tolerances, relative and absolute)
3. Initialise t and tout (t = initial val, tout = requested solution point)
4. Set itol to 4
5. Set itask to 1, indicating normal computation
6. Set istart to 1, indicating first call to lsoda
7. Set iopt = 0 for no optional inputs
8. jt = 2 for internal evaluation of jacobian
9. Call Setfcn (fcn) to install your dydt routine
10. Call lsoda (y, t, tout) to perfom one iteration }
{ See lsoda.doc for further details of interface. There may be further changes to
this source in the future. The object interface is not neat enough yet, but it
does work, see included example. Also xome works needs to be done to the body }
{ Note on TVector. TVector implements a dynamic array type of Doubles. Use
v := TVector.Create (10) to create 10 element array. Access data via v[i].
v.size returns number of elements in vector. See vector.pas for more details }
{ Note on TMat. TMat is a simple matrix object type which serves a similar role
to TVector except of course TMatrix is a 2D version }
{ LsodaMat includes two routines for doing LU decomposition and backward-
substitution, painfully translated from FORTRAN code, couldn't use my own coz'
I think LSODA requires particular structure to LU result. These routines use a
TVectori type (included with vector.pas) which simply handles dynamics arrays of
integers }
{ Note to FORTRAN coders: please stop playing 'neat' tricks with arrays, it make
translating decent algorithms written in FORTRAN a hellish experience! }
type
ELsodaException=class(Exception);
{ This is the type for the dydt function }
fcnProc=procedure(t: Double; y, dydt: TVector) of object;
TErrorType=(eNone, eDerivative, eBuildAlphaBeta, eChiSqr, eDelta,
eNormalisation, eMatrixInversion, ePoorConvergence);
vector13=array[1..13] of Double; { Used in declaring pc in cfode }
{mat1314 = array [1..13,1..14] of Double;
mat134 = array [1..13,1..4] of Double;
vec14 = array[1..14] of double;
vec6 = array[1..6] of Double;
mat12ne = array[1..13] of TVector;}
TLsoda=class(TObject)
private
// EuAdd 2
neq: integer; { # of first-order odes }
fAborted: Boolean;
tn, h, hu, tsw, tolsf: Double;
// nje, nfe, prfl, nq, nqu, meth, mused, nst, imxer: integer; // EuConvert prfl->Fprfl
nje, nfe, Fprfl, nq, nqu, meth, mused, nst, imxer: integer;
{ static variables for lsoda() }
ccmax, el0, hmin, hmxi, rc, pdnorm: Double;
illin, init, mxstep, mxhnil, nhnil, ntrep,
nslast, nyh, ierpj, iersl, jcur, jstart, kflag, l,
miter, maxord, maxcor, msbp, mxncf, n,
ixpr, jtyp, mxordn, mxords: integer;
{ non-static variable for prja(), solsy() }
{ static variables for stoda() }
conit, crate, hold, rmax, pdest, pdlast, ratio: Double;
elco, tesco: TMatrix;
ialth, ipup, lmax, meo, nslp, icount, irflag: integer;
cm1, cm2, el: TVector;
{ static variables for various vectors and the Jacobian. }
yh: array[1..13] of TVector;
wm: TMatrix;
perm: TVectori; { Permuation vector for LU decomp }
ewt, savf, acor: TVector;
sqrteta: Double; { sqrt (ETA) }
Frtol, Fatol: TVector;
Fitol, Fitask, Fistate, Fiopt, Fjt, Fiwork5, Fiwork6: integer;
Fiwork7, Fiwork8, Fiwork9: integer;
Frwork1, Frwork5, Frwork6, Frwork7: Double;
FDerivatives: fcnProc;
procedure DummyFcn(t: Double; y, dydt: TVector);
procedure terminate(var istate: integer);
procedure terminate2(var y: TVector; var t: Double);
procedure successreturn(var y: TVector; var t: Double;
itask, ihit: integer; tcrit: Double; var istate: integer);
procedure ewset(itol: integer; rtol, atol, ycur: TVector);
procedure prja(neq: integer; var y: TVector);
procedure corfailure(var told, rh: Double; var ncf, corflag: integer);
procedure solsy(var y: TVector);
procedure methodswitch(dsm, pnorm: Double; var pdh, rh: Double);
procedure endstoda;
procedure orderswitch(var rhup: Double; dsm: Double; var pdh, rh: Double;
var orderflag: integer);
procedure resetcoeff;
procedure correction(neq: integer; var y: TVector; var corflag: integer;
pnorm: Double; var del, delp, told: Double;
var ncf: integer; var rh: Double; var m: integer);
procedure intdy(t: Double; k: integer; var dky: TVector; var iflag: integer);
procedure cfode(meth: integer);
procedure scaleh(var rh, pdh: Double);
procedure stoda(var neq: integer; var y: TVector);
function Getrtol(i: integer): Double;
procedure Setrtol(i: integer; d: Double);
function Getatol(i: integer): Double;
procedure Setatol(i: integer; d: Double);
public
// EuAdd 3
property Aborted: Boolean read fAborted write fAborted;
property prfl: integer read Fprfl write Fprfl;
property NumberOfEquation: integer read neq;
constructor Create(n: integer); virtual;
destructor destroy; override;
procedure Setfcn(fcn: fcnProc);
{ y = array of initial values of variables. t = initial value of
independent variable, tout, value of t when output is required.
On output, y holds new values of variables and t updated to tout }
procedure Execute(var y: TVector; var t, tout: Double);
property rtol[i: Integer]: Double read Getrtol write Setrtol;
property atol[i: Integer]: Double read Getatol write Setatol;
property itol: integer read Fitol write Fitol;
property itask: integer read Fitask write Fitask;
property istate: integer read Fistate write Fistate;
property iopt: integer read Fiopt write Fiopt;
property jt: integer read Fjt write Fjt;
property iwork5: integer read Fiwork5 write Fiwork5;
property iwork6: integer read Fiwork6 write Fiwork6;
property iwork7: integer read Fiwork7 write Fiwork7;
property iwork8: integer read Fiwork8 write Fiwork8;
property iwork9: integer read Fiwork9 write Fiwork9;
property rwork1: Double read Frwork1 write Frwork1;
property rwork5: Double read Frwork5 write Frwork5;
property rwork6: Double read Frwork6 write Frwork6;
property rwork7: Double read Frwork7 write Frwork7;
// AddEu 1
property istart: integer read jstart write jstart; // 0-first
end;
{ ------------------------------------------------------------------------- }
// EuAdd 1
var
StdOut: TStringList;
implementation
// EuAdd 1
uses Forms;
{Unit Vector.pas}
{ ------------------------------------------------------------------------- }
{ START OF VECTOR TYPE IMPLEMETATION }
{ ------------------------------------------------------------------------- }
{ The data space which holds the data for a vector is typed as [1..x] so that
indexing autmatically starts at one, therefore there is no need in the
following code to add 1 to the size of the vector when creating or destroying it }
{ Create a vector of size i }
constructor TVector.CreateFromFloatList(const Src: TFloatList);
var
I: integer;
begin
Create(Src.Count);
for I:= 1 to Self.Size do
Self[I]:= Src[I-1];
end;
constructor TVector.create(i: integer);
begin
inherited Create;
s:= 0; vx:= nil; { vx set to Nil to indicate empty vector, used by SetSize }
if i>0 then Self.SetSize(i);
end;
constructor TVector.createTmp(i: integer);
begin
inherited Create;
s:= 0; vx:= nil; { vx set to Nil to indicate empty vector, used by SetSize }
if i>0 then Self.SetSize(i);
Tmp:= true;
end;
destructor TVector.destroy;
begin
FreeSpace;
inherited Destroy;
end;
{ Private internal procedure }
procedure TVector.FreeSpace;
begin
if vx<>nil then
if Self.s>0 then
try
// Finalize(vx);
FreeMem(vx, sizeof(Double)*Self.s);
finally
Self.s:= 0;
vx:= nil;
end;
end;
{ Internal routine to allocate space. If space already exists then it frees it first }
procedure TVector.SetSize(i: integer);
begin
if vx<>nil then FreeMem(vx, sizeof(Double)*s);
s:= i; vx:= AllocMem(sizeof(Double)*s);
end;
{ Increase the size of the vector without destroying and existing data }
procedure TVector.EnLargeBy(n: integer);
begin
if n<0 then raise EVectorSizeError.Create('Argument to EnLargeBy must be positive');
ReAllocMem(vx, sizeof(Double)*(s+n)); inc(s, n); { Modified for D2 }
end;
{ Reduce the size of the vector }
procedure TVector.ReduceBy(n: integer);
begin
if n>=s then
raise EVectorSizeError.Create('Can''t reduce size of vector to below zero elements');
ReAllocMem(vx, sizeof(Double)*(s-n)); dec(s, n); { modified for D2 }
end;
{ Enlarge the vector by one element without destroying any existing data }
procedure TVector.Enlarge;
begin
ReAllocMem(vx, sizeof(Double)*(s+1)); inc(s); { Modified for D2 }
end;
{ Reduce the vector by one element, the top most element is destroyed }
procedure TVector.Reduce;
begin
ReAllocMem(vx, sizeof(Double)*(s-1)); dec(s); { Modified for D2 }
end;
{ Clears the vector, sets all elements to zero }
procedure TVector.Zero;
var
i: integer;
begin
for i:= 1 to s do vx^[i]:= 0.0;
end;
{ Clears the vector, sets all elements to zero }
procedure TVector.Clear;
begin
Zero;
end;
{ used internally but is also accessible from the outside }
procedure TVector.Setval(i: integer; v: Double);
begin
vx^[i]:= v;
end;
{ used internally but is also accessible from the outside }
function TVector.Getval(ii: integer): Double;
begin
result:= vx^[ii]
end;
{ Copies vector v to self. If self is not the same size as v then self is resized
Usage: u.Assign (v) }
procedure TVector.Assign(v: TVector);
begin
v.Tmp:= false; { just in case its a temporary variable }
if v.s<>Self.s then Self.SetSize(v.s);
move(v.vx^, Self.vx^, sizeof(Double)*s)
end;
{ Add the vectors, 'v' and 'u' together to produce Self. Error if v and u are not
the same size. If Self is not sized correctly, then Add will resize Self }
function TVector.Add(v, u: TVector): TVector;
var
i: integer;
begin
if v.s<>u.s then raise EVectorSizeError.Create('Vectors must be the same size to sum them');
if Self.s<>v.s then Self.SetSize(v.s);
for i:= 1 to v.s do Self[i]:= v[i]+u[i];
if v.tmp then v.free; if u.tmp then u.free;
result:= Self;
end;
class function TVector.xAdd(v, u: TVector): TVector;
var
i: integer; t: TVector;
begin
if v.s<>u.s then raise EVectorSizeError.Create('Vectors must be the same size to sum them');
t:= TVector.CreateTmp(v.s);
for i:= 1 to v.s do t[i]:= v[i]+u[i];
result:= t;
end;
{ Subtract the vectors, 'v' and 'u' together to produce Self. Error if v and u are not
the same size. If Self is not sized correctly, then Subtract will resize Self }
function TVector.Sub(v, u: TVector): TVector;
var
i: integer;
begin
if v.s<>u.s then raise EVectorSizeError.Create('Vectors must be the same size to subtract them');
if Self.s<>v.s then Self.SetSize(v.s);
for i:= 1 to v.s do Self[i]:= v[i]-u[i];
if v.tmp then v.free; if u.tmp then u.free;
result:= Self;
end;
class function TVector.xSub(v, u: TVector): TVector;
var
i: integer; t: TVector;
begin
if v.s<>u.s then raise EVectorSizeError.Create('Vectors must be the same size to subtract them');
t:= TVector.CreateTmp(v.s);
for i:= 1 to v.s do t[i]:= v[i]-u[i];
result:= t;
end;
{ Compute the dot product of vectors 'u' and 'v' Usage: d := dot (u, v); }
class function TVector.Dot(u, v: TVector): Double;
var
i: integer;
begin
if u.Size<>v.Size then
raise EVectorSizeError.Create('Vectors must be of the same size to compute dot product');
result:= 0.0;
for i:= 1 to u.Size do result:= result+u[i]*v[i];
end;
{ Apply a dot product to Self and arg, 'v' Usage: d := u.dotU (v); }
function TVector.DotU(v: TVector): Double;
var
i: integer;
begin
if Self.Size<>v.Size then
raise EVectorSizeError.Create('Vectors must be of the same size to compute dot product');
result:= 0.0;
for i:= 1 to Self.Size do
result:= result+Self[i]*v[i];
end;
{ compute the cross product of Self and vector 'v', replacing Self
Usage: v.CrossU (u) }
function TVector.CrossU(v: TVector): TVector;
begin
if (v.Size=3)and(Self.Size=3) then
begin
Self[1]:= Self[2]*v[3]-Self[3]*v[2];
Self[2]:= Self[3]*v[1]-Self[1]*v[3];
Self[3]:= Self[1]*v[2]-Self[2]*v[1];
result:= Self;
end
else
raise EVectorSizeError.Create('Cross product can only be calculated for vectors in 3D');
end;
{ compute the cross product of 'v1' and vector 'v2' giving Self
Usage: v.Cross (v1, v2) }
function TVector.Cross(v1, v2: TVector): TVector;
begin
if (v1.Size=3)and(v2.Size=3)and(Self.Size=3) then
begin
Self[1]:= v1[2]*v2[3]-v1[3]*v2[2];
Self[2]:= v1[3]*v2[1]-v1[1]*v2[3];
Self[3]:= v1[1]*v2[2]-v1[2]*v2[1];
result:= Self;
end
else
raise EVectorSizeError.Create('Cross product can only be calculated for vectors in 3D');
end;
{ Returns the sum of values in the vector
Usage: total := v.sum }
function TVector.Sum: Double;
var
i: integer;
begin
result:= 0.0;
for i:= 1 to s do result:= result+vx^[i];
end;
{ Returns the mean of the elements of the vector
Usage: average := v.mean; }
function TVector.Mean: Double;
begin
if s>0 then result:= sum/s
else result:= 1E-13; //EuAdd
end;
{ Returns the sum of the squares of values in Data
Usage: s := v.SumOfSquares; }
function TVector.SumOfSquares: Double;
var
i: integer;
begin
result:= 0.0;
for i:= 1 to s do result:= result+sqr(vx^[i]);
end;
{ Returns the sample standard deviation
Usage: sd := v.StdDev; }
function TVector.StdDev: Double;
var
sq, total: Double; i: integer;
begin
sq:= 0; total:= 0;
if s>0 then
begin
for i:= 1 to s do
begin sq:= sq+sqr(vx^[i]); total:= total+vx^[i]; end;
result:= sqrt((sq-sqr(total)/s)/(s-1));
{Easier to read but slightly slower:
result := sqrt ((SumOfSquares - sqr (sum)/s)/(s-1));}
end
else result:= 1E-13; //EuAdd
end;
{ Scale the vector by factor
Usage: v.Scale (2) Mults all elements by 2 }
procedure TVector.Scale(factor: Double);
var
i: integer;
begin
for i:= 1 to s do vx^[i]:= vx^[i]*factor;
end;
{ ------------------------------------------------------------------------- }
{ START OF INTEGER VECTOR IMPLEMETATION }
{ ------------------------------------------------------------------------- }
{ Create a vector of size i }
constructor TVectori.CreateFromLongIntList(const Src: TLongIntList);
var
I: integer;
begin
Create(Src.Count);
for I:= 1 to Self.Size do
Self[I]:= Src[I-1];
end;
constructor TVectori.create(i: integer);
begin
inherited Create; vx:= nil;
Self.SetSize(i);
end;
destructor TVectori.destroy;
begin
if vx<>nil then FreeMem(vx, sizeof(integer)*s);
inherited Destroy;
end;
{ Internal routine used by define }
procedure TVectori.SetSize(NewSize: integer);
begin
if vx<>nil then FreeMem(vx, sizeof(integer)*s);
s:= NewSize; vx:= AllocMem(sizeof(integer)*NewSize);
end;
procedure TVectori.EnLargeBy(n: integer);
begin
ReAllocMem(vx, sizeof(integer)*(s+n)); inc(s, n); { Modified for D2 }
end;
procedure TVectori.ReduceBy(n: integer);
begin
if n>=s then
raise EVectorSizeError.Create('Can''t reduce size of vector to below zero elements');
ReAllocMem(vx, sizeof(integer)*(s-n)); dec(s, n); { Modified for D2 }
end;
{ Enlarge the vector by one element without destroying any existing data }
procedure TVectori.Enlarge;
begin
ReAllocMem(vx, sizeof(integer)*(s+1)); inc(s); { Modified for D2 }
end;
{ Reduce the vector by one element, the top most element is destroyed }
procedure TVectori.Reduce;
begin
ReAllocMem(vx, sizeof(integer)*(s-1)); dec(s); { Modified for D2 }
end;
{ Clear the vector, sets all elements to zero }
procedure TVectori.Zero;
var
i: integer;
begin
for i:= 1 to s do vx^[i]:= 0;
end;
{ Clear the vector, sets all elements to zero }
procedure TVectori.Clear;
begin
Zero;
end;
procedure TVectori.Assign(v: TVectori);
begin
if v.s<>Self.s then Self.SetSize(v.s);
move(v.vx^, Self.vx^, sizeof(integer)*s)
end;
{ used internally but is also accessible from the outside }
procedure TVectori.Setval(i: integer; v: integer);
begin
vx^[i]:= v;
end;
{ used internally but is also accessible from the outside }
function TVectori.Getval(ii: integer): integer;
begin
result:= vx^[ii];
end;
function TVectori.GetSize: integer;
begin
result:= s;
end;
{Unit Mat.pas}
const
MATERROR='Matrix Operation Error:';
{ ------------------------------------------------------------------------- }
{ START OF MATRIX IMPLEMETATION }
{ ------------------------------------------------------------------------- }
{ ------------------------- Constructors first ---------------------------- }
{ ******************************************************************** }
{ Usage: A := TMatrix.create (3, 2); }
{ ******************************************************************** }
constructor TMatrix.create(r, c: integer);
begin
inherited Create; nr:= 0; nc:= 0; mx:= nil;
Self.SetSize(r, c);
end;
{ ******************************************************************** }
{ Create an identity matrix }
{ }
{ Usage: A := TMatrix.createI (3); }
{ ******************************************************************** }
constructor TMatrix.createI(n: integer);
var
i: integer;
begin
inherited Create; nr:= 0; nc:= 0; mx:= nil;
Self.SetSize(n, n);
for i:= 1 to n do Self[i, i]:= 1.0;
end;
{ ******************************************************************** }
{ Create a matrix filled with values from array d given that the }
{ number of columns equals c. }
{ }
{ Usage: A := TMatrix.createLit (2, [1, 2, 3, 4]); }
{ Creates a 2 by 2 array }
{ ******************************************************************** }
constructor TMatrix.createLit(c: integer; d: array of TMatElement);
var
i, j, ri, count: integer;
begin
inherited Create; nr:= 0; nc:= 0; mx:= nil;
ri:= (High(d)+1)div c;
Self.SetSize(ri, c);
count:= 0;
for i:= 1 to ri do
for j:= 1 to c do
begin
Self[i, j]:= d[count];
inc(count);
end;
end;
{ ******************************************************************** }
{ Usage: A.destroy, use a.free in a program }
{ ******************************************************************** }
destructor TMatrix.destroy;
begin
FreeSpace;
inherited Destroy;
end;
{ Free the data space but not the object }
procedure TMatrix.FreeSpace;
var
i: integer;
begin
if mx<>nil then
begin
for i:= 1 to nr do
if mx^[i]<>nil then
begin FreeMem(mx^[i], sizeof(TMatElement)*(nc+1)); mx^[i]:= nil; end;
FreeMem(mx, sizeof(PTRowList)*(nr+1)); mx:= nil;
end;
DestroyNameLists;
end;
{ Internal routine used set size of matrix and allocate space }
procedure TMatrix.SetSize(ri, ci: integer);
var
i: integer;
begin
FreeSpace;
nr:= ri; nc:= ci;
mx:= AllocMem(sizeof(pTRowList)*(nr+1)); { r+1 so that I can index from 1 }
for i:= 1 to nr do mx^[i]:= AllocMem(sizeof(TMatElement)*(nc+1));
CreateNameLists(ri, ci);
end;
{ Add an empty row to the bottom of matrix without destroying data in other rows }
procedure TMatrix.AddRow;
var
tmp: TMatrix; i: integer;
begin
tmp:= TMatrix.Create(r+1, c); tmp.zero;
try
{ Copy a whole row at a time using move }
for i:= 1 to r do move(Self.mx^[i]^, tmp.mx^[i]^, sizeof(TMatElement)*(c+1));
tmp.FRowNames.Assign(Self.FRowNames); tmp.FColumnNames.Assign(Self.FColumnNames);
Self.FreeSpace; Self.SetSize(tmp.nr, tmp.nc);
Self.Copy(tmp);
finally
tmp.free;
end;
end;
procedure TMatrix.CreateNameLists(ri, ci: integer);
var
i: integer;
begin
FRowNames:= TStringList.Create; FColumnNames:= TStringList.Create;
{ Build some dummy names, o entries are dummy entries }
for i:= 0 to ri do FRowNames.add('R'+inttostr(i));
for i:= 0 to ci do FColumnNames.add('C'+inttostr(i));
end;
procedure TMatrix.DestroyNameLists;
begin
FRowNames.free; FRowNames:= nil; FColumnNames.free; FColumnNames:= nil;
end;
{ ---------------------------------------------------------------------------- }
{ BASIC ROUTINES }
{ ---------------------------------------------------------------------------- }
{ ******************************************************************** }
{ Used internally but is also accessible from the outside }
{ }
{ Normal Usage: A[2, 3] := 1.2; }
{ }
{ ******************************************************************** }
procedure TMatrix.Setval(ri, ci: integer; v: TMatElement);
begin
mx^[ri]^[ci]:= v;
end;
{ ******************************************************************** }
{ Used internally but is also accessible from the outside }
{ }
{ Normal Usage: d := A[2, 3]; }
{ }
{ ******************************************************************** }
function TMatrix.Getval(ri, ci: integer): TMatElement;
begin
result:= mx^[ri]^[ci];
end;
procedure TMatrix.SetRowName(ri: integer; name: string);
begin
FRowNames[ri]:= name;