]> gitweb.factorcode.org Git - factor.git/blob - basis/math/statistics/statistics.factor
math.statistics: fix calculation of the harmonic mean
[factor.git] / basis / math / statistics / statistics.factor
1 ! Copyright (C) 2008 Doug Coleman, Michael Judge, Loryn Jenkins.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays assocs combinators fry generalizations grouping
4 kernel locals math math.functions math.order math.vectors
5 sequences sequences.private sorting ;
6 IN: math.statistics
7
8 : power-mean ( seq p -- x )
9     [ '[ _ ^ ] map-sum ] [ [ length / ] [ recip ^ ] bi* ] 2bi ; inline
10
11 ! Delta in degrees-of-freedom
12 : mean-ddof ( seq ddof -- x )
13     [ [ sum ] [ length ] bi ] dip -
14     [ drop 0 ] [ / ] if-zero ; inline
15
16 : mean ( seq -- x )
17     0 mean-ddof ; inline
18
19 : unbiased-mean ( seq -- x )
20     1 mean-ddof ; inline
21
22 : sum-of-squares ( seq -- x )
23     [ sq ] map-sum ; inline
24
25 : sum-of-squared-errors ( seq -- x )
26     [ mean ] keep [ - sq ] with map-sum ; inline
27
28 : sum-of-absolute-errors ( seq -- x )
29     [ mean ] keep [ - ] with map-sum ; inline
30
31 : quadratic-mean ( seq -- x ) ! root-mean-square
32     [ sum-of-squares ] [ length ] bi / sqrt ; inline
33
34 : geometric-mean ( seq -- x )
35     [ [ log ] map-sum ] [ length ] bi /f e^ ; inline
36
37 : harmonic-mean ( seq -- x )
38     [ [ recip ] map-sum ] [ length swap / ] bi ; inline
39
40 : contraharmonic-mean ( seq -- x )
41     [ sum-of-squares ] [ sum ] bi / ; inline
42
43 <PRIVATE
44
45 : trim-points ( p seq -- from to seq  )
46     [ length [ * >integer ] keep over - ] keep ;
47
48 PRIVATE>
49
50 : trimmed-mean ( seq p -- x )
51     swap natural-sort trim-points <slice> mean ;
52
53 : winsorized-mean ( seq p -- x )
54     swap natural-sort trim-points
55     [ <slice> ]
56     [ nip dupd nth <array> ]
57     [ [ 1 - ] dip nth <array> ] 3tri
58     surround mean ;
59
60 <PRIVATE
61
62 :: kth-object-impl ( seq k nth-quot exchange-quot quot: ( x y -- ? ) -- elt )
63     ! Wirth's method, Algorithm's + Data structues = Programs p. 84
64     k seq bounds-check 2drop
65     0 :> i!
66     0 :> j!
67     0 :> l!
68     0 :> x!
69     seq length 1 - :> m!
70     [ l m < ]
71     [
72         k seq nth-unsafe x!
73         l i!
74         m j!
75         [ i j <= ]
76         [
77             [ i seq nth-quot call x quot call ] [ i 1 + i! ] while
78             [ x j seq nth-quot call quot call ] [ j 1 - j! ] while
79             i j <= [
80                 i j seq exchange-quot call
81                 i 1 + i!
82                 j 1 - j!
83             ] when
84         ] do while
85
86         j k < [ i l! ] when
87         k i < [ j m! ] when
88     ] while
89     k seq nth-unsafe ; inline
90
91 : (kth-object) ( seq k nth-quot exchange-quot quot: ( x y -- ? ) -- elt )
92     ! The algorithm modifiers seq, so we clone it
93     [ >array ] 4dip kth-object-impl ; inline
94
95 : kth-object-unsafe ( seq k quot: ( x y -- ? ) -- elt )
96     [ [ nth-unsafe ] [ exchange-unsafe ] ] dip (kth-object) ; inline
97
98 : kth-objects-unsafe ( seq kths quot: ( x y -- ? ) -- elts )
99     '[ _ kth-object-unsafe ] with map ; inline
100
101 PRIVATE>
102
103 : kth-object ( seq k quot: ( x y -- ? ) -- elt )
104     [ [ nth ] [ exchange ] ] dip (kth-object) ; inline
105
106 : kth-objects ( seq kths quot: ( x y -- ? ) -- elts )
107     '[ _ kth-object ] with map ; inline
108
109 : kth-smallests ( seq kths -- elts ) [ < ] kth-objects-unsafe ;
110
111 : kth-smallest ( seq k -- elt ) [ < ] kth-object-unsafe ;
112
113 : kth-largests ( seq kths -- elts ) [ > ] kth-objects-unsafe ;
114
115 : kth-largest ( seq k -- elt ) [ > ] kth-object-unsafe ;
116
117 : count-relative ( seq k -- lt eq gt )
118     [ 0 0 0 ] 2dip '[
119         _ <=> {
120             { +lt+ [ [ 1 + ] 2dip ] }
121             { +gt+ [ 1 + ] }
122             { +eq+ [ [ 1 + ] dip ] }
123         } case
124     ] each ;
125
126 : minmax-relative ( seq k -- lt eq gt lt-max gt-min )
127     [ 0 0 0 -1/0. 1/0. ] 2dip '[
128         dup _ <=> {
129             { +lt+ [ [ 1 + ] 5 ndip '[ _ max ] dip ] }
130             { +gt+ [ [ 1 + ] 3dip min ] }
131             { +eq+ [ [ 1 + ] 4dip drop ] }
132         } case
133     ] each ;
134
135 : lower-median-index ( seq -- n )
136     [ midpoint@ ]
137     [ length odd? [ 1 - ] unless ] bi ;
138
139 : lower-median ( seq -- elt )
140     [ ] [ lower-median-index ] bi kth-smallest ;
141
142 : upper-median ( seq -- elt )
143     dup midpoint@ kth-smallest ;
144
145 : medians ( seq -- lower upper )
146     [ ]
147     [ [ lower-median-index ] [ midpoint@ ] bi 2array ]
148     bi kth-smallests first2 ;
149
150 : median ( seq -- x )
151     dup length odd? [ lower-median ] [ medians + 2 / ] if ;
152
153 ! quantile can be any n-tile. quartile is n = 4, percentile is n = 100
154 ! a,b,c,d parameters, N - number of samples, q is quantile (1/2 for median, 1/4 for 1st quartile)
155 ! http://mathworld.wolfram.com/Quantile.html
156 ! a + (N + b) q - 1
157 ! could subtract 1 from a
158
159 : quantile-x ( a b N q -- x )
160     [ + ] dip * + 1 - ; inline
161
162 ! 2+1/4 frac is 1/4
163 : frac ( x -- x' )
164     >fraction [ /mod nip ] keep / ; inline
165
166 :: quantile-indices ( seq qs a b -- seq )
167     qs [ [ a b seq length ] dip quantile-x ] map ;
168
169 :: qabcd ( y-floor y-ceiling x c d -- qabcd )
170     y-floor y-ceiling y-floor - c d x frac * + * + ;
171
172 :: quantile-abcd ( seq qs a b c d -- quantile )
173     seq qs a b quantile-indices :> indices
174     indices [ [ floor 0 max ] [ ceiling seq length 1 - min ] bi 2array ] map
175     concat :> index-pairs
176
177     seq index-pairs kth-smallests
178     2 group indices [ [ first2 ] dip c d qabcd ] 2map ;
179
180 : quantile1 ( seq qs -- seq' )
181     0 0 1 0 quantile-abcd ;
182
183 : quantile3 ( seq qs -- seq' )
184     1/2 0 0 0 quantile-abcd ;
185
186 : quantile4 ( seq qs -- seq' )
187     0 0 0 1 quantile-abcd ;
188
189 : quantile5 ( seq qs -- seq' )
190     1/2 0 0 1 quantile-abcd ;
191
192 : quantile6 ( seq qs -- seq' )
193     0 1 0 1 quantile-abcd ;
194
195 : quantile7 ( seq qs -- seq' )
196     1 -1 0 1 quantile-abcd ;
197
198 : quantile8 ( seq qs -- seq' )
199     1/3 1/3 0 1 quantile-abcd ;
200
201 : quantile9 ( seq qs -- seq' )
202     3/8 1/4 0 1 quantile-abcd ;
203
204 : quartile ( seq -- seq' )
205     { 1/4 1/2 3/4 } quantile5 ;
206
207 : trimean ( seq -- x )
208     quartile first3 [ 2 * ] dip + + 4 / ;
209
210 : histogram! ( hashtable seq -- hashtable )
211     over '[ _ inc-at ] each ;
212
213 : histogram-by ( seq quot: ( x -- bin ) -- hashtable )
214     H{ } clone [ '[ @ _ inc-at ] each ] keep ; inline
215
216 : histogram ( seq -- hashtable )
217     [ ] histogram-by ;
218
219 : sorted-histogram ( seq -- alist )
220     histogram sort-values ;
221
222 : normalized-histogram ( seq -- alist )
223     [ histogram ] [ length ] bi '[ _ / ] assoc-map ;
224
225 : equal-probabilities ( n -- array )
226     dup recip <array> ; inline
227
228 : mode ( seq -- x )
229     histogram >alist [ second ] supremum-by first ;
230
231 : minmax ( seq -- min max )
232     [ first dup ] keep [ [ min ] [ max ] bi-curry bi* ] 1 each-from ;
233
234 : range ( seq -- x )
235     minmax swap - ;
236
237 : var-ddof ( seq n -- x )
238     2dup [ length ] dip - 0 <= [
239         2drop 0
240     ] [
241         [ [ sum-of-squared-errors ] [ length ] bi ] dip - /
242     ] if ; inline
243
244 : population-var ( seq -- x ) 0 var-ddof ; inline
245
246 : sample-var ( seq -- x ) 1 var-ddof ; inline
247
248 : std-ddof ( seq n -- x ) var-ddof sqrt ; inline
249
250 : population-std ( seq -- x ) 0 std-ddof ; inline
251
252 : sample-std ( seq -- x ) 1 std-ddof ; inline
253
254 ALIAS: std sample-std
255
256 : signal-to-noise ( seq -- x ) [ mean ] [ population-std ] bi / ;
257
258 : demean ( seq -- seq' ) dup mean v-n ;
259
260 : mean-dev ( seq -- x ) demean vabs mean ;
261
262 : demedian ( seq -- seq' ) dup median v-n ;
263
264 : median-dev ( seq -- x ) demedian vabs mean ;
265
266 : ste-ddof ( seq n -- x ) '[ _ std-ddof ] [ length ] bi sqrt / ;
267
268 : population-ste ( seq -- x ) 0 ste-ddof ;
269
270 : sample-ste ( seq -- x ) 1 ste-ddof ;
271
272 <PRIVATE
273 : r-sum-diffs ( x-mean y-mean x-seq y-seq -- (r) )
274     ! finds sigma((xi-mean(x))(yi-mean(y))
275     0 [ [ [ pick ] dip swap - ] bi@ * + ] 2reduce 2nip ;
276
277 : (r) ( x-mean y-mean x-seq y-seq x-std y-std -- r )
278     * recip [ [ r-sum-diffs ] keep length 1 - / ] dip * ;
279
280 : r-stats ( xy-pairs -- x-mean y-mean x-seq y-seq x-std y-std )
281     first2 [ [ [ mean ] bi@ ] 2keep ] 2keep [ population-std ] bi@ ;
282 PRIVATE>
283
284 : pearson-r ( xy-pairs -- r ) r-stats (r) ;
285
286 : least-squares ( xy-pairs -- alpha beta )
287     r-stats [ 2dup ] 4 ndip
288     ! stack is x-mean y-mean x-mean y-mean x-seq y-seq x-std y-std
289     [ (r) ] 2keep ! stack is mean(x) mean(y) r sx sy
290     swap / * ! stack is mean(x) mean(y) beta
291     [ swapd * - ] keep ;
292
293 : cov-ddof ( x-seq y-seq ddof -- cov )
294     [ [ demean ] bi@ v* ] dip mean-ddof ;
295
296 : population-cov ( x-seq y-seq -- cov ) 0 cov-ddof ; inline
297
298 : sample-cov ( x-seq y-seq -- cov ) 1 cov-ddof ; inline
299
300 : corr-ddof ( x-seq y-seq n -- corr )
301     [ [ population-cov ] ] dip
302     '[ [ _ var-ddof ] bi@ * sqrt ] 2bi / ;
303
304 : population-corr ( x-seq y-seq -- corr ) 0 corr-ddof ; inline
305
306 : sample-corr ( x-seq y-seq -- corr ) 1 corr-ddof ; inline
307
308 : cum-sum ( seq -- seq' )
309     0 [ + ] accumulate* ;
310
311 : cum-sum0 ( seq -- seq' )
312     0 [ + ] accumulate nip ;
313
314 : cum-product ( seq -- seq' )
315     1 [ * ] accumulate* ;
316
317 : cum-product1 ( seq -- seq' )
318     1 [ * ] accumulate nip ;
319
320 : cum-mean ( seq -- seq' )
321     0 swap [ [ + dup ] dip 1 + / ] map-index nip ;
322
323 : cum-count ( seq quot: ( elt -- ? ) -- seq' )
324     [ 0 ] dip '[ @ [ 1 + ] when ] accumulate* ; inline
325
326 : cum-min ( seq -- seq' )
327     dup ?first [ min ] accumulate* ;
328
329 : cum-max ( seq -- seq' )
330     dup ?first [ max ] accumulate* ;
331
332 : entropy ( probabilities -- n )
333     dup sum '[ _ / dup log * ] map-sum neg ;
334
335 : maximum-entropy ( probabilities -- n )
336     length log ;
337
338 : normalized-entropy ( probabilities -- n )
339     [ entropy ] [ maximum-entropy ] bi / ;
340
341 : binary-entropy ( p -- h )
342     [ dup log * ] [ 1 swap - dup log * ] bi + neg 2 log / ;
343
344 : standardize ( u -- v )
345     [ demean ] [ sample-std ] bi [ v/n ] unless-zero ;
346
347 : standardize-2d ( u -- v )
348     flip [ standardize ] map flip ;
349
350 : differences ( u -- v )
351     [ rest-slice ] keep v- ;
352
353 : rescale ( u -- v )
354     dup minmax over - [ v-n ] [ v/n ] bi* ;
355
356 : rankings ( histogram -- assoc )
357     sort-keys 0 swap [ rot [ + ] keep swapd ] H{ } assoc-map-as nip ;
358
359 : rank-values ( seq -- seq' )
360     dup histogram rankings '[ _ at ] map ;
361
362 : z-score ( seq -- n )
363     [ demean ] [ sample-std ] bi v/n ;