Compare commits

...

2 Commits

Author SHA1 Message Date
4bc04bd7e3 refactors Problem, adds Solution 2019-02-15 13:46:39 +01:00
4b21fd873b breaking things up, refactors Problem with vectors... 2019-02-14 21:50:19 +01:00
2 changed files with 68 additions and 81 deletions

View File

@@ -5,20 +5,19 @@ extern crate cookbook;
use std::time;
use std::fmt::Debug;
use std::fmt::Display;
use std::hash::Hash;
use cookbook::*;
use planner::{
*, Value,
solver::{
Variables,
Solution,
Domain,
Problem
}
};
fn pretty_output<K: Eq + Hash + Debug>(res: &Variables<Value, K>) -> String {
fn pretty_output<K: Eq + Hash + Debug>(res: &Solution<Value, K>) -> String {
let mut repr = String::new();
for (var,value) in res {
let value = match value {

View File

@@ -7,11 +7,13 @@ use std::clone::Clone;
use std::collections::HashMap;
/// An assignments map of variables
pub type Variables<'a, V, K> = HashMap<K, Option<&'a V>>;
type Variables<'a, V> = Vec<Option<&'a V>>;
/// A solution returned by [`Solver`]
pub type Solution<'a, V, K> = HashMap<K, Option<&'a V>>;
enum Assignment<'a, V, K> {
Update(K, &'a V),
Clear(K)
enum Assignment<'a, V> {
Update(usize, &'a V),
Clear(usize)
}
/// Collection of references to values owned by a domain.
@@ -99,7 +101,7 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
}
pub type Constraint<'a,V, K> = fn(&Variables<'a,V, K>) -> bool;
pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
/// Could be more efficient to just use fixed array of options as variables,
@@ -108,12 +110,13 @@ pub type Constraint<'a,V, K> = fn(&Variables<'a,V, K>) -> bool;
/// It makes sense with an array where indexing is O(1)
pub struct Problem<'a, V, K> {
keys: Vec<K>,
/// The initial assignements map
variables: Variables<'a, V, K>,
variables: Variables<'a, V>,
/// Each variable has its associated domain
domains: HashMap<K, DomainValues<'a,V>>,
domains: Vec<DomainValues<'a,V>>,
/// Set of constraints to validate
constraints: Vec<Constraint<'a,V,K>>,
constraints: Vec<Constraint<'a,V>>,
}
impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
@@ -123,14 +126,14 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
}
pub fn from_template() -> Problem<'a, V, K> {
let mut builder = Self::build();
let 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>>> {
fn _push_updates(&self) -> Option<Vec<Assignment<'a,V>>> {
// TODO: should be able to inject a choosing strategy
if let Some(key) = self._next_assign() {
let domain_values = self.domains
@@ -142,10 +145,7 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
// TODO: should be able to filter domain values (inference, pertinence)
domain_values.iter().for_each(|value| {
updates.push(
Assignment::Update(
key.clone(),
*value
)
Assignment::Update(key, *value)
);
});
Some(updates)
@@ -154,11 +154,11 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
}
}
fn _next_assign(&self) -> Option<&K> {
self.variables
.iter()
.find_map(|(key, val)| {
if val.is_none() { Some(key) }
fn _next_assign(&self) -> Option<usize> {
self.variables.iter()
.enumerate()
.find_map(|(idx, val)| {
if val.is_none() { Some(idx) }
else { None }
})
}
@@ -171,13 +171,9 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
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![];
fn _solve(&mut self, limit: Option<usize>) -> Vec<Solution<'a, V, K>> {
let mut solutions: Vec<Solution<V, K>> = vec![];
let mut stack: Vec<Assignment<'a, V>> = vec![];
if let Some(mut init_updates) = self._push_updates() {
stack.append(&mut init_updates);
} else {
@@ -187,66 +183,56 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
loop {
let node = stack.pop();
// There is no more combination to try out
if node.is_none() { break; };
// Exit early if we have enough solutions
if limit.is_some()
&& solutions.len() == limit.unwrap()
{
break;
};
match node.unwrap() {
Assignment::Update(key, val) => {
Assignment::Update(idx, val) => {
// Assign the variable and open new branches, if any.
*self.variables.get_mut(&key).unwrap() = Some(val);
self.variables[idx] = 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());
solutions.push(
// Builds Solution
self.keys.iter().cloned()
.zip(self.variables.iter().cloned())
.collect()
);
};
};
},
Assignment::Clear(key) => {
Assignment::Clear(idx) => {
// We are closing this branch, unset the variable
*self.variables.get_mut(&key).unwrap() = None;
self.variables[idx] = None;
},
};
};
solutions
}
pub fn solve_one(&mut self) -> Option<Variables<'a,V,K>>
}
/// Returns all complete solutions, after visiting all possible outcomes using a stack (DFS).
pub fn solve_all(&mut self) -> Vec<Solution<'a,V,K>>
where V: Clone + fmt::Debug,
K: Clone + fmt::Debug,
{
let mut stack: Vec<Assignment<'a, V, K>> = vec![];
if let Some(mut init_updates) = self._push_updates() {
stack.append(&mut init_updates);
} else {
panic!("Could not initialize !");
self._solve(None) // No limit
}
loop {
let node = stack.pop();
if node.is_none() {
return None;
};
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() {
return Some(self.variables.clone());
};
};
},
Assignment::Clear(key) => {
// We are closing this branch, unset the variable
*self.variables.get_mut(&key).unwrap() = None;
},
};
}
pub fn solve_one(&mut self) -> Option<Solution<'a,V,K>>
where V: Clone + fmt::Debug,
K: Clone + fmt::Debug,
{
self._solve(Some(1)).pop()
}
}
@@ -256,20 +242,22 @@ impl<'a, V, K: Eq + Hash + Clone> ProblemBuilder<'a, V, K> {
fn new() -> ProblemBuilder<'a, V, K> {
ProblemBuilder(
Problem{
keys: Vec::new(),
variables: Variables::new(),
domains: HashMap::new(),
domains: Vec::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.0.keys.push(name);
self.0.variables.push(value);
self.0.domains.push(domain);
self
}
pub fn add_constraint(mut self, cons: Constraint<'a,V, K>) -> Self {
pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
self.0.constraints.push(cons);
self
}
@@ -289,15 +277,15 @@ mod tests {
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()
.add_constraint(|assign: &Variables<i32>| {
assign[0] == assign[1]
})
.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(),
let solutions: Vec<Solution<i32, _>> = vec![
[(String::from("Left"), Some(&3)), (String::from("Right"), Some(&3))].iter().cloned().collect(),
[(String::from("Left"), Some(&2)), (String::from("Right"), Some(&2))].iter().cloned().collect(),
[(String::from("Left"), Some(&1)), (String::from("Right"), Some(&1))].iter().cloned().collect(),
];
assert_eq!(problem.solve_all(), solutions);
@@ -310,13 +298,13 @@ mod tests {
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()
.add_constraint( |assign: &Variables<i32>| {
assign[0] == assign[1]
})
.finish();
let solutions: Vec<Variables<i32, _>> = vec![
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
let solutions: Vec<Solution<i32, String>> = vec![
[(String::from("Left"), Some(&2)), (String::from("Right"), Some(&2))].iter().cloned().collect(),
];
assert_eq!(problem.solve_all(), solutions);