|
| 1 | +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// https://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or https://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 | +use Rng; |
| 12 | +use distributions::Distribution; |
| 13 | +use distributions::uniform::{UniformSampler, SampleUniform, SampleBorrow}; |
| 14 | +use ::core::cmp::PartialOrd; |
| 15 | +use ::{Error, ErrorKind}; |
| 16 | + |
| 17 | +// Note that this whole module is only imported if feature="alloc" is enabled. |
| 18 | +#[cfg(not(feature="std"))] use alloc::Vec; |
| 19 | + |
| 20 | +/// A distribution using weighted sampling to pick a discretely selected item. |
| 21 | +/// |
| 22 | +/// Sampling a `WeightedIndex` distribution returns the index of a randomly |
| 23 | +/// selected element from the iterator used when the `WeightedIndex` was |
| 24 | +/// created. The chance of a given element being picked is proportional to the |
| 25 | +/// value of the element. The weights can use any type `X` for which an |
| 26 | +/// implementation of [`Uniform<X>`] exists. |
| 27 | +/// |
| 28 | +/// # Example |
| 29 | +/// |
| 30 | +/// ``` |
| 31 | +/// use rand::prelude::*; |
| 32 | +/// use rand::distributions::WeightedIndex; |
| 33 | +/// |
| 34 | +/// let choices = ['a', 'b', 'c']; |
| 35 | +/// let weights = [2, 1, 1]; |
| 36 | +/// let dist = WeightedIndex::new(&weights).unwrap(); |
| 37 | +/// let mut rng = thread_rng(); |
| 38 | +/// for _ in 0..100 { |
| 39 | +/// // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c' |
| 40 | +/// println!("{}", choices[dist.sample(&mut rng)]); |
| 41 | +/// } |
| 42 | +/// |
| 43 | +/// let items = [('a', 0), ('b', 3), ('c', 7)]; |
| 44 | +/// let dist2 = WeightedIndex::new(items.iter().map(|item| item.1)).unwrap(); |
| 45 | +/// for _ in 0..100 { |
| 46 | +/// // 0% chance to print 'a', 30% chance to print 'b', 70% chance to print 'c' |
| 47 | +/// println!("{}", items[dist2.sample(&mut rng)].0); |
| 48 | +/// } |
| 49 | +/// ``` |
| 50 | +#[derive(Debug, Clone)] |
| 51 | +pub struct WeightedIndex<X: SampleUniform + PartialOrd> { |
| 52 | + cumulative_weights: Vec<X>, |
| 53 | + weight_distribution: X::Sampler, |
| 54 | +} |
| 55 | + |
| 56 | +impl<X: SampleUniform + PartialOrd> WeightedIndex<X> { |
| 57 | + /// Creates a new a `WeightedIndex` [`Distribution`] using the values |
| 58 | + /// in `weights`. The weights can use any type `X` for which an |
| 59 | + /// implementation of [`Uniform<X>`] exists. |
| 60 | + /// |
| 61 | + /// Returns an error if the iterator is empty, if any weight is `< 0`, or |
| 62 | + /// if its total value is 0. |
| 63 | + /// |
| 64 | + /// [`Distribution`]: trait.Distribution.html |
| 65 | + /// [`Uniform<X>`]: struct.Uniform.html |
| 66 | + pub fn new<I>(weights: I) -> Result<WeightedIndex<X>, Error> |
| 67 | + where I: IntoIterator, |
| 68 | + I::Item: SampleBorrow<X>, |
| 69 | + X: for<'a> ::core::ops::AddAssign<&'a X> + |
| 70 | + Clone + |
| 71 | + Default { |
| 72 | + let mut iter = weights.into_iter(); |
| 73 | + let mut total_weight: X = iter.next() |
| 74 | + .ok_or(Error::new(ErrorKind::Unexpected, "Empty iterator in WeightedIndex::new"))? |
| 75 | + .borrow() |
| 76 | + .clone(); |
| 77 | + |
| 78 | + let zero = <X as Default>::default(); |
| 79 | + if total_weight < zero { |
| 80 | + return Err(Error::new(ErrorKind::Unexpected, "Negative weight in WeightedIndex::new")); |
| 81 | + } |
| 82 | + |
| 83 | + let mut weights = Vec::<X>::with_capacity(iter.size_hint().0); |
| 84 | + for w in iter { |
| 85 | + if *w.borrow() < zero { |
| 86 | + return Err(Error::new(ErrorKind::Unexpected, "Negative weight in WeightedIndex::new")); |
| 87 | + } |
| 88 | + weights.push(total_weight.clone()); |
| 89 | + total_weight += w.borrow(); |
| 90 | + } |
| 91 | + |
| 92 | + if total_weight == zero { |
| 93 | + return Err(Error::new(ErrorKind::Unexpected, "Total weight is zero in WeightedIndex::new")); |
| 94 | + } |
| 95 | + let distr = X::Sampler::new(zero, total_weight); |
| 96 | + |
| 97 | + Ok(WeightedIndex { cumulative_weights: weights, weight_distribution: distr }) |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +impl<X> Distribution<usize> for WeightedIndex<X> where |
| 102 | + X: SampleUniform + PartialOrd { |
| 103 | + fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> usize { |
| 104 | + use ::core::cmp::Ordering; |
| 105 | + let chosen_weight = self.weight_distribution.sample(rng); |
| 106 | + // Find the first item which has a weight *higher* than the chosen weight. |
| 107 | + self.cumulative_weights.binary_search_by( |
| 108 | + |w| if *w <= chosen_weight { Ordering::Less } else { Ordering::Greater }).unwrap_err() |
| 109 | + } |
| 110 | +} |
| 111 | + |
| 112 | +#[cfg(test)] |
| 113 | +mod test { |
| 114 | + use super::*; |
| 115 | + |
| 116 | + #[test] |
| 117 | + fn test_weightedindex() { |
| 118 | + let mut r = ::test::rng(700); |
| 119 | + const N_REPS: u32 = 5000; |
| 120 | + let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; |
| 121 | + let total_weight = weights.iter().sum::<u32>() as f32; |
| 122 | + |
| 123 | + let verify = |result: [i32; 14]| { |
| 124 | + for (i, count) in result.iter().enumerate() { |
| 125 | + let exp = (weights[i] * N_REPS) as f32 / total_weight; |
| 126 | + let mut err = (*count as f32 - exp).abs(); |
| 127 | + if err != 0.0 { |
| 128 | + err /= exp; |
| 129 | + } |
| 130 | + assert!(err <= 0.25); |
| 131 | + } |
| 132 | + }; |
| 133 | + |
| 134 | + // WeightedIndex from vec |
| 135 | + let mut chosen = [0i32; 14]; |
| 136 | + let distr = WeightedIndex::new(weights.to_vec()).unwrap(); |
| 137 | + for _ in 0..N_REPS { |
| 138 | + chosen[distr.sample(&mut r)] += 1; |
| 139 | + } |
| 140 | + verify(chosen); |
| 141 | + |
| 142 | + // WeightedIndex from slice |
| 143 | + chosen = [0i32; 14]; |
| 144 | + let distr = WeightedIndex::new(&weights[..]).unwrap(); |
| 145 | + for _ in 0..N_REPS { |
| 146 | + chosen[distr.sample(&mut r)] += 1; |
| 147 | + } |
| 148 | + verify(chosen); |
| 149 | + |
| 150 | + // WeightedIndex from iterator |
| 151 | + chosen = [0i32; 14]; |
| 152 | + let distr = WeightedIndex::new(weights.iter()).unwrap(); |
| 153 | + for _ in 0..N_REPS { |
| 154 | + chosen[distr.sample(&mut r)] += 1; |
| 155 | + } |
| 156 | + verify(chosen); |
| 157 | + |
| 158 | + for _ in 0..5 { |
| 159 | + assert_eq!(WeightedIndex::new(&[0, 1]).unwrap().sample(&mut r), 1); |
| 160 | + assert_eq!(WeightedIndex::new(&[1, 0]).unwrap().sample(&mut r), 0); |
| 161 | + assert_eq!(WeightedIndex::new(&[0, 0, 0, 0, 10, 0]).unwrap().sample(&mut r), 4); |
| 162 | + } |
| 163 | + |
| 164 | + assert!(WeightedIndex::new(&[10][0..0]).is_err()); |
| 165 | + assert!(WeightedIndex::new(&[0]).is_err()); |
| 166 | + assert!(WeightedIndex::new(&[10, 20, -1, 30]).is_err()); |
| 167 | + assert!(WeightedIndex::new(&[-10, 20, 1, 30]).is_err()); |
| 168 | + assert!(WeightedIndex::new(&[-10]).is_err()); |
| 169 | + } |
| 170 | +} |
0 commit comments