Skip to main content

Registry

Struct Registry 

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

The distributions and pure functions programs can call, by name.

Registry::new (also Default) holds the built-ins: the distributions Normal, Uniform, LogNormal, Exponential, Beta, Gamma, InverseGamma, StudentT, Cauchy, Laplace, Weibull, ChiSquared (f64 sites), Bernoulli (bool), Binomial, Poisson (u64), Categorical (usize) and DiscreteUniform (i64), with fugue’s constructors and parameterizations; and the functions exp, ln (alias log), sqrt, abs, floor, sin, cos, tanh (one argument) and pow, min, max (two), all on f64. Categorical takes either its probabilities as arguments, Categorical(0.2, 0.8), or one array, Categorical(probs), of any length.

A host adds its own with register_distribution and register_function; registering an existing name replaces it. Names a program can call are identifiers (the text syntax’s); an entry under any other name is unreachable.

use fugue::program::{Arity, Data, HostDist, Program, Registry, SiteType, Value};
use fugue::{Categorical, Distribution};

let mut registry = Registry::new();
// A usize site whose probabilities come from the program's arguments.
registry.register_distribution("Pick", SiteType::Usize, Arity::Exact(1), |args| {
    let p = args[0].as_f64().ok_or("Pick: p must be a number")?;
    let d = Categorical::new(vec![1.0 - p, p]).map_err(|e| e.to_string())?;
    Ok(HostDist::Usize(d.clone_box()))
});
// A pure function over ints and bools.
registry.register_function("bump", Arity::Exact(2), |args| {
    let n = args[0].as_i64().ok_or("bump: n must be an integer")?;
    let on = args[1].as_bool().ok_or("bump: flag must be a bool")?;
    Ok(Value::Int(if on { n + 1 } else { n }))
});

let program = Program::parse(
    r#"let k <- sample(addr!("k"), Pick(0.25));
       pure(bump(3, k == 1))"#,
)
.unwrap();
assert!(program.compile(&registry, &Data::new()).is_ok());
// Unknown names are compile-time errors.
assert!(program.compile(&Registry::new(), &Data::new()).is_err());

Implementations§

Source§

impl Registry

Source

pub fn new() -> Registry

A registry holding the built-in distributions and functions.

Source

pub fn empty() -> Registry

A registry with nothing in it, for hosts that want to expose only their own vocabulary.

Source

pub fn register_distribution<F>( &mut self, name: impl Into<String>, site: SiteType, arity: Arity, ctor: F, ) -> &mut Registry
where F: Fn(&[Value]) -> Result<HostDist, String> + Send + Sync + 'static,

Register a distribution constructor under name.

site declares the type of the sites it builds; the constructor must return a HostDist of that type. The declaration is what lets a site keep a stable type when construction fails: an Err from the constructor (or a HostDist of another type) is a runtime soft error — the site is filled with a placeholder of the declared type, the execution’s weight becomes -inf, and a warning is recorded (see the module docs’ error policy). arity is checked at compile time.

The constructor sees the argument values exactly as the program computed them; Value’s accessors apply the language’s coercions. It must be deterministic in its arguments (replay and scoring rebuild the same site many times) and must not panic.

Source

pub fn register_function<F>( &mut self, name: impl Into<String>, arity: Arity, f: F, ) -> &mut Registry
where F: Fn(&[Value]) -> Result<Value, String> + Send + Sync + 'static,

Register a pure function under name. arity is checked at compile time; an Err at runtime is a soft error (weight -inf plus a warning). The function must be deterministic and must not panic.

Source

pub fn has_distribution(&self, name: &str) -> bool

Whether a distribution is registered under name.

Source

pub fn has_function(&self, name: &str) -> bool

Whether a function is registered under name.

Source

pub fn distribution_site_type(&self, name: &str) -> Option<SiteType>

The declared site type of the distribution registered under name.

Trait Implementations§

Source§

impl Clone for Registry

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 Debug for Registry

Source§

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

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

impl Default for Registry

Source§

fn default() -> Self

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

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