]> git.lizzy.rs Git - rust.git/blob - src/librand/distributions/mod.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / librand / distributions / mod.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Sampling from random distributions.
12 //!
13 //! This is a generalization of `Rand` to allow parameters to control the
14 //! exact properties of the generated values, e.g. the mean and standard
15 //! deviation of a normal distribution. The `Sample` trait is the most
16 //! general, and allows for generating values that change some state
17 //! internally. The `IndependentSample` trait is for generating values
18 //! that do not need to record state.
19
20 #![unstable(feature = "rand")]
21
22 use core::prelude::*;
23 use core::num::{Float, Int};
24
25 use {Rng, Rand};
26
27 pub use self::range::Range;
28 pub use self::gamma::{Gamma, ChiSquared, FisherF, StudentT};
29 pub use self::normal::{Normal, LogNormal};
30 pub use self::exponential::Exp;
31
32 pub mod range;
33 pub mod gamma;
34 pub mod normal;
35 pub mod exponential;
36
37 /// Types that can be used to create a random instance of `Support`.
38 pub trait Sample<Support> {
39     /// Generate a random value of `Support`, using `rng` as the
40     /// source of randomness.
41     fn sample<R: Rng>(&mut self, rng: &mut R) -> Support;
42 }
43
44 /// `Sample`s that do not require keeping track of state.
45 ///
46 /// Since no state is recorded, each sample is (statistically)
47 /// independent of all others, assuming the `Rng` used has this
48 /// property.
49 // FIXME maybe having this separate is overkill (the only reason is to
50 // take &self rather than &mut self)? or maybe this should be the
51 // trait called `Sample` and the other should be `DependentSample`.
52 pub trait IndependentSample<Support>: Sample<Support> {
53     /// Generate a random value.
54     fn ind_sample<R: Rng>(&self, &mut R) -> Support;
55 }
56
57 /// A wrapper for generating types that implement `Rand` via the
58 /// `Sample` & `IndependentSample` traits.
59 pub struct RandSample<Sup>;
60
61 impl<Sup: Rand> Sample<Sup> for RandSample<Sup> {
62     fn sample<R: Rng>(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) }
63 }
64
65 impl<Sup: Rand> IndependentSample<Sup> for RandSample<Sup> {
66     fn ind_sample<R: Rng>(&self, rng: &mut R) -> Sup {
67         rng.gen()
68     }
69 }
70
71 /// A value with a particular weight for use with `WeightedChoice`.
72 pub struct Weighted<T> {
73     /// The numerical weight of this item
74     pub weight: uint,
75     /// The actual item which is being weighted
76     pub item: T,
77 }
78
79 /// A distribution that selects from a finite collection of weighted items.
80 ///
81 /// Each item has an associated weight that influences how likely it
82 /// is to be chosen: higher weight is more likely.
83 ///
84 /// The `Clone` restriction is a limitation of the `Sample` and
85 /// `IndependentSample` traits. Note that `&T` is (cheaply) `Clone` for
86 /// all `T`, as is `uint`, so one can store references or indices into
87 /// another vector.
88 ///
89 /// # Example
90 ///
91 /// ```rust
92 /// use std::rand;
93 /// use std::rand::distributions::{Weighted, WeightedChoice, IndependentSample};
94 ///
95 /// let mut items = vec!(Weighted { weight: 2, item: 'a' },
96 ///                      Weighted { weight: 4, item: 'b' },
97 ///                      Weighted { weight: 1, item: 'c' });
98 /// let wc = WeightedChoice::new(items.as_mut_slice());
99 /// let mut rng = rand::thread_rng();
100 /// for _ in 0..16 {
101 ///      // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
102 ///      println!("{}", wc.ind_sample(&mut rng));
103 /// }
104 /// ```
105 pub struct WeightedChoice<'a, T:'a> {
106     items: &'a mut [Weighted<T>],
107     weight_range: Range<uint>
108 }
109
110 impl<'a, T: Clone> WeightedChoice<'a, T> {
111     /// Create a new `WeightedChoice`.
112     ///
113     /// Panics if:
114     /// - `v` is empty
115     /// - the total weight is 0
116     /// - the total weight is larger than a `uint` can contain.
117     pub fn new(items: &'a mut [Weighted<T>]) -> WeightedChoice<'a, T> {
118         // strictly speaking, this is subsumed by the total weight == 0 case
119         assert!(!items.is_empty(), "WeightedChoice::new called with no items");
120
121         let mut running_total = 0;
122
123         // we convert the list from individual weights to cumulative
124         // weights so we can binary search. This *could* drop elements
125         // with weight == 0 as an optimisation.
126         for item in &mut *items {
127             running_total = match running_total.checked_add(item.weight) {
128                 Some(n) => n,
129                 None => panic!("WeightedChoice::new called with a total weight \
130                                larger than a uint can contain")
131             };
132
133             item.weight = running_total;
134         }
135         assert!(running_total != 0, "WeightedChoice::new called with a total weight of 0");
136
137         WeightedChoice {
138             items: items,
139             // we're likely to be generating numbers in this range
140             // relatively often, so might as well cache it
141             weight_range: Range::new(0, running_total)
142         }
143     }
144 }
145
146 impl<'a, T: Clone> Sample<T> for WeightedChoice<'a, T> {
147     fn sample<R: Rng>(&mut self, rng: &mut R) -> T { self.ind_sample(rng) }
148 }
149
150 impl<'a, T: Clone> IndependentSample<T> for WeightedChoice<'a, T> {
151     fn ind_sample<R: Rng>(&self, rng: &mut R) -> T {
152         // we want to find the first element that has cumulative
153         // weight > sample_weight, which we do by binary since the
154         // cumulative weights of self.items are sorted.
155
156         // choose a weight in [0, total_weight)
157         let sample_weight = self.weight_range.ind_sample(rng);
158
159         // short circuit when it's the first item
160         if sample_weight < self.items[0].weight {
161             return self.items[0].item.clone();
162         }
163
164         let mut idx = 0;
165         let mut modifier = self.items.len();
166
167         // now we know that every possibility has an element to the
168         // left, so we can just search for the last element that has
169         // cumulative weight <= sample_weight, then the next one will
170         // be "it". (Note that this greatest element will never be the
171         // last element of the vector, since sample_weight is chosen
172         // in [0, total_weight) and the cumulative weight of the last
173         // one is exactly the total weight.)
174         while modifier > 1 {
175             let i = idx + modifier / 2;
176             if self.items[i].weight <= sample_weight {
177                 // we're small, so look to the right, but allow this
178                 // exact element still.
179                 idx = i;
180                 // we need the `/ 2` to round up otherwise we'll drop
181                 // the trailing elements when `modifier` is odd.
182                 modifier += 1;
183             } else {
184                 // otherwise we're too big, so go left. (i.e. do
185                 // nothing)
186             }
187             modifier /= 2;
188         }
189         return self.items[idx + 1].item.clone();
190     }
191 }
192
193 mod ziggurat_tables;
194
195 /// Sample a random number using the Ziggurat method (specifically the
196 /// ZIGNOR variant from Doornik 2005). Most of the arguments are
197 /// directly from the paper:
198 ///
199 /// * `rng`: source of randomness
200 /// * `symmetric`: whether this is a symmetric distribution, or one-sided with P(x < 0) = 0.
201 /// * `X`: the $x_i$ abscissae.
202 /// * `F`: precomputed values of the PDF at the $x_i$, (i.e. $f(x_i)$)
203 /// * `F_DIFF`: precomputed values of $f(x_i) - f(x_{i+1})$
204 /// * `pdf`: the probability density function
205 /// * `zero_case`: manual sampling from the tail when we chose the
206 ///    bottom box (i.e. i == 0)
207
208 // the perf improvement (25-50%) is definitely worth the extra code
209 // size from force-inlining.
210 #[inline(always)]
211 fn ziggurat<R: Rng, P, Z>(
212             rng: &mut R,
213             symmetric: bool,
214             x_tab: ziggurat_tables::ZigTable,
215             f_tab: ziggurat_tables::ZigTable,
216             mut pdf: P,
217             mut zero_case: Z)
218             -> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 {
219     static SCALE: f64 = (1u64 << 53) as f64;
220     loop {
221         // reimplement the f64 generation as an optimisation suggested
222         // by the Doornik paper: we have a lot of precision-space
223         // (i.e. there are 11 bits of the 64 of a u64 to use after
224         // creating a f64), so we might as well reuse some to save
225         // generating a whole extra random number. (Seems to be 15%
226         // faster.)
227         //
228         // This unfortunately misses out on the benefits of direct
229         // floating point generation if an RNG like dSMFT is
230         // used. (That is, such RNGs create floats directly, highly
231         // efficiently and overload next_f32/f64, so by not calling it
232         // this may be slower than it would be otherwise.)
233         // FIXME: investigate/optimise for the above.
234         let bits: u64 = rng.gen();
235         let i = (bits & 0xff) as uint;
236         let f = (bits >> 11) as f64 / SCALE;
237
238         // u is either U(-1, 1) or U(0, 1) depending on if this is a
239         // symmetric distribution or not.
240         let u = if symmetric {2.0 * f - 1.0} else {f};
241         let x = u * x_tab[i];
242
243         let test_x = if symmetric { x.abs() } else {x};
244
245         // algebraically equivalent to |u| < x_tab[i+1]/x_tab[i] (or u < x_tab[i+1]/x_tab[i])
246         if test_x < x_tab[i + 1] {
247             return x;
248         }
249         if i == 0 {
250             return zero_case(rng, u);
251         }
252         // algebraically equivalent to f1 + DRanU()*(f0 - f1) < 1
253         if f_tab[i + 1] + (f_tab[i] - f_tab[i + 1]) * rng.gen() < pdf(x) {
254             return x;
255         }
256     }
257 }
258
259 #[cfg(test)]
260 mod tests {
261     use std::prelude::v1::*;
262
263     use {Rng, Rand};
264     use super::{RandSample, WeightedChoice, Weighted, Sample, IndependentSample};
265
266     #[derive(PartialEq, Debug)]
267     struct ConstRand(uint);
268     impl Rand for ConstRand {
269         fn rand<R: Rng>(_: &mut R) -> ConstRand {
270             ConstRand(0)
271         }
272     }
273
274     // 0, 1, 2, 3, ...
275     struct CountingRng { i: u32 }
276     impl Rng for CountingRng {
277         fn next_u32(&mut self) -> u32 {
278             self.i += 1;
279             self.i - 1
280         }
281         fn next_u64(&mut self) -> u64 {
282             self.next_u32() as u64
283         }
284     }
285
286     #[test]
287     fn test_rand_sample() {
288         let mut rand_sample = RandSample::<ConstRand>;
289
290         assert_eq!(rand_sample.sample(&mut ::test::rng()), ConstRand(0));
291         assert_eq!(rand_sample.ind_sample(&mut ::test::rng()), ConstRand(0));
292     }
293     #[test]
294     fn test_weighted_choice() {
295         // this makes assumptions about the internal implementation of
296         // WeightedChoice, specifically: it doesn't reorder the items,
297         // it doesn't do weird things to the RNG (so 0 maps to 0, 1 to
298         // 1, internally; modulo a modulo operation).
299
300         macro_rules! t {
301             ($items:expr, $expected:expr) => {{
302                 let mut items = $items;
303                 let wc = WeightedChoice::new(&mut items);
304                 let expected = $expected;
305
306                 let mut rng = CountingRng { i: 0 };
307
308                 for &val in &expected {
309                     assert_eq!(wc.ind_sample(&mut rng), val)
310                 }
311             }}
312         }
313
314         t!(vec!(Weighted { weight: 1, item: 10}), [10]);
315
316         // skip some
317         t!(vec!(Weighted { weight: 0, item: 20},
318                 Weighted { weight: 2, item: 21},
319                 Weighted { weight: 0, item: 22},
320                 Weighted { weight: 1, item: 23}),
321            [21,21, 23]);
322
323         // different weights
324         t!(vec!(Weighted { weight: 4, item: 30},
325                 Weighted { weight: 3, item: 31}),
326            [30,30,30,30, 31,31,31]);
327
328         // check that we're binary searching
329         // correctly with some vectors of odd
330         // length.
331         t!(vec!(Weighted { weight: 1, item: 40},
332                 Weighted { weight: 1, item: 41},
333                 Weighted { weight: 1, item: 42},
334                 Weighted { weight: 1, item: 43},
335                 Weighted { weight: 1, item: 44}),
336            [40, 41, 42, 43, 44]);
337         t!(vec!(Weighted { weight: 1, item: 50},
338                 Weighted { weight: 1, item: 51},
339                 Weighted { weight: 1, item: 52},
340                 Weighted { weight: 1, item: 53},
341                 Weighted { weight: 1, item: 54},
342                 Weighted { weight: 1, item: 55},
343                 Weighted { weight: 1, item: 56}),
344            [50, 51, 52, 53, 54, 55, 56]);
345     }
346
347     #[test] #[should_fail]
348     fn test_weighted_choice_no_items() {
349         WeightedChoice::<int>::new(&mut []);
350     }
351     #[test] #[should_fail]
352     fn test_weighted_choice_zero_weight() {
353         WeightedChoice::new(&mut [Weighted { weight: 0, item: 0},
354                                   Weighted { weight: 0, item: 1}]);
355     }
356     #[test] #[should_fail]
357     fn test_weighted_choice_weight_overflows() {
358         let x = (-1) as uint / 2; // x + x + 2 is the overflow
359         WeightedChoice::new(&mut [Weighted { weight: x, item: 0 },
360                                   Weighted { weight: 1, item: 1 },
361                                   Weighted { weight: x, item: 2 },
362                                   Weighted { weight: 1, item: 3 }]);
363     }
364 }