rand_distr::weighted_tree

Struct WeightedTreeIndex

Source
pub struct WeightedTreeIndex<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> { /* private fields */ }
Expand description

A distribution using weighted sampling to pick a discretely selected item.

Sampling a WeightedTreeIndex<W> distribution returns the index of a randomly selected element from the vector used to create the WeightedTreeIndex<W>. The chance of a given element being picked is proportional to the value of the element. The weights can have any type W for which an implementation of Weight exists.

§Key differences

The main distinction between WeightedTreeIndex<W> and rand::distr::WeightedIndex<W> lies in the internal representation of weights. In WeightedTreeIndex<W>, weights are structured as a tree, which is optimized for frequent updates of the weights.

§Caution: Floating point types

When utilizing WeightedTreeIndex<W> with floating point types (such as f32 or f64), exercise caution due to the inherent nature of floating point arithmetic. Floating point types are susceptible to numerical rounding errors. Since operations on floating point weights are repeated numerous times, rounding errors can accumulate, potentially leading to noticeable deviations from the expected behavior.

Ideally, use fixed point or integer types whenever possible.

§Performance

A WeightedTreeIndex<W> with n elements requires O(n) memory.

Time complexity for the operations of a WeightedTreeIndex<W> are:

  • Constructing: Building the initial tree from an iterator of weights takes O(n) time.
  • Sampling: Choosing an index (traversing down the tree) requires O(log n) time.
  • Weight Update: Modifying a weight (traversing up the tree), requires O(log n) time.
  • Weight Addition (Pushing): Adding a new weight (traversing up the tree), requires O(log n) time.
  • Weight Removal (Popping): Removing a weight (traversing up the tree), requires O(log n) time.

§Example

use rand_distr::WeightedTreeIndex;
use rand::prelude::*;

let choices = vec!['a', 'b', 'c'];
let weights = vec![2, 0];
let mut dist = WeightedTreeIndex::new(&weights).unwrap();
dist.push(1).unwrap();
dist.update(1, 1).unwrap();
let mut rng = rand::rng();
let mut samples = [0; 3];
for _ in 0..100 {
    // 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c'
    let i = dist.sample(&mut rng);
    samples[i] += 1;
}
println!("Results: {:?}", choices.iter().zip(samples.iter()).collect::<Vec<_>>());

Implementations§

Source§

impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> WeightedTreeIndex<W>

Source

pub fn new<I>(weights: I) -> Result<Self, WeightError>
where I: IntoIterator, I::Item: SampleBorrow<W>,

Creates a new WeightedTreeIndex from a slice of weights.

Error cases:

Source

pub fn is_empty(&self) -> bool

Returns true if the tree contains no weights.

Source

pub fn len(&self) -> usize

Returns the number of weights.

Source

pub fn is_valid(&self) -> bool

Returns true if we can sample.

This is the case if the total weight of the tree is greater than zero.

Source

pub fn get(&self, index: usize) -> W

Gets the weight at an index.

Source

pub fn pop(&mut self) -> Option<W>

Removes the last weight and returns it, or None if it is empty.

Source

pub fn push(&mut self, weight: W) -> Result<(), WeightError>

Appends a new weight at the end.

Error cases:

Source

pub fn update(&mut self, index: usize, weight: W) -> Result<(), WeightError>

Updates the weight at an index.

Error cases:

Source§

impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> WeightedTreeIndex<W>

Source

pub fn try_sample<R: Rng + ?Sized>( &self, rng: &mut R, ) -> Result<usize, WeightError>

Samples a randomly selected index from the weighted distribution.

Returns an error if there are no elements or all weights are zero. This is unlike Distribution::sample, which panics in those cases.

Trait Implementations§

Source§

impl<W: Clone + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Clone for WeightedTreeIndex<W>

Source§

fn clone(&self) -> WeightedTreeIndex<W>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<W: Debug + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Debug for WeightedTreeIndex<W>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<W: Default + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Default for WeightedTreeIndex<W>

Source§

fn default() -> WeightedTreeIndex<W>

Returns the “default value” for a type. Read more
Source§

impl<'de, W> Deserialize<'de> for WeightedTreeIndex<W>

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Distribution<usize> for WeightedTreeIndex<W>

Samples a randomly selected index from the weighted distribution.

Caution: This method panics if there are no elements or all weights are zero. However, it is guaranteed that this method will not panic if a call to WeightedTreeIndex::is_valid returns true.

Source§

fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> usize

Generate a random value of T, using rng as the source of randomness.
Source§

fn sample_iter<R>(self, rng: R) -> DistIter<Self, R, T>
where R: Rng, Self: Sized,

Create an iterator that generates random values of T, using rng as the source of randomness. Read more
Source§

fn map<F, S>(self, func: F) -> DistMap<Self, F, T, S>
where F: Fn(T) -> S, Self: Sized,

Create a distribution of values of ‘S’ by mapping the output of Self through the closure F Read more
Source§

impl<W: PartialEq + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> PartialEq for WeightedTreeIndex<W>

Source§

fn eq(&self, other: &WeightedTreeIndex<W>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<W> Serialize for WeightedTreeIndex<W>

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> StructuralPartialEq for WeightedTreeIndex<W>

Auto Trait Implementations§

§

impl<W> Freeze for WeightedTreeIndex<W>

§

impl<W> RefUnwindSafe for WeightedTreeIndex<W>
where W: RefUnwindSafe,

§

impl<W> Send for WeightedTreeIndex<W>
where W: Send,

§

impl<W> Sync for WeightedTreeIndex<W>
where W: Sync,

§

impl<W> Unpin for WeightedTreeIndex<W>
where W: Unpin,

§

impl<W> UnwindSafe for WeightedTreeIndex<W>
where W: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,