Crate r_gen[][src]

Expand description

A framework for writing generative models in the rust programming language.

Example of Importance Sampling

use r_gen::{sample, r_gen}; 
use r_gen::{simulate, generate, distributions::{Value, Distribution}, trace::{Choicemap, Trace}}; 
use std::rc::Rc;
fn main() {
    //Define our generative model. 
    #[r_gen]
    fn my_model(():()){
        let p = sample!(format!("p"), Distribution::Beta(1.0, 1.0)); 
        sample!(format!("num_heads"), Distribution::Binomial(100, p.into()));
    }

    //Run the model once in the forward direction and record the observations. 
    let (t, _) : (Trace, _)= simulate(&mut my_model, ());
    let choices = Choicemap::from(vec![("num_heads", t.choices["num_heads"].clone())]);

    //Perform importance resampling to get an estimate for the value of p. 
    let mut traces = Vec::new();
    for _ in 0..1000 {
        let (gt, _) : (Trace, _)= generate(&mut my_model, (), &choices);
        traces.push(gt); 
    }
    
    println!("Actual value for p:\t {}", t.choices["p"]); 
    println!("Generated value for p:\t {}", Trace::sample_weighted_traces(&traces).unwrap().choices["p"]); 
}

Outputs:

Actual value for p:      0.8011431168181488
Generated value for p:   0.7879998086169554

Modules

distributions

Distributions a generative model can sample from.

trace

Trace objects that represent a run of a generative model.

Macros

sample

The macro that is used for sampling from a distribution.

Functions

generate

Run a generative model in the forward direction, fixing certian decisions or observations. As input, it takes a generative model (function with the #r_gen tag), the arguments to that function, and a choicemap of the observed variables. Returns a tuple of the trace generated by running the function and the return value of the function itself.

simulate

Run the given generative model in the forward direction. As input, it takes a generative model (function with the #r_gen tag) and the arguments to that function. Returns a tuple of the trace generated by running the function and the return value of the function itself.

Attribute Macros

r_gen