Compare commits

..

4 Commits

Author SHA1 Message Date
e5b16ae955 some more thinking... 2019-02-19 16:24:05 +01:00
f69d94d758 thinking about rules implementation... 2019-02-19 15:57:27 +01:00
619542357b working on constraint design 2019-02-16 15:13:33 +01:00
4e5aab323e small fixes 2019-02-15 14:18:17 +01:00
8 changed files with 317 additions and 83 deletions

View File

@@ -57,6 +57,7 @@ pub mod ingredients {
use super::{SqliteConnection, schema};
use super::diesel::prelude::*;
/// A wrapper of [`IngredientList`] with DB connection capacity.
pub struct IngredientListManager<'a>(&'a SqliteConnection, IngredientList);
impl<'a> IngredientListManager<'a> {
@@ -98,12 +99,9 @@ pub mod ingredients {
fn find(conn: &SqliteConnection, name: &str) -> Option<Ingredient> {
use self::schema::ingredients::dsl::*;
match ingredients.filter(alias.like(name))
.first(conn)
{
Ok(ingdt) => Some(ingdt),
Err(_) => None,
}
ingredients.filter(alias.like(name))
.first(conn)
.ok()
}
fn create(conn: &SqliteConnection, name: &str) -> Result<i32,String> {

View File

@@ -144,6 +144,12 @@ pub struct Recipe {
pub preparation: String,
}
impl PartialEq for Recipe {
fn eq(&self, other: &Recipe) -> bool {
self.id == other.id
}
}
#[derive(Insertable, Debug)]
#[table_name="recipes"]
pub struct NewRecipe<'a> {

135
planner/src/constraint.rs Normal file
View File

@@ -0,0 +1,135 @@
//! Constraints building
//!
//! # Ideas
//!
//! Each constraints will be updated on every assignment,
//! thus their status is always inspectable.
//! A constraint applies to a set of variables, identified
//! by a key of type `K`.
//! A constraint owns references to actual values assigned,
//! used to perform checks.
//!
//!
//! The problem is to clarify the way Constraints operate.
//! Do they compute their status from some data on demand ?
//! Do they keep their status updated by watching the Variables
//! they act on ?
//! Worse, do they have superpowers ?
//! Could they filter on a variable domain, according to some other variable
//! state ? This would mean that constraints won't judge a result, but guide
//! the solving process to avoid erroring paths, like a constraint-driven
//! solving. This would be powerfull but maybe far too complex...
//!
//! On the other hand, we can implement a simple Observer pattern, with strong
//! coupling to [`Problem`](crate::solver::Problem).
//! Because of this, we can safely play with private fields of Problem, and in
//! return, provide a public api to build specific constraints.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Status {
Validated,// Solution is valid
Unknown, // Constraint cannot resolve yet (unbound variables)
Violated, // Solution is invalid
}
use std::collections::HashMap;
// *Like this
enum ValueChecker {
AllDifferent,
AllSame,
}
pub struct Constraint<'c, V, K> {
status: Status,
variables: HashMap<&'c K, Option<&'c V>>,
// TODO: add a ValueChecker Trait object,
// or just a simple Enum.*
// to provide the check_status procedure, given
// a vector to variables values.
}
impl<'c, V, K> Constraint<'c, V, K>
where K: Eq + std::hash::Hash,
V: PartialEq,
{
pub fn new(vars: Vec<&'c K>) -> Self {
let len = vars.len();
Self {
status: Status::Unknown,
variables: vars.into_iter()
.zip(vec![None; len])
.collect(),
}
}
pub fn status(&self) -> &Status {
&self.status
}
fn check_status(vars: Vec<&Option<&V>>) -> Status {
/// LEts do an hacky NotEqualConstraint
let vars_len = vars.len();
let set_vars: Vec<&Option<&V>> = vars.into_iter().filter(|v| v.is_some()).collect();
let is_complete = vars_len == set_vars.len();
for (idx, value) in set_vars.iter().enumerate() {
let violated = set_vars.iter()
.enumerate()
.filter(|(i,_)| *i != idx)
.fold(false, |res, (_,v)| {
res || v == value
});
if violated { return Status::Violated; }
}
match is_complete {
true => Status::Validated,
false => Status::Unknown,
}
}
fn update_status(&mut self) {
self.status = Self::check_status(self.variables.values().collect());
}
pub fn update(&mut self, key: &K, new_value: Option<&'c V>) {
if let Some(value) = self.variables.get_mut(key) {
// Actually update values
dbg!(*value = new_value);
self.update_status();
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_all_different_problem() {
use crate::solver::{Domain, Problem};
use super::Constraint;
let domain = Domain::new(vec![1, 2, 3]);
let problem = Problem::build()
.add_variable("Left", domain.all(), None)
.add_variable("Right", domain.all(), None)
.add_constraint(Constraint::new(vec![&"Left", &"Right"]))
.finish();
let solutions = vec![
(("Left", Some(&1)), ("Right", Some(&2))),
(("Left", Some(&1)), ("Right", Some(&3))),
(("Left", Some(&2)), ("Right", Some(&1))),
(("Left", Some(&2)), ("Right", Some(&3))),
(("Left", Some(&3)), ("Right", Some(&1))),
(("Left", Some(&3)), ("Right", Some(&2))),
];
let results = problem.solve_all();
println!("{:#?}", results);
assert!(results.len() == solutions.len());
results.into_iter().for_each(|res| {
let res = (("Left", *res.get("Left").unwrap()),
("Right", *res.get("Right").unwrap())) ;
assert!(solutions.contains(&res));
});
}
}

View File

@@ -3,7 +3,7 @@ use cookbook::recipes::Recipe;
pub mod solver;
pub mod template;
pub mod constraint;
pub use solver::{Domain, DomainValues};
/// We mainly use Recipe as the domain value type

View File

@@ -1,16 +1,56 @@
//! Rules used by the `planner`
//! A rule is a constraint on valid solutions, but also provides insights
//! and eventually inferences to optimize the solving process.
//!
//! * Basic repartition
//! * All different meals
//! * Map recipes categories to each meals
//! * (Eating a dish over two days (leftovers))
//! * Nutritional values
//! * Per day : according to user profile (man: 2000kcal, woman: 1800kcal)
//! * Per meal : some meals should have higher nutrional values than others
//!
//! * Ingredients
//! * Per week : should use most of a limited set of ingredients (excluding
//! condiments, ...)
//! * To consume : must use a small set of ingredients (leftovers)
//!
//!
//! Price
//! - Per week : should restrict ingredients cost to a given amount
// Nutritional values
// - Per day : according to user profile (man: 2000kcal, woman: 1800kcal)
// - Per meal : some meals should have higher nutrional values than others
enum Status {
Ok,
Violated,
}
// Ingredients
// - Per week : should use most of a limited set of ingredients (excluding
// condiments, ...)
// - To consume : must use a small set of ingredients (leftovers)
//
trait Rule {
type Key;
type Value;
// Price
// - Per week : should restrict ingredients cost to a given amount
fn status(&self, state: (Vec<&Self::Key>, Vec<&Self::Value>));
fn update(&self, idx: usize, value: Option<Self::Value>) -> Option<Filter>;
};
struct AllDifferentMeals;
impl Rule for AllDifferentMeals {
type State = Vec<Recipe>;
fn status(&self, _: Self::State) -> Status {
Status::Ok // Always enforced by update rule
}
fn update(&self, _: Self::State) -> Option<Filter> {
// Returns a filter excluding this value from domain.
// so that it is impossible to select the same meal twice.
None
}
}
struct FilterRecipeByMeals; // Essentially work on domain
struct NutritionalByDayAverageReq;
struct NutritionalByMealAverageValues;
struct IngredientsInFridge;
struct IngredientsMustUse;

View File

@@ -6,11 +6,16 @@ use std::hash::Hash;
use std::clone::Clone;
use std::collections::HashMap;
/// An assignments map of variables
type Variables<'a, V> = Vec<Option<&'a V>>;
use crate::constraint::{Status, Constraint};
/// A solution returned by [`Solver`]
pub type Solution<'a, V, K> = HashMap<K, Option<&'a V>>;
/// An assignments map of variables
type Variables<'a, V> = Vec<Option<&'a V>>;
/// Orders used by solver to update variables
enum Assignment<'a, V> {
Update(usize, &'a V),
Clear(usize)
@@ -100,8 +105,48 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
}
}
/// Or we can have a much more complex version of Domain.
/// We want to retrieve a filtered domain for each variable.
/// Filters will be static (filter by category,...) or dynamic
/// (inserted by rules updates).
///
/// For every variable, we can retrieve its filtered values (values,
/// filtered by all globals, filtered by one local).
/// Plus, set a dynamic filter that will apply to all other variables.
/// Of course, it also affects this variable, but considering that dynamic
/// filters are cleared and repopulated on every assign, this side-effect
/// can never occur.
struct SDomain<V, Filter> {
values: Vec<V>,
global_filters: Vec<Filter>, // Globals are dynamic Filters
local_filters: Vec<Filter>, // Locals are static Filters
}
pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
impl<V, F> SDomain<V, F> {
fn new(values: Vec<V>) -> Self {
Self {
values,
global_filters: Vec::new(),
local_filters: Vec::new(),
}
}
/// Returns the current domain values for a variable by index
fn get(&self, idx: usize) -> DomainValues<V> {
self.values
.iter()
.collect()
}
/// Adds a dynamic filter to globals, identified by its setter's id
/// /!\ Previously set filters are overriden, hence dynamic
fn set_global(&mut self, setter: usize, filter: F) {
self.global_filters[setter] = filter;
}
}
//pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
/// Could be more efficient to just use fixed array of options as variables,
@@ -109,23 +154,23 @@ pub type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
/// Domains could be a similar array of DomainValues.
/// It makes sense with an array where indexing is O(1)
pub struct Problem<'a, V, K> {
pub struct Problem<'p, V, K> {
keys: Vec<K>,
/// The initial assignements map
variables: Variables<'a, V>,
/// The initial assignements
variables: Variables<'p, V>,
/// Each variable has its associated domain
domains: Vec<DomainValues<'a,V>>,
domains: Vec<DomainValues<'p,V>>,
/// Set of constraints to validate
constraints: Vec<Constraint<'a,V>>,
constraints: Vec<Constraint<'p,V,K>>,
}
impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
impl<'p, V: PartialEq, K: Eq + Hash + Clone> Problem<'p, V, K> {
pub fn build() -> ProblemBuilder<'a,V, K> {
pub fn build() -> ProblemBuilder<'p,V, K> {
ProblemBuilder::new()
}
pub fn from_template() -> Problem<'a, V, K> {
pub fn from_template() -> Problem<'p, V, K> {
let builder = Self::build();
builder.finish()
@@ -133,19 +178,20 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
/// 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>>> {
// TODO: should be able to inject a choosing strategy
if let Some(key) = self._next_assign() {
fn _push_updates(&self) -> Option<Vec<Assignment<'p,V>>> {
if let Some(idx) = self._next_assign() {
// TODO: Domain will filter possible values for us
// let values = self.domain.get(idx);
let domain_values = self.domains
.get(key)
.get(idx)
.expect("No domain for variable !");
// TODO: handle case of empty domain.values
assert!(!domain_values.is_empty());
// Push a clear assignment first, just before going up the stack.
let mut updates = vec![Assignment::Clear(key.clone())];
// TODO: should be able to filter domain values (inference, pertinence)
let mut updates = vec![Assignment::Clear(idx.clone())];
domain_values.iter().for_each(|value| {
updates.push(
Assignment::Update(key, *value)
Assignment::Update(idx, *value)
);
});
Some(updates)
@@ -155,6 +201,7 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
}
fn _next_assign(&self) -> Option<usize> {
// TODO: should be able to inject a choosing strategy
self.variables.iter()
.enumerate()
.find_map(|(idx, val)| {
@@ -165,15 +212,41 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
/// 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; }
for status in self.constraints.iter().map(|c| c.status()) {
if status == &Status::Violated { return false; }
}
return true;
}
fn _solve(&mut self, limit: Option<usize>) -> Vec<Solution<'a, V, K>> {
fn _get_key(&self, idx: usize) -> &K {
&self.keys[idx]
}
fn _get_solution(&self) -> Solution<'p, V, K> {
// Returns the current state wrapped in a Solution type.
self.keys.iter().cloned()
.zip(self.variables.iter().cloned())
.collect()
}
/// Assigns a new value to the given index, then calls update
/// on every constraints.
fn _assign(&mut self, idx: usize, value: Option<&'p V>) {
self.variables[idx] = value;
let var_key = &self.keys[idx];
// TODO: manage dynamic filters on Domain
// let filters: Filter::Chain = self.constraints.iter_mut().map([...]).collect();
// self.domain.set_global(idx, filters);
self.constraints.iter_mut()
.for_each(|c| {
c.update(&var_key, value);
});
}
fn _solve(&mut self, limit: Option<usize>) -> Vec<Solution<'p, V, K>> {
let mut solutions: Vec<Solution<V, K>> = vec![];
let mut stack: Vec<Assignment<'a, V>> = vec![];
let mut stack: Vec<Assignment<'p, V>> = vec![];
if let Some(mut init_updates) = self._push_updates() {
stack.append(&mut init_updates);
} else {
@@ -195,25 +268,19 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'a, V, K> {
match node.unwrap() {
Assignment::Update(idx, val) => {
// Assign the variable and open new branches, if any.
self.variables[idx] = Some(val);
// TODO: handle case of empty domain.values
self._assign(idx, Some(val));
if let Some(mut nodes) = self._push_updates() {
stack.append(&mut nodes);
} else {
// Assignements are completed
if self._is_valid() {
solutions.push(
// Builds Solution
self.keys.iter().cloned()
.zip(self.variables.iter().cloned())
.collect()
);
solutions.push(self._get_solution());
};
};
},
Assignment::Clear(idx) => {
// We are closing this branch, unset the variable
self.variables[idx] = None;
self._assign(idx, None);
},
};
};
@@ -221,25 +288,25 @@ impl<'a, V, K: Eq + Hash + Clone> Problem<'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,
pub fn solve_all(mut self) -> Vec<Solution<'p,V,K>>
where V: fmt::Debug,
K: fmt::Debug,
{
self._solve(None) // No limit
}
pub fn solve_one(&mut self) -> Option<Solution<'a,V,K>>
where V: Clone + fmt::Debug,
K: Clone + fmt::Debug,
pub fn solve_one(mut self) -> Option<Solution<'p,V,K>>
where V: fmt::Debug,
K: fmt::Debug,
{
self._solve(Some(1)).pop()
}
}
pub struct ProblemBuilder<'a, V, K>(Problem<'a, V, K>);
pub struct ProblemBuilder<'p, V, K>(Problem<'p, V, K>);
impl<'a, V, K: Eq + Hash + Clone> ProblemBuilder<'a, V, K> {
fn new() -> ProblemBuilder<'a, V, K> {
impl<'p, V, K: Eq + Hash + Clone> ProblemBuilder<'p, V, K> {
fn new() -> ProblemBuilder<'p, V, K> {
ProblemBuilder(
Problem{
keys: Vec::new(),
@@ -249,20 +316,20 @@ impl<'a, V, K: Eq + Hash + Clone> ProblemBuilder<'a, V, K> {
})
}
pub fn add_variable(mut self, name: K, domain: Vec<&'a V>, value: Option<&'a V>) -> Self
pub fn add_variable(mut self, name: K, static_filter: Vec<&'p V>, initial: Option<&'p V>) -> Self
{
self.0.keys.push(name);
self.0.variables.push(value);
self.0.domains.push(domain);
self.0.variables.push(initial);
self.0.domains.push(static_filter);
self
}
pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
pub fn add_constraint(mut self, cons: Constraint<'p,V,K>) -> Self {
self.0.constraints.push(cons);
self
}
pub fn finish(self) -> Problem<'a, V, K> {
pub fn finish(self) -> Problem<'p,V, K> {
self.0
}
}
@@ -274,12 +341,9 @@ mod tests {
fn test_solver_find_pairs() {
use super::*;
let domain = Domain::new(vec![1,2,3]);
let mut problem: Problem<_, _> = Problem::build()
let 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[0] == assign[1]
})
.finish();
let solutions: Vec<Solution<i32, _>> = vec![
@@ -295,12 +359,9 @@ mod tests {
fn test_solver_find_pairs_with_initial() {
use super::*;
let domain = Domain::new(vec![1,2,3]);
let mut problem: Problem<_, _> = Problem::build()
let 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[0] == assign[1]
})
.finish();
let solutions: Vec<Solution<i32, String>> = vec![

View File

@@ -100,9 +100,8 @@ mod api {
for (var, dom, ini) in template::Template::generate_variables(&domain) {
problem = problem.add_variable(var, dom, ini);
}
let mut problem = problem
.add_constraint(|_| true)
.finish();
let problem = problem.finish();
if let Some(one_result) = problem.solve_one() {
Json(TemplateObject {
items: one_result
@@ -127,8 +126,6 @@ mod api {
solver::{Domain, Problem}
};
println!("{:?}", partial);
println!("Building problem");
let possible_values = recipes::load_all(&conn);
let domain = Domain::new(possible_values);
let mut problem = Problem::build();
@@ -144,16 +141,15 @@ mod api {
&& slot.key.1 == format!("{:?}",var.1)
{
let id = slot.value.as_ref().unwrap().id;
println!("found initial : recipe with id {}", id);
//println!("found initial : recipe with id {}", id);
Some(id)
} else {
None
}
});
let ini = if let Some(id) = initial_id {
// Not working because we're capturing `id`
let new_ini = domain.find(|r| {r.id == id});
println!("Overrided {:?}", new_ini);
//println!("Overrided {:?}", new_ini);
new_ini
} else {
ini
@@ -161,9 +157,8 @@ mod api {
// If found, override initial value
problem = problem.add_variable(var, dom, ini);
};
let mut problem = problem
.add_constraint(|_| true)
.finish();
let problem = problem.finish();
if let Some(one_result) = problem.solve_one() {
Json(TemplateObject {
items: one_result

View File

@@ -120,12 +120,11 @@ export default {
body,
})
.then((res) => {
this.is_loading = false;
return res.json();}
)
.then((data) => this.template.updateJson(data))
.catch((err) => console.error(err));
this.is_loading = false;
},
unsetMeal: function(mealKey) {
let idx = this.template.findIndexByKey(mealKey);