Skip to main content

WeightedIndex

Struct WeightedIndex 

Source
pub struct WeightedIndex { /* private fields */ }
Expand description

A collection of weights at fixed indices supporting proportional and uniform draws and updates.

Construction takes O(n) time and space. Sampling and changing a weight take O(log n) time. Zero-weight entries are never sampled. Draws use only integer arithmetic, so a fixed sequence of weights and random input is reproducible across platforms.

§Examples

use commonware_utils::sampling::WeightedIndex;
use rand::{SeedableRng, rngs::StdRng};

let mut rng = StdRng::seed_from_u64(0);
let mut weights = WeightedIndex::new([0, 5]);
assert_eq!(weights.sample(&mut rng), Some(1));
assert_eq!(weights.update(1, |weight| weight * 2), 5);
assert_eq!(weights.weight(1), 10);
weights.set(1, 0);
assert_eq!(weights.sample(&mut rng), None);

Implementations§

Source§

impl WeightedIndex

Source

pub fn new(weights: impl IntoIterator<Item = u64>) -> Self

Builds an index over weights, preserving their order.

Source

pub const fn total(&self) -> u128

Returns the sum of all weights.

Source

pub fn weight(&self, index: usize) -> u64

Returns the weight at index.

§Panics

Panics if index is out of bounds.

Source

pub fn set(&mut self, index: usize, weight: u64) -> u64

Replaces the weight at index, returning its previous value.

§Panics

Panics if index is out of bounds.

Source

pub fn update(&mut self, index: usize, f: impl FnOnce(u64) -> u64) -> u64

Applies f to the weight at index, returning its previous value. Returning the same weight skips the update.

§Panics

Panics if index is out of bounds, before invoking f. If f panics, self is unchanged.

Source

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

Draws an index with probability proportional to its weight.

Returns None without consuming randomness when the total weight is zero.

Source

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

Draws uniformly from the indices with positive weight.

Returns None without consuming randomness when all weights are zero.

Source

pub const fn without_replacement(&mut self) -> WithoutReplacement<'_>

Starts a sequence of draws that can choose each positive-weight index at most once.

Dropping the sequence restores all weights, including during unwinding. Construction takes constant time without allocating. Each draw takes amortized O(log n) time, and k draws use O(k) space. Stopping after the first draw leaves the index unchanged and needs no restoration.

§Examples
use commonware_utils::sampling::WeightedIndex;
use rand::{SeedableRng, rngs::StdRng};

let mut rng = StdRng::seed_from_u64(0);
let mut weights = WeightedIndex::new([0, 5, 3]);
{
    let mut draws = weights.without_replacement();
    let first = draws.sample(&mut rng).unwrap();
    let second = draws.sample_uniform(&mut rng).unwrap();
    assert_ne!(first, second);
    assert!(draws.is_empty());
}
assert_eq!(weights.total(), 8);
Source

pub const fn into_without_replacement(self) -> WithoutReplacement<'static>

Consumes this index for draws that can choose each positive-weight index at most once.

Construction takes constant time without allocating. Each draw takes O(log n) time and constant extra space, because a consumed index is never restored.

Auto Trait Implementations§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Threaded<T> for T

Source§

type Rest = ()

The outputs beyond the threaded value.
Source§

fn split(self) -> (T, ())

Splits into the threaded value and the extra outputs.
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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> 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