Compare commits

...

7 Commits

Author SHA1 Message Date
874a9f86f8 Minor refactoring 2019-01-29 21:44:05 +01:00
4576ffb03b Adds ingredients managing 2019-01-28 21:25:25 +01:00
202d7c5976 Adds write script for recipes, adds ingredients migrations 2019-01-28 15:23:39 +01:00
fb4d24ef44 building db support with diesel.rs 2019-01-27 21:52:46 +01:00
940927d376 Refactores solver, removes dead binary code 2019-01-21 21:08:50 +01:00
14f604283c Some cleanup and removing dead code warnings 2019-01-21 15:21:43 +01:00
f7ba3ed3a6 Drafting 2019-01-21 15:02:29 +01:00
20 changed files with 439 additions and 173 deletions

1
cookbook/.env Normal file
View File

@@ -0,0 +1 @@
DATABASE_URL=db.sqlite3

View File

@@ -5,3 +5,6 @@ authors = ["artus <artus@landoftheunicorn.hd.free.fr>"]
edition = "2018" edition = "2018"
[dependencies] [dependencies]
libsqlite3-sys = { version = "*", features = ["bundled"] }
diesel = { version = "1.4.1", features = ["sqlite"] }
dotenv = "0.9.0"

BIN
cookbook/db.sqlite3 Normal file

Binary file not shown.

5
cookbook/diesel.toml Normal file
View File

@@ -0,0 +1,5 @@
# For documentation on how to configure this file,
# see diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/schema.rs"

View File

View File

@@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLE recipes

View File

@@ -0,0 +1,8 @@
-- Your SQL goes here
CREATE TABLE recipes (
id INTEGER PRIMARY KEY NOT NULL,
title VARCHAR NOT NULL,
category INTEGER NOT NULL,
ingredients TEXT NOT NULL,
preparation TEXT NOT NULL
)

View File

@@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLE ingredients

View File

@@ -0,0 +1,5 @@
-- Your SQL goes here
CREATE TABLE ingredients (
id INTEGER PRIMARY KEY NOT NULL,
alias VARCHAR NOT NULL
)

View File

@@ -0,0 +1,23 @@
extern crate cookbook;
extern crate diesel;
use self::cookbook::*;
use self::models::*;
use self::diesel::prelude::*;
fn main() {
use cookbook::schema::recipes::dsl::*;
let conn = establish_connection();
let result = recipes
.limit(5)
.load::<Recipe>(&conn)
.expect("Error loading recipes");
println!("Here are {} recipes :", result.len());
for rec in result {
println!("*************\n{}", rec.title);
println!("-------------\n");
println!("{}", rec.ingredients);
}
}

View File

@@ -0,0 +1,81 @@
extern crate cookbook;
extern crate diesel;
use std::io::{Read, stdin};
use diesel::SqliteConnection;
use self::cookbook::*;
use self::models::NewRecipe;
struct CreateRecipe<'a> {
connection: &'a SqliteConnection,
title: &'a str,
ingredients: String,
}
impl<'a> CreateRecipe<'a> {
fn new(conn: &'a SqliteConnection) -> Self {
CreateRecipe{
connection: conn,
title: "New recipe",
ingredients: String::new(),
}
}
fn set_title(&mut self, title: &'a str) {
self.title = title;
}
fn add_ingredient(&mut self, name: String) {
use crate::ingredients::*;
// Check it exists or create
if let Some(_ingdt) = find(self.connection, &name) {
println!("=");
} else {
create(self.connection, &name);
println!("+{}", &name);
}
self.ingredients.push_str(&name);
}
/// Builds a NewRecipe instance from current data and insert it.
fn insert(self) {
let new_recipe = NewRecipe::new(self.title, 0, &self.ingredients, "");
match new_recipe.insert(self.connection) {
Ok(new) => println!("Added {}", new.title),
Err(e) => println!("Error: {}", e),
};
}
}
fn main() {
let conn = establish_connection();
let mut builder = CreateRecipe::new(&conn);
println!("Title : ");
let mut title = String::new();
stdin().read_line(&mut title).unwrap();
let title = &title[..(title.len() - 1)];
builder.set_title(title);
println!("Ingredients (empty line to finish): ");
loop {
let mut ingdts = String::new();
stdin().read_line(&mut ingdts).unwrap();
if &ingdts == "\r\n" {
break;
}
builder.add_ingredient(ingdts.clone());
}
builder.insert();
}
#[cfg(not(windows))]
const EOF: &'static str = "CTRL+D";
#[cfg(windows)]
const EOF: &'static str = "CTRL+Z";

View File

@@ -1,16 +1,58 @@
mod meal; #[macro_use]
mod storage; extern crate diesel;
extern crate dotenv;
pub mod schema;
pub mod models;
mod recipe;
mod importer; mod importer;
pub use self::meal::Meal; use diesel::prelude::*;
use dotenv::dotenv;
use std::env;
use crate::models::{Recipe, NewRecipe};
pub fn fetch_meals() -> Vec<Meal> { pub fn establish_connection() -> SqliteConnection {
vec![ dotenv().ok();
Meal::new("Raclette".to_string(), 800),
Meal::new("Soupe".to_string(), 400), let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set !");
] SqliteConnection::establish(&db_url)
.expect(&format!("Error connecting to {}", db_url))
} }
pub mod ingredients {
use crate::models::{Ingredient, NewIngredient};
use super::{SqliteConnection, schema};
use super::diesel::prelude::*;
pub fn find(conn: &SqliteConnection, name: &str) -> Option<Ingredient> {
use self::schema::ingredients::dsl::*;
let results = ingredients.filter(alias.like(name))
.limit(1)
.load::<Ingredient>(conn)
.expect("Error finding ingredient");
if !results.is_empty() {
Some(results.into_iter().nth(0).unwrap())
} else {
None
}
}
pub fn create(conn: &SqliteConnection, name: &str) -> usize {
use self::schema::ingredients;
diesel::insert_into(ingredients::table)
.values(&NewIngredient { alias: name })
.execute(conn)
.expect("Error inserting ingredient")
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#[test] #[test]

View File

@@ -1,31 +0,0 @@
/// An individual ingredient
pub struct Ingredient {
name: String,
}
impl Ingredient {
pub(super) fn new(name: String) -> Ingredient {
Ingredient { name }
}
}
/// An ordered set of dishes
#[derive(Debug,Clone)]
pub struct Meal {
name: String,
nutritional_value: i32,
}
impl Meal {
pub(super) fn new(name: String, nutritional_value: i32) -> Meal {
Meal { name, nutritional_value }
}
pub fn nutritional_value(&self) -> i32 {
self.nutritional_value
}
}

52
cookbook/src/models.rs Normal file
View File

@@ -0,0 +1,52 @@
use super::schema::recipes;
use super::schema::ingredients;
use super::diesel::prelude::*;
#[derive(Queryable)]
pub struct Recipe {
pub id: i32,
pub title: String,
pub category: i32,
pub ingredients: String,
pub preparation: String,
}
#[derive(Insertable)]
#[table_name="recipes"]
pub struct NewRecipe<'a> {
pub title: &'a str,
pub category: i32,
pub ingredients: &'a str,
pub preparation: &'a str,
}
impl<'a> NewRecipe<'a> {
pub fn new(title: &'a str, category: i32, ingredients: &'a str, preparation: &'a str) -> Self {
NewRecipe{
title,
category,
ingredients,
preparation,
}
}
pub fn insert(self, conn: &SqliteConnection) -> Result<Self, String> {
diesel::insert_into(recipes::table)
.values(&self)
.execute(conn)
.expect("Error inserting recipe");
Ok(self)
}
}
#[derive(Queryable)]
pub struct Ingredient {
pub id: i32,
pub alias: String,
}
#[derive(Insertable)]
#[table_name="ingredients"]
pub struct NewIngredient<'a> {
pub alias: &'a str,
}

36
cookbook/src/recipe.rs Normal file
View File

@@ -0,0 +1,36 @@
/// Tag associated with ingredients
#[allow(dead_code)]
pub enum FoodTag {
Viande,
Poisson,
Legume,
}
/// Categories for recipe, to organize them for navigation and planning
#[allow(dead_code)]
pub enum RecipeCategory {
PetitDejeuner,
Entree,
Plat,
Dessert,
}
/// A collection of tags, to be improved
type FoodTags = Vec<FoodTag>;
/// Nutritionnal values per 100g, to be improved
#[derive(Default)]
struct NutritionnalValues;
/// An individual ingredient
#[derive(Default)]
#[allow(dead_code)]
pub struct Ingredient {
/// All known alias of a same ingredient
alias: Vec<String>,
/// Nutrionnal values per 100g
nutrition: NutritionnalValues,
/// Associated tags to constraint planning
tags: FoodTags,
}

21
cookbook/src/schema.rs Normal file
View File

@@ -0,0 +1,21 @@
table! {
ingredients (id) {
id -> Integer,
alias -> Text,
}
}
table! {
recipes (id) {
id -> Integer,
title -> Text,
category -> Integer,
ingredients -> Text,
preparation -> Text,
}
}
allow_tables_to_appear_in_same_query!(
ingredients,
recipes,
);

View File

@@ -1,20 +0,0 @@
//! Storage backend for persistent data
//!
use std::collections::HashMap;
/// An entry in the storage
struct Entry<T>(T);
/// A storage container
pub struct Storage<T> {
content: HashMap<String, Entry<T>>,
}
impl<T> Storage<T> {
pub(super) fn insert(&mut self, item: T) -> Result<(), ()> {
Err(())
}
}

View File

@@ -1,44 +1,2 @@
//! The weekly menu planner //! The weekly menu planner
//! //!
use cookbook::{Meal, fetch_meals};
use planner::solver::{Variables, Domain, solve_all};
fn generate_weekly_menu() -> String {
let assignments: Variables<Meal> = [
("LundiMidi".to_string(), None), ("LundiSoir".to_string(), None),
("MardiMidi".to_string(), None), ("MardiSoir".to_string(), None),
("MercrediMidi".to_string(), None), ("MercrediSoir".to_string(), None),
].iter().cloned().collect();
let meals: Domain<Meal> = Domain::new(fetch_meals());
let validator = |vars: &Variables<Meal>| {
let mut result = true;
for day in ["Lundi", "Mardi", "Mercredi"].into_iter() {
let all_day = vars.keys().filter(|k| k.starts_with(day));
let mut nutri_value = 0;
for key in all_day {
nutri_value += vars.get(key)
.expect("no value here !")
.expect("no meal there !")
.nutritional_value()
}
println!("{} -> {}", day, nutri_value);
if nutri_value != 1200 { result = false; };
}
println!("Validator returns {}", result);
result
};
let solutions = solve_all(assignments, &meals, validator);
format!("{:#?}", solutions)
}
fn main() {
println!("{}", generate_weekly_menu());
}
#[cfg(test)]
mod tests {
}

View File

@@ -32,65 +32,114 @@ impl<V: fmt::Debug> fmt::Debug for Domain<V> {
} }
} }
type Constraint<'a,V> = fn(&Variables<'a,V>) -> bool;
/// Returns all possible Updates for next assignements, prepended with pub struct Problem<'a, V> {
/// a Clear to ensure the variable is unset before when leaving the branch. /// The initial assignements map
fn assign_next<'a,'b, V>(assign: &'b Variables<'a, V>, domain: &'a Domain<V>) variables: Variables<'a, V>,
-> Option<Vec<Assignment<'a, V>>> /// Each variable has its associated domain
where V: fmt::Debug domains: HashMap<String, &'a Domain<V>>,
{ /// Set of constraints to validate
// Panics on empty domain constraints: Vec<Constraint<'a,V>>,
// If domain values are filtered, then the branch is a dead end }
if domain.values.is_empty() { panic!("No values in domain : {:?}", domain); };
// TODO: should be able to inject a choosing strategy impl<'a,V> Problem<'a, V> {
if let Some((key,_)) = assign.iter().find(|(_, val)| val.is_none()) {
let mut updates = vec![Assignment::Clear(key.clone())]; pub fn build() -> ProblemBuilder<'a,V> {
// TODO: should be able to filter domain values (inference, pertinence) ProblemBuilder::new()
for value in domain.values.iter() { }
updates.push(Assignment::Update(key.clone(), value));
/// 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
} }
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
} }
} }
/// Visit all possible solutions, using a stack. pub struct ProblemBuilder<'a, V>(Problem<'a, V>);
pub fn solve_all<'a, V>(
mut assign: Variables<'a, V>, impl<'a, V> ProblemBuilder<'a, V> {
domain: &'a Domain<V>, fn new() -> ProblemBuilder<'a, V> {
is_valid: fn(&Variables<'a,V>) -> bool ProblemBuilder(
) -> Vec<Variables<'a, V>> Problem{
where V: Clone + fmt::Debug variables: Variables::new(),
{ domains: HashMap::new(),
let mut solutions: Vec<Variables<V>> = vec![]; constraints: Vec::new(),
let mut stack: Vec<Assignment<'a, V>> = vec![]; })
stack.append(&mut assign_next(&assign,domain).unwrap()); }
loop {
let node = stack.pop(); pub fn add_variable(mut self,
if node.is_none() { break; }; name: String,
match node.unwrap() { domain: &'a Domain<V>,
Assignment::Update(key, val) => { value: Option<&'a V>,
// Assign the variable and open new branches, if any. ) -> Self {
*assign.get_mut(&key).unwrap() = Some(val); self.0.variables.insert(name.clone(), value);
// TODO: handle case of empty domain.values self.0.domains.insert(name, domain);
if let Some(mut nodes) = assign_next(&assign, domain) { self
stack.append(&mut nodes); }
} else {
// Assignements are completed pub fn add_constraint(mut self, cons: Constraint<'a,V>) -> Self {
if is_valid(&assign) { self.0.constraints.push(cons);
solutions.push(assign.clone()); self
}; }
};
}, pub fn finish(self) -> Problem<'a, V> {
Assignment::Clear(key) => { self.0
// We are closing this branch, unset the variable }
*assign.get_mut(&key).unwrap() = None;
},
};
};
solutions
} }
@@ -99,41 +148,40 @@ mod tests {
#[test] #[test]
fn test_solver_find_pairs() { fn test_solver_find_pairs() {
use super::*; use super::*;
// Find all pairs of two differents
let assign: Variables<i32> = [
("Left".to_string(), None),
("Right".to_string(), None),
].iter().cloned().collect();
let domain = Domain::new(vec![1,2,3]); let domain = Domain::new(vec![1,2,3]);
let constraint = |assign: &Variables<i32>| { let mut problem: Problem<_> = Problem::build()
assign.get("Left").unwrap() == assign.get("Right").unwrap() .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![ let solutions: Vec<Variables<i32>> = vec![
[("Left".to_string(), Some(&3)), ("Right".to_string(), Some(&3)),].iter().cloned().collect(), [("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(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
[("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(), [("Left".to_string(), Some(&1)), ("Right".to_string(), Some(&1)),].iter().cloned().collect(),
]; ];
assert_eq!(solve_all(assign, &domain, constraint), solutions); assert_eq!(problem.solve_all(), solutions);
} }
#[test] #[test]
fn test_solver_find_pairs_with_initial() { fn test_solver_find_pairs_with_initial() {
use super::*; use super::*;
// Find all pairs of two differents
let assign: Variables<i32> = [
("Left".to_string(), None),
("Right".to_string(), Some(&2)),
].iter().cloned().collect();
let domain = Domain::new(vec![1,2,3]); let domain = Domain::new(vec![1,2,3]);
let constraint = |assign: &Variables<i32>| { let mut problem: Problem<_> = Problem::build()
assign.get("Left").unwrap() == assign.get("Right").unwrap() .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![ let solutions: Vec<Variables<i32>> = vec![
[("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(), [("Left".to_string(), Some(&2)), ("Right".to_string(), Some(&2)),].iter().cloned().collect(),
]; ];
assert_eq!(solve_all(assign, &domain, constraint), solutions); assert_eq!(problem.solve_all(), solutions);
} }
} }

30
web/index.html Normal file
View File

@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>Cook Assistant</h1>
<p>Fetch value from wasm : {{ value }}</p>
<strong>{{ message }}</strong>
</div>
</body>
<script type="text/javascript">
var getWasmValue = function() {
return 42
};
var app = new Vue({
el: '#app',
data: {
message: 'Hello ! We are trying out here...',
},
computed: {
value: getWasmValue,
}
});
</script>
</html>