-
Notifications
You must be signed in to change notification settings - Fork 9
/
stats.clj
2545 lines (2223 loc) · 99.4 KB
/
stats.clj
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
(ns fastmath.stats
"#### Statistics functions.
* Descriptive statistics.
* Correlation / covariance
* Outliers
* Confidence intervals
* Extents
* Effect size
* Tests
* Histogram
* ACF/PACF
* Bootstrap (see `fastmath.stats.bootstrap`)
* Binary measures
Functions are backed by Apache Commons Math or SMILE libraries. All work with Clojure sequences.
##### Descriptive statistics
All in one function [[stats-map]] contains:
* `:Size` - size of the samples, `(count ...)`
* `:Min` - [[minimum]] value
* `:Max` - [[maximum]] value
* `:Range` - range of values
* `:Mean` - [[mean]]/average
* `:Median` - [[median]], see also: [[median-3]]
* `:Mode` - [[mode]], see also: [[modes]]
* `:Q1` - first quartile, use: [[percentile]], [[quartile]]
* `:Q3` - third quartile, use: [[percentile]], [[quartile]]
* `:Total` - [[sum]] of all samples
* `:SD` - sample standard deviation
* `:Variance` - variance
* `:MAD` - [[median-absolute-deviation]]
* `:SEM` - standard error of mean
* `:LAV` - lower adjacent value, use: [[adjacent-values]]
* `:UAV` - upper adjacent value, use: [[adjacent-values]]
* `:IQR` - interquartile range, `(- q3 q1)`
* `:LOF` - lower outer fence, `(- q1 (* 3.0 iqr))`
* `:UOF` - upper outer fence, `(+ q3 (* 3.0 iqr))`
* `:LIF` - lower inner fence, `(- q1 (* 1.5 iqr))`
* `:UIF` - upper inner fence, `(+ q3 (* 1.5 iqr))`
* `:Outliers` - list of [[outliers]], samples which are outside outer fences
* `:Kurtosis` - [[kurtosis]]
* `:Skewness` - [[skewness]]
Note: [[percentile]] and [[quartile]] can have 10 different interpolation strategies. See [docs](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.html)"
(:require [fastmath.core :as m]
[fastmath.random :as r]
[fastmath.distance :as d]
[fastmath.vector :as v]
[fastmath.interpolation :as interp]
[fastmath.optimization :as opt]
[fastmath.kernel :as k])
(:import [org.apache.commons.math3.stat StatUtils]
[org.apache.commons.math3.stat.descriptive.rank Percentile Percentile$EstimationType]
[org.apache.commons.math3.stat.descriptive.moment Kurtosis Skewness]
[org.apache.commons.math3.stat.correlation KendallsCorrelation SpearmansCorrelation PearsonsCorrelation]
[org.apache.commons.math3.stat.regression SimpleRegression]
[org.apache.commons.math3.analysis.integration RombergIntegrator]
[org.apache.commons.math3.analysis UnivariateFunction]))
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(def ^{:doc "List of estimation strategies for [[percentile]]/[[quantile]] functions."}
estimation-strategies-list {:legacy Percentile$EstimationType/LEGACY
:r1 Percentile$EstimationType/R_1
:r2 Percentile$EstimationType/R_2
:r3 Percentile$EstimationType/R_3
:r4 Percentile$EstimationType/R_4
:r5 Percentile$EstimationType/R_5
:r6 Percentile$EstimationType/R_6
:r7 Percentile$EstimationType/R_7
:r8 Percentile$EstimationType/R_8
:r9 Percentile$EstimationType/R_9})
(defn percentile
"Calculate percentile of a `vs`.
Percentile `p` is from range 0-100.
See [docs](http://commons.apache.org/proper/commons-math/javadocs/api-3.4/org/apache/commons/math3/stat/descriptive/rank/Percentile.html).
Optionally you can provide `estimation-strategy` to change interpolation methods for selecting values. Default is `:legacy`. See more [here](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html)
See also [[quantile]]."
(^double [vs ^double p]
(StatUtils/percentile (m/seq->double-array vs) p))
(^double [vs ^double p estimation-strategy]
(let [^Percentile perc (.withEstimationType ^Percentile (Percentile.) (get estimation-strategies-list estimation-strategy Percentile$EstimationType/LEGACY))]
(.evaluate perc (m/seq->double-array vs) p))))
(defn percentiles
"Calculate percentiles of a `vs`.
Percentiles are sequence of values from range 0-100.
See [docs](http://commons.apache.org/proper/commons-math/javadocs/api-3.4/org/apache/commons/math3/stat/descriptive/rank/Percentile.html).
Optionally you can provide `estimation-strategy` to change interpolation methods for selecting values. Default is `:legacy`. See more [here](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html)
See also [[quantile]]."
([vs] (percentiles vs [25 50 75 100]))
([vs ps] (percentiles vs ps nil))
([vs ps estimation-strategy]
(let [^Percentile perc (.withEstimationType ^Percentile (Percentile.) (or (estimation-strategies-list estimation-strategy) Percentile$EstimationType/LEGACY))]
(.setData perc (m/seq->double-array vs))
(mapv (fn [^double p] (.evaluate perc p)) ps))))
(defn quantile
"Calculate quantile of a `vs`.
Quantile `q` is from range 0.0-1.0.
See [docs](http://commons.apache.org/proper/commons-math/javadocs/api-3.4/org/apache/commons/math3/stat/descriptive/rank/Percentile.html) for interpolation strategy.
Optionally you can provide `estimation-strategy` to change interpolation methods for selecting values. Default is `:legacy`. See more [here](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html)
See also [[percentile]]."
(^double [vs ^double q]
(percentile vs (m/constrain (* q 100.0) 0.0 100.0)))
(^double [vs ^double q estimation-strategy]
(percentile vs (m/constrain (* q 100.0) 0.0 100.0) estimation-strategy)))
(defn quantiles
"Calculate quantiles of a `vs`.
Quantilizes is sequence with values from range 0.0-1.0.
See [docs](http://commons.apache.org/proper/commons-math/javadocs/api-3.4/org/apache/commons/math3/stat/descriptive/rank/Percentile.html) for interpolation strategy.
Optionally you can provide `estimation-strategy` to change interpolation methods for selecting values. Default is `:legacy`. See more [here](http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/stat/descriptive/rank/Percentile.EstimationType.html)
See also [[percentiles]]."
([vs] (quantiles vs [0.25 0.5 0.75 1.0]))
([vs qs]
(percentiles vs (map #(m/constrain (* ^double % 100.0) 0.0 100.0) qs)))
([vs qs estimation-strategy]
(percentiles vs (map #(m/constrain (* ^double % 100.0) 0.0 100.0) qs) estimation-strategy)))
(defn- wquantile-interpolator
[vs ws method]
(let [sorted (sort-by first (map vector vs ws))
probabilities (map second sorted)
data (map first sorted)
data (conj data (first data))
^double wsum (reduce m/fast+ probabilities)
weights (conj (reductions m/fast+ (map (fn [^double p] (/ p wsum)) probabilities)) 0.0)]
(case method
:linear (interp/linear-smile weights data)
:average (let [interp1 (interp/step-before weights data)
interp2 (interp/step-after weights data)]
(fn [^double x] (* 0.5 (+ ^double (interp1 x)
^double (interp2 x)))))
:step (interp/step-before weights data))))
;; based on spatstat.geom::weighted.quantile
(defn wquantile
"Weighted quantile.
Calculation is done using interpolation. There are three methods:
* `:linear` - linear interpolation, default
* `:step` - step interpolation
* `:average` - average of ties
Based on `spatstat.geom::weighted.quantile` from R."
(^double [vs ws ^double q] (wquantile vs ws q :linear))
(^double [vs ws ^double q method]
(let [interp (wquantile-interpolator vs ws method)]
(interp q))))
(defn wquantiles
"Weighted quantiles.
Calculation is done using interpolation. There are three methods:
* `:linear` - linear interpolation, default
* `:step` - step interpolation
* `:average` - average of ties
Based on `spatstat.geom::weighted.quantile` from R."
([vs ws] (wquantiles vs ws [0.25 0.5 0.75 1.0]))
([vs ws qs] (wquantiles vs ws qs :linear))
([vs ws qs method]
(let [interp (wquantile-interpolator vs ws method)]
(mapv interp qs))))
(defn wmedian
"Weighted median.
Calculation is done using interpolation. There are three methods:
* `:linear` - linear interpolation, default
* `:step` - step interpolation
* `:average` - average of ties
Based on `spatstat.geom::weighted.quantile` from R."
(^double [vs ws] (wquantile vs ws 0.5))
(^double [vs ws method] (wquantile vs ws 0.5 method)))
(defn median
"Calculate median of `vs`. See [[median-3]]."
(^double [vs estimation-strategy]
(percentile vs 50.0 estimation-strategy))
(^double [vs]
(percentile vs 50.0)))
(defn median-3
"Median of three values. See [[median]]."
^double [^double a ^double b ^double c]
(m/max (m/min a b) (m/min (m/max a b) c)))
(defn mean
"Calculate mean of `vs`"
(^double [vs] (StatUtils/mean (m/seq->double-array vs))))
(defn geomean
"Geometric mean for positive values only"
^double [vs]
(m/exp (mean (map (fn [^double v] (m/log v)) vs))))
(defn harmean
"Harmonic mean"
^double [vs]
(/ (mean (map (fn [^double v] (/ v)) vs))))
(defn powmean
"Generalized power mean"
^double [vs ^double power]
(cond
(zero? power) (geomean vs)
(m/one? power) (mean vs)
(== power m/THIRD) (m/cb (mean (map #(m/cbrt %) vs)))
(== power 0.5) (m/sq (mean (map #(m/sqrt %) vs)))
(== power 2.0) (m/sqrt (mean (map m/sq vs)))
(== power 3.0) (m/cbrt (mean (map m/cb vs)))
:else (m/pow (mean (map (fn [^double v] (m/pow v power)) vs)) (/ power))))
(defn wmean
"Weighted mean"
(^double [vs] (mean vs))
(^double [vs weights]
(/ ^double (reduce m/fast+ (map m/fast* vs weights))
^double (reduce m/fast+ weights))))
(defn population-variance
"Calculate population variance of `vs`.
See [[variance]]."
(^double [vs]
(StatUtils/populationVariance (m/seq->double-array vs)))
(^double [vs ^double u]
(StatUtils/populationVariance (m/seq->double-array vs) u)))
(defn variance
"Calculate variance of `vs`.
See [[population-variance]]."
(^double [vs]
(StatUtils/variance (m/seq->double-array vs)))
(^double [vs ^double u]
(StatUtils/variance (m/seq->double-array vs) u)))
(defn population-stddev
"Calculate population standard deviation of `vs`.
See [[stddev]]."
(^double [vs]
(m/sqrt (population-variance vs)))
(^double [vs u]
(m/sqrt (population-variance vs u))))
(defn stddev
"Calculate standard deviation of `vs`.
See [[population-stddev]]."
(^double [vs]
(m/sqrt (variance vs)))
(^double [vs u]
(m/sqrt (variance vs u))))
(defn variation
"Coefficient of variation CV = stddev / mean"
^double [vs]
(let [vs (m/seq->double-array vs)]
(/ (stddev vs)
(mean vs))))
(defn median-absolute-deviation
"Calculate MAD"
(^double [vs] (median-absolute-deviation vs nil))
(^double [vs center]
(let [m (double (or center (median vs)))]
(median (map (fn [^double x] (m/abs (- x m))) vs))))
(^double [vs center estimation-strategy]
(let [m (double (or center (median vs estimation-strategy)))]
(median (map (fn [^double x] (m/abs (- x m))) vs) estimation-strategy))))
(def ^{:doc "Alias for [[median-absolute-deviation]]"}
mad median-absolute-deviation)
(defn mean-absolute-deviation
"Calculate mean absolute deviation"
(^double [vs] (mean-absolute-deviation vs nil))
(^double [vs center]
(let [m (double (or center (mean vs)))]
(mean (map (fn [^double x] (m/abs (- x m))) vs)))))
(defn sem
"Standard error of mean"
^double [vs]
(let [s (stddev vs)]
(/ s (m/sqrt (count vs)))))
(defmacro ^:private build-extent
[nm mid ext]
`(defn ~nm
~(str " -/+ " ext " and " mid)
[~'vs]
(let [vs# (m/seq->double-array ~'vs)
m# (~mid vs#)
s# (~ext vs#)]
[(- m# s#) (+ m# s#) m#])))
(build-extent stddev-extent mean stddev)
(build-extent mad-extent median median-absolute-deviation)
(build-extent sem-extent mean sem)
(defn percentile-extent
"Return percentile range and median.
`p` - calculates extent of `p` and `100-p` (default: `p=25`)"
([vs] (percentile-extent vs 25.0))
([vs ^double p] (percentile-extent vs p (- 100.0 p)))
([vs p1 p2] (percentile-extent vs p1 p2 :legacy))
([vs ^double p1 ^double p2 estimation-strategy]
(let [avs (m/seq->double-array vs)]
[(percentile avs p1 estimation-strategy)
(percentile avs p2 estimation-strategy)
(median avs)])))
(defn quantile-extent
"Return quantile range and median.
`q` - calculates extent of `q` and `1.0-q` (default: `q=0.25`)"
([vs] (quantile-extent vs 0.25))
([vs ^double q] (quantile-extent vs q (- 1.0 q)))
([vs q1 q2] (quantile-extent vs q1 q2 :legacy))
([vs ^double q1 ^double q2 estimation-strategy]
(let [avs (m/seq->double-array vs)]
[(quantile avs q1 estimation-strategy)
(quantile avs q2 estimation-strategy)
(median avs)])))
(defn pi
"Returns PI as a map, quantile intervals based on interval size.
Quantiles are `(1-size)/2` and `1-(1-size)/2`"
([vs] (pi vs 0.5))
([vs ^double size] (pi vs size :legacy))
([vs ^double size estimation-strategy]
(let [a (* 0.5 (- 1.0 size))
avs (m/seq->double-array vs)
q1 (quantile avs a estimation-strategy)
q2 (quantile avs (- 1.0 a) estimation-strategy)]
{(m/approx (* a 100.0) 2) q1
(m/approx (* (- 1.0 a) 100.0) 2) q2})))
(defn pi-extent
"Returns PI extent, quantile intervals based on interval size + median.
Quantiles are `(1-size)/2` and `1-(1-size)/2`"
([vs] (pi-extent vs 0.5))
([vs ^double size] (pi-extent vs size :legacy))
([vs ^double size estimation-strategy]
(let [a (* 0.5 (- 1.0 size))]
(quantile-extent vs a (- 1.0 a) estimation-strategy))))
(defn hpdi-extent
"Higher Posterior Density interval + median.
`size` parameter is the target probability content of the interval."
([vs] (hpdi-extent vs 0.95))
([vs ^double size]
(let [avs (m/seq->double-array vs)
nsamp (alength avs)
gap (m/constrain (m/round (* nsamp size)) 1 (dec nsamp))
max-idx (- nsamp gap)]
(java.util.Arrays/sort avs)
(loop [idx (long 0)
min-idx (long 0)
mn Double/MAX_VALUE]
(if (< idx max-idx)
(let [diff (- (aget avs (+ idx gap))
(aget avs idx))]
(if (< diff mn)
(recur (inc idx) idx diff)
(recur (inc idx) min-idx mn)))
[(aget avs min-idx) (aget avs (+ min-idx gap)) (median avs)])))))
(defn iqr
"Interquartile range."
(^double [vs] (iqr vs :legacy))
(^double [vs estimation-strategy]
(let [[^double q1 ^double q3] (percentile-extent vs 25.0 75.0 estimation-strategy)]
(- q3 q1))))
(defn adjacent-values
"Lower and upper adjacent values (LAV and UAV).
Let Q1 is 25-percentile and Q3 is 75-percentile. IQR is `(- Q3 Q1)`.
* LAV is smallest value which is greater or equal to the LIF = `(- Q1 (* 1.5 IQR))`.
* UAV is largest value which is lower or equal to the UIF = `(+ Q3 (* 1.5 IQR))`.
* third value is a median of samples
Optional `estimation-strategy` argument can be set to change quantile calculations estimation type. See [[estimation-strategies]]."
([vs]
(adjacent-values vs :legacy))
([vs estimation-strategy]
(let [avs (m/seq->double-array vs)
[q1 m q3] (percentiles avs [25.0 50.0 75.0] estimation-strategy)]
(adjacent-values avs q1 q3 m)))
([vs ^double q1 ^double q3 ^double m]
(let [avs (m/seq->double-array vs)
iqr (* 1.5 (- q3 q1))
lav-thr (- q1 iqr)
uav-thr (+ q3 iqr)]
(java.util.Arrays/sort avs)
[(first (filter #(>= (double %) lav-thr) avs))
(last (filter #(<= (double %) uav-thr) avs))
m])))
(defn inner-fence-extent
"Returns LIF, UIF and median"
([vs] (inner-fence-extent vs :legacy))
([vs estimation-strategy]
(let [[^double q1 ^double m ^double q3] (percentiles vs [25.0 50.0 75.0] estimation-strategy)
iqr+ (* 1.5 (- q3 q1))]
[(- q1 iqr+) (+ q3 iqr+) m])))
(defn outer-fence-extent
"Returns LOF, UOF and median"
([vs] (outer-fence-extent vs :legacy))
([vs estimation-strategy]
(let [[^double q1 ^double m ^double q3] (percentiles vs [25.0 50.0 75.0] estimation-strategy)
iqr+ (* 3.0 (- q3 q1))]
[(- q1 iqr+) (+ q3 iqr+) m])))
(defn outliers
"Find outliers defined as values outside inner fences.
Let Q1 is 25-percentile and Q3 is 75-percentile. IQR is `(- Q3 Q1)`.
* LIF (Lower Inner Fence) equals `(- Q1 (* 1.5 IQR))`.
* UIF (Upper Inner Fence) equals `(+ Q3 (* 1.5 IQR))`.
Returns sequence.
Optional `estimation-strategy` argument can be set to change quantile calculations estimation type. See [[estimation-strategies]]."
([vs]
(outliers vs :legacy))
([vs estimation-strategy]
(let [avs (m/seq->double-array vs)
q1 (percentile avs 25.0 estimation-strategy)
q3 (percentile avs 75.0 estimation-strategy)]
(outliers avs q1 q3)))
([vs ^double q1 ^double q3]
(let [ ;;avs (m/seq->double-array vs)
iqr (* 1.5 (- q3 q1))
lif-thr (- q1 iqr)
uif-thr (+ q3 iqr)]
;; (java.util.Arrays/sort avs)
(filter #(let [v (double %)]
(or (< v lif-thr)
(> v uif-thr))) vs))))
(declare histogram)
(defn modes
"Find the values that appears most often in a dataset `vs`.
Returns sequence with all most appearing values in increasing order.
See also [[mode]]."
([vs method] (modes vs method {}))
([vs method opts]
(let [avs (m/seq->double-array vs)]
(case method
:histogram (let [{:keys [bins ^double step]} (histogram avs (get opts :bins :rice))
ibins (vec (map-indexed #(conj %2 %1) bins))]
(->> ibins
(map (fn [[^double L ^long fm ^long id]]
(let [^long f1 (second (get ibins (dec id) [0 0]))
^long f2 (second (get ibins (inc id) [0 0]))]
[(+ L (* step (/ (- fm f1)
(- (* 2.0 fm) f1 f2)))) (- fm)])))
(sort-by second)
(map first)))
:pearson (let [mu (mean avs)
m (median avs (:estimation-strategy opts))]
[(- (* 3.0 m) (* 2.0 mu))])
:kde (let [kde (k/kernel-density (get opts :kernel :gaussian) avs (:bandwidth opts))]
(->> (map (fn [^double v] [v (- ^double (kde v))]) vs)
(sort-by second)
(map first)))
(seq ^doubles (StatUtils/mode avs)))))
([vs]
(seq ^doubles (StatUtils/mode (m/seq->double-array vs)))))
(defn mode
"Find the value that appears most often in a dataset `vs`.
For sample from continuous distribution, three algorithms are possible:
* `:histogram` - calculated from [[histogram]]
* `:kde` - calculated from KDE
* `:pearson` - mode = mean-3(median-mean)
* `:default` - discrete mode
Histogram accepts optional `:bins` (see [[histogram]]). KDE method accepts `:kde` for kernel name (default `:gaussian`) and `:bandwidth` (auto). Pearson can accept `:estimation-strategy` for median.
See also [[modes]]."
(^double [vs method] (mode vs method {}))
(^double [vs method opts]
(first (modes vs method opts)))
(^double [vs]
(let [m (StatUtils/mode (m/seq->double-array vs))]
(aget ^doubles m 0))))
(defn minimum
"Minimum value from sequence."
^double [vs]
(if (= (type vs) m/double-array-type)
(smile.math.MathEx/min ^doubles vs)
(reduce clojure.core/min vs)))
(defn maximum
"Maximum value from sequence."
^double [vs]
(if (= (type vs) m/double-array-type)
(smile.math.MathEx/max ^doubles vs)
(reduce clojure.core/max vs)))
(defn span
"Width of the sample, maximum value minus minimum value"
^double [vs]
(let [avs (m/seq->double-array vs)]
(- (maximum avs) (minimum avs))))
(defn extent
"Return extent (min, max, mean) values from sequence"
[vs]
(let [^double fv (first vs)]
(conj (reduce (fn [[^double mn ^double mx] ^double v]
[(min mn v) (max mx v)]) [fv fv] (rest vs)) (mean vs))))
(defn sum
"Sum of all `vs` values."
^double [vs]
(if (= (type vs) m/double-array-type)
(smile.math.MathEx/sum ^doubles vs)
(reduce (fn [^double x ^double y] (+ x y)) 0.0 vs)))
(defn moment
"Calculate moment (central or/and absolute) of given order (default: 2).
Additional parameters as a map:
* `:absolute?` - calculate sum as absolute values (default: `false`)
* `:mean?` - returns mean (proper moment) or just sum of differences (default: `true`)
* `:center` - value of center (default: `nil` = mean)
* `:normalize?` - apply normalization by standard deviation to the order power"
(^double [vs] (moment vs 2.0 nil))
(^double [vs ^double order] (moment vs order nil))
(^double [vs ^double order {:keys [absolute? center mean? normalize?]
:or {mean? true}}]
(let [in (m/seq->double-array vs)
cin (alength in)
out (double-array cin)
nf (if normalize? (m/pow (variance in) (* 0.5 order)) 1.0)
^double center (or center (mean in))
f (cond
(m/one? order) m/fast-identity
(== order 2.0) m/sq
(== order 3.0) m/cb
(== order 4.0) (fn ^double [^double diff] (m/sq (m/sq diff)))
:else (fn ^double [^double diff] (m/pow diff order)))
a (if absolute? m/abs m/fast-identity)]
(loop [idx (int 0)]
(when (< idx cin)
(aset out idx ^double (f (a (- (aget in idx) center))))
(recur (inc idx))))
(/ (if mean? (mean out) (sum out)) nf))))
(def ^{:deprecated "Use [[moment]] function"} second-moment moment)
(defn- yule-skewness
^double [vs ^double u]
(let [[^double q1 ^double q2 ^double q3] (quantiles vs [u 0.5 (- 1.0 u)])]
(/ (+ q3 (* -2.0 q2) q1)
(- q3 q1))))
(defn skewness
"Calculate skewness from sequence.
Possible types: `:G1` (default), `:g1` (`:pearson`), `:b1`, `:B1` (`:yule`), `:B3`, `:skew`, `:mode` or `:median`."
(^double [vs] (skewness vs :G1))
(^double [vs typ]
(let [vs (m/seq->double-array vs)]
(cond
(sequential? typ) (cond
(= :mode (first typ)) (let [[_ method opts] typ]
(/ (- (mean vs) (mode vs method opts)) (stddev vs)))
(#{:B1 :yule} (first typ)) (yule-skewness vs (second typ)))
(= :mode typ) (/ (- (mean vs) (mode vs)) (stddev vs))
(= :median typ) (/ (* 3.0 (- (mean vs) (median vs))) (stddev vs))
(#{:B1 :yule} typ) (yule-skewness vs 0.25)
(= :B3 typ) (let [v (median vs)]
(/ (- (mean vs) v)
(moment vs 1.0 {:absolute? true :center v})))
:else (let [^Skewness k (Skewness.)
n (alength vs)
v (.evaluate k vs)]
(cond
(= :b1 typ) (* v (/ (* (- n 2.0) (dec n)) (* n n)))
(#{:pearson :g1} typ) (* v (/ (- n 2.0) (m/sqrt (* n (dec n)))))
(= :skew typ) (* v (/ (- n 2.0) (* n (m/sqrt (dec n))))) ;; artificial, to match BCa skew definition
:else v))))))
(defn kurtosis
"Calculate kurtosis from sequence.
Possible typs: `:G2` (default), `:g2` (or `:excess`), `:geary` or `:kurt`."
(^double [vs] (kurtosis vs nil))
(^double [vs typ]
(let [vs (m/seq->double-array vs)
n (alength vs) ]
(if (= typ :geary)
(/ (mean-absolute-deviation vs)
(population-stddev vs))
(let [^Kurtosis k (Kurtosis.)
v (.evaluate k vs)]
(cond
(#{:excess :g2} typ) (/ (- (/ (* v (- n 2) (- n 3)) (dec n)) 6.0)
(inc n))
(= :kurt typ) (+ 3.0 (/ (- (/ (* v (- n 2) (- n 3)) (dec n)) 6.0)
(inc n)))
:else v))))))
(defn ci
"T-student based confidence interval for given data. Alpha value defaults to 0.05.
Last value is mean."
([vs] (ci vs 0.05))
([vs ^double alpha]
(let [vsa (m/seq->double-array vs)
cnt (count vs)
dist (r/distribution :t {:degrees-of-freedom (dec cnt)})
^double crit-val (r/icdf dist (- 1.0 (* 0.5 alpha)))
mean-ci (/ (* crit-val (stddev vsa)) (m/sqrt cnt))
mn (mean vsa)]
[(- mn mean-ci) (+ mn mean-ci) mn])))
;; https://ocw.mit.edu/courses/mathematics/18-05-introduction-to-probability-and-statistics-spring-2014/readings/MIT18_05S14_Reading24.pdf
(defn bootstrap-ci
"Bootstrap method to calculate confidence interval.
Alpha defaults to 0.98, samples to 1000.
Last parameter is statistical function used to measure, default: [[mean]].
Returns ci and statistical function value."
{:deprecated "Please use fastmath.stats.boostrap/ci-basic instead"}
([vs] (bootstrap-ci vs 0.98))
([vs alpha] (bootstrap-ci vs alpha 1000))
([vs alpha samples] (bootstrap-ci vs alpha samples mean))
([vs ^double alpha ^long samples stat-fn]
(let [vsa (m/seq->double-array vs)
cnt (count vs)
dist (r/distribution :enumerated-real {:data vsa})
^double m (stat-fn vsa)
deltas (m/seq->double-array (repeatedly samples #(- ^double (mean (r/->seq dist cnt)) m)))
q1 (quantile deltas alpha)
q2 (quantile deltas (- 1.0 alpha))]
[(- m q1) (- m q2) m])))
(defn bootstrap
{:doc "Generate set of samples of given size from provided data.
Default `samples` is 200, number of `size` defaults to sample size."
:deprecated "Please use fastmath.stats.bootstrap/bootstrap instead"}
([vs] (bootstrap vs 200))
([vs samples] (bootstrap vs samples (count vs)))
([vs samples size]
(let [dist (r/distribution :enumerated-real {:data vs})]
(repeatedly samples #(r/->seq dist size)))))
(defn stats-map
"Calculate several statistics of `vs` and return as map.
Optional `estimation-strategy` argument can be set to change quantile calculations estimation type. See [[estimation-strategies]]."
([vs] (stats-map vs :legacy))
([vs estimation-strategy]
(let [avs (m/seq->double-array vs)
sz (alength avs)
mn (smile.math.MathEx/min avs)
mx (smile.math.MathEx/max avs)
sm (smile.math.MathEx/sum avs)
u (/ sm sz)
mdn (median avs)
q1 (percentile avs 25.0 estimation-strategy)
q3 (percentile avs 75.0 estimation-strategy)
iqr (- q3 q1)
sd (stddev avs)
mad (median-absolute-deviation avs)
[lav uav] (adjacent-values avs q1 q3 mdn)]
{:Size sz
:Min mn
:Max mx
:Range (- mx mn)
:Mean u
:Median mdn
:Mode (mode avs)
:Q1 q1
:Q3 q3
:Total sm
:SD sd
:Variance (* sd sd)
:MAD mad
:SEM (/ sd (m/sqrt sz))
:LAV lav
:UAV uav
:IQR iqr
:LOF (- q1 (* 3.0 iqr))
:UOF (+ q3 (* 3.0 iqr))
:LIF (- q1 (* 1.5 iqr))
:UIF (+ q3 (* 1.5 iqr))
:Outliers (outliers avs q1 q3)
:Kurtosis (kurtosis avs)
:Skewness (skewness avs)})))
(defn standardize
"Normalize samples to have mean = 0 and stddev = 1."
[vs]
(seq ^doubles (StatUtils/normalize (m/seq->double-array vs))))
(defn robust-standardize
"Normalize samples to have median = 0 and MAD = 1.
If `q` argument is used, scaling is done by quantile difference (Q_q, Q_(1-q)). Set 0.25 for IQR."
([vs]
(let [avs (m/seq->double-array vs)
mad (median-absolute-deviation avs)
md (median avs)]
(map (fn [^double x] (/ (- x md) mad)) vs)))
([vs ^double q]
(let [[^double q1 ^double md ^double q2] (quantiles vs [q 0.5 (- 1.0 q)])
diff (m/abs (- q2 q1))]
(map (fn [^double x] (/ (- x md) diff)) vs))))
(defn demean
"Subtract mean from sequence"
[vs]
(let [m (mean vs)]
(map (fn [^double v]
(- v m)) vs)))
(defn winsor
"Return winsorized data. Trim is done by using quantiles, by default is set to 0.2."
([vs] (winsor vs 0.2))
([vs quantile] (winsor vs quantile :legacy))
([vs ^double quantile estimation-strategy]
(let [[qlow qmid qhigh] (quantiles (remove m/nan? vs)
[quantile 0.5 (- 1.0 quantile)] estimation-strategy)]
(winsor vs qlow qhigh qmid)))
([vs ^double low ^double high nan]
(let [[^double low ^double high] (if (< low high) [low high] [high low])]
(map (fn [^double v]
(if (m/nan? v)
nan
(m/constrain v low high))) vs))))
(defn trim
"Return trimmed data. Trim is done by using quantiles, by default is set to 0.2."
([vs] (trim vs 0.2))
([vs quantile] (trim vs quantile :legacy))
([vs ^double quantile estimation-strategy]
(let [[qlow qmid qhigh] (quantiles (remove m/nan? vs)
[quantile 0.5 (- 1.0 quantile)] estimation-strategy)]
(trim vs qlow qhigh qmid)))
([vs ^double low ^double high nan]
(let [[^double low ^double high] (if (< low high) [low high] [high low])]
(->> (filter (fn [^double v]
(or (m/nan? v)
(<= low v high))) vs)
(map (fn [^double v] (if (m/nan? v) nan v)))))))
(defn rescale
"Lineary rascale data to desired range, [0,1] by default"
([vs] (rescale vs 0.0 1.0))
([vs ^double low ^double high]
(let [avs (m/seq->double-array vs)
mn (minimum avs)
mx (maximum avs)
n (m/make-norm mn mx low high)]
(map n vs))))
(defn covariance
"Covariance of two sequences."
(^double [[vs1 vs2]] (covariance vs1 vs2))
(^double [vs1 vs2]
(smile.math.MathEx/cov (m/seq->double-array vs1) (m/seq->double-array vs2))))
(defn correlation
"Correlation of two sequences."
(^double [[vs1 vs2]] (correlation vs1 vs2))
(^double [vs1 vs2]
(smile.math.MathEx/cor (m/seq->double-array vs1) (m/seq->double-array vs2))))
(defn spearman-correlation
"Spearman's correlation of two sequences."
(^double [[vs1 vs2]] (spearman-correlation vs1 vs2))
(^double [vs1 vs2]
(.correlation ^SpearmansCorrelation (SpearmansCorrelation.) (m/seq->double-array vs1) (m/seq->double-array vs2))))
(defn pearson-correlation
"Pearson's correlation of two sequences."
(^double [[vs1 vs2]] (pearson-correlation vs1 vs2))
(^double [vs1 vs2]
(.correlation ^PearsonsCorrelation (PearsonsCorrelation.) (m/seq->double-array vs1) (m/seq->double-array vs2))))
(defn kendall-correlation
"Kendall's correlation of two sequences."
(^double [[vs1 vs2]] (kendall-correlation vs1 vs2))
(^double [vs1 vs2]
(.correlation ^KendallsCorrelation (KendallsCorrelation.) (m/seq->double-array vs1) (m/seq->double-array vs2))))
(defn kullback-leibler-divergence
"Kullback-Leibler divergence of two sequences."
(^double [[vs1 vs2]] (kullback-leibler-divergence vs1 vs2))
(^double [vs1 vs2]
(smile.math.MathEx/KullbackLeiblerDivergence (m/seq->double-array vs1) (m/seq->double-array vs2))))
(defn jensen-shannon-divergence
"Jensen-Shannon divergence of two sequences."
(^double [[vs1 vs2]] (jensen-shannon-divergence vs1 vs2))
(^double [vs1 vs2]
(smile.math.MathEx/JensenShannonDivergence (m/seq->double-array vs1) (m/seq->double-array vs2))))
(defn coefficient-matrix
"Generate coefficient (correlation, covariance, any two arg function) matrix from seq of seqs. Row order.
Default method: pearson-correlation"
([vss] (coefficient-matrix vss pearson-correlation))
([vss measure-fn] (coefficient-matrix vss measure-fn true))
([vss measure-fn symmetric?]
(if symmetric?
(let [avss (map-indexed (fn [id v] [id (m/seq->double-array v)]) vss)
cache (atom {})]
(for [[^long id1 ^doubles a] avss]
(mapv (fn [[^long id2 ^doubles b]]
(let [key (if (< id1 id2) [id1 id2] [id2 id1])]
(if (contains? @cache key)
(@cache key)
(let [cov (measure-fn a b)]
(swap! cache assoc key cov)
cov)))) avss)))
(let [avss (map m/seq->double-array vss)]
(for [^doubles a avss]
(mapv #(measure-fn a ^doubles %) avss))))))
(defn correlation-matrix
"Generate correlation matrix from seq of seqs. Row order.
Possible measures: `:pearson` (default), `:kendall`, `:spearman`, `:kullback-leibler` and `jensen-shannon`."
([vss] (correlation-matrix vss :pearson))
([vss measure]
(let [measure (get {:pearson pearson-correlation
:kendall kendall-correlation
:spearman spearman-correlation
:kullback-leibler kullback-leibler-divergence
:jensen-shannon jensen-shannon-divergence} measure pearson-correlation)]
(coefficient-matrix vss measure true))))
(defn covariance-matrix
"Generate covariance matrix from seq of seqs. Row order."
[vss] (coefficient-matrix vss covariance true))
(defn- maybe-number->seq [v] (if (number? v) (repeat v) v))
(defn me
"Mean error"
(^double [[vs1 vs2-or-val]] (me vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(mean (map m/fast- vs1 (maybe-number->seq vs2-or-val)))))
(defn mae
"Mean absolute error"
(^double [[vs1 vs2-or-val]] (mae vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(mean (map (comp m/abs m/fast-) vs1 (maybe-number->seq vs2-or-val)))))
(defn mape
"Mean absolute percentage error"
(^double [[vs1 vs2-or-val]] (mape vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(mean (map (fn [^double a ^double b]
(m/abs (/ (- a b) a))) vs1 (maybe-number->seq vs2-or-val)))))
(defn rss
"Residual sum of squares"
(^double [[vs1 vs2-or-val]] (rss vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(sum (map (comp m/sq m/fast-) vs1 (maybe-number->seq vs2-or-val)))))
(defn r2
"R2"
(^double [[vs1 vs2-or-val]] (r2 vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(- 1.0 (/ (rss vs1 vs2-or-val)
(moment vs1 2 {:mean? false})))))
(defn mse
"Mean squared error"
(^double [[vs1 vs2-or-val]] (mse vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(mean (map (comp m/sq m/fast-) vs1 (maybe-number->seq vs2-or-val)))))
(defn rmse
"Root mean squared error"
(^double [[vs1 vs2-or-val]] (rmse vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(m/sqrt (mse vs1 vs2-or-val))))
(defn count=
"Count equal values in both seqs. Same as [[L0]]"
(^long [[vs1 vs2-or-val]] (count= vs1 vs2-or-val))
(^long [vs1 vs2-or-val]
(count (filter (fn [^double v] (zero? v)) (map m/fast- vs1 (maybe-number->seq vs2-or-val))))))
(def ^{:doc "Count equal values in both seqs. Same as [[count==]]"} L0 count=)
(defn L1
"Manhattan distance"
(^double [[vs1 vs2-or-val]] (L1 vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(d/manhattan vs1 (take (count vs1) (maybe-number->seq vs2-or-val)))))
(defn L2sq
"Squared euclidean distance"
(^double [[vs1 vs2-or-val]] (L2sq vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(d/euclidean-sq vs1 (take (count vs1) (maybe-number->seq vs2-or-val)))))
(defn L2
"Euclidean distance"
(^double [[vs1 vs2-or-val]] (L2 vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(d/euclidean vs1 (take (count vs1) (maybe-number->seq vs2-or-val)))))
(defn LInf
"Chebyshev distance"
(^double [[vs1 vs2-or-val]] (LInf vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(d/chebyshev vs1 (take (count vs1) (maybe-number->seq vs2-or-val)))))
(defn psnr
"Peak signal to noise, `max-value` is maximum possible value (default: max from `vs1` and `vs2`)"
(^double [[vs1 vs2-or-val]] (psnr vs1 vs2-or-val))
(^double [vs1 vs2-or-val]
(let [mx1 (maximum vs1)
^double mx2 (if (number? vs2-or-val) vs2-or-val (maximum vs2-or-val))]
(psnr vs1 vs2-or-val (max mx1 mx2))))
(^double [vs1 vs2-or-val ^double max-value]
(- (* 20.0 (m/log10 max-value))
(* 10.0 (m/log10 (mse vs1 vs2-or-val))))))
;;
(defn- scott-fd-helper
"Calculate number of bins based on width of the bin."
^double [vvs ^double h]
(let [h (if (< h m/EPSILON) (median-absolute-deviation vvs) h)]
(if (pos? h)
(let [[^double mn ^double mx] (extent vvs)]
(m/ceil (/ (- mx mn) h)))
1.0)))
(defn estimate-bins
"Estimate number of bins for histogram.
Possible methods are: `:sqrt` `:sturges` `:rice` `:doane` `:scott` `:freedman-diaconis` (default).
The number returned is not higher than number of samples."
([vs] (estimate-bins vs :freedman-diaconis))
([vs bins-or-estimate-method]
(if-not (keyword? bins-or-estimate-method)
(or bins-or-estimate-method (estimate-bins vs))
(let [n (count vs)]