Skip to main content

WithMeta

Struct WithMeta 

Source
pub struct WithMeta<D, M> { /* private fields */ }
Expand description

A distribution D that carries metadata M for the handler that runs its site (#63).

A handler sees only (addr, dist) at a site. When it needs more than the distribution (the question to put to a model, the names of the options, a slice of state), WithMeta carries it along with the distribution. A handler that knows the type recovers both with downcast_ref, and falls back to its usual behaviour when the downcast returns None.

For sampling and scoring, a WithMeta<D, M> is just D. sample, log_prob and support forward to the inner distribution, so the built-in handlers and inference routines, and any handler that doesn’t look for M, record the same values, log-probabilities and weights as with the bare D, draw for draw from the same seed. clone_box keeps the metadata.

§Metadata that belongs to the site, or to the handler

WithMeta is for metadata that belongs to the site. It is built with the distribution, it can depend on values sampled earlier in the same execution, and it needs no bookkeeping outside the model. Metadata that is known outside the model, such as configuration keyed by address, can instead live in a HashMap<Address, M> that the handler holds and looks up by the site’s addr. That way the model doesn’t change at all.

§Naming the type

A downcast matches the exact type, so the handler names both parameters: WithMeta<Categorical, Question>, not Categorical. The inner distribution is reached through dist. Reading M without knowing D would need a second hook on Distribution, and there isn’t one; a handler that accepts several inner types tries each of them.

§Example

/// What a decision site asks, and the names of its options.
#[derive(Clone, Debug)]
struct Question {
    text: &'static str,
    options: Vec<&'static str>,
}

let site = WithMeta::new(
    Categorical::new(vec![0.6, 0.3, 0.1]).unwrap(),
    Question { text: "Which tool next?", options: vec!["search", "edit", "test"] },
);

// In a model it is the categorical: the same draw from the same seed.
let mut rng = StdRng::seed_from_u64(7);
let handler = PriorHandler { rng: &mut rng, trace: Trace::default() };
let (wrapped, _) = runtime::handler::run(handler, sample(addr!("tool"), site.clone()));
let mut rng = StdRng::seed_from_u64(7);
let handler = PriorHandler { rng: &mut rng, trace: Trace::default() };
let (bare, _) = runtime::handler::run(handler, sample(addr!("tool"), site.dist().clone()));
assert_eq!(wrapped, bare);

// A handler's `on_sample_usize` receives a `&dyn Distribution<usize>`. One
// that knows the type reads the question and the probabilities directly.
let dist: &dyn Distribution<usize> = &site;
let found = dist.downcast_ref::<WithMeta<Categorical, Question>>().unwrap();
assert_eq!(found.meta().text, "Which tool next?");
let edit = found.meta().options.iter().position(|&o| o == "edit").unwrap();
assert_eq!(found.dist().probs()[edit], 0.3);

Implementations§

Source§

impl<D, M> WithMeta<D, M>

Source

pub fn new(dist: D, meta: M) -> Self

Attach meta to dist.

let site = WithMeta::new(Bernoulli::new(0.9).unwrap(), "Is the build green?");
// Sampled exactly as the bare Bernoulli would be.
let model: Model<bool> = sample(addr!("green"), site);
Source

pub fn dist(&self) -> &D

The wrapped distribution.

let site = WithMeta::new(Normal::new(1.0, 2.0).unwrap(), "offset");
assert_eq!(site.dist().mu(), 1.0);
Source

pub fn meta(&self) -> &M

The metadata.

let site = WithMeta::new(Poisson::new(3.0).unwrap(), vec!["arrivals", "per hour"]);
assert_eq!(site.meta()[0], "arrivals");
Source

pub fn into_parts(self) -> (D, M)

Split into the distribution and the metadata.

let (dist, meta) = WithMeta::new(Beta::new(2.0, 5.0).unwrap(), 42u32).into_parts();
assert_eq!(dist.alpha(), 2.0);
assert_eq!(meta, 42);

Trait Implementations§

Source§

impl<D: Clone, M: Clone> Clone for WithMeta<D, M>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<D: Debug, M: Debug> Debug for WithMeta<D, M>

Source§

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

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

impl<T, D, M> Distribution<T> for WithMeta<D, M>
where D: Distribution<T> + Clone + 'static, M: Clone + Send + Sync + 'static,

Source§

fn sample(&self, rng: &mut dyn RngCore) -> T

Generate a random sample (with its natural type), T, from the distribution, using the provided random number generator, rng. Read more
Source§

fn log_prob(&self, x: &T) -> LogF64

Compute the log-probability density (continuous) or mass (discrete) of a value, x, from the distribution. Read more
Source§

fn clone_box(&self) -> Box<dyn Distribution<T>>

Clone the distribution into a boxed trait object, Box<dyn Distribution<T>>. Read more
Source§

fn support(&self) -> Support

The distribution’s support, used by the MCMC kernels to pick a proposal that is a function of the site alone (FG-N1). See Support. Read more
Source§

fn as_any(&self) -> Option<&dyn Any>

The distribution as Any, so that a handler can downcast the distribution at a site to a type it knows (#63). Read more

Auto Trait Implementations§

§

impl<D, M> Freeze for WithMeta<D, M>
where D: Freeze, M: Freeze,

§

impl<D, M> RefUnwindSafe for WithMeta<D, M>

§

impl<D, M> Send for WithMeta<D, M>
where D: Send, M: Send,

§

impl<D, M> Sync for WithMeta<D, M>
where D: Sync, M: Sync,

§

impl<D, M> Unpin for WithMeta<D, M>
where D: Unpin, M: Unpin,

§

impl<D, M> UnsafeUnpin for WithMeta<D, M>
where D: UnsafeUnpin, M: UnsafeUnpin,

§

impl<D, M> UnwindSafe for WithMeta<D, M>
where D: UnwindSafe, M: 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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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 = !

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V