summaryrefslogtreecommitdiff
path: root/crates/elfmind/src/knowledge.rs
blob: a6103283639e7f57c4abaef093d24ef373cbe162 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
pub mod relation;
pub use relation::*;

use crate::time::*;
use crate::item::*;
use crate::character::*;

use std::collections::{HashMap, HashSet};
use itertools::Itertools;

use enum_map::EnumMap;
use strum::IntoDiscriminant;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Var { index: u64 }

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Value {
    Var(Var),
    Item(Item),
    Character(Character),
    Time(Time),
}
impl From<Var> for Value { fn from(x: Var) -> Self {Value::Var(x)} }
impl From<Item> for Value { fn from(x: Item) -> Self {Value::Item(x)} }
impl From<Character> for Value { fn from(x: Character) -> Self {Value::Character(x)} }
impl From<Time> for Value { fn from(x: Time) -> Self {Value::Time(x)} }
impl TryFrom<Value> for Var {
    type Error = ();
    fn try_from(v: Value) -> Result<Self, Self::Error> {
        if let Value::Var(x) = v { Ok(x) } else { Err(()) }
    }
}
impl TryFrom<Value> for Item {
    type Error = ();
    fn try_from(v: Value) -> Result<Self, Self::Error> {
        if let Value::Item(x) = v { Ok(x) } else { Err(()) }
    }
}
impl TryFrom<Value> for Character {
    type Error = ();
    fn try_from(v: Value) -> Result<Self, Self::Error> {
        if let Value::Character(x) = v { Ok(x) } else { Err(()) }
    }
}
impl TryFrom<Value> for Time {
    type Error = ();
    fn try_from(v: Value) -> Result<Self, Self::Error> {
        if let Value::Time(x) = v { Ok(x) } else { Err(()) }
    }
}

#[derive(Debug, Default)]
pub struct Unification {
    assignment: HashMap<Var, Value>,
}
impl Unification {
    pub fn lookup(&self, v: &Var) -> Option<Value> {
        self.assignment.get(v).cloned()
    }
    pub fn add(&mut self, v: Var, x: impl Into<Value>) -> bool {
        let y = x.into();
        if let Some(old) = self.assignment.get(&v) {
            if let Value::Var(v2) = y {
                self.add(v2, *old)
            } else if let Value::Var(v2) = old {
                self.add(*v2, y)
            } else {
                *old == y
            }
        } else {
            self.assignment.insert(v, y);
            true
        }
    }
    pub fn unify_hole<A, B>(&mut self, h1: &Hole<A>, h2: &Hole<B>) -> bool
    where Value: From<A>, Value: From<B>, A: Copy, B: Copy {
        match (h1, h2) {
            (Hole::Var(v1), Hole::Var(v2)) =>
                self.add(*v1, *v2) && self.add(*v2, *v1),
            (Hole::Val(x1), Hole::Val(x2)) => Value::from(*x1) == Value::from(*x2),
            (Hole::Var(v1), Hole::Val(x2)) => self.add(*v1, *x2),
            (Hole::Val(x1), Hole::Var(v2)) => self.add(*v2, *x1),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Hole<T> {
    Var(Var),
    Val(T),
}
impl<T: Clone + TryFrom<Value>> Hole<T> {
    pub fn substitute(&self, u: &Unification) -> Self {
        match self {
            x@Self::Var(v) => if let Some(y) = u.lookup(v) && let Ok(z) = T::try_from(y) {
                Hole::Val(z)
            } else {
                x.clone()
            }
            x => x.clone(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Rule {
    pub head: Relation,
    pub body: Vec<Relation>,
}
impl Rule {
    pub fn unify_body(&self, facts: &[&Relation]) -> Option<Unification> {
        if self.body.len() != facts.len() { return None; }
        let mut u = Unification::default();
        for (r, f) in self.body.iter().zip(facts) {
            u = r.unify(f, u)?;
        }
        Some(u)
    }
}

#[derive(Debug, Default, Clone)]
pub struct Facts {
    facts: EnumMap<RelationDiscriminants, HashSet<Relation>>,
}
impl Facts {
    pub fn add(&mut self, f: Relation) -> bool {
        self.facts[f.discriminant()].insert(f)
    }
    pub fn with_sort(&self, s: RelationDiscriminants) -> &HashSet<Relation> {
        &self.facts[s]
    }
    pub fn with_sort_mut(&mut self, s: RelationDiscriminants) -> &mut HashSet<Relation> {
        &mut self.facts[s]
    }
    pub fn contains(&self, f: &Relation) -> bool {
        self.facts[f.discriminant()].contains(f)
    }
    pub fn absorb(&mut self, other: &mut Facts) {
        for (rd, fs) in self.facts.iter_mut() {
            fs.extend(other.with_sort_mut(rd).drain());
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct Database {
    facts: Facts,
    rules: Vec<Rule>,
}
impl Database {
    pub fn is_known(&self, r: &Relation) -> bool { self.facts.contains(r) }
    pub fn query<'a>(&'a mut self) -> Query<'a> {
        Query {
            db: self,
            facts: Facts::default(),
            rules: Vec::new(),
        }
    }
}

#[must_use]
#[derive(Debug)]
pub struct Query<'a> {
    db: &'a mut Database,
    facts: Facts,
    rules: Vec<Rule>,
}
#[derive(Debug, Clone, Copy)]
enum QueryFactsToConsider<'a> {
    LastIteration(&'a Facts),
    Query,
    DB,
}
impl<'a> Query<'a> {
    fn apply_rule(&self, r: &Rule, new_facts: &mut Facts, required_facts: QueryFactsToConsider) -> bool {
        // we don't need to consider every possible fact against each body term (naive evaluation)
        // instead, we can limit ourselves to the subset where at least one of the facts is new (semi-naive)
        // let found: Vec<Unification> = r.body.iter()
        //     .map(|r| {
        //         let d = r.discriminant();
        //         new_facts.with_sort(d).iter()
        //             .chain(self.facts.with_sort(d).iter())
        //             .chain(self.db.facts.with_sort(d).iter())
        //     })
        //     .multi_cartesian_product()
        //     .filter_map(|fs| r.unify_body(&fs))
        //     .collect();
        let mut found = Vec::new();
        // identify which slots of this rule body possibly have new facts to consider
        let changed_slots = r.body.iter()
            .enumerate()
            .filter_map(|(i, r)| {
                match required_facts {
                    // if we are only considering facts from the provided set
                    QueryFactsToConsider::LastIteration(rf) =>
                        if rf.with_sort(r.discriminant()).is_empty() { None } else { Some(i) },
                    // if we are only considering facts added by this query
                    QueryFactsToConsider::Query =>
                        if self.facts.with_sort(r.discriminant()).is_empty() { None } else { Some(i) },
                    // if we are considering all facts, simply consider every index
                    QueryFactsToConsider::DB => Some(i),
                }
            });
        let empty = HashSet::new();
        for cs in changed_slots {
            let attempts = r.body.iter()
                .enumerate()
                .map(|(i, r)| {
                    let d = r.discriminant();
                    match required_facts {
                        // if this is an index that changed, limit it to only the provided set of facts
                        QueryFactsToConsider::LastIteration(rf) if i == cs =>
                             rf.with_sort(d).iter().chain(empty.iter()),
                        // (or the set of facts from this query)
                        QueryFactsToConsider::Query if i == cs =>
                             self.facts.with_sort(d).iter().chain(empty.iter()),
                        // otherwise, consider all facts - a new fact might be used alongside an unchanged fact!
                        _ =>
                            self.facts.with_sort(d).iter().chain(self.db.facts.with_sort(d).iter()),
                    }
                })
                .multi_cartesian_product();
            for fs in attempts {
                if let Some(u) = r.unify_body(&fs) {
                    found.push(u);
                }
            }
        }
        let mut changed = false;
        for u in found {
            let new = r.head.substitute(&u);
            if new.is_concrete() && !self.facts.contains(&new) && !self.db.facts.contains(&new) {
                if new_facts.add(new) { changed = true; }
            }
        }
        changed
    }
    fn apply_new_once(&mut self, new_facts: &mut Facts, required_facts: QueryFactsToConsider) -> bool {
        let mut changed = false;
        match &required_facts {
            QueryFactsToConsider::DB => {
                // if we are considering only DB facts, we only need to consider new rules
                for r in self.rules.iter() {
                    if self.apply_rule(r, new_facts, required_facts) { changed = true }
                }
            },
            _ => { // otherwise, we should consider all rules
                for r in self.rules.iter().chain(self.db.rules.iter()) {
                    if self.apply_rule(r, new_facts, required_facts) { changed = true }
                }
            }
        }
        changed
    }
    pub fn fact(mut self, r: Relation) -> Self {
        if !self.db.is_known(&r) {
            self.facts.add(r);
        }
        self
    }
    pub fn rule(mut self, r: Rule) -> Self {
        self.rules.push(r);
        self
    }
    fn run(&mut self) {
        let mut new_facts = Facts::default();
        // compare the new rules with the old facts
        self.apply_new_once(&mut new_facts, QueryFactsToConsider::DB);
        // compare the new+old rules with the new facts
        self.apply_new_once(&mut new_facts, QueryFactsToConsider::Query);
        let mut prev_facts = new_facts.clone();
        self.facts.absorb(&mut new_facts);
        while self.apply_new_once(&mut new_facts, QueryFactsToConsider::LastIteration(&prev_facts)) {
            prev_facts = new_facts.clone();
            self.facts.absorb(&mut new_facts);
        }
    }
    pub fn ask(mut self) -> Facts {
        self.run();
        self.facts
    }
    pub fn learn(mut self) {
        self.run();
        self.db.facts.absorb(&mut self.facts);
        self.db.rules.extend_from_slice(&mut self.rules);
    }
}

#[derive(Debug, Default)]
pub struct Context {
    next_index: u64,
    var_names: HashMap<Var, String>,
}
impl Context {
    pub fn fresh(&mut self) -> Var {
        let ret = Var { index: self.next_index };
        self.next_index += 1;
        ret
    }
    pub fn var(&mut self, nm: &str) -> Var {
        let ret = self.fresh();
        self.var_names.insert(ret, nm.to_owned());
        ret
    }
}