WeightedTreeIndex

Struct WeightedTreeIndex 

Source
pub struct WeightedTreeIndex<W>{ /* 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 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::weighted::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> WeightedTreeIndex<W>

Source

pub fn new<I>(weights: I) -> Result<WeightedTreeIndex<W>, Error>

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<(), Error>

Appends a new weight at the end.

Error cases:

Source

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

Updates the weight at an index.

Error cases:

Source§

impl<W> WeightedTreeIndex<W>

Source

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

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 for WeightedTreeIndex<W>

Source§

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

Returns a duplicate 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 for WeightedTreeIndex<W>

Source§

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

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

impl<W> Default for WeightedTreeIndex<W>

Source§

fn default() -> WeightedTreeIndex<W>

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

impl<W> 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>(&self, rng: &mut R) -> usize
where R: Rng + ?Sized,

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

fn sample_iter<R>(self, rng: R) -> Iter<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) -> Map<Self, F, T, S>
where F: Fn(T) -> S, Self: Sized,

Map sampled values to type S Read more
Source§

impl<W> 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> 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> Az for T

Source§

fn az<Dst>(self) -> Dst
where T: Cast<Dst>,

Casts the value.
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<Src, Dst> CastFrom<Src> for Dst
where Src: Cast<Dst>,

Source§

fn cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> CheckedAs for T

Source§

fn checked_as<Dst>(self) -> Option<Dst>
where T: CheckedCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> CheckedCastFrom<Src> for Dst
where Src: CheckedCast<Dst>,

Source§

fn checked_cast_from(src: Src) -> Option<Dst>

Casts the value.
Source§

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

Source§

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

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

impl<D, T> DistributionExt<T> for D
where D: Distribution<T>,

Source§

fn random_array<R: Rng, Dim: Dimension>( &self, rng: &mut Random<R>, shape: Dim, ) -> Array<T, Dim>
where Self: Copy,

Create a random array with values from this distribution
Source§

fn sample_vec<R: Rng>(&self, rng: &mut Random<R>, size: usize) -> Vec<T>
where Self: Copy,

Create a random vector with values from this distribution
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> OverflowingAs for T

Source§

fn overflowing_as<Dst>(self) -> (Dst, bool)
where T: OverflowingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> OverflowingCastFrom<Src> for Dst
where Src: OverflowingCast<Dst>,

Source§

fn overflowing_cast_from(src: Src) -> (Dst, bool)

Casts the value.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> SaturatingAs for T

Source§

fn saturating_as<Dst>(self) -> Dst
where T: SaturatingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> SaturatingCastFrom<Src> for Dst
where Src: SaturatingCast<Dst>,

Source§

fn saturating_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
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<T> UnwrappedAs for T

Source§

fn unwrapped_as<Dst>(self) -> Dst
where T: UnwrappedCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> UnwrappedCastFrom<Src> for Dst
where Src: UnwrappedCast<Dst>,

Source§

fn unwrapped_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WrappingAs for T

Source§

fn wrapping_as<Dst>(self) -> Dst
where T: WrappingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> WrappingCastFrom<Src> for Dst
where Src: WrappingCast<Dst>,

Source§

fn wrapping_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,

Source§

impl<T> Ungil for T
where T: Send,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,