-
Notifications
You must be signed in to change notification settings - Fork 0
/
cl-statistics.lisp
1834 lines (1552 loc) · 72.5 KB
/
cl-statistics.lisp
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
;;; Statistical functions in Common Lisp. Version 1.04 Feb 24, 2005
;;;
;;; This code is copyright (c) 2000, 2001, 2002, 2005 by Larry Hunter
;;; ([email protected]) except where otherwise noted.
;;; Thanks to Paul Cohen for the original CLASP package. Thanks also to bug
;;; reports from Rob St. Amant and Lee Ayres, and several bug fixes from
;;; Robert Goldman.
;;;
;;; This program is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU Lesser General Public License as published by the
;;; Free Software Foundation; either version 2 of the License, or (at your
;;; option) any later version.
;;; This program is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;; You should have received a copy of the GNU Lesser General Public License along
;;; with this program; if not, write to the Free Software Foundation, Inc.,
;;; 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;; The formulas and methods used are largely taken from Bernard Rosner,
;;; "Fundamentals of Biostatistics," 5th edition. "Rosner x" is a page
;;; number. Some numeric functions were taken from CLASP, a 1994 common
;;; lisp package that implemented some of the statistical functions from
;;; "Numeric recipes in C" For CLASP functions, see copyright notice below.
;;; These abreviations used in function and variable names:
;;; ci = confidence interval
;;; cdf = cumulative density function
;;; ge = greater than or equal to
;;; le = less than or equal to
;;; pdf = probability density function
;;; sd = standard deviation
;;; rxc = rows by columns
;;; sse = sample size estimate
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Functions provided:
;;;
;;; Descriptive statistics
;;; Mean, median, mode, geometric mean, range, percentile, variance,
;;; standard-deviation (sd), coefficient-of-variation,
;;; standard-error-of-the-mean
;;;
;;; Distributional functions
;;; Poisson & Binomial
;;; binomial-probability, binomial-cumulative-probability,
;;; binomial-ge-probability, poisson-probability,
;;; poisson-cumulative-probability, poisson-ge-probability, Normal
;;; normal-pdf, convert-to-standard-normal, phi, z, t-distribution,
;;; chi-square, chi-square-cdf
;;;
;;; Confidence Intervals
;;; binomial-probability-ci, poisson-mu-ci, normal-mean-ci,
;;; normal-mean-ci-on-sequences, normal-variance-ci,
;;; normal-variance-ci-on-sequence, normal-sd-ci
;;;
;;; Hypothesis tests (parametric)
;;; z-test, z-test-on-sequence, t-test-one-sample,
;;; t-test-one-sample-on-sequence, t-test-paired,
;;; t-test-paired-on-sequences, t-test-two-sample,
;;; t-test-two-sample-on-sequences, chi-square-test-one-sample, f-test,
;;; binomial-test-one-sample, binomial-test-two-sample, fisher-exact-test,
;;; mcnemars-test, poisson-test-one-sample
;;;
;;; Hypothesis tests (non-parametric)
;;; sign-test, sign-test-on-sequence, wilcoxon-signed-rank-test,
;;; chi-square-test-rxc, chi-square-test-for-trend
;;; Sample size estimates
;;; t-test-one-sample-sse, t-test-two-sample-sse
;;; t-test-paired-sse, binomial-test-one-sample-sse,
;;; binomial-test-two-sample-sse,
;;; binomial-test-paired-sse, correlation-sse
;;; Correlation and Regression
;;; linear-regression, correlation-coefficient,
;;; correlation-test-two-sample, spearman-rank-correlation
;;; Significance test functions
;;; t-significance, f-significance (chi square significance is calculated
;;; from chi-square-cdf in various ways depending on the problem).
;;; Utilities
;;; random-sample, random-pick, bin-and-count, fishers-z-transform,
;;; mean-sd-n, square, choose, permutations, round-float
(declaim (optimize (speed 3) (safety 1) (debug 1)))
(defpackage :statistics
(:nicknames :stats)
(:use :common-lisp)
(:export #:mean #:median #:mode #:geometric-mean #:range #:percentile
#:variance #:standard-deviation #:sd #:coefficient-of-variation
#:standard-error-of-the-mean #:permutations #:choose
#:binomial-probability #:binomial-cumulative-probability
#:binomial-ge-probability #:poisson-probability
#:poisson-cumulative-probability #:poisson-ge-probability
#:poisson-cdf #:normal-pdf #:convert-to-standard-normal #:phi #:z
#:t-distribution #:chi-square #:chi-square-cdf
#:binomial-probability-ci #:poisson-mu-ci #:normal-mean-ci
#:normal-mean-ci-on-sequence #:normal-variance-ci
#:normal-variance-ci-on-sequence #:normal-sd-ci
#:normal-sd-ci-on-sequence #:z-test #:z-test-on-sequence
#:t-test-one-sample #:t-test-one-sample-on-sequence
#:t-test-paired #:t-test-paired-on-sequences #:t-test-two-sample
#:t-test-two-sample-on-sequences #:chi-square-test-one-sample
#:f-test #:binomial-test-one-sample #:binomial-test-two-sample
#:fisher-exact-test #:mcnemars-test #:poisson-test-one-sample
#:sign-test #:sign-test-on-sequences #:wilcoxon-signed-rank-test
#:wilcoxon-signed-rank-test-on-sequences
#:chi-square-test-rxc #:chi-square-test-for-trend
#:t-test-one-sample-sse #:t-test-two-sample-sse
#:t-test-paired-sse #:binomial-test-one-sample-sse
#:binomial-test-two-sample-sse #:binomial-test-paired-sse
#:correlation-sse #:linear-regression #:correlation-coefficient
#:correlation-test-two-sample
#:correlation-test-two-sample-on-sequences #:spearman-rank-correlation
#:t-significance #:f-significance #:random-sample #:random-pick #:test-variables
#:bin-and-count #:fisher-z-transform #:mean-sd-n #:square
#:round-float #:false-discovery-correction
#:random-normal))
(in-package :statistics)
;;;;; Macros
;; This macro makes assertions more readable. There are several special
;; types defined: :probability (:prob), :positive-integer (:posint),
;; :positive-number (:posnum), :number-sequence (:numseq),
;; :positive-integer-sequence (:posintseq), :probability-sequence
;; (:probseq), :nonzero-number-sequence (:nonzero-numseq) and :percentage
;; (:percent). Other assertions are assumed to be internal types. The
;; arguments to test-variables are lists. The first element of the list is
;; a variable name, and the second element is either a special or built-in
;; type. If the variable binding is not of the type specified, and error is
;; signalled indicating the problem. One variable may have multiple type
;; requirements, which are conjunctive.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro test-variables (&rest args)
(let ((assertions nil))
(dolist (arg args (append `(or ,@(nreverse assertions))))
(let* ((name (first arg))
(type (second arg))
(test (case type
((:probability :prob)
`(and (numberp ,name) (not (minusp ,name)) (<= ,name 1)))
((:positive-integer :posint)
`(and (integerp ,name) (plusp ,name)))
((:positive-number :posnum)
`(and (numberp ,name) (plusp ,name)))
((:number-sequence :numseq)
`(and (typep ,name 'sequence) (every #'numberp ,name)
(not (null ,name))))
((:nonzero-number-sequence :nonzero-numseq)
`(and (typep ,name 'sequence) (not (null ,name))
(every #'(lambda (x) (and (numberp x) (not (= 0 x))))
,name)))
((:probability-sequence :probseq)
`(and (typep ,name 'sequence) (not (null ,name))
(every #'(lambda (x) (and (numberp x) (not (minusp x))
(<= x 1.0))) ,name)))
((:positive-integer-sequence :posintseq)
`(and (typep ,name 'sequence) (not (null ,name))
(every #'(lambda (x) (and (typep x 'integer) (plusp
x)))
,name)))
(:percentage
`(and (numberp ,name) (plusp ,name) (<= ,name 100)))
(:test (third arg))
(t `(typep ,name ',type))))
(message `(error
,(if (eql type :test)
name
(format nil "~a = ~~a is not a ~a" name
(case type
((:positive-integer :posint)
"positive integer")
((:positive-number :posnum)
"positive number")
((:probability :prob) "probability")
((:number-sequence :numseq)
"sequence of numbers")
((:nonzero-number-sequence
:nonzero-numseq)
"sequence of non-zero numbers")
((:positive-integer-sequence :posintseq)
"sequence of positive integers")
((:probability-sequence :probseq)
"sequence of probabilities")
((:percent :percentile) "percent")
(t type))))
,@(unless (eql type :test) `(,name)))))
(push `(unless ,test ,message) assertions)))))
;; SQUARE
(defmacro square (x)
`(* ,x ,x))
(defmacro underflow-goes-to-zero (&body body)
"Protects against floating point underflow errors and sets the value to 0.0 instead."
`(handler-case
(progn ,@body)
(floating-point-underflow (condition)
(declare (ignore condition))
(values 0.0d0))))
) ;end eval-when
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Descriptive statistics
;;;
;; MEAN
;; Rosner 10
(defun mean (sequence)
(test-variables (sequence :numseq))
(/ (reduce #'+ sequence) (length sequence)))
;; MEDIAN
;; Rosner 12 (and 19)
(defun median (sequence)
(test-variables (sequence :numseq))
(percentile sequence 50))
;; MODE
;; Rosner 14
;; returns two values: a list of the modes and the number of times they
;; occur. Rob St. Amant <[email protected]> suggested using a hash
;; table instead of an alist, and Lee Ayres <[email protected]> noted that
;; my revision failed to handle multiple modes properly.
(defun mode (sequence)
(test-variables (sequence :numseq))
(let ((count-table (make-hash-table :test #'eql))
(modes nil)
(mode-count 0))
(map nil (lambda (elt) (incf (gethash elt count-table 0))) sequence)
(maphash (lambda (key value)
(cond ((> value mode-count)
(setf modes (list key)
mode-count value))
((= value mode-count)
(push key modes))))
count-table)
(values modes mode-count)))
;; GEOMETRIC-MEAN
;; Rosner 16
(defun geometric-mean (sequence &optional (base 10))
(test-variables (sequence :nonzero-numseq) (base :posnum))
(expt base (mean (map 'list #'(lambda (x) (log x base)) sequence))))
;; RANGE
;; Rosner 18
(defun range (sequence)
(test-variables (sequence :numseq))
(- (reduce #'max sequence) (reduce #'min sequence)))
;; PERCENTILE
;; Rosner 19
;; NB: Aref is 0 based!
(defun percentile (sequence percent)
(test-variables (sequence :numseq) (percent :percentage))
(let* ((sorted-vect (coerce (sort (copy-seq sequence) #'<) 'simple-vector))
(n (length sorted-vect))
(k (* n (/ percent 100)))
(floor-k (floor k)))
(if (= k floor-k)
(/ (+ (aref sorted-vect k)
(aref sorted-vect (1- k)))
2)
(aref sorted-vect floor-k))))
;; VARIANCE
;; Rosner 21
(defun variance (sequence)
(test-variables (sequence :numseq))
(let ((mean (mean sequence))
(n (length sequence)))
(/ (reduce #'+ (map 'list #'(lambda (x) (square (- mean x))) sequence))
(1- n))))
;; STANDARD-DEVIATION (SD)
;; Rosner 21
(defun standard-deviation (sequence)
(test-variables (sequence :numseq))
(let ((mean (mean sequence))
(n (length sequence)))
(sqrt (/ (reduce #'+ (map 'list #'(lambda (x) (square (- mean x))) sequence))
(1- n)))))
(defun sd (sequence)
(test-variables (sequence :numseq))
(let ((mean (mean sequence))
(n (length sequence)))
(sqrt (/ (reduce #'+ (map 'list #'(lambda (x) (square (- mean x))) sequence))
(1- n)))))
;; COEFFICIENT-OF-VARIATION
;; Rosner 24
(defun coefficient-of-variation (sequence)
(* 100 (/ (standard-deviation sequence) (mean sequence))))
;; STANDARD-ERROR-OF-THE-MEAN
;; Rosner 172
(defun standard-error-of-the-mean (sequence)
(/ (standard-deviation sequence) (sqrt (length sequence))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Distributional functions
;;;
;;;
;;; Binomial and Poisson distributions
;;;
;; BIONOMIAL-PROBABILITY
;; exact: Rosner 93, approximate 105
;; P(X=k) for X a binomial random variable with parameters n & p.
;; Binomial expectations for seeing k events in N trials, each having
;; probability p. Use the Poisson approximation if N>100 and P<0.01.
(defun binomial-probability (n k p)
(test-variables (n :posint) (p :prob)
("K must be between 0 and N (inclusive)" :test (and (>= k 0) (<= k n))))
(if (and (> n 100) (< p 0.01))
(poisson-probability (* n p) k)
(let ((p (coerce p 'double-float)))
(* (choose n k)
(expt p k)
(expt (- 1 p) (- n k))))))
;; BINOMIAL-CUMULATIVE-PROBABILITY
;; Rosner 94
;; P(X<k) for X a binomial random variable with parameters n & p.
;; Bionomial expecations for fewer than k events in N trials, each having
;; probability p.
(defun binomial-cumulative-probability (n k p)
(test-variables (n :posint) (k :posint) (p :prob)
("K must be less than or equal to N" :test (<= k n)))
(let ((sum-up-to-k-1 0d0))
(dotimes (i k sum-up-to-k-1)
(incf sum-up-to-k-1 (binomial-probability n i p)))))
;; BINOMIAL-GE-PROBABILITY
;; Rosner 94
;; The probability of k or more occurances in N events, each with
;; probability p.
(defun binomial-ge-probability (n k p)
(- 1 (binomial-cumulative-probability n k p)))
;; Just for convenience later, binomial-le-probability
(defun binomial-le-probability (n k p)
(test-variables (n :posint) (k :posint) (p :prob)
("K must be less than or equal to N" :test (<= k n)))
(let ((sum-up-to-k 0d0))
(dotimes (i (1+ k) sum-up-to-k)
(incf sum-up-to-k (binomial-probability n i p)))))
;; POISSON-PROBABILITY
;; Rosner 100
;; Probability of seeing k events over a time period when the expected
;; number of events over that time is mu.
(defun poisson-probability (mu k)
(test-variables (mu :posnum) (k :posint))
(let ((mu (coerce mu 'double-float)))
(/ (* (exp (- mu)) (expt mu k))
(factorial k))))
;; POISSON-CUMULATIVE-PROBABILITY
;; Rosner 197
;; Probability of seeing fewer than K events over a time period when the
;; expected number events over that time is mu.
(defun poisson-cumulative-probability (mu k)
(test-variables (mu :posnum) (k :posint))
(if (< k 170)
(let ((sum 0d0))
(dotimes (x k sum)
(incf sum (poisson-probability mu x))))
(let ((mu (coerce mu 'double-float))
(k (coerce k 'double-float)))
(- 1d0 (gamma-incomplete k mu)))))
;; POISSON-GE-PROBABILITY
;; Probability of X or more events when expected is mu.
(defun poisson-ge-probability (mu x)
(- 1 (poisson-cumulative-probability mu x)))
;;;
;;; Normal distributional functions
;;;
;; NORMAL-PDF
;; The probability density function (PDF) for a normal distribution with
;; mean mu and variance sigma at point x.
;; Rosner 115
(defun Normal-pdf (x mu sigma)
(test-variables (x number) (mu number) (sigma :posnum))
(* (/ (* (sqrt (* 2 pi)) sigma))
(exp (* (- (/ (* 2 (square sigma)))) (square (- x mu))))))
;; CONVERT-TO-STANDARD-NORMAL
;; Rosner 130
;; Convert X from a Normal distribution with mean mu and variance sigma to
;; standard normal
(defun convert-to-standard-normal (x mu sigma)
(test-variables (x number) (mu number) (sigma :posnum))
(/ (- x mu) sigma))
;; PHI
;; the CDF of standard normal distribution
;; Rosner 125
(defun phi (x)
"Adopted from CLASP 1.4.3, see copyright notice at http://eksl-www.cs.umass.edu/clasp.html"
(test-variables (x number))
(setf x (coerce x 'double-float))
(locally (declare (type double-float x))
(* 0.5d0 (+ 1.0d0 (error-function (/ x (sqrt 2.0d0)))))))
;; Z
;; The inverse normal function, P(X<Zu) = u where X is distributed as the
;; standard normal. Uses binary search.
;; Rosner 128.
(defun z (percentile &key (epsilon 1d-15))
(test-variables (percentile :prob))
(let ((target (coerce percentile 'double-float)))
(do ((min -9d0 min)
(max 9d0 max)
(guess 0d0 (+ min (/ (- max min) 2d0))))
((< (- max min) epsilon) guess)
(let ((result (coerce (phi guess) 'double-float)))
(if (< result target)
(setq min guess)
(setq max guess))))))
;; T-DISTRIBUTION
;; Rosner 178
;; Returns the point which is the indicated percentile in the T distribution
;; with dof degrees of freedom
(defun t-distribution (dof percentile)
"Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html"
(test-variables (dof :posint) (percentile :prob))
(find-critical-value
#'(lambda (x) (t-significance x dof :tails :positive))
(- 1 percentile)))
;; CHI-SQUARE
;; Rosner 187
;; Returns the point which is the indicated percentile in the Chi Square
;; distribution with dof degrees of freedom.
(defun chi-square (dof percentile)
(test-variables (dof :posint) (percentile :prob))
(find-critical-value #'(lambda (x) (chi-square-cdf x dof))
(- 1 percentile)))
;; Chi-square-cdf computes the left hand tail area under the chi square
;; distribution under dof degrees of freedom up to X.
(defun chi-square-cdf (x dof)
"Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html"
(test-variables (x :posnum) (dof :posint))
(gamma-incomplete (* 0.5 dof) (* 0.5 x)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Confidence intervals
;;;
;; BINOMIAL-PROBABILITY-CI
;; Rosner 193 (approximate) & 194 (exact)
;; Confidence intervals on a binomial probability. If a binomial
;; probability of p has been observed in N trials, what is the 1-alpha
;; confidence interval around p? Approximate (using normal theory
;; approximation) when npq >= 10 unless told otherwise
(defun binomial-probability-ci (n p alpha &key exact?)
(test-variables (n :posint) (p :prob) (alpha :prob))
(if (and (> (* n p (- 1 p)) 10) (not exact?))
(let ((difference (* (z (- 1 (/ alpha 2)))
(sqrt (/ (* p (- 1 p)) n)))))
(values (- p difference) (+ p difference)))
(values (find-critical-value
(lambda (p1) (binomial-cumulative-probability n (floor (* p n)) p1))
(- 1 (/ alpha 2)))
(find-critical-value
(lambda (p2) (binomial-cumulative-probability n (1+ (floor (* p n))) p2))
(/ alpha 2)))))
;; POISSON-MU-CI
;; Confidence interval for the Poisson parameter mu
;; Rosner 197
;;
;; Given x observations in a unit of time, what is the 1-alpha confidence
;; interval on the Poisson parameter mu (= lambda*T)?
;;
;; Since find-critical-value assumes that the function is monotonic
;; increasing, adjust the value we are looking for taking advantage of
;; reflectiveness
(defun poisson-mu-ci (x alpha)
(test-variables (x :posnum) (alpha :prob))
(values
(find-critical-value
#'(lambda (mu) (poisson-cumulative-probability mu (1- x)))
(- 1 (/ alpha 2)))
(find-critical-value
#'(lambda (mu) (poisson-cumulative-probability mu x))
(/ alpha 2))))
;; NORMAL-MEAN-CI
;; Confidence interval for the mean of a normal distribution
;; Rosner 180
;; The 1-alpha percent confidence interval on the mean of a normal
;; distribution with parameters mean, sd & n.
(defun normal-mean-ci (mean sd n alpha)
(test-variables (mean number) (sd :posnum) (n :posint) (alpha :prob))
(let ((t-value (t-distribution (1- n) (- 1 (/ alpha 2)))))
(values (- mean (* t-value (/ sd (sqrt n))))
(+ mean (* t-value (/ sd (sqrt n)))))))
;; NORMAL-MEAN-CI-ON-SEQUENCE
;;
;; The 1-alpha confidence interval on the mean of a sequence of numbers
;; drawn from a Normal distribution.
(defun normal-mean-ci-on-sequence (sequence alpha)
(test-variables (alpha :prob)) ; sequence tested by mean-sd-n
(multiple-value-call #'normal-mean-ci (mean-sd-n sequence) alpha))
;; NORMAL-VARIANCE-CI
;; Rosner 190
;; The 1-alpha confidence interval on the variance of a sequence of numbers
;; drawn from a Normal distribution.
(defun normal-variance-ci (variance n alpha)
(test-variables (variance :posnum) (n :posint) (alpha :prob))
(let ((chi-square-low (chi-square (1- n) (- 1 (/ alpha 2))))
(chi-square-high (chi-square (1- n) (/ alpha 2)))
(numerator (* (1- n) variance)))
(values (/ numerator chi-square-low) (/ numerator chi-square-high))))
;; NORMAL-VARIANCE-CI-ON-SEQUENCE
(defun normal-variance-ci-on-sequence (sequence alpha)
(test-variables (sequence :numseq) (alpha :prob))
(let ((variance (variance sequence))
(n (length sequence)))
(normal-variance-ci variance n alpha)))
;; NORMAL-SD-CI
;; Rosner 190
;; As above, but a confidence inverval for the standard deviation.
(defun normal-sd-ci (sd n alpha)
(multiple-value-bind (low high)
(normal-variance-ci (square sd) n alpha)
(values (sqrt low) (sqrt high))))
;; NORMAL-SD-CI-ON-SEQUENCE
(defun normal-sd-ci-on-sequence (sequence alpha)
(test-variables (sequence :numseq) (alpha :prob))
(let ((sd (standard-deviation sequence))
(n (length sequence)))
(normal-sd-ci sd n alpha)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Hypothesis testing
;;;
;; Z-TEST
;; Rosner 228
;; The significance of a one sample Z test for the mean of a normal
;; distribution with known variance. mu is the null hypothesis mean, x-bar
;; is the observed mean, sigma is the standard deviation and N is the number
;; of observations. If tails is :both, the significance of a difference
;; between x-bar and mu. If tails is :positive, the significance of x-bar
;; is greater than mu, and if tails is :negative, the significance of x-bar
;; being less than mu. Returns a p value.
(defun z-test (x-bar n &key (mu 0) (sigma 1) (tails :both))
(test-variables (x-bar number) (n :posint) (mu number) (sigma :posnum))
(let ((z (/ (- x-bar mu) (/ sigma (sqrt n)))))
(ecase tails
(:both (if (< z 0)
(* 2 (phi z))
(* 2 (- 1 (phi z)))))
(:negative (phi z))
(:positive (- 1 (phi z))))))
;; Z-TEST-ON-SEQUENCE
(defun z-test-on-sequence (sequence &key (mu 0) (sigma 1) (tails :both))
(test-variables (sequence :numseq)) ; the rest handled by z-test
(let ((x-bar (mean sequence))
(n (length sequence)))
(z-test x-bar n :mu mu :sigma sigma :tails tails)))
;; T-TEST-ONE-SAMPLE
;; T-TEST-ONE-SAMPLE-ON-SEQUENCE
;; Rosner 216
;; The significance of a one sample T test for the mean of a normal
;; distribution with unknown variance. X-bar is the observed mean, sd is
;; the observed standard deviation, N is the number of observations and mu
;; is the test mean. -ON-SAMPLE is the same, but calculates the observed
;; values from a sequence of numbers.
(defun t-test-one-sample (x-bar sd n mu &key (tails :both))
(test-variables (x-bar number) (sd :posnum) (n :posint) (mu number))
(t-significance (/ (- x-bar mu) (/ sd (sqrt n))) (1- n) :tails tails))
(defun t-test-one-sample-on-sequence (sequence mu &key (tails :both))
(multiple-value-call #'t-test-one-sample
(mean-sd-n sequence) mu :tails tails))
;; T-TEST-PAIRED
;; Rosner 276
;; The significance of a paired t test for the means of two normal
;; distributions in a longitudinal study. D-bar is the mean difference, sd
;; is the standard deviation of the differences, N is the number of pairs.
(defun t-test-paired (d-bar sd n &key (tails :both))
(test-variables (d-bar number) (sd :posnum) (n :posint))
(t-significance (/ d-bar (/ sd (sqrt n))) (1- n) :tails tails))
;; T-TEST-PAIRED-ON-SEQUENCES
;; Rosner 276
;; The significance of a paired t test for means of two normal distributions
;; in a longitudinal study. Before is a sequence of before values, after is
;; the sequence of paired after values (which must be the same length as the
;; before sequence).
(defun t-test-paired-on-sequences (before after &key (tails :both))
(test-variables (before :numseq) (after :numseq)
("Before and after sequences must be of equal length"
:test (= (length before) (length after))))
(multiple-value-call #'t-test-paired
(mean-sd-n (map 'list #'- before after)) :tails tails))
;; T-TEST-TWO-SAMPLE
;; Rosner 282, 294, 297
;; The significance of the difference of two means (x-bar1 and x-bar2) with
;; standard deviations sd1 and sd2, and sample sizes n1 and n2 respectively.
;; The form of the two sample t test depends on whether the sample variances
;; are equal or not. If the variable variances-equal? is :test, then we
;; use an F test and the variance-significance-cutoff to determine if they
;; are equal. If the variances are equal, then we use the two sample t test
;; for equal variances. If they are not equal, we use the Satterthwaite
;; method, which has good type I error properties (at the loss of some
;; power).
(defun t-test-two-sample (x-bar1 sd1 n1 x-bar2 sd2 n2 &key
(variances-equal? :test)
(variance-significance-cutoff 0.05)
(tails :both))
(test-variables (x-bar1 number) (sd1 :posnum) (n1 :posint)
(x-bar2 number) (sd2 :posnum) (n2 :posint))
(let (t-statistic dof)
(if (ecase variances-equal?
(:test (> (f-test (square sd1) n1 (square sd2) n2 :tails tails)
variance-significance-cutoff))
((t :yes :equal) t)
((nil :no :unequal) nil))
(let ((s (sqrt (/ (+ (* (1- n1) (square sd1))
(* (1- n2) (square sd2)))
(+ n1 n2 -2)))))
(setq t-statistic (/ (- x-bar1 x-bar2)
(* s (sqrt (+ (/ n1) (/ n2)))))
dof (+ n1 n2 -2)))
(let* ((variance-ratio1 (/ (square sd1) n1))
(variance-ratio2 (/ (square sd2) n2)))
(setq t-statistic (/ (- x-bar1 x-bar2)
(sqrt (+ variance-ratio1 variance-ratio2)))
dof (round (/ (square (+ variance-ratio1 variance-ratio2))
(+ (/ (square variance-ratio1) (1- n1))
(/ (square variance-ratio2) (1- n2))))))))
(t-significance t-statistic dof :tails tails)))
;; T-TEST-TWO-SAMPLE-ON-SEQUENCES
;; Same as above, but providing the sequences rather than the summaries.
(defun t-test-two-sample-on-sequences (sequence1 sequence2 &key
(variance-significance-cutoff 0.05)
(tails :both))
(multiple-value-call #'t-test-two-sample
(mean-sd-n sequence1) (mean-sd-n sequence2) :tails tails
:variance-significance-cutoff variance-significance-cutoff))
;; F-TEST
;; Rosner 290
;; F test for the equality of two variances
(defun f-test (variance1 n1 variance2 n2 &key (tails :both))
(test-variables (variance1 :posnum) (n1 :posint) (variance2 :posnum) (n2 :posint))
(let ((significance (f-significance (/ variance1 variance2) (1- n1) (1- n2)
(not (eql tails :both)))))
(ecase tails
(:both significance)
(:positive (if (> variance1 variance2) significance (- 1 significance)))
(:negative (if (< variance1 variance2) significance (- 1 significance))))))
;; CHI-SQUARE-TEST-ONE-SAMPLE
;; Rosner 246
;; The significance of a one sample Chi square test for the variance of a
;; normal distribution. Variance is the observed variance, N is the number
;; of observations, and sigma-squared is the test variance.
(defun chi-square-test-one-sample (variance n sigma-squared &key (tails :both))
(test-variables (variance :posnum) (n :posint) (sigma-squared :posnum))
(let ((cdf (chi-square-cdf (/ (* (1- n) variance) sigma-squared) (1- n))))
(ecase tails
(:negative cdf)
(:positive (- 1 cdf))
(:both (if (<= variance sigma-squared)
(* 2 cdf)
(* 2 (- 1 cdf)))))))
;; BINOMIAL-TEST-ONE-SAMPLE
;; Rosner 249
;; The significance of a one sample test for the equality of an observed
;; probability p-hat to an expected probability p under a binomial
;; distribution with N observations. Use the normal theory approximation if
;; n*p*(1-p) > 10 (unless the exact flag is true).
(defun binomial-test-one-sample (p-hat n p &key (tails :both) (exact? nil))
(test-variables (p-hat :prob) (n :posint) (p :prob))
(let ((q (- 1 p)))
(if (and (> (* n p q) 10) (not exact?))
(let ((z (/ (- p-hat p) (sqrt (/ (* p q) n)))))
(ecase tails
(:negative (phi z))
(:positive (- 1 (phi z)))
(:both (* 2 (if (<= p-hat p) (phi z) (- 1 (phi z)))))))
(let* ((observed (round (* p-hat n)))
(probability-more-extreme
(if (<= p-hat p)
(binomial-cumulative-probability n observed p)
(binomial-ge-probability n observed p))))
(ecase tails
((:negative :positive) probability-more-extreme)
(:both (min (* 2 probability-more-extreme) 1.0)))))))
;; BINOMIAL-TEST-TWO-SAMPLE
;; Rosner 357
;; Are the observed probabilities of an event (p-hat1 and p-hat2) in N1/N2
;; trials different? The normal theory method implemented here. The exact
;; test is Fisher's contingency table method, below.
(defun binomial-test-two-sample (p-hat1 n1 p-hat2 n2 &key (tails :both)
(exact? nil))
(test-variables (p-hat1 :prob) (n1 :posint) (p-hat2 :prob) (n2 :posint))
(let* ((p-hat (/ (+ (* p-hat1 n1) (* p-hat2 n2)) (+ n1 n2)))
(q-hat (- 1 p-hat))
(z (/ (- (abs (- p-hat1 p-hat2)) (+ (/ (* 2 n1)) (/ (* 2 n2))))
(sqrt (* p-hat q-hat (+ (/ n1) (/ n2)))))))
(if (and (> (* n1 p-hat q-hat) 5)
(> (* n2 p-hat q-hat) 5)
(not exact?))
(* (- 1 (phi z)) (if (eql tails :both) 2 1))
(let ((contingency-table (make-array '(2 2))))
(setf (aref contingency-table 0 0) (* p-hat1 n1)
(aref contingency-table 0 1) (- 1 (* p-hat1 n1))
(aref contingency-table 1 0) (* p-hat2 n2)
(aref contingency-table 1 1) (- 1 (* p-hat2 n2)))
(fisher-exact-test contingency-table :tails tails)))))
;; FISHER-EXACT-TEST
;; Rosner 371
;; Fisher's exact test. Gives a p value for a particular 2x2 contingency table
(defun fisher-exact-test (contingency-table &key (tails :both))
(flet ((table-probability (a b c d)
(let ((n (+ a b c d)))
(/ (* (factorial (+ a b)) (factorial (+ c d))
(factorial (+ a c)) (factorial (+ b d)))
(* (factorial n) (factorial a) (factorial b)
(factorial c) (factorial d))))))
(let ((a (aref contingency-table 0 0))
(b (aref contingency-table 0 1))
(c (aref contingency-table 1 0))
(d (aref contingency-table 1 1)))
(test-variables (a number) (b number) (c number) (d number))
(let* ((row-margin1 (+ a b))
(row-margin2 (+ c d))
(column-margin1 (+ a c))
(column-margin2 (+ b d))
(n (+ a b c d))
(table-probabilities
(make-array (1+ (min row-margin1 row-margin2 column-margin1
column-margin2)))))
;; rearrange so that the first row and column marginals are
;; smallest. Only need to change first margins and a.
(cond ((and (< row-margin2 row-margin1) (< column-margin2 column-margin1))
(psetq a d
row-margin1 row-margin2
column-margin1 column-margin2))
((< row-margin2 row-margin1)
(psetq a c
row-margin1 row-margin2))
((< column-margin2 column-margin1)
(psetq a b
column-margin1 column-margin2)))
(dotimes (i (length table-probabilities))
(let* ((test-a i)
(test-b (- row-margin1 i))
(test-c (- column-margin1 i))
(test-d (- n (+ test-a test-b test-c))))
(setf (aref table-probabilities i)
(table-probability test-a test-b test-c test-d))))
(let ((above (reduce #'+ (subseq table-probabilities 0 (1+ a))))
(below (reduce #'+ (subseq table-probabilities a))))
(float
(ecase tails
((:both) (* 2 (min above below)))
((:positive) below)
((:negative) above))
1d0))))))
;; MCNEMARS-TEST
;; Rosner 379 and 381
;; McNemar's test for correlated proportions, used for longitudinal
;; studies. Look only at the number of discordant pairs (one treatment is
;; effective and the other is not). If the two treatments are A and B,
;; a-discordant-count is the number where A worked and B did not, and
;; b-discordant-count is the number where B worked and A did not.
(defun mcnemars-test (a-discordant-count b-discordant-count &key (exact? nil))
(test-variables (a-discordant-count :posint) (b-discordant-count :posint))
(let ((n (+ a-discordant-count b-discordant-count)))
(if (and (> n 20) (not exact?))
(let ((x2 (/ (square
(- (abs (- a-discordant-count b-discordant-count)) 1))
n)))
(- 1 (chi-square-cdf x2 1)))
(cond ((= a-discordant-count b-discordant-count) 1.0)
((< a-discordant-count b-discordant-count)
(* 2 (binomial-le-probability n a-discordant-count 1/2)))
(t (* 2 (binomial-ge-probability n a-discordant-count 1/2)))))))
;; POISSON-TEST-ONE-SAMPLE
;; Rosner 256 (approximation on 259)
;; The significance of a one sample test for the equality of an observed
;; number of events (observed) and an expected number mu under the poisson
;; distribution. Normal theory approximation is not that great, so don't
;; use it unless told.
(defun poisson-test-one-sample (observed mu &key (tails :both) (approximate? nil))
(test-variables (observed :posnum) (mu :posnum))
(if approximate?
(let ((x-square (/ (square (- observed mu)) mu)))
(- 1 (chi-square-cdf x-square 1)))
(let ((probability-more-extreme
(if (< observed mu)
(poisson-cumulative-probability mu observed)
(poisson-ge-probability mu observed))))
(ecase tails
((:negative :positive) probability-more-extreme)
(:both (min (* 2 probability-more-extreme) 1.0))))))
;;;
;;; Non-parametric hypothesis testing
;;;
;; SIGN-TEST
;; Rosner 335-7.
;; Really just a special case of the binomial one sample test with p = 1/2.
;; The normal theory version has a correction factor to make it a better
;; approximation.
(defun sign-test (plus-count minus-count &key (exact? nil) (tails :both))
(test-variables (plus-count :posint) (minus-count :posint))
(let* ((n (+ plus-count minus-count))
(p-hat (/ plus-count n)))
(if (or (< n 20) exact?)
(binomial-test-one-sample p-hat n 0.5 :tails tails :exact? t)
(let ((area (- 1 (phi (/ (1- (abs (- plus-count minus-count)))
(sqrt n))))))
(if (eql tails :both)
(* 2 area)
area)))))
;; SIGN-TEST-ON-SEQUENCE
;; Same as above, but takes two sequences and tests whether the entries in
;; one are different (greater or less) than the other.
(defun sign-test-on-sequences (sequence1 sequence2 &key (exact? nil) (tails :both))
(test-variables (sequence1 :numseq) (sequence2 :numseq)
("Sequences must be of equal length"
:test (= (length sequence1) (length sequence2))))
(let* ((differences (map 'list #'- sequence1 sequence2))
(plus-count (count #'plusp differences))
(minus-count (count #'minusp differences)))
(sign-test plus-count minus-count :exact? exact? :tails tails)))
;; WILCOXON-SIGNED-RANK-TEST
;; Rosner 341
;; A test on the ranking of positive and negative differences (are the
;; positive differences significantly larger/smaller than the negative
;; ones). Assumes a continuous and symmetric distribution of differences,
;; although not a normal one. This is the normal theory approximation,
;; which is only valid when N > 15.
;; This test is completely equivalent to the Mann-Whitney test.
(defun wilcoxon-signed-rank-test (differences &optional (tails :both))
(let* ((nonzero-differences (remove 0 differences :test #'=))
(sorted-list (sort (mapcar #'(lambda (dif)
(list (abs dif) (sign dif)))
nonzero-differences)
#'<
:key #'first))
(distinct-values (delete-duplicates (mapcar #'first sorted-list)))
(ties nil))
(when (< (length nonzero-differences) 16)
(error "This Wilcoxon Signed-Rank Test (normal approximation method) requires nonzero N > 15"))
(unless (member tails '(:positive :negative :both))
(error "tails must be one of :positive, :negative or :both, not ~a" tails))
; add avg-rank to the sorted values
(dolist (value distinct-values)
(let ((first (position value sorted-list :key #'first))
(last (position value sorted-list :key #'first :from-end t)))
(if (= first last)
(nconc (find value sorted-list :key #'first) (list (1+ first)))
(let ((number-tied (1+ (- last first)))