forked from inversed-ru/InvLibs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Statistics.pas
1128 lines (970 loc) · 30.2 KB
/
Statistics.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
{
Copyright (c) Peter Karpov 2010 - 2017.
Usage of the works is permitted provided that this instrument is retained with
the works, so that any entity that uses the works is notified of this instrument.
DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.
}
{$IFDEF FPC} {$MODE DELPHI} {$ENDIF}
unit Statistics; ////////////////////////////////////////////////////////////////////
{
>> Version: 2.0
>> Description
Unit for calculation of various statistical quantities. Part of InvLibs unit
collection.
>> Author
Peter Karpov
Email : [email protected]
Homepage : inversed.ru
GitHub : inversed-ru
Twitter : @inversed_ru
>> Notes
Delphi 7 and FreePascal 3.0.4's implementations of variance and standard deviation
functions in the Math unit are numerically unstable. Variance may return negative
values and StdDev may crash. All related routines (MeanAndStdDev, TotalVariance,
...) are plagued by the same issue and should be avoided entirely. This unit uses
StandDev and SqrStandDev in function names to avoid confusion.
Quantile function uses interpolation and thus needs to find two elements, but
quickselect normally finds only one. A slight modification of element search
seems to do the job, but its correctness remains to be proven. Moreover, even
determining the required array index is not trivial. The method that has been
reported as the most accurate in [1] is employed.
RobustMean function is based on a modified one-step estimator, but uses a variable
rather than fixed rejection threshold. Modification that used the differences
between the quartiles and the median instead of MAD was also tested. While it may
work better for assymetric distributions, it was found to be less robust for small
datasets.
Although Mean and Sum functions duplicate the Math unit functionality, they cannot
be easily removed because of the way Delphi handles overloads.
>> ToDo
- Prove correctness of quickselect modification used in Quantile function
- Test RobustMean function
>> References
[1] Estimation of population percentiles.
Schoonjans F, De Bacquer D, Schmid P.
>> Changelog
2.0 : 2017.12.11 ~ Many routines renamed. Procedures now have the
"Get" prefix, functions do not
- RandMinIndex, RandMaxIndex functions moved to
Arrays unit
1.20 : 2015.06.26 + PowerMean function
1.19 : 2014.08.27 + Correlation section
1.18 : 2013.06.14 + Integer version of GetSum
1.17 : 2013.06.13 + Integer version of Midspread
1.16 : 2013.06.09 + Normalization argument for RankTransform, overloaded
version for integer data
1.15 : 2013.05.25 + GetVariance function
+ GetSigma for TRealArray2D
1.14 : 2013.05.23 + Overloaded versions of GetMean
1.13 : 2013.03.26 + Weighted average procedure
+ Overloaded versions of Quantile and GetMedian
for ArrayNs and IntArrays
1.12 : 2013.02.08 + Zero mean normalization type
+ Overloaded version of Normalize
1.11 : 2013.01.08 + GetSum function
+ Unit sum normalization type
1.10 : 2012.12.21 + RankTransform procedure
1.9 : 2012.04.18 + GetSigma function
1.8 : 2011.11.28 + mean absolute deviation function
1.7 : 2011.11.15 + New normalization modes
1.6 : 2011.11.05 ~ Rewritten quantile function to use interpolation
+ RobustMean function
+ Normalization
1.4.1 : 2011.10.14 ~ Moved to generic types
1.4 : 2011.09.10 ~ RandMinIndex, RandMaxIndex: open arrays, improved speed
1.3 : 2011.07.11 + Minimum, Maximum for open arrays and ints
1.2 : 2011.06.14 + Minimum, Maximum, RandMinIndex, RandMaxIndex functions
1.1 : 2011.06.07 ~ Rewritten 'Mean, Sigma, Skew' section
1.0 : 2011.04.13 + 'Quantiles' and 'Error Measures' sections
0.4 : 2011.03.28 + Open array parameters
0.0 : 2011.01.30 + Initial version
Notation: + added, - removed, * fixed, ~ changed
}
interface ///////////////////////////////////////////////////////////////////////////
uses
Arrays;
{-----------------------<< Moments >>-----------------------------------------------}
// Sum of Data elements
function Sum(
const Data : array of Real
) : Real;
overload;
function Sum(
const Data : array of Integer
) : Integer;
overload;
// Arithmetic mean of Data
function Mean(
const Data : array of Real
) : Real;
overload;
function Mean(
const Data : TRealArrayN
) : Real;
overload;
// Return the mean and the bias-corrected variance of Data.
// SqrStandDev is set to zero if there are less than 2 values.
procedure GetMeanSqrStandDev(
var Mean,
SqrStandDev : Real;
const Data : array of Real);
// Return the mean and bias-corrected standard deviation of Data.
// StandDev is set to zero if there are less than 2 values.
procedure GetMeanStandDev(
var Mean,
StandDev : Real;
const Data : array of Real);
// Return the variance of Data or zero if there are less than 2 values
function SqrStandDev(
const Data : TRealArray
) : Real;
overload;
function SqrStandDev(
const Data : TRealArray2D
) : Real;
overload;
// Return the standard deviation of Data or zero if there are less than 2 values
function StandDev(
const Data : TRealArray
) : Real;
overload;
function StandDev(
const Data : TRealArray2D
) : Real;
overload;
// Return the mean, standard deviation and skewness of Data. StandDev and
// Skew are set to 0 if there are less than 2 and 3 values respectively.
procedure GetMeanStandDevSkew(
var Mean,
StandDev,
Skew : Real;
const Data : array of Real);
{-----------------------<< Other measures of location and scale >>------------------}
// Weighted average of X with weights W
function WeightedAverage(
const X, W : TRealArrayN
) : Real;
overload;
function WeightedAverage(
const x, w : TRealArray
) : Real;
overload;
// Power mean of Data with exponent p
function PowerMean(
const Data : array of Real;
p : Integer
) : Real;
// Return the mean of Data excluding outliers.
function RobustMean(
const Data : TRealArray
) : Real;
// Mean absolute deviation = Mean(|A - Mean(A)|)
function MeanAbsDeviation(
const A : TRealArray
) : Real;
// Median absolute deviation = Median(|A - Median(A)|)
function MedAbsDeviation(
const A : TRealArray
) : Real;
{-----------------------<< Quantiles >>---------------------------------------------}
// Return a quantile corresponding to probability P. Uses interpolation between two
// closest values. Quickselect algorithm, O(N) expected runtime.
function Quantile(
const A : TRealArray;
P : Real // [0 .. 1]
) : Real;
overload;
function Quantile(
const A : TRealArrayN;
P : Real // [0 .. 1]
) : Real;
overload;
function Quantile(
const A : TIntArray;
P : Real // [0 .. 1]
) : Real;
overload;
function Quantile(
const A : TIntArrayN;
P : Real // [0 .. 1]
) : Real;
overload;
// Median of A, O(N) expected runtime
function Median(
const A : TRealArray
) : Real;
overload;
function Median(
const A : TRealArrayN
) : Real;
overload;
function Median(
const A : TIntArray
) : Real;
overload;
function Median(
const A : TIntArrayN
) : Real;
overload;
// Interquartile range
function Midspread(
const A : TRealArray
) : Real;
overload;
function Midspread(
const A : TIntArray
) : Real;
overload;
{-----------------------<< Min, Max >>----------------------------------------------}
// Minimal value of the elements of A
function Minimum(
const A : array of Real
) : Real;
overload;
function Minimum(
const A : array of Integer
) : Integer;
overload;
// Maximal value of the elements of A
function Maximum(
const A : array of Real
) : Real;
overload;
function Maximum(
const A : array of Integer
) : Integer;
overload;
{-----------------------<< Normalization >>-----------------------------------------}
type
TNormalization = (normUnitSum, normDivMax, normUnit, normNormal, normZeroMean);
// Normalize the Data according to the specified method
procedure Normalize(
var Data : TRealArray;
Norm : TNormalization);
overload;
procedure Normalize(
var NormData : TRealArray;
const Data : TRealArray;
Norm : TNormalization);
overload;
// Perform ranking transformation. Rank of equal items is the mean of their integer
// ranks. Invert changes the sorting direction, Normalized gives [0 .. 1) range.
procedure RankTransform(
var Ranks : TRealArray;
const Data : TRealArray;
Invert,
Normalized : Boolean);
overload;
procedure RankTransform(
var Ranks : TRealArray;
const Data : TIntArray;
Invert,
Normalized : Boolean);
overload;
{-----------------------<< Correlation >>-------------------------------------------}
// Pearson correlation between X and Y
function Corr(
const X, Y : TRealArray
) : Real;
// Spearman's rank correlation between X and Y
function RankCorr(
const X, Y : TRealArray
) : Real;
{-----------------------<< Error measures >>----------------------------------------}
type
TErrorMeasure = (emRMSE, emMAE, emMdAE, emRMSRE, emMARE, emMdARE);
// Return an error measure between two datasets. Relative error measures are
// assymetric, X1 stands for the actual and X2 for predicted values.
function ErrorMeasure(
const X1, X2 : TRealArray;
Measure : TErrorMeasure
) : Real;
implementation //////////////////////////////////////////////////////////////////////
uses
Math,
ExtraMath, // SignedPower, Clip
Sorting,
SpecFuncs;
const
ErrorSmallArray = 'Too little data';
{-----------------------<< Moments >>-----------------------------------------------}
// Sum of the first Len Data elements
function Sum(
const Data : array of Real;
Len : Integer
) : Real;
overload;
var
i : Integer;
Sum : Real;
begin
Sum := 0;
for i := 0 to Len - 1 do
Sum := Sum + Data[i];
Result := Sum;
end;
// Sum of Data elements
function Sum(
const Data : array of Real
) : Real;
overload;
begin
Result := Sum(Data, High(Data) - Low(Data) + 1);
end;
function Sum(
const Data : array of Integer
) : Integer;
overload;
var
i, Sum : Integer;
begin
Sum := 0;
for i := 0 to High(Data) do
Sum := Sum + Data[i];
Result := Sum;
end;
// Arithmetic mean of the first Len elements of Data
function Mean(
const Data : array of Real;
Len : Integer
) : Real;
overload;
begin
Result := Sum(Data, Len) / Len;
end;
// Arithmetic mean of Data
function Mean(
const Data : array of Real
) : Real;
overload;
var
N : Integer;
begin
N := High(Data) - Low(Data) + 1;
Assert(N > 0, ErrorSmallArray);
Result := Mean(Data, N);
end;
function Mean(
const Data : TRealArrayN
) : Real;
overload;
begin
Assert(Data.N > 0, ErrorSmallArray);
Result := Mean(Data._, Data.N);
end;
// Return the mean and the bias-corrected variance of Data.
// SqrStandDev is set to zero if there are less than 2 values.
procedure GetMeanSqrStandDev(
var Mean,
SqrStandDev : Real;
const Data : array of Real);
var
N, i : Integer;
Sum2 : Real;
begin
N := High(Data) - Low(Data) + 1;
Assert(N > 0, ErrorSmallArray);
Mean := Statistics.Mean(Data);
Sum2 := 0;
for i := Low(Data) to High(Data) do
Sum2 := Sum2 + Sqr(Data[i] - Mean);
if N > 1 then
SqrStandDev := Sum2 / (N - 1) else
SqrStandDev := 0;
end;
// Return the mean and bias-corrected standard deviation of Data.
// StandDev is set to zero if there are less than 2 values.
procedure GetMeanStandDev(
var Mean,
StandDev : Real;
const Data : array of Real);
begin
GetMeanSqrStandDev(Mean, StandDev, Data);
StandDev := Sqrt(StandDev);
end;
// Return the variance of Data or zero if there are less than 2 values
function SqrStandDev(
const Data : TRealArray
) : Real;
overload;
var
Mean : Real;
begin
GetMeanSqrStandDev(Mean, Result, Data);
end;
function SqrStandDev(
const Data : TRealArray2D
) : Real;
overload;
var
Scanline : TRealArray;
begin
ToScanline(Scanline, Data);
Result := SqrStandDev(Scanline);
end;
// Return the standard deviation of Data or zero if there are less than 2 values
function StandDev(
const Data : TRealArray
) : Real;
overload;
begin
Result := Sqrt(SqrStandDev(Data));
end;
function StandDev(
const Data : TRealArray2D
) : Real;
overload;
begin
Result := Sqrt(SqrStandDev(Data));
end;
// Return the mean, standard deviation and skewness of Data. StandDev and
// Skew are set to 0 if there are less than 2 and 3 values respectively.
procedure GetMeanStandDevSkew(
var Mean,
StandDev,
Skew : Real;
const Data : array of Real);
var
N, i : Integer;
Variance,
Sum3,
Temp : Real;
begin
N := High(Data) - Low(Data) + 1;
Assert(N > 0, ErrorSmallArray);
// Mean, Variance
GetMeanSqrStandDev(Mean, Variance, Data);
StandDev := Sqrt(Variance);
// Skew
if N > 2 then
begin
Sum3 := 0;
for i := Low(Data) to High(Data) do
begin
Temp := Data[i] - Mean;
Sum3 := Sum3 + Temp * Temp * Temp;
end;
if StandDev = 0 then
Skew := 0
else
Skew := ( ( N * Sqrt(N - 1) ) / (N - 2) ) * Sum3 / (Variance * StandDev);
end
else
Skew := 0;
end;
{-----------------------<< Other measures of location and scale >>------------------}
// Weighted average of the first Len elements of X with weights W
function WeightedAverage(
const x, w : TRealArray;
Len : Integer
) : Real;
overload;
var
SumW, SumWX : Real;
i : Integer;
begin
SumW := 0;
SumWX := 0;
for i := 0 to Len - 1 do
begin
SumWX := SumWX + w[i] * x[i];
SumW := SumW + w[i];
end;
Result := SumWX / SumW;
end;
// Weighted average of X with weights W
function WeightedAverage(
const x, w : TRealArrayN
) : Real;
overload;
begin
Assert(x.N = w.N);
Result := WeightedAverage(x._, w._, x.N);
end;
function WeightedAverage(
const x, w : TRealArray
) : Real;
overload;
begin
Assert(Length(x) = Length(w));
Result := WeightedAverage(x, w, Length(x));
end;
// Power mean of Data with exponent p
function PowerMean(
const Data : array of Real;
p : Integer
) : Real;
var
N, i : Integer;
Sum : Real;
begin
N := High(Data) - Low(Data) + 1;
Assert(N > 0, ErrorSmallArray);
Sum := 0;
for i := Low(Data) to High(Data) do
Sum := Sum + IntPower(Data[i], p);
Result := SignedPower(Sum / N, 1 / p);
end;
// Return the mean of Data excluding outliers.
// #TODO try iterative procedure: at each iteration, label all outliers based on
// current mean estimate and compute new estimate. Stop when there are no changes
// in labeling.
function RobustMean(
const Data : TRealArray
) : Real;
var
N, NOk, i : Integer;
QuarterZ, MaxZ,
Med, Sigma,
MinX, MaxX,
Sum : Real;
begin
N := High(Data) - Low(Data) + 1;
Assert(N > 0, ErrorSmallArray);
// Determine the bounds for outliers using Chauvenet's criterion:
// rejection rate for Gaussian distribution is 1 / 2N
Med := Median(Data);
QuarterZ := InvNormalCCDF(1 / 4);
MaxZ := InvNormalCCDF(1 / (2 * N));
Sigma := MedAbsDeviation(Data) / QuarterZ;
MinX := Med - MaxZ * Sigma;
MaxX := Med + MaxZ * Sigma;
// Find the mean of data except outliers
Sum := 0;
NOk := 0;
for i := Low(Data) to High(Data) do
if (Data[i] >= MinX) and (Data[i] <= MaxX) then
begin
Sum := Sum + Data[i];
Inc(NOk);
end;
Result := Sum / NOk;
end;
// Mean absolute deviation = Mean(|A - Mean(A)|)
function MeanAbsDeviation(
const A : TRealArray
) : Real;
var
AbsDev : TRealArray;
Mean : Real;
i : Integer;
begin
AbsDev := Copy(A);
Mean := Statistics.Mean(A);
for i := 0 to Length(A) - 1 do
AbsDev[i] := Abs(A[i] - Mean);
Result := Statistics.Mean(AbsDev);
end;
// Median absolute deviation = Median(|A - Median(A)|)
function MedAbsDeviation(
const A : TRealArray
) : Real;
var
AbsDev : TRealArray;
M : Real;
i : Integer;
begin
AbsDev := Copy(A);
M := Median(A);
for i := 0 to Length(A) - 1 do
AbsDev[i] := Abs(A[i] - M);
Result := Median(AbsDev);
end;
{-----------------------<< Quantiles >>---------------------------------------------}
// Return a quantile of the first Len elements of A corresponding to probability P.
// Uses interpolation between two closest values. Quickselect algorithm,
// O(N) expected runtime.
// #UNOPT switch to insertion sort after a threshold?
function Quantile(
const A : TRealArray;
P : Real; // [0 .. 1]
Len : Integer
) : Real;
overload;
// Subarray A[Left .. Right] is rearranged: A <= Pivot, Pivot, A >= Pivot.
// Index of the pivot element is returned.
function Partition(
var A : TRealArray;
Left, Right : Integer
) : Integer;
var
PivotValue : Real;
PivotIndex,
IndexL, IndexR : Integer;
begin
PivotIndex := Left + Random(Right - Left + 1);
PivotValue := A[PivotIndex];
Swap(A, Left, PivotIndex);
IndexL := Left;
IndexR := Right + 1;
while True do
begin
repeat
Inc(IndexL);
until (IndexL > Right) or (A[IndexL] >= PivotValue);
repeat
Dec(IndexR);
until A[IndexR] <= PivotValue;
if IndexL >= IndexR then
{*} break;
Swap(A, IndexL, IndexR);
end;
Swap(A, Left, IndexR);
Result := IndexR;
end;
var
Work : TRealArray;
Index,
PivotIndex,
Left, Right : Integer;
RealIndex,
X, Y, Alpha : Real;
begin
Assert( (P >=0) and (P <= 1) , 'Invalid quantile probability');
// Copy into working array
Work := Copy(A);
Right := Len - 1;
Left := 0;
Assert(Len > 0, ErrorSmallArray);
// Set percentile index and blending factor
RealIndex := Clip(P * Len - 1 / 2, 0, Len - 1);
Index := Floor(RealIndex);
Alpha := Frac (RealIndex);
// Find the quantile
repeat
PivotIndex := Partition(Work, Left, Right);
if RealIndex < PivotIndex then
Right := PivotIndex - 1
else
Left := PivotIndex + 1;
until Left >= Right;
// Interpolate
X := Work[Index];
Y := Work[Min(Index + 1, Len - 1)];
Result := (1 - Alpha) * X + Alpha * Y;
end;
// Return a quantile corresponding to probability P. Uses interpolation between two
// closest values. Quickselect algorithm, O(N) expected runtime.
function Quantile(
const A : TRealArray;
P : Real // [0 .. 1]
) : Real;
overload;
begin
Result := Quantile(A, P, Length(A));
end;
function Quantile(
const A : TRealArrayN;
P : Real // [0 .. 1]
) : Real;
overload;
begin
Result := Quantile(A._, P, A.N);
end;
function Quantile(
const A : TIntArray;
P : Real // [0 .. 1]
) : Real;
overload;
var
RealA : TRealArray;
begin
ConvertToReal(RealA, A);
Result := Quantile(RealA, P, Length(A));
end;
function Quantile(
const A : TIntArrayN;
P : Real // [0 .. 1]
) : Real;
overload;
var
RealA : TRealArrayN;
begin
ConvertToReal(RealA, A);
Result := Quantile(RealA._, P, A.N);
end;
// Median of A, O(N) expected runtime
function Median(
const A : TRealArray
) : Real;
overload;
begin
Result := Quantile(A, 1 / 2);
end;
function Median(
const A : TRealArrayN
) : Real;
overload;
begin
Result := Quantile(A, 1 / 2);
end;
function Median(
const A : TIntArray
) : Real;
overload;
begin
Result := Quantile(A, 1 / 2);
end;
function Median(
const A : TIntArrayN
) : Real;
overload;
begin
Result := Quantile(A, 1 / 2);
end;
// Interquartile range
function Midspread(
const A : TRealArray
) : Real;
overload;
begin
Result := Quantile(A, 3 / 4) - Quantile(A, 1 / 4);
end;
function Midspread(
const A : TIntArray
) : Real;
overload;
var
B : TRealArray;
begin
ConvertToReal(B, A);
Result := Midspread(B);
end;
{-----------------------<< Min, Max >>----------------------------------------------}
// Minimal value of the elements of A
function Minimum(
const A : array of Real
) : Real;
overload;
var
i : Integer;
begin
Result := A[0];
for i := 1 to Length(A) - 1 do
Result := Min(Result, A[i]);
end;
function Minimum(
const A : array of Integer
) : Integer;
overload;
var
i : Integer;
begin
Result := A[0];
for i := 1 to Length(A) - 1 do
Result := Min(Result, A[i]);
end;
// Maximal value of the elements of A
function Maximum(
const A : array of Real
) : Real;
overload;
var
i : Integer;
begin
Result := A[0];
for i := 1 to Length(A) - 1 do
Result := Max(Result, A[i]);
end;
function Maximum(
const A : array of Integer
) : Integer;
overload;
var
i : Integer;
begin
Result := A[0];
for i := 1 to Length(A) - 1 do
Result := Max(Result, A[i]);
end;
{-----------------------<< Normalization >>-----------------------------------------}
// Normalize the Data according to the specified method
procedure Normalize(
var Data : TRealArray;
Norm : TNormalization);
overload;
var
i : Integer;
B, C : Real;
begin
// Calculate normalization coefficients
B := 0;
C := 1;
case Norm of
normUnitSum:
C := Sum(Data);
normDivMax:
C := Maximum(Data);
normUnit:
begin
B := Minimum(Data);
C := Maximum(Data) - B;
end;
normNormal:
GetMeanStandDev(B, C, Data);
normZeroMean:
B := Mean(Data);
else
Assert(False, 'Unknown normalization');
end;
// Normalize
if C = 0 then
C := 1;
for i := 0 to Length(Data) - 1 do
Data[i] := (Data[i] - B) / C;
end;
procedure Normalize(
var NormData : TRealArray;
const Data : TRealArray;
Norm : TNormalization);
overload;
begin
NormData := Copy(Data);
Normalize(NormData, Norm);
end;
// Perform ranking transformation. Rank of equal items is the mean of their integer
// ranks. Invert changes the sorting direction, Normalized gives [0 .. 1) range.
procedure RankTransform(
var Ranks : TRealArray;
const Data : TRealArray;
Invert,
Normalized : Boolean);
overload;
var
i, j, k,
Len, Sum : Integer;
Order : TIntArray;
SortedRanks : TRealArray;
SortOrder : TSortOrder;
MeanRank,
NormFac : Real;
begin
// Calculate integer rankings
Len := Length(Data);
if Invert then
SortOrder := soDescending else
SortOrder := soAscending;
OrderRealArray(Order, Data, SortOrder);
// Calculate sorted fractional rankings
SetLength(SortedRanks, Len);
i := 0;
j := 0;
repeat
// Calculate sum of integer ranks of equal items
Sum := 0;
while (j < Len) and (Data[Order[i]] = Data[Order[j]]) do
begin