-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMathBase.Interchange.pas
More file actions
2002 lines (1907 loc) · 69.4 KB
/
Copy pathMathBase.Interchange.pas
File metadata and controls
2002 lines (1907 loc) · 69.4 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
unit MathBase.Interchange;
{-----------------------------------------------------------------------------
MathBase.Interchange
Optional, dependency-free numerical interchange. Persistence is invariant and
separate from locale-aware display. Binary loads validate version, shape,
byte count, element limit, and CRC-32 before constructing a result.
-----------------------------------------------------------------------------}
{$mode objfpc}{$H+}{$J-}
interface
uses
Classes, SysUtils, Math,
MathBase.SharedTypes, MathBase.Complex, MathBase.Random,
AlgebraLib.DenseMatrices, AlgebraLib.SparseMatrices;
const
DEFAULT_MAX_INTERCHANGE_ELEMENTS = 16000000;
DEFAULT_MAX_SPARSE_DIMENSION = 16000000;
type
EInterchangeError = class(Exception);
TInterchangeScalarType = (istFloat64, istComplex128);
TInterchangeValueKind = (ivkVector, ivkMatrix);
TValueMetadata = record
Kind:TInterchangeValueKind;
ScalarType:TInterchangeScalarType;
Rows:SizeInt;
Columns:SizeInt;
Elements:QWord;
end;
function ComplexToInvariant(const Value: TComplex): string;
function ParseComplexInvariant(const Text: string): TComplex;
function DoubleVectorToInvariant(const Values: TDoubleArray): string;
function ParseDoubleVectorInvariant(const Text: string;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS): TDoubleArray;
function ComplexVectorToInvariant(const Values: TComplexArray): string;
function ParseComplexVectorInvariant(const Text: string;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS): TComplexArray;
function DenseMatrixToInvariant(const Matrix: IDenseDoubleMatrix): string;
function ParseDenseMatrixInvariant(const Text: string;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS):
IDenseDoubleMatrix;
procedure WriteDelimitedMatrix(const Stream: TStream;
const Matrix: IDenseDoubleMatrix; const Delimiter: Char = ',');
function ReadDelimitedMatrix(const Stream: TStream; const Delimiter: Char = ',';
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS):
IDenseDoubleMatrix;
procedure WriteMatrixMarket(const Stream: TStream;
const Matrix: IDenseDoubleMatrix); overload;
procedure WriteMatrixMarket(const Stream: TStream;
const Matrix: IDenseComplexMatrix); overload;
function ReadMatrixMarketDouble(const Stream: TStream;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS):
IDenseDoubleMatrix;
function ReadMatrixMarketComplex(const Stream: TStream;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS):
IDenseComplexMatrix;
procedure WriteSparseMatrixMarket(const Stream: TStream;
const Matrix: ISparseDoubleMatrix); overload;
procedure WriteSparseMatrixMarket(const Stream: TStream;
const Matrix: ISparseComplexMatrix); overload;
function ReadSparseMatrixMarketDouble(const Stream: TStream;
const Format: TSparseFormat = sfCSR;
const MaxNonZeros: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS;
const MaxDimension: QWord = DEFAULT_MAX_SPARSE_DIMENSION):
ISparseDoubleMatrix;
function ReadSparseMatrixMarketComplex(const Stream: TStream;
const Format: TSparseFormat = sfCSR;
const MaxNonZeros: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS;
const MaxDimension: QWord = DEFAULT_MAX_SPARSE_DIMENSION):
ISparseComplexMatrix;
procedure SaveBinary(const Stream: TStream;
const Values: TDoubleArray); overload;
procedure SaveBinary(const Stream: TStream;
const Values: TComplexArray); overload;
procedure SaveBinary(const Stream: TStream;
const Matrix: IDenseDoubleMatrix); overload;
procedure SaveBinary(const Stream: TStream;
const Matrix: IDenseComplexMatrix); overload;
function LoadDoubleVectorBinary(const Stream: TStream;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS): TDoubleArray;
function LoadComplexVectorBinary(const Stream: TStream;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS): TComplexArray;
function LoadDoubleMatrixBinary(const Stream: TStream;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS):
IDenseDoubleMatrix;
function LoadComplexMatrixBinary(const Stream: TStream;
const MaxElements: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS):
IDenseComplexMatrix;
procedure SaveSparseBinary(const Stream: TStream;
const Matrix: ISparseSingleMatrix); overload;
procedure SaveSparseBinary(const Stream: TStream;
const Matrix: ISparseDoubleMatrix); overload;
procedure SaveSparseBinary(const Stream: TStream;
const Matrix: ISparseSingleComplexMatrix); overload;
procedure SaveSparseBinary(const Stream: TStream;
const Matrix: ISparseComplexMatrix); overload;
function LoadSparseSingleBinary(const Stream: TStream;
const MaxNonZeros: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS;
const MaxDimension: QWord = DEFAULT_MAX_SPARSE_DIMENSION):
ISparseSingleMatrix;
function LoadSparseDoubleBinary(const Stream: TStream;
const MaxNonZeros: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS;
const MaxDimension: QWord = DEFAULT_MAX_SPARSE_DIMENSION):
ISparseDoubleMatrix;
function LoadSparseSingleComplexBinary(const Stream: TStream;
const MaxNonZeros: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS;
const MaxDimension: QWord = DEFAULT_MAX_SPARSE_DIMENSION):
ISparseSingleComplexMatrix;
function LoadSparseComplexBinary(const Stream: TStream;
const MaxNonZeros: QWord = DEFAULT_MAX_INTERCHANGE_ELEMENTS;
const MaxDimension: QWord = DEFAULT_MAX_SPARSE_DIMENSION):
ISparseComplexMatrix;
procedure SaveRandomStateBinary(const Stream: TStream;
const State: TRandomState);
function LoadRandomStateBinary(const Stream: TStream): TRandomState;
function Summarize(const Values: TDoubleArray;
const MaximumValues: SizeInt = 8): string; overload;
function Summarize(const Values:TComplexArray;
const MaximumValues:SizeInt=8):string; overload;
function Summarize(const Matrix: IDenseDoubleMatrix;
const MaximumRows: SizeInt = 4;
const MaximumColumns: SizeInt = 6): string; overload;
function Describe(const Values:TDoubleArray):TValueMetadata; overload;
function Describe(const Values:TComplexArray):TValueMetadata; overload;
function Describe(const Matrix:IDenseDoubleMatrix):TValueMetadata; overload;
function Describe(const Matrix:IDenseComplexMatrix):TValueMetadata; overload;
implementation
type
TBinaryKind = (bkDoubleVector = 1, bkComplexVector = 2,
bkDoubleMatrix = 3, bkComplexMatrix = 4, bkRandomState = 5,
bkSparseSingle = 6, bkSparseDouble = 7,
bkSparseSingleComplex = 8, bkSparseComplex = 9);
TBinaryHeader = record
Kind: TBinaryKind;
Rows, Columns, PayloadBytes: QWord;
Checksum: LongWord;
end;
const
BINARY_MAGIC: array[0..7] of Byte =
(Ord('M'), Ord('F'), Ord('P'), Ord('B'), Ord('I'), Ord('N'), Ord('1'), 0);
BINARY_VERSION = 1;
MAX_TEXT_BYTES_PER_ELEMENT = 96;
TEXT_BASE_ALLOWANCE = 1048576;
function InvariantFormatSettings: TFormatSettings;
begin
Result := DefaultFormatSettings;
Result.DecimalSeparator := '.';
Result.ThousandSeparator := #0;
end;
function Summarize(const Values:TComplexArray;
const MaximumValues:SizeInt):string;
var
Builder:TStringBuilder;
I,DisplayCount:SizeInt;
begin
if MaximumValues<0 then
raise EInterchangeError.Create(
'Summarize(complex vector): MaximumValues must be non-negative.');
Builder:=TStringBuilder.Create;
try
Builder.Append('Complex vector length=').Append(IntToStr(Length(Values))).
Append(' [');
DisplayCount:=Min(Length(Values),MaximumValues);
for I:=0 to DisplayCount-1 do
begin
if I>0 then Builder.Append(', ');
Builder.Append(ComplexToInvariant(Values[I]));
end;
if DisplayCount<Length(Values) then Builder.Append(', ...');
Builder.Append(']');
Result:=Builder.ToString;
finally
Builder.Free;
end;
end;
procedure RequireFinite(const Value: Double; const Operation: string);
begin
if IsNan(Value) or IsInfinite(Value) then
raise EInterchangeError.Create(Operation + ': values must be finite.');
end;
procedure RequireMatrix(const Matrix: IDenseDoubleMatrix;
const Operation: string); overload;
var
RowIndex, ColumnIndex: SizeInt;
begin
if Matrix = nil then
raise EInterchangeError.Create(Operation +
': matrix handle must not be nil.');
for RowIndex := 0 to Matrix.Rows - 1 do
for ColumnIndex := 0 to Matrix.Cols - 1 do
RequireFinite(Matrix[RowIndex, ColumnIndex], Operation);
end;
procedure RequireMatrix(const Matrix: IDenseComplexMatrix;
const Operation: string); overload;
var
RowIndex, ColumnIndex: SizeInt;
begin
if Matrix = nil then
raise EInterchangeError.Create(Operation +
': matrix handle must not be nil.');
for RowIndex := 0 to Matrix.Rows - 1 do
for ColumnIndex := 0 to Matrix.Cols - 1 do
if not Matrix[RowIndex, ColumnIndex].IsFinite then
raise EInterchangeError.Create(Operation +
': matrix values must be finite.');
end;
function ParseInvariantFloat(const Text, Operation: string): Double;
var
Settings: TFormatSettings;
begin
Settings := InvariantFormatSettings;
if not TryStrToFloat(Trim(Text), Result, Settings) then
raise EInterchangeError.CreateFmt('%s: invalid invariant number "%s".',
[Operation, Text]);
RequireFinite(Result, Operation);
end;
function FloatInvariant(const Value: Double): string;
var
Settings: TFormatSettings;
begin
RequireFinite(Value, 'FloatInvariant');
Settings := InvariantFormatSettings;
Result := FloatToStr(Value, Settings);
end;
function ComplexToInvariant(const Value: TComplex): string;
begin
if not Value.IsFinite then
raise EInterchangeError.Create(
'ComplexToInvariant: real and imaginary parts must be finite.');
Result := '(' + FloatInvariant(Value.Re) + ',' +
FloatInvariant(Value.Im) + ')';
end;
function ParseComplexInvariant(const Text: string): TComplex;
var
Value, RealText, ImaginaryText: string;
Separator: SizeInt;
begin
Value := Trim(Text);
if (Length(Value) < 5) or (Value[1] <> '(') or
(Value[Length(Value)] <> ')') then
raise EInterchangeError.Create(
'ParseComplexInvariant: expected "(real,imaginary)".');
Value := Copy(Value, 2, Length(Value) - 2);
Separator := Pos(',', Value);
if (Separator <= 1) or (Separator = Length(Value)) or
(Pos(',', Copy(Value, Separator + 1, MaxInt)) <> 0) then
raise EInterchangeError.Create(
'ParseComplexInvariant: expected exactly two components.');
RealText := Copy(Value, 1, Separator - 1);
ImaginaryText := Copy(Value, Separator + 1, MaxInt);
Result := TComplex.Create(
ParseInvariantFloat(RealText, 'ParseComplexInvariant'),
ParseInvariantFloat(ImaginaryText, 'ParseComplexInvariant'));
end;
function StripBrackets(const Text, Operation: string): string;
begin
Result := Trim(Text);
if (Length(Result) < 2) or (Result[1] <> '[') or
(Result[Length(Result)] <> ']') then
raise EInterchangeError.Create(Operation +
': expected surrounding square brackets.');
Result := Copy(Result, 2, Length(Result) - 2);
end;
function DoubleVectorToInvariant(const Values: TDoubleArray): string;
var
Builder: TStringBuilder;
I: SizeInt;
begin
Builder := TStringBuilder.Create;
try
Builder.Append('[');
for I := 0 to High(Values) do
begin
if I > 0 then Builder.Append(',');
Builder.Append(FloatInvariant(Values[I]));
end;
Builder.Append(']');
Result := Builder.ToString;
finally
Builder.Free;
end;
end;
function SplitStrict(const Text: string; const Delimiter: Char): TStringList;
begin
Result := TStringList.Create;
Result.StrictDelimiter := True;
Result.Delimiter := Delimiter;
Result.DelimitedText := Text;
end;
function ParseDoubleVectorInvariant(const Text: string;
const MaxElements: QWord): TDoubleArray;
var
Inner: string;
Parts: TStringList;
I: SizeInt;
begin
Result := nil;
Inner := StripBrackets(Text, 'ParseDoubleVectorInvariant');
if Trim(Inner) = '' then Exit;
Parts := SplitStrict(Inner, ',');
try
if QWord(Parts.Count) > MaxElements then
raise EInterchangeError.CreateFmt(
'ParseDoubleVectorInvariant: %d elements exceed limit %d.',
[Parts.Count, MaxElements]);
SetLength(Result, Parts.Count);
for I := 0 to Parts.Count - 1 do
Result[I] := ParseInvariantFloat(Parts[I],
'ParseDoubleVectorInvariant');
finally
Parts.Free;
end;
end;
function ComplexVectorToInvariant(const Values: TComplexArray): string;
var
Builder: TStringBuilder;
I: SizeInt;
begin
Builder := TStringBuilder.Create;
try
Builder.Append('[');
for I := 0 to High(Values) do
begin
if I > 0 then Builder.Append(';');
Builder.Append(ComplexToInvariant(Values[I]));
end;
Builder.Append(']');
Result := Builder.ToString;
finally
Builder.Free;
end;
end;
function ParseComplexVectorInvariant(const Text: string;
const MaxElements: QWord): TComplexArray;
var
Inner: string;
Parts: TStringList;
I: SizeInt;
begin
Result := nil;
Inner := StripBrackets(Text, 'ParseComplexVectorInvariant');
if Trim(Inner) = '' then Exit;
Parts := SplitStrict(Inner, ';');
try
if QWord(Parts.Count) > MaxElements then
raise EInterchangeError.CreateFmt(
'ParseComplexVectorInvariant: %d elements exceed limit %d.',
[Parts.Count, MaxElements]);
SetLength(Result, Parts.Count);
for I := 0 to Parts.Count - 1 do
Result[I] := ParseComplexInvariant(Parts[I]);
finally
Parts.Free;
end;
end;
function DenseMatrixToInvariant(const Matrix: IDenseDoubleMatrix): string;
var
Builder: TStringBuilder;
RowIndex, ColumnIndex: SizeInt;
begin
RequireMatrix(Matrix, 'DenseMatrixToInvariant');
Builder := TStringBuilder.Create;
try
Builder.Append('[');
for RowIndex := 0 to Matrix.Rows - 1 do
begin
if RowIndex > 0 then Builder.Append(';');
for ColumnIndex := 0 to Matrix.Cols - 1 do
begin
if ColumnIndex > 0 then Builder.Append(',');
Builder.Append(FloatInvariant(Matrix[RowIndex, ColumnIndex]));
end;
end;
Builder.Append(']');
Result := Builder.ToString;
finally
Builder.Free;
end;
end;
function ParseDenseMatrixInvariant(const Text: string;
const MaxElements: QWord): IDenseDoubleMatrix;
var
Inner: string;
Rows, Fields: TStringList;
RowIndex, ColumnIndex, ColumnCount: SizeInt;
ElementCount: QWord;
begin
Inner := StripBrackets(Text, 'ParseDenseMatrixInvariant');
if Trim(Inner) = '' then
Exit(TDenseDoubleMatrix.Zeros(0, 0));
Rows := SplitStrict(Inner, ';');
try
ColumnCount := -1;
for RowIndex := 0 to Rows.Count - 1 do
begin
Fields := SplitStrict(Rows[RowIndex], ',');
try
if ColumnCount < 0 then ColumnCount := Fields.Count;
if (Fields.Count = 0) or (Fields.Count <> ColumnCount) then
raise EInterchangeError.Create(
'ParseDenseMatrixInvariant: rows must be non-empty and rectangular.');
finally
Fields.Free;
end;
end;
ElementCount := QWord(Rows.Count) * QWord(ColumnCount);
if ElementCount > MaxElements then
raise EInterchangeError.CreateFmt(
'ParseDenseMatrixInvariant: %d elements exceed limit %d.',
[ElementCount, MaxElements]);
Result := TDenseDoubleMatrix.Zeros(Rows.Count, ColumnCount);
for RowIndex := 0 to Rows.Count - 1 do
begin
Fields := SplitStrict(Rows[RowIndex], ',');
try
for ColumnIndex := 0 to ColumnCount - 1 do
Result[RowIndex, ColumnIndex] := ParseInvariantFloat(
Fields[ColumnIndex], 'ParseDenseMatrixInvariant');
finally
Fields.Free;
end;
end;
finally
Rows.Free;
end;
end;
procedure WriteString(const Stream: TStream; const Text: string);
begin
if Stream = nil then
raise EInterchangeError.Create('WriteString: Stream must not be nil.');
if Length(Text) > 0 then
Stream.WriteBuffer(Text[1], Length(Text));
end;
function ReadTextLimited(const Stream: TStream; const MaxElements: QWord;
const Operation: string): string;
var
Buffer: array[0..8191] of Byte;
Memory: TMemoryStream;
Count: LongInt;
MaximumBytes, CurrentBytes: QWord;
begin
if Stream = nil then
raise EInterchangeError.Create(Operation + ': Stream must not be nil.');
if MaxElements > (High(QWord) - TEXT_BASE_ALLOWANCE) div
MAX_TEXT_BYTES_PER_ELEMENT then
MaximumBytes := High(QWord)
else
MaximumBytes := MaxElements * MAX_TEXT_BYTES_PER_ELEMENT +
TEXT_BASE_ALLOWANCE;
Memory := TMemoryStream.Create;
try
CurrentBytes := 0;
repeat
Count := Stream.Read(Buffer, SizeOf(Buffer));
if Count < 0 then
raise EInterchangeError.Create(Operation + ': stream read failed.');
if QWord(Count) > MaximumBytes - CurrentBytes then
raise EInterchangeError.CreateFmt(
'%s: text input exceeds the configured size limit.', [Operation]);
if Count > 0 then Memory.WriteBuffer(Buffer, Count);
Inc(CurrentBytes, Count);
until Count = 0;
SetLength(Result, Memory.Size);
if Memory.Size > 0 then
begin
Memory.Position := 0;
Memory.ReadBuffer(Result[1], Memory.Size);
end;
finally
Memory.Free;
end;
end;
procedure WriteDelimitedMatrix(const Stream: TStream;
const Matrix: IDenseDoubleMatrix; const Delimiter: Char);
var
Builder: TStringBuilder;
RowIndex, ColumnIndex: SizeInt;
begin
RequireMatrix(Matrix, 'WriteDelimitedMatrix');
if Delimiter in [#0, #10, #13, '"', '+', '-', '.', '0'..'9'] then
raise EInterchangeError.Create(
'WriteDelimitedMatrix: Delimiter must not conflict with numeric syntax.');
Builder := TStringBuilder.Create;
try
for RowIndex := 0 to Matrix.Rows - 1 do
begin
for ColumnIndex := 0 to Matrix.Cols - 1 do
begin
if ColumnIndex > 0 then Builder.Append(Delimiter);
Builder.Append(FloatInvariant(Matrix[RowIndex, ColumnIndex]));
end;
Builder.Append(LineEnding);
end;
WriteString(Stream, Builder.ToString);
finally
Builder.Free;
end;
end;
function ReadDelimitedMatrix(const Stream: TStream; const Delimiter: Char;
const MaxElements: QWord): IDenseDoubleMatrix;
var
Text: string;
Lines, Fields: TStringList;
RowIndex, ColumnIndex, ColumnCount, EffectiveRows: SizeInt;
ElementCount: QWord;
begin
Text := ReadTextLimited(Stream, MaxElements, 'ReadDelimitedMatrix');
Lines := TStringList.Create;
try
Lines.Text := Text;
while (Lines.Count > 0) and
(Trim(Lines[Lines.Count - 1]) = '') do
Lines.Delete(Lines.Count - 1);
if Lines.Count = 0 then
Exit(TDenseDoubleMatrix.Zeros(0, 0));
EffectiveRows := Lines.Count;
ColumnCount := -1;
for RowIndex := 0 to EffectiveRows - 1 do
begin
if Trim(Lines[RowIndex]) = '' then
raise EInterchangeError.Create(
'ReadDelimitedMatrix: blank rows are not permitted.');
Fields := SplitStrict(Lines[RowIndex], Delimiter);
try
if ColumnCount < 0 then ColumnCount := Fields.Count;
if (Fields.Count = 0) or (Fields.Count <> ColumnCount) then
raise EInterchangeError.Create(
'ReadDelimitedMatrix: rows must be non-empty and rectangular.');
finally
Fields.Free;
end;
end;
ElementCount := QWord(EffectiveRows) * QWord(ColumnCount);
if ElementCount > MaxElements then
raise EInterchangeError.CreateFmt(
'ReadDelimitedMatrix: %d elements exceed limit %d.',
[ElementCount, MaxElements]);
Result := TDenseDoubleMatrix.Zeros(EffectiveRows, ColumnCount);
for RowIndex := 0 to EffectiveRows - 1 do
begin
Fields := SplitStrict(Lines[RowIndex], Delimiter);
try
for ColumnIndex := 0 to ColumnCount - 1 do
Result[RowIndex, ColumnIndex] := ParseInvariantFloat(
Fields[ColumnIndex], 'ReadDelimitedMatrix');
finally
Fields.Free;
end;
end;
finally
Lines.Free;
end;
end;
procedure WriteMatrixMarket(const Stream: TStream;
const Matrix: IDenseDoubleMatrix);
var
Builder: TStringBuilder;
RowIndex, ColumnIndex: SizeInt;
begin
RequireMatrix(Matrix, 'WriteMatrixMarket(double)');
Builder := TStringBuilder.Create;
try
Builder.Append('%%MatrixMarket matrix array real general').Append(LineEnding);
Builder.Append(IntToStr(Matrix.Rows)).Append(' ').
Append(IntToStr(Matrix.Cols)).Append(LineEnding);
for ColumnIndex := 0 to Matrix.Cols - 1 do
for RowIndex := 0 to Matrix.Rows - 1 do
Builder.Append(FloatInvariant(Matrix[RowIndex, ColumnIndex])).
Append(LineEnding);
WriteString(Stream, Builder.ToString);
finally
Builder.Free;
end;
end;
procedure WriteMatrixMarket(const Stream: TStream;
const Matrix: IDenseComplexMatrix);
var
Builder: TStringBuilder;
RowIndex, ColumnIndex: SizeInt;
begin
RequireMatrix(Matrix, 'WriteMatrixMarket(complex)');
Builder := TStringBuilder.Create;
try
Builder.Append('%%MatrixMarket matrix array complex general').
Append(LineEnding);
Builder.Append(IntToStr(Matrix.Rows)).Append(' ').
Append(IntToStr(Matrix.Cols)).Append(LineEnding);
for ColumnIndex := 0 to Matrix.Cols - 1 do
for RowIndex := 0 to Matrix.Rows - 1 do
Builder.Append(FloatInvariant(Matrix[RowIndex, ColumnIndex].Re)).
Append(' ').
Append(FloatInvariant(Matrix[RowIndex, ColumnIndex].Im)).
Append(LineEnding);
WriteString(Stream, Builder.ToString);
finally
Builder.Free;
end;
end;
function MatrixMarketLines(const Stream: TStream;
const MaxElements: QWord; const Operation: string): TStringList;
var
Text: string;
Index: Integer;
begin
Text := ReadTextLimited(Stream, MaxElements, Operation);
Result := TStringList.Create;
Result.Text := Text;
Index := 1;
while Index < Result.Count do
if (Trim(Result[Index]) <> '') and (Trim(Result[Index])[1] = '%') then
Result.Delete(Index)
else
Inc(Index);
end;
procedure ParseMatrixMarketShape(const Line, Operation: string;
out Rows, Columns: SizeInt; const MaxElements: QWord);
var
Fields: TStringList;
Rows64, Columns64, Elements: QWord;
begin
Fields := SplitStrict(Trim(Line), ' ');
try
while Fields.IndexOf('') >= 0 do Fields.Delete(Fields.IndexOf(''));
if (Fields.Count <> 2) or
not TryStrToQWord(Fields[0], Rows64) or
not TryStrToQWord(Fields[1], Columns64) then
raise EInterchangeError.Create(Operation +
': invalid Matrix Market shape line.');
if (Rows64 > QWord(High(SizeInt))) or
(Columns64 > QWord(High(SizeInt))) then
raise EInterchangeError.Create(Operation +
': Matrix Market dimensions exceed platform limits.');
if (Rows64 <> 0) and (Columns64 > High(QWord) div Rows64) then
raise EInterchangeError.Create(Operation +
': Matrix Market element count overflow.');
Elements := Rows64 * Columns64;
if Elements > MaxElements then
raise EInterchangeError.CreateFmt(
'%s: %d elements exceed limit %d.',
[Operation, Elements, MaxElements]);
Rows := Rows64;
Columns := Columns64;
finally
Fields.Free;
end;
end;
function ReadMatrixMarketDouble(const Stream: TStream;
const MaxElements: QWord): IDenseDoubleMatrix;
var
Lines: TStringList;
Rows, Columns, RowIndex, ColumnIndex, ValueIndex: SizeInt;
begin
Lines := MatrixMarketLines(Stream, MaxElements, 'ReadMatrixMarketDouble');
try
if (Lines.Count < 2) or
(LowerCase(Trim(Lines[0])) <>
'%%matrixmarket matrix array real general') then
raise EInterchangeError.Create(
'ReadMatrixMarketDouble: expected dense real Matrix Market array.');
ParseMatrixMarketShape(Lines[1], 'ReadMatrixMarketDouble',
Rows, Columns, MaxElements);
if QWord(Lines.Count - 2) <> QWord(Rows) * QWord(Columns) then
raise EInterchangeError.Create(
'ReadMatrixMarketDouble: payload value count does not match shape.');
Result := TDenseDoubleMatrix.Zeros(Rows, Columns);
ValueIndex := 2;
for ColumnIndex := 0 to Columns - 1 do
for RowIndex := 0 to Rows - 1 do
begin
Result[RowIndex, ColumnIndex] := ParseInvariantFloat(
Lines[ValueIndex], 'ReadMatrixMarketDouble');
Inc(ValueIndex);
end;
finally
Lines.Free;
end;
end;
function ReadMatrixMarketComplex(const Stream: TStream;
const MaxElements: QWord): IDenseComplexMatrix;
var
Lines, Fields: TStringList;
Rows, Columns, RowIndex, ColumnIndex, ValueIndex: SizeInt;
begin
Lines := MatrixMarketLines(Stream, MaxElements, 'ReadMatrixMarketComplex');
try
if (Lines.Count < 2) or
(LowerCase(Trim(Lines[0])) <>
'%%matrixmarket matrix array complex general') then
raise EInterchangeError.Create(
'ReadMatrixMarketComplex: expected dense complex Matrix Market array.');
ParseMatrixMarketShape(Lines[1], 'ReadMatrixMarketComplex',
Rows, Columns, MaxElements);
if QWord(Lines.Count - 2) <> QWord(Rows) * QWord(Columns) then
raise EInterchangeError.Create(
'ReadMatrixMarketComplex: payload value count does not match shape.');
Result := TDenseComplexMatrix.Zeros(Rows, Columns);
ValueIndex := 2;
for ColumnIndex := 0 to Columns - 1 do
for RowIndex := 0 to Rows - 1 do
begin
Fields := SplitStrict(Trim(Lines[ValueIndex]), ' ');
try
while Fields.IndexOf('') >= 0 do Fields.Delete(Fields.IndexOf(''));
if Fields.Count <> 2 then
raise EInterchangeError.Create(
'ReadMatrixMarketComplex: each value needs real and imaginary fields.');
Result[RowIndex, ColumnIndex] := TComplex.Create(
ParseInvariantFloat(Fields[0], 'ReadMatrixMarketComplex'),
ParseInvariantFloat(Fields[1], 'ReadMatrixMarketComplex'));
finally
Fields.Free;
end;
Inc(ValueIndex);
end;
finally
Lines.Free;
end;
end;
procedure WriteSparseMatrixMarket(const Stream: TStream;
const Matrix: ISparseDoubleMatrix);
var
Builder: TStringBuilder;
OuterIndex, K, RowIndex, ColumnIndex: SizeInt;
begin
if Matrix = nil then
raise EInterchangeError.Create(
'WriteSparseMatrixMarket(double): matrix must not be nil.');
for K := 0 to Matrix.NonZeroCount - 1 do
if Matrix.GetStoredValue(K) = 0.0 then
raise EInterchangeError.Create(
'WriteSparseMatrixMarket(double): explicit stored zeros are outside the canonical coordinate subset.');
Builder := TStringBuilder.Create;
try
Builder.Append('%%MatrixMarket matrix coordinate real general').
Append(LineEnding);
Builder.Append(IntToStr(Matrix.Rows)).Append(' ').
Append(IntToStr(Matrix.Cols)).Append(' ').
Append(IntToStr(Matrix.NonZeroCount)).Append(LineEnding);
if Matrix.Format = sfCSR then
for OuterIndex := 0 to Matrix.Rows - 1 do
for K := Matrix.GetOuterPointer(OuterIndex) to
Matrix.GetOuterPointer(OuterIndex + 1) - 1 do
Builder.Append(IntToStr(OuterIndex + 1)).Append(' ').
Append(IntToStr(Matrix.GetInnerIndex(K) + 1)).Append(' ').
Append(FloatInvariant(Matrix.GetStoredValue(K))).Append(LineEnding)
else
for OuterIndex := 0 to Matrix.Cols - 1 do
for K := Matrix.GetOuterPointer(OuterIndex) to
Matrix.GetOuterPointer(OuterIndex + 1) - 1 do
begin
RowIndex := Matrix.GetInnerIndex(K);
ColumnIndex := OuterIndex;
Builder.Append(IntToStr(RowIndex + 1)).Append(' ').
Append(IntToStr(ColumnIndex + 1)).Append(' ').
Append(FloatInvariant(Matrix.GetStoredValue(K))).Append(LineEnding);
end;
WriteString(Stream, Builder.ToString);
finally
Builder.Free;
end;
end;
procedure WriteSparseMatrixMarket(const Stream: TStream;
const Matrix: ISparseComplexMatrix);
var
Builder: TStringBuilder;
OuterIndex, K, RowIndex, ColumnIndex: SizeInt;
Value: TComplex;
begin
if Matrix = nil then
raise EInterchangeError.Create(
'WriteSparseMatrixMarket(complex): matrix must not be nil.');
for K := 0 to Matrix.NonZeroCount - 1 do
begin
Value := Matrix.GetStoredValue(K);
if (Value.Re = 0.0) and (Value.Im = 0.0) then
raise EInterchangeError.Create(
'WriteSparseMatrixMarket(complex): explicit stored zeros are outside the canonical coordinate subset.');
end;
Builder := TStringBuilder.Create;
try
Builder.Append('%%MatrixMarket matrix coordinate complex general').
Append(LineEnding);
Builder.Append(IntToStr(Matrix.Rows)).Append(' ').
Append(IntToStr(Matrix.Cols)).Append(' ').
Append(IntToStr(Matrix.NonZeroCount)).Append(LineEnding);
if Matrix.Format = sfCSR then
for OuterIndex := 0 to Matrix.Rows - 1 do
for K := Matrix.GetOuterPointer(OuterIndex) to
Matrix.GetOuterPointer(OuterIndex + 1) - 1 do
begin
Value := Matrix.GetStoredValue(K);
Builder.Append(IntToStr(OuterIndex + 1)).Append(' ').
Append(IntToStr(Matrix.GetInnerIndex(K) + 1)).Append(' ').
Append(FloatInvariant(Value.Re)).Append(' ').
Append(FloatInvariant(Value.Im)).Append(LineEnding);
end
else
for OuterIndex := 0 to Matrix.Cols - 1 do
for K := Matrix.GetOuterPointer(OuterIndex) to
Matrix.GetOuterPointer(OuterIndex + 1) - 1 do
begin
RowIndex := Matrix.GetInnerIndex(K);
ColumnIndex := OuterIndex;
Value := Matrix.GetStoredValue(K);
Builder.Append(IntToStr(RowIndex + 1)).Append(' ').
Append(IntToStr(ColumnIndex + 1)).Append(' ').
Append(FloatInvariant(Value.Re)).Append(' ').
Append(FloatInvariant(Value.Im)).Append(LineEnding);
end;
WriteString(Stream, Builder.ToString);
finally
Builder.Free;
end;
end;
procedure ParseSparseMatrixMarketShape(const Line, Operation: string;
const MaxNonZeros, MaxDimension: QWord;
out Rows, Columns, NonZeros: SizeInt);
var
Fields: TStringList;
Rows64, Columns64, NonZeros64: QWord;
begin
Fields := SplitStrict(Trim(Line), ' ');
try
while Fields.IndexOf('') >= 0 do Fields.Delete(Fields.IndexOf(''));
if (Fields.Count <> 3) or
not TryStrToQWord(Fields[0], Rows64) or
not TryStrToQWord(Fields[1], Columns64) or
not TryStrToQWord(Fields[2], NonZeros64) then
raise EInterchangeError.Create(
Operation + ': invalid coordinate shape line.');
if (Rows64 > QWord(High(SizeInt))) or
(Columns64 > QWord(High(SizeInt))) or
(NonZeros64 > QWord(High(SizeInt))) then
raise EInterchangeError.Create(
Operation + ': shape or nonzero count exceeds platform limits.');
if NonZeros64 > MaxNonZeros then
raise EInterchangeError.CreateFmt(
'%s: declared %d nonzeros exceed limit %d.',
[Operation, NonZeros64, MaxNonZeros]);
if (Rows64 > MaxDimension) or (Columns64 > MaxDimension) then
raise EInterchangeError.CreateFmt(
'%s: declared shape %d x %d exceeds dimension limit %d.',
[Operation, Rows64, Columns64, MaxDimension]);
Rows := SizeInt(Rows64);
Columns := SizeInt(Columns64);
NonZeros := SizeInt(NonZeros64);
finally
Fields.Free;
end;
end;
function ReadSparseMatrixMarketDouble(const Stream: TStream;
const Format: TSparseFormat; const MaxNonZeros, MaxDimension: QWord):
ISparseDoubleMatrix;
var
Lines, Fields: TStringList;
Builder: TSparseDoubleTripletBuilder;
Rows, Columns, NonZeros, I: SizeInt;
Row64, Column64: QWord;
begin
Lines := MatrixMarketLines(Stream, MaxNonZeros,
'ReadSparseMatrixMarketDouble');
try
if (Lines.Count < 2) or
(LowerCase(Trim(Lines[0])) <>
'%%matrixmarket matrix coordinate real general') then
raise EInterchangeError.Create(
'ReadSparseMatrixMarketDouble: expected coordinate real general.');
ParseSparseMatrixMarketShape(Lines[1],
'ReadSparseMatrixMarketDouble', MaxNonZeros, MaxDimension,
Rows, Columns, NonZeros);
if Lines.Count - 2 <> NonZeros then
raise EInterchangeError.Create(
'ReadSparseMatrixMarketDouble: payload count does not match declaration.');
Builder := TSparseDoubleTripletBuilder.Create(Rows, Columns);
try
for I := 0 to NonZeros - 1 do
begin
Fields := SplitStrict(Trim(Lines[I + 2]), ' ');
try
while Fields.IndexOf('') >= 0 do Fields.Delete(Fields.IndexOf(''));
if (Fields.Count <> 3) or
not TryStrToQWord(Fields[0], Row64) or
not TryStrToQWord(Fields[1], Column64) or
(Row64 = 0) or (Column64 = 0) or
(Row64 > QWord(Rows)) or (Column64 > QWord(Columns)) then
raise EInterchangeError.Create(
'ReadSparseMatrixMarketDouble: invalid one-based coordinate.');
Builder.Add(SizeInt(Row64 - 1), SizeInt(Column64 - 1),
ParseInvariantFloat(Fields[2],
'ReadSparseMatrixMarketDouble'));
finally
Fields.Free;
end;
end;
if Format = sfCSR then Result := Builder.ToCSR(szDrop)
else Result := Builder.ToCSC(szDrop);
if Result.NonZeroCount <> NonZeros then
raise EInterchangeError.Create(
'ReadSparseMatrixMarketDouble: duplicates or explicit zeros are outside the canonical subset.');
finally
Builder.Free;
end;
finally
Lines.Free;
end;
end;
function ReadSparseMatrixMarketComplex(const Stream: TStream;
const Format: TSparseFormat; const MaxNonZeros, MaxDimension: QWord):
ISparseComplexMatrix;
var
Lines, Fields: TStringList;
Builder: TSparseComplexTripletBuilder;
Rows, Columns, NonZeros, I: SizeInt;
Row64, Column64: QWord;
begin
Lines := MatrixMarketLines(Stream, MaxNonZeros,
'ReadSparseMatrixMarketComplex');
try
if (Lines.Count < 2) or
(LowerCase(Trim(Lines[0])) <>
'%%matrixmarket matrix coordinate complex general') then
raise EInterchangeError.Create(
'ReadSparseMatrixMarketComplex: expected coordinate complex general.');
ParseSparseMatrixMarketShape(Lines[1],
'ReadSparseMatrixMarketComplex', MaxNonZeros, MaxDimension,
Rows, Columns, NonZeros);
if Lines.Count - 2 <> NonZeros then
raise EInterchangeError.Create(
'ReadSparseMatrixMarketComplex: payload count does not match declaration.');
Builder := TSparseComplexTripletBuilder.Create(Rows, Columns);
try
for I := 0 to NonZeros - 1 do
begin
Fields := SplitStrict(Trim(Lines[I + 2]), ' ');
try
while Fields.IndexOf('') >= 0 do Fields.Delete(Fields.IndexOf(''));
if (Fields.Count <> 4) or
not TryStrToQWord(Fields[0], Row64) or
not TryStrToQWord(Fields[1], Column64) or
(Row64 = 0) or (Column64 = 0) or
(Row64 > QWord(Rows)) or (Column64 > QWord(Columns)) then
raise EInterchangeError.Create(
'ReadSparseMatrixMarketComplex: invalid one-based coordinate.');
Builder.Add(SizeInt(Row64 - 1), SizeInt(Column64 - 1),
TComplex.Create(
ParseInvariantFloat(Fields[2],
'ReadSparseMatrixMarketComplex'),
ParseInvariantFloat(Fields[3],
'ReadSparseMatrixMarketComplex')));
finally
Fields.Free;
end;
end;
if Format = sfCSR then Result := Builder.ToCSR(szDrop)