Files
CookAssistant/planner/src/solver.rs

221 lines
7.1 KiB
Rust

//! # Solver
//!
//! Provides `Variables`, `Domain` structs and `solve_all` function.
use std::fmt;
use std::hash::Hash;
use std::clone::Clone;
use std::collections::HashMap;
/// An assignments map of variables
pub type Variables<'a, V, K> = HashMap<K, Option<&'a V>>;
enum Assignment<'a, V, K> {
Update(K, &'a V),
Clear(K)
}
pub type DomainValues<'a, V> = Vec<&'a V>;
/// The domain of values that can be assigned to variables
#[derive(Clone)]
pub struct Domain<V> {
values: Vec<V>
}
impl<V> Domain<V> {
pub fn new(values: Vec<V>) -> Domain<V> {
Domain { values }
}
/// Returns all values of a Domain instance
pub fn all(&self) -> DomainValues<V> {
self.values.iter().collect()
}
/// Returns a Filter filter applied to inner values
///
/// # Examples
///
/// ```
/// # extern crate planner;
/// # use planner::solver::Domain;
/// let domain = Domain::new(vec![1,2,3]);
/// fn even(i: &i32) -> bool {
/// i % 2 == 0
/// };
/// assert_eq!(domain.filter(even), vec![&2]);
/// assert_eq!(domain.filter(|i: &i32| i % 2 == 1), vec![&1,&3]);
/// ```
pub fn filter(&self, filter_func: fn(&V) -> bool) -> DomainValues<V> {
self.values
.iter()
.filter(|v: &&V| filter_func(*v))
.collect()
}
}
impl<V: fmt::Debug> fmt::Debug for Domain<V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Domain<{:?}>", self.values)
}
}
pub type Constraint<'a,V, K> = fn(&Variables<'a,V, K>) -> bool;
pub struct Problem<'a, V, K> {
/// The initial assignements map
variables: Variables<'a, V, K>,
/// Each variable has its associated domain
domains: HashMap<K, DomainValues<'a,V>>,
/// Set of constraints to validate
constraints: Vec<Constraint<'a,V,K>>,
}
impl<'a,V, K: Eq + Hash + Clone> Problem<'a, V, K> {
pub fn build() -> ProblemBuilder<'a,V, K> {
ProblemBuilder::new()
}
pub fn from_template() -> Problem<'a, V, K> {
let mut builder = Self::build();
builder.finish()
}
/// Returns all possible Updates for next assignements, prepended with
/// a Clear to ensure the variable is unset before when leaving the branch.
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V, K>>> {
// TODO: should be able to inject a choosing strategy
if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
let domain_values = self.domains.get(key).expect("No domain for variable !");
// Push a clear assignment first, just before going up the stack.
let mut updates = vec![Assignment::Clear(key.clone())];
if domain_values.is_empty() { panic!("No value in domain !"); }
// TODO: should be able to filter domain values (inference, pertinence)
for value in domain_values.into_iter() {
updates.push(Assignment::Update(key.clone(), *value));
}
Some(updates)
} else { // End of assignements
None
}
}
/// Checks that the current assignments doesn't violate any constraint
fn _is_valid(&self) -> bool {
for validator in self.constraints.iter() {
if validator(&self.variables) == false { return false; }
}
return true;
}
/// Returns all complete solutions, after visiting all possible outcomes using a stack (DFS).
pub fn solve_all(&mut self) -> Vec<Variables<'a,V,K>>
where V: Clone + fmt::Debug,
K: Clone + fmt::Debug,
{
let mut solutions: Vec<Variables<V, K>> = vec![];
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
stack.append(&mut self._push_updates().unwrap());
loop {
let node = stack.pop();
if node.is_none() { break; };
match node.unwrap() {
Assignment::Update(key, val) => {
// Assign the variable and open new branches, if any.
*self.variables.get_mut(&key).unwrap() = Some(val);
// TODO: handle case of empty domain.values
if let Some(mut nodes) = self._push_updates() {
stack.append(&mut nodes);
} else {
// Assignements are completed
if self._is_valid() {
solutions.push(self.variables.clone());
};
};
},
Assignment::Clear(key) => {
// We are closing this branch, unset the variable
*self.variables.get_mut(&key).unwrap() = None;
},
};
};
solutions
}
}
pub struct ProblemBuilder<'a, V, K>(Problem<'a, V, K>);
impl<'a, V, K: Eq + Hash + Clone> ProblemBuilder<'a, V, K> {
fn new() -> ProblemBuilder<'a, V, K> {
ProblemBuilder(
Problem{
variables: Variables::new(),
domains: HashMap::new(),
constraints: Vec::new(),
})
}
pub fn add_variable(mut self, name: K, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
{
self.0.variables.insert(name.clone(), value);
self.0.domains.insert(name, domain);
self
}
pub fn add_constraint(mut self, cons: Constraint<'a,V, K>) -> Self {
self.0.constraints.push(cons);
self
}
pub fn finish(self) -> Problem<'a, V, K> {
self.0
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solver_find_pairs() {
use super::*;
let domain = Domain::new(vec![1,2,3]);
let mut problem: Problem<_, _> = Problem::build()
.add_variable(String::from("Left"), domain.all(), None)
.add_variable(String::from("Right"), domain.all(), None)
.add_constraint(|assign: &Variables<i32, _>| {
assign.get("Left").unwrap() == assign.get("Right").unwrap()
})
.finish();
let solutions: Vec<Variables<i32, _>> = vec![
[("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(),
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
[("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
];
assert_eq!(problem.solve_all(), solutions);
}
#[test]
fn test_solver_find_pairs_with_initial() {
use super::*;
let domain = Domain::new(vec![1,2,3]);
let mut problem: Problem<_, _> = Problem::build()
.add_variable("Left".to_string(), domain.all(), None)
.add_variable("Right".to_string(), domain.all(), Some(&2))
.add_constraint( |assign: &Variables<i32, _>| {
assign.get("Left").unwrap() == assign.get("Right").unwrap()
})
.finish();
let solutions: Vec<Variables<i32, _>> = vec![
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
];
assert_eq!(problem.solve_all(), solutions);
}
}