Struct programinduction::pcfg::Grammar[][src]

pub struct Grammar {
    pub start: Type,
    pub rules: HashMap<Type, Vec<Rule>>,
}

(representation) Probabilistic context-free grammar. Currently cannot handle bound variables or polymorphism.

Each nonterminal corresponds to a non-polymorphic Type.

Fields

Methods

impl Grammar
[src]

Rules are normalized according to their associated nonterminal proportional to the supplied probabilities.

So each rules' logprob is not treated as log-probability in this constructor, they are treated like un-normalized probabilities.

Important traits for Box<R>

Enumerate statements in the PCFG, including log-probabilities.

Examples

use programinduction::pcfg::{Grammar, Rule, AppliedRule};

let g = Grammar::new(
    tp!(EXPR),
    vec![
        Rule::new("0", tp!(EXPR), 1.0),
        Rule::new("1", tp!(EXPR), 1.0),
        Rule::new("plus", tp!(@arrow[tp!(EXPR), tp!(EXPR), tp!(EXPR)]), 1.0),
    ],
);
let exprs: Vec<AppliedRule> = g.enumerate()
    .take(8)
    .map(|(ar, _logprior)| ar)
    .collect();

assert_eq!(
    exprs,
    vec![
        g.parse("0").unwrap(),
        g.parse("1").unwrap(),
        g.parse("plus(0,0)").unwrap(),
        g.parse("plus(0,1)").unwrap(),
        g.parse("plus(1,0)").unwrap(),
        g.parse("plus(1,1)").unwrap(),
        g.parse("plus(0,plus(0,0))").unwrap(),
        g.parse("plus(0,plus(0,1))").unwrap(),
    ]
);

Important traits for Box<R>

Enumerate subsentences in the Grammar for the given nonterminal.

Set parameters based on supplied sentences. This is performed by Grammar::compress.

Evaluate a sentence using a evaluator.

Examples

use programinduction::pcfg::{Grammar, Rule, task_by_evaluation};

fn evaluator(name: &str, inps: &[i32]) -> Result<i32, ()> {
    match name {
        "0" => Ok(0),
        "1" => Ok(1),
        "plus" => Ok(inps[0] + inps[1]),
        _ => unreachable!(),
    }
}

let g = Grammar::new(
    tp!(EXPR),
    vec![
        Rule::new("0", tp!(EXPR), 1.0),
        Rule::new("1", tp!(EXPR), 1.0),
        Rule::new("plus", tp!(@arrow[tp!(EXPR), tp!(EXPR), tp!(EXPR)]), 1.0),
    ],
);

let expr = g.parse("plus(1, plus(1, plus(1,1)))").unwrap();
assert_eq!(Ok(4), g.eval(&expr, &evaluator));

Sample a statement of the PCFG.

#[macro_use] extern crate polytype;
extern crate programinduction;
extern crate rand;

use programinduction::pcfg::{Grammar, Rule};

let g = Grammar::new(
    tp!(EXPR),
    vec![
        Rule::new("0", tp!(EXPR), 1.0),
        Rule::new("1", tp!(EXPR), 1.0),
        Rule::new("plus", tp!(@arrow[tp!(EXPR), tp!(EXPR), tp!(EXPR)]), 1.0),
    ],
);
let ar = g.sample(&tp!(EXPR), &mut rand::thread_rng());
assert_eq!(&ar.0, &tp!(EXPR));
println!("{}", g.display(&ar));

Get the log-likelihood of an expansion for the given nonterminal.

Examples

use programinduction::pcfg::{Grammar, Rule};

let g = Grammar::new(
    tp!(EXPR),
    vec![
        Rule::new("0", tp!(EXPR), 1.0),
        Rule::new("1", tp!(EXPR), 1.0),
        Rule::new("plus", tp!(@arrow[tp!(EXPR), tp!(EXPR), tp!(EXPR)]), 1.0),
        Rule::new("zero?", tp!(@arrow[tp!(EXPR), tp!(BOOL)]), 1.0),
        Rule::new("if", tp!(@arrow[tp!(BOOL), tp!(EXPR), tp!(EXPR)]), 1.0),
        Rule::new("nand", tp!(@arrow[tp!(BOOL), tp!(BOOL), tp!(BOOL)]), 1.0),
    ]
);

let expr = g.parse("plus(0,0)").unwrap();
assert_eq!(g.likelihood(&expr), -4.1588830833596715);

let expr = g.parse("if( zero?(plus(0 , 0)), 1, 0)").unwrap();
assert_eq!(g.likelihood(&expr), -7.6246189861593985);

Parse a valid sentence in the Grammar. The inverse of display.

Non-terminating production rules are followed by parentheses containing comma-separated productions plus(0, 1). Extraneous white space is ignored.

Parse a valid subsentence in the Grammar which is producible from the given nonterminal.

The inverse of parse.

Trait Implementations

impl Debug for Grammar
[src]

Formats the value using the given formatter. Read more

impl Clone for Grammar
[src]

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

impl EC for Grammar
[src]

An Expression is a sentence in the representation. Tasks are solved by Expressions.

Many representations have some parameters for compression. They belong here.

Iterate over [Expression]s for a given type, with their corresponding log-priors, until a condition is met. This enumeration should be best-first: the log-prior of enumerated expressions should generally increase, so simple expressions are enumerated first. Read more

This is exactly the same as Grammar::update_parameters, but optimized to deal with frontiers.

The entry point for one iteration of the EC algorithm. Read more

The entry point for one iteration of the EC algorithm with a recognizer, very similar to [ec]. Read more

Important traits for Vec<u8>

Enumerate solutions for the given tasks. Read more

Important traits for Vec<u8>

Like [explore], but with specific "recognized" representations for each task. Read more

impl GP for Grammar
[src]

An Expression is a sentence in the representation. Tasks are solved by Expressions.

Extra parameters for a representation go here.

Important traits for Vec<u8>

Create an initial population for a particular requesting type.

Mutate a single program.

Important traits for Vec<u8>

Perform crossover between two programs. There must be at least one child.

A tournament selects an individual from a population.

Important traits for Vec<u8>

Initializes a population, which is a list of programs and their scores sorted by score. The most-fit individual is the first element in the population. Read more

Evolves a population. This will repeatedly run a Bernoulli trial with parameter [mutation_prob] and perform mutation or crossover depending on the outcome until [n_delta] expressions are determined. Read more

Auto Trait Implementations

impl Send for Grammar

impl Sync for Grammar