]> gitweb.factorcode.org Git - factor.git/blob - basis/random/random.factor
random: implement random for assocs.
[factor.git] / basis / random / random.factor
1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types alien.data arrays assocs
4 byte-arrays byte-vectors combinators combinators.short-circuit
5 fry hashtables hashtables.private hints io.backend io.binary
6 kernel locals math math.bitwise math.constants math.functions
7 math.order math.ranges namespaces sequences sequences.private
8 sets summary system typed vocabs ;
9 IN: random
10
11 SYMBOL: system-random-generator
12 SYMBOL: secure-random-generator
13 SYMBOL: random-generator
14
15 GENERIC# seed-random 1 ( tuple seed -- tuple' )
16 GENERIC: random-32* ( tuple -- r )
17 GENERIC: random-bytes* ( n tuple -- byte-array )
18
19 M: object random-bytes* ( n tuple -- byte-array )
20     [ [ <byte-vector> ] keep 4 /mod ] dip
21     [ pick '[ _ random-32* int <ref> _ push-all ] times ]
22     [
23         over zero?
24         [ 2drop ] [ random-32* int <ref> swap head append! ] if
25     ] bi-curry bi* B{ } like ;
26
27 HINTS: M\ object random-bytes* { fixnum object } ;
28
29 M: object random-32* ( tuple -- r ) 4 swap random-bytes* be> ;
30
31 ERROR: no-random-number-generator ;
32
33 M: no-random-number-generator summary
34     drop "Random number generator is not defined." ;
35
36 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
37
38 M: f random-32* ( obj -- * ) no-random-number-generator ;
39
40 : random-32 ( -- n ) random-generator get random-32* ;
41
42 TYPED: random-bytes ( n: fixnum -- byte-array: byte-array )
43     random-generator get random-bytes* ; inline
44
45 <PRIVATE
46
47 :: ((random-integer)) ( bits obj -- n required-bits )
48     obj random-32* 32 bits 32 - [ dup 0 > ] [
49         [ 32 shift obj random-32* + ] [ 32 + ] [ 32 - ] tri*
50     ] while drop ;
51
52 : (random-integer) ( n obj -- n' )
53     [ dup next-power-of-2 log2 ] dip ((random-integer))
54     [ * ] [ 2^ /i ] bi* ;
55
56 : random-integer ( n -- n' )
57     random-generator get (random-integer) ;
58
59 PRIVATE>
60
61 : random-bits ( numbits -- r ) 2^ random-integer ;
62
63 : random-bits* ( numbits -- n )
64     1 - [ random-bits ] keep set-bit ;
65
66 GENERIC: random ( obj -- elt )
67
68 M: integer random [ f ] [ random-integer ] if-zero ;
69
70 M: sequence random
71     [ f ] [
72         [ length random-integer ] keep nth
73     ] if-empty ;
74
75 M: assoc random >alist random ;
76
77 M: hashtable random
78     dup assoc-size [ drop f ] [
79         [ 0 ] [ array>> ] [ random ] tri* 1 + [
80             [ 2dup array-nth tombstone? [ 2 + ] 2dip ] loop
81         ] times [ 2 - ] dip
82         [ array-nth ] [ [ 1 + ] dip array-nth ] 2bi 2array
83     ] if-zero ;
84
85 : randomize-n-last ( seq n -- seq )
86     [ dup length dup ] dip - 1 max '[ dup _ > ]
87     [ [ random ] [ 1 - ] bi [ pick exchange-unsafe ] keep ]
88     while drop ;
89
90 : randomize ( seq -- randomized )
91     dup length randomize-n-last ;
92
93 ERROR: too-many-samples seq n ;
94
95 : sample ( seq n -- seq' )
96     2dup [ length ] dip < [ too-many-samples ] when
97     [ [ length iota >array ] dip [ randomize-n-last ] keep tail-slice* ]
98     [ drop ] 2bi nths ;
99
100 : delete-random ( seq -- elt )
101     [ length random-integer ] keep [ nth ] 2keep remove-nth! drop ;
102
103 : with-random ( tuple quot -- )
104     random-generator swap with-variable ; inline
105
106 : with-system-random ( quot -- )
107     system-random-generator get swap with-random ; inline
108
109 : with-secure-random ( quot -- )
110     secure-random-generator get swap with-random ; inline
111
112 <PRIVATE
113
114 : (uniform-random-float) ( min max obj -- n )
115     [ 4 4 ] dip [ random-bytes* uint deref >float ] curry bi@
116     2.0 32 ^ * +
117     [ over - 2.0 -64 ^ * ] dip
118     * + ; inline
119
120 PRIVATE>
121
122 : uniform-random-float ( min max -- n )
123     random-generator get (uniform-random-float) ; inline
124
125 : random-unit ( -- n )
126     0.0 1.0 uniform-random-float ; inline
127
128 : random-units ( length -- sequence )
129     random-generator get '[ 0.0 1.0 _ (uniform-random-float) ] replicate ;
130
131 : random-integers ( length n -- sequence )
132     random-generator get '[ _ _ (random-integer) ] replicate ;
133
134 : (cos-random-float) ( -- n )
135     0. 2pi uniform-random-float cos ;
136
137 : (log-sqrt-random-float) ( -- n )
138     random-unit log -2. * sqrt ;
139
140 : normal-random-float ( mean sigma -- n )
141     (cos-random-float) (log-sqrt-random-float) * * + ;
142
143 : lognormal-random-float ( mean sigma -- n )
144     normal-random-float e^ ;
145
146 : exponential-random-float ( lambda -- n )
147     random-unit log neg swap / ;
148
149 : weibull-random-float ( alpha beta -- n )
150     [
151         [ random-unit log neg ] dip
152         1. swap / ^
153     ] dip * ;
154
155 : pareto-random-float ( k alpha -- n )
156     [ random-unit ] dip recip ^ /f ;
157
158 :: (gamma-random-float>1) ( alpha beta -- n )
159     ! Uses R.C.H. Cheng, "The generation of Gamma
160     ! variables with non-integral shape parameters",
161     ! Applied Statistics, (1977), 26, No. 1, p71-74
162     2. alpha * 1 - sqrt :> ainv
163     alpha 4. log -      :> bbb
164     alpha ainv +        :> ccc
165
166     0 :> r! 0 :> z! 0 :> result! ! initialize locals
167     [
168         r {
169             [ 1. 4.5 log + + z 4.5 * - 0 >= ]
170             [ z log >= ]
171         } 1|| not
172     ] [
173         random-unit :> u1
174         random-unit :> u2
175
176         u1 1. u1 - / log ainv / :> v
177         alpha v e^ *           :> x
178         u1 sq u2 *              z!
179         bbb ccc v * + x -       r!
180
181         x beta *                result!
182     ] do while result ;
183
184 : (gamma-random-float=1) ( alpha beta -- n )
185     nip random-unit log neg * ;
186
187 :: (gamma-random-float<1) ( alpha beta -- n )
188     ! Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
189     alpha e + e / :> b
190
191     0 :> x! 0 :> p! ! initialize locals
192     [
193         p 1.0 > [
194             random-unit x alpha 1 - ^ >
195         ] [
196             random-unit x neg e^ >
197         ] if
198     ] [
199         random-unit b * p!
200         p 1.0 <= [
201             p 1. alpha / ^
202         ] [
203             b p - alpha / log neg
204         ] if x!
205     ] do while x beta * ;
206
207 : gamma-random-float ( alpha beta -- n )
208     {
209         { [ over 1 > ] [ (gamma-random-float>1) ] }
210         { [ over 1 = ] [ (gamma-random-float=1) ] }
211         [ (gamma-random-float<1) ]
212     } cond ;
213
214 : beta-random-float ( alpha beta -- n )
215     [ 1. gamma-random-float ] dip over zero?
216     [ 2drop 0 ] [ 1. gamma-random-float dupd + / ] if ;
217
218 :: von-mises-random-float ( mu kappa -- n )
219     ! Based upon an algorithm published in: Fisher, N.I.,
220     ! "Statistical Analysis of Circular Data", Cambridge
221     ! University Press, 1993.
222     kappa 1e-6 <= [
223         2pi random-unit *
224     ] [
225         4. kappa sq * 1. + sqrt 1. + :> a
226         a 2. a * sqrt - 2. kappa * / :> b
227         b sq 1. + 2. b * /           :> r
228
229         0 :> c! 0 :> _f! ! initialize locals
230         [
231             random-unit {
232                 [ 2. c - c * < ] [ 1. c - e^ c * <= ]
233             } 1|| not
234         ] [
235             random-unit pi * cos :> z
236             r z * 1. + r z + /   _f!
237             r _f - kappa *       c!
238         ] do while
239
240         mu 2pi mod _f cos random-unit 0.5 > [ + ] [ - ] if
241     ] if ;
242
243 :: (triangular-random-float) ( low high mode -- n )
244     mode low - high low - / :> c!
245     random-unit :> u!
246     high low
247     u c > [ 1. u - u! 1. c - c! swap ] when
248     [ - u c * sqrt * ] keep + ;
249
250 : triangular-random-float ( low high -- n )
251     2dup + 2 /f (triangular-random-float) ;
252
253 : laplace-random-float ( mean scale -- n )
254     random-unit dup 0.5 <
255     [ 2 * log ] [ 1 swap - 2 * log neg ] if * + ;
256
257 : cauchy-random-float ( median scale -- n )
258     random-unit 0.5 - pi * tan * + ;
259
260 : chi-square-random-float ( dof -- n )
261     [ 0.5 ] dip 2 * gamma-random-float ;
262
263 : student-t-random-float ( dof -- n )
264     [ 0 1 normal-random-float ] dip
265     [ chi-square-random-float ] [ / ] bi sqrt / ;
266
267 : inv-gamma-random-float ( shape scale -- n )
268     recip gamma-random-float recip ;
269
270 : rayleigh-random-float ( mode -- n )
271     random-unit log -2 * sqrt * ;
272
273 : gumbel-random-float ( loc scale -- n )
274     random-unit log neg log * - ;
275
276 : logistic-random-float ( loc scale -- n )
277     random-unit dup 1 swap - / log * + ;
278
279 : power-random-float ( alpha -- n )
280     [ random-unit log e^ 1 swap - ] dip recip ^ ;
281
282 {
283     { [ os windows? ] [ "random.windows" require ] }
284     { [ os unix? ] [ "random.unix" require ] }
285 } cond
286
287 "random.mersenne-twister" require