207 lines
6.6 KiB
Rust
207 lines
6.6 KiB
Rust
//! # Solver
|
|
//!
|
|
//! Provides `Variables`, `Domain` structs and `solve_all` function.
|
|
use std::fmt;
|
|
use std::clone::Clone;
|
|
use std::collections::HashMap;
|
|
|
|
/// An assignments map of variables
|
|
pub type Variables<'a, V> = HashMap<String, Option<&'a V>>;
|
|
|
|
enum Assignment<'a, V> {
|
|
Update(String, &'a V),
|
|
Clear(String)
|
|
}
|
|
|
|
type Domains<'a, V> = HashMap<String, &'a Domain<V>>;
|
|
/// The domain of values that can be assigned to variables
|
|
#[derive(Clone)]
|
|
pub struct Domain<V> {
|
|
pub values: Vec<V>
|
|
}
|
|
|
|
impl<V> Domain<V> {
|
|
pub fn new(values: Vec<V>) -> Domain<V> {
|
|
Domain { values }
|
|
}
|
|
|
|
/// Returns a new domain with the given 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).values, &vec![2]);
|
|
/// ```
|
|
pub fn filter(&self, f: fn(&V) -> bool) -> Domain<V>
|
|
where V: std::clone::Clone
|
|
{
|
|
Domain {
|
|
values: self.values.iter().cloned().filter(f).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> = fn(&Variables<'a,V>) -> bool;
|
|
|
|
pub struct Problem<'a, V> {
|
|
/// The initial assignements map
|
|
variables: Variables<'a, V>,
|
|
/// Each variable has its associated domain
|
|
domains: Domains<'a,V>,
|
|
/// Set of constraints to validate
|
|
constraints: Vec<Constraint<'a,V>>,
|
|
}
|
|
|
|
impl<'a,V> Problem<'a, V> {
|
|
|
|
pub fn build() -> ProblemBuilder<'a,V> {
|
|
ProblemBuilder::new()
|
|
}
|
|
|
|
/// Returns all possible Updates for next assignements, prepended with
|
|
/// a Clear to ensure the variable is unset before when leaving the branch.
|
|
fn _assign_next(&self) -> Option<Vec<Assignment<'a,V>>> {
|
|
// TODO: should be able to inject a choosing strategy
|
|
if let Some((key,_)) = self.variables.iter().find(|(_, val)| val.is_none()) {
|
|
let domain = self.domains.get(key).expect("No domain for variable !");
|
|
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.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;
|
|
}
|
|
|
|
/// Visit all possible solutions, using a stack.
|
|
pub fn solve_all(&mut self) -> Vec<Variables<'a,V>>
|
|
where V: Clone + fmt::Debug
|
|
{
|
|
let mut solutions: Vec<Variables<V>> = vec![];
|
|
let mut stack: Vec<Assignment<'a, V>> = vec![];
|
|
stack.append(&mut self._assign_next().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._assign_next() {
|
|
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>(Problem<'a, V>);
|
|
|
|
impl<'a, V> ProblemBuilder<'a, V> {
|
|
fn new() -> ProblemBuilder<'a, V> {
|
|
ProblemBuilder(
|
|
Problem{
|
|
variables: Variables::new(),
|
|
domains: HashMap::new(),
|
|
constraints: Vec::new(),
|
|
})
|
|
}
|
|
|
|
pub fn add_variable<S>(mut self, name: S, domain: &'a Domain<V>, value: Option<&'a V>) -> Self
|
|
where S: Into<String>
|
|
{
|
|
let name = name.into();
|
|
self.0.variables.insert(name.clone(), value);
|
|
self.0.domains.insert(name, domain);
|
|
self
|
|
}
|
|
|
|
pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
|
|
self.0.constraints.push(cons);
|
|
self
|
|
}
|
|
|
|
pub fn finish(self) -> Problem<'a, V> {
|
|
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, None)
|
|
.add_variable(String::from("Right"), &domain, 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, None)
|
|
.add_variable("Right".to_string(), &domain, 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);
|
|
}
|
|
}
|