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>
impl<W> WeightedTreeIndex<W>
Sourcepub fn new<I>(weights: I) -> Result<WeightedTreeIndex<W>, Error>
pub fn new<I>(weights: I) -> Result<WeightedTreeIndex<W>, Error>
Creates a new WeightedTreeIndex from a slice of weights.
Error cases:
Error::InvalidWeightwhen a weight is not-a-number or negative.Error::Overflowwhen the sum of all weights overflows.
Sourcepub fn is_valid(&self) -> bool
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.
Sourcepub fn pop(&mut self) -> Option<W>
pub fn pop(&mut self) -> Option<W>
Removes the last weight and returns it, or None if it is empty.
Sourcepub fn push(&mut self, weight: W) -> Result<(), Error>
pub fn push(&mut self, weight: W) -> Result<(), Error>
Appends a new weight at the end.
Error cases:
Error::InvalidWeightwhen a weight is not-a-number or negative.Error::Overflowwhen the sum of all weights overflows.
Sourcepub fn update(&mut self, index: usize, weight: W) -> Result<(), Error>
pub fn update(&mut self, index: usize, weight: W) -> Result<(), Error>
Updates the weight at an index.
Error cases:
Error::InvalidWeightwhen a weight is not-a-number or negative.Error::Overflowwhen the sum of all weights overflows.
Source§impl<W> WeightedTreeIndex<W>
impl<W> WeightedTreeIndex<W>
Sourcepub fn try_sample<R>(&self, rng: &mut R) -> Result<usize, Error>
pub fn try_sample<R>(&self, rng: &mut R) -> Result<usize, Error>
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>
impl<W> Clone for WeightedTreeIndex<W>
Source§fn clone(&self) -> WeightedTreeIndex<W>
fn clone(&self) -> WeightedTreeIndex<W>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl<W> Debug for WeightedTreeIndex<W>
impl<W> Debug for WeightedTreeIndex<W>
Source§impl<W> Default for WeightedTreeIndex<W>
impl<W> Default for WeightedTreeIndex<W>
Source§fn default() -> WeightedTreeIndex<W>
fn default() -> WeightedTreeIndex<W>
Source§impl<W> Distribution<usize> for WeightedTreeIndex<W>
Samples a randomly selected index from the weighted distribution.
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§impl<W> PartialEq for WeightedTreeIndex<W>
impl<W> PartialEq for WeightedTreeIndex<W>
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CheckedAs for T
impl<T> CheckedAs for T
Source§fn checked_as<Dst>(self) -> Option<Dst>where
T: CheckedCast<Dst>,
fn checked_as<Dst>(self) -> Option<Dst>where
T: CheckedCast<Dst>,
Source§impl<Src, Dst> CheckedCastFrom<Src> for Dstwhere
Src: CheckedCast<Dst>,
impl<Src, Dst> CheckedCastFrom<Src> for Dstwhere
Src: CheckedCast<Dst>,
Source§fn checked_cast_from(src: Src) -> Option<Dst>
fn checked_cast_from(src: Src) -> Option<Dst>
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<D, T> DistributionExt<T> for Dwhere
D: Distribution<T>,
impl<D, T> DistributionExt<T> for Dwhere
D: Distribution<T>,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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 moreSource§impl<T> OverflowingAs for T
impl<T> OverflowingAs for T
Source§fn overflowing_as<Dst>(self) -> (Dst, bool)where
T: OverflowingCast<Dst>,
fn overflowing_as<Dst>(self) -> (Dst, bool)where
T: OverflowingCast<Dst>,
Source§impl<Src, Dst> OverflowingCastFrom<Src> for Dstwhere
Src: OverflowingCast<Dst>,
impl<Src, Dst> OverflowingCastFrom<Src> for Dstwhere
Src: OverflowingCast<Dst>,
Source§fn overflowing_cast_from(src: Src) -> (Dst, bool)
fn overflowing_cast_from(src: Src) -> (Dst, bool)
Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
Source§impl<T> SaturatingAs for T
impl<T> SaturatingAs for T
Source§fn saturating_as<Dst>(self) -> Dstwhere
T: SaturatingCast<Dst>,
fn saturating_as<Dst>(self) -> Dstwhere
T: SaturatingCast<Dst>,
Source§impl<Src, Dst> SaturatingCastFrom<Src> for Dstwhere
Src: SaturatingCast<Dst>,
impl<Src, Dst> SaturatingCastFrom<Src> for Dstwhere
Src: SaturatingCast<Dst>,
Source§fn saturating_cast_from(src: Src) -> Dst
fn saturating_cast_from(src: Src) -> Dst
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self is actually part of its subset T (and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self to the equivalent element of its superset.