Skip to main content

Delegate

Struct Delegate 

Source
pub struct Delegate<H, O = ()> {
    pub inner: H,
    pub overrides: O,
}
Expand description

A Handler that forwards every site to an inner handler, through the hooks of an Overrides value.

Each site goes to the matching hook of overrides, with inner as its extra argument, and each hook defaults to forwarding the site to inner. So Delegate::new(h) (overrides ()) behaves exactly like h, and Delegate::with(h, o) behaves like h except at the sites o overrides.

Delegates nest. In Delegate<Delegate<H, A>, B> the hooks of B see each site first, and their inner is the Delegate<H, A>, which passes the site on through A to H. At the end of the run B::finish runs first, and A::finish runs when B::finish finishes its inner handler.

A Delegate is a plain struct of its two fields: no boxing, and every hook call is statically dispatched.

Example (two decorators nested around a PriorHandler):

/// Logs the f64 sample sites it sees, under a name, and forwards them.
struct Log<'a>(&'static str, &'a std::cell::RefCell<Vec<String>>);

impl<H: Handler> Overrides<H> for Log<'_> {
    fn on_sample_f64(
        &mut self,
        inner: &mut H,
        addr: &Address,
        dist: &dyn Distribution<f64>,
    ) -> f64 {
        self.1.borrow_mut().push(format!("{} saw {}", self.0, addr));
        inner.on_sample_f64(addr, dist)
    }
}

let log = std::cell::RefCell::new(Vec::new());
let mut rng = StdRng::seed_from_u64(1);
let prior = PriorHandler { rng: &mut rng, trace: Trace::default() };
let handler = Delegate::with(Delegate::with(prior, Log("inner", &log)), Log("outer", &log));

let (_x, trace) =
    runtime::handler::run(handler, sample(addr!("x"), Normal::new(0.0, 1.0).unwrap()));

assert_eq!(log.into_inner(), ["outer saw x", "inner saw x"]);
assert!(trace.get_f64(&addr!("x")).is_some()); // recorded by the PriorHandler

Fields§

§inner: H

The handler that every site not overridden is forwarded to.

§overrides: O

The hooks, and whatever state they keep.

Implementations§

Source§

impl<H> Delegate<H>

Source

pub fn new(inner: H) -> Self

Wrap inner with no overrides, so every site is forwarded to it.

The result behaves exactly like inner: same values, same trace.

Example:

let model = || sample(addr!("x"), Normal::new(0.0, 1.0).unwrap());

let mut rng = StdRng::seed_from_u64(7);
let (x, _) = runtime::handler::run(
    PriorHandler { rng: &mut rng, trace: Trace::default() },
    model(),
);

let mut rng = StdRng::seed_from_u64(7);
let delegate = Delegate::new(PriorHandler { rng: &mut rng, trace: Trace::default() });
let (y, trace) = runtime::handler::run(delegate, model());

assert_eq!(x, y); // same seed, same draw
assert_eq!(trace.get_f64(&addr!("x")), Some(x));
Source§

impl<H, O> Delegate<H, O>

Source

pub fn with(inner: H, overrides: O) -> Self

Wrap inner, sending each site through the hooks of overrides first.

Example (clamp every f64 sample to [-1, 1] before the model sees it; the trace keeps the value the inner handler drew):

struct Clamp;

impl<H: Handler> Overrides<H> for Clamp {
    fn on_sample_f64(
        &mut self,
        inner: &mut H,
        addr: &Address,
        dist: &dyn Distribution<f64>,
    ) -> f64 {
        inner.on_sample_f64(addr, dist).clamp(-1.0, 1.0)
    }
}

let mut rng = StdRng::seed_from_u64(3);
let handler = Delegate::with(PriorHandler { rng: &mut rng, trace: Trace::default() }, Clamp);
let (x, _trace) =
    runtime::handler::run(handler, sample(addr!("x"), Normal::new(0.0, 10.0).unwrap()));

assert!((-1.0..=1.0).contains(&x));

Trait Implementations§

Source§

impl<H: Clone, O: Clone> Clone for Delegate<H, O>

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<H: Debug, O: Debug> Debug for Delegate<H, O>

Source§

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

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

impl<H: Handler, O: Overrides<H>> Handler for Delegate<H, O>

Every method calls the hook of the same name on overrides, passing inner.

Source§

fn on_sample_f64(&mut self, addr: &Address, dist: &dyn Distribution<f64>) -> f64

Handle an f64 sampling operation (continuous distributions).
Source§

fn on_sample_bool( &mut self, addr: &Address, dist: &dyn Distribution<bool>, ) -> bool

Handle a bool sampling operation (Bernoulli).
Source§

fn on_sample_u64(&mut self, addr: &Address, dist: &dyn Distribution<u64>) -> u64

Handle a u64 sampling operation (Poisson, Binomial).
Source§

fn on_sample_usize( &mut self, addr: &Address, dist: &dyn Distribution<usize>, ) -> usize

Handle a usize sampling operation (Categorical).
Source§

fn on_sample_i64(&mut self, addr: &Address, dist: &dyn Distribution<i64>) -> i64

Handle an i64 sampling operation (signed discrete distributions). Read more
Source§

fn on_observe_f64( &mut self, addr: &Address, dist: &dyn Distribution<f64>, value: f64, )

Handle an f64 observation operation.
Source§

fn on_observe_bool( &mut self, addr: &Address, dist: &dyn Distribution<bool>, value: bool, )

Handle a bool observation operation.
Source§

fn on_observe_u64( &mut self, addr: &Address, dist: &dyn Distribution<u64>, value: u64, )

Handle a u64 observation operation.
Source§

fn on_observe_usize( &mut self, addr: &Address, dist: &dyn Distribution<usize>, value: usize, )

Handle a usize observation operation.
Source§

fn on_observe_i64( &mut self, addr: &Address, dist: &dyn Distribution<i64>, value: i64, )

Handle an i64 observation operation. Read more
Source§

fn on_factor(&mut self, logw: f64)

Handle a factor operation. Read more
Source§

fn finish(self) -> Trace

Finalize the handler and return the accumulated trace. Read more

Auto Trait Implementations§

§

impl<H, O> Freeze for Delegate<H, O>
where H: Freeze, O: Freeze,

§

impl<H, O> RefUnwindSafe for Delegate<H, O>

§

impl<H, O> Send for Delegate<H, O>
where H: Send, O: Send,

§

impl<H, O> Sync for Delegate<H, O>
where H: Sync, O: Sync,

§

impl<H, O> Unpin for Delegate<H, O>
where H: Unpin, O: Unpin,

§

impl<H, O> UnsafeUnpin for Delegate<H, O>
where H: UnsafeUnpin, O: UnsafeUnpin,

§

impl<H, O> UnwindSafe for Delegate<H, O>
where H: UnwindSafe, O: 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