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