|
| 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, or its total value is 0. |
| 62 | + /// |
| 63 | + /// # Panics |
| 64 | + /// |
| 65 | + /// If a value in the iterator is `< 0`. |
| 66 | + /// |
| 67 | + /// [`Distribution`]: trait.Distribution.html |
| 68 | + /// [`Uniform<X>`]: struct.Uniform.html |
| 69 | + pub fn new<I>(weights: I) -> Result<WeightedIndex<X>, Error> |
| 70 | + where I: IntoIterator, |
| 71 | + I::Item: SampleBorrow<X>, |
| 72 | + X: for<'a> ::core::ops::AddAssign<&'a X> + |
| 73 | + Clone + |
| 74 | + Default { |
| 75 | + let mut iter = weights.into_iter(); |
| 76 | + let mut total_weight: X = iter.next() |
| 77 | + .ok_or(Error::new(ErrorKind::Unexpected, "Empty iterator in WeightedIndex::new"))? |
| 78 | + .borrow() |
| 79 | + .clone(); |
| 80 | + |
| 81 | + let zero = <X as Default>::default(); |
| 82 | + let weights = iter.map(|w| { |
| 83 | + assert!(*w.borrow() >= zero, "Negative weight in WeightedIndex::new"); |
| 84 | + let prev_weight = total_weight.clone(); |
| 85 | + total_weight += w.borrow(); |
| 86 | + prev_weight |
| 87 | + }).collect::<Vec<X>>(); |
| 88 | + |
| 89 | + if total_weight == zero { |
| 90 | + return Err(Error::new(ErrorKind::Unexpected, "Total weight is zero in WeightedIndex::new")); |
| 91 | + } |
| 92 | + let distr = X::Sampler::new(zero, total_weight); |
| 93 | + |
| 94 | + Ok(WeightedIndex { cumulative_weights: weights, weight_distribution: distr }) |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +impl<X> Distribution<usize> for WeightedIndex<X> where |
| 99 | + X: SampleUniform + PartialOrd { |
| 100 | + fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> usize { |
| 101 | + let chosen_weight = self.weight_distribution.sample(rng); |
| 102 | + // Invariants: indexes in range [start, end] (inclusive) are candidate indexes |
| 103 | + // cumulative_weights[start-1] <= chosen_weight |
| 104 | + // chosen_weight < cumulative_weights[end] |
| 105 | + // The returned index is the first one whose value is >= chosen_weight |
| 106 | + let mut start = 0usize; |
| 107 | + let mut end = self.cumulative_weights.len(); |
| 108 | + while start < end { |
| 109 | + let mid = (start + end) / 2; |
| 110 | + if chosen_weight >= * unsafe { self.cumulative_weights.get_unchecked(mid) } { |
| 111 | + start = mid + 1; |
| 112 | + } else { |
| 113 | + end = mid; |
| 114 | + } |
| 115 | + } |
| 116 | + debug_assert_eq!(start, end); |
| 117 | + start |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +#[cfg(test)] |
| 122 | +mod test { |
| 123 | + use super::*; |
| 124 | + #[cfg(feature="std")] |
| 125 | + use core::panic::catch_unwind; |
| 126 | + |
| 127 | + #[test] |
| 128 | + fn test_weightedindex() { |
| 129 | + let mut r = ::test::rng(700); |
| 130 | + const N_REPS: u32 = 5000; |
| 131 | + let weights = [1u32, 2, 3, 0, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]; |
| 132 | + let total_weight = weights.iter().sum::<u32>() as f32; |
| 133 | + |
| 134 | + let verify = |result: [i32; 14]| { |
| 135 | + for (i, count) in result.iter().enumerate() { |
| 136 | + let exp = (weights[i] * N_REPS) as f32 / total_weight; |
| 137 | + let mut err = (*count as f32 - exp).abs(); |
| 138 | + if err != 0.0 { |
| 139 | + err /= exp; |
| 140 | + } |
| 141 | + assert!(err <= 0.25); |
| 142 | + } |
| 143 | + }; |
| 144 | + |
| 145 | + // WeightedIndex from vec |
| 146 | + let mut chosen = [0i32; 14]; |
| 147 | + let distr = WeightedIndex::new(weights.to_vec()).unwrap(); |
| 148 | + for _ in 0..N_REPS { |
| 149 | + chosen[distr.sample(&mut r)] += 1; |
| 150 | + } |
| 151 | + verify(chosen); |
| 152 | + |
| 153 | + // WeightedIndex from slice |
| 154 | + chosen = [0i32; 14]; |
| 155 | + let distr = WeightedIndex::new(&weights[..]).unwrap(); |
| 156 | + for _ in 0..N_REPS { |
| 157 | + chosen[distr.sample(&mut r)] += 1; |
| 158 | + } |
| 159 | + verify(chosen); |
| 160 | + |
| 161 | + // WeightedIndex from iterator |
| 162 | + chosen = [0i32; 14]; |
| 163 | + let distr = WeightedIndex::new(weights.iter()).unwrap(); |
| 164 | + for _ in 0..N_REPS { |
| 165 | + chosen[distr.sample(&mut r)] += 1; |
| 166 | + } |
| 167 | + verify(chosen); |
| 168 | + |
| 169 | + assert!(WeightedIndex::new(&[10][0..0]).is_err()); |
| 170 | + assert!(WeightedIndex::new(&[0]).is_err()); |
| 171 | + } |
| 172 | + |
| 173 | + #[test] |
| 174 | + #[cfg(all(feature="std", |
| 175 | + not(target_arch = "wasm32"), |
| 176 | + not(target_arch = "asmjs")))] |
| 177 | + fn test_weighted_assertions() { |
| 178 | + assert!(catch_unwind(|| WeightedIndex::new(&[1, 2, 3])).is_ok()); |
| 179 | + assert!(catch_unwind(|| WeightedIndex::new(&[10, -1, 10])).is_err()); |
| 180 | + assert!(catch_unwind(|| WeightedIndex::new(&[1, -1])).is_err()); |
| 181 | + } |
| 182 | +} |
0 commit comments