elinvar-engine 0.1.0

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
Documentation
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! The boolean circuit (LOGIC.md sections 12.3 and 12.4).
//!
//! A value is a node and a sign. Node 0 is the constant true, nodes 1 to P
//! the primary variables, and later nodes are `and` gates in the order they
//! are first built. Building a gate simplifies and shares: asking twice for
//! an `and` of the same inputs gives the same gate.

use crate::sat::{Lit, Solver, Var};
use std::collections::BTreeMap;

/// A boolean value of the circuit.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Bool(u32);

impl Bool {
    /// The constant true.
    pub const TRUE: Bool = Bool(0);
    /// The constant false.
    pub const FALSE: Bool = Bool(1);

    fn node(self) -> u32 {
        self.0 / 2
    }

    fn negated(self) -> bool {
        self.0 & 1 == 1
    }

    /// Whether this is a constant.
    pub fn is_constant(self) -> bool {
        self.node() == 0
    }
}

impl std::ops::Not for Bool {
    type Output = Bool;
    fn not(self) -> Bool {
        Bool(self.0 ^ 1)
    }
}

/// A gate of the circuit.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Gate {
    And(Vec<Bool>),
    Xor(Bool, Bool),
    Maj(Bool, Bool, Bool),
}

/// The circuit and the clauses already made from it.
#[derive(Default)]
pub struct Circuit {
    primary: u32,
    /// Each gate; gate `k` is node `primary + 1 + k`.
    gates: Vec<Gate>,
    /// Lookup only, never iterated (AGENTS.md law 16).
    shared: BTreeMap<Gate, u32>,
    /// Which of each gate's clauses are in the solver: bit 1 those that
    /// hold where it occurs positively (the gate implies its inputs'
    /// condition), bit 2 those for where it occurs negatively (the inputs'
    /// condition implies the gate).
    encoded: Vec<u8>,
    /// Solver variables made so far: one per node from 1.
    solver_vars: u32,
}

impl Circuit {
    /// A circuit with no variables.
    pub fn new() -> Circuit {
        Circuit::default()
    }

    /// A new primary variable. All primary variables come before any gate.
    pub fn new_var(&mut self) -> Bool {
        assert!(
            self.gates.is_empty(),
            "primary variables are numbered before gates (LOGIC.md 12.3)"
        );
        self.primary += 1;
        Bool(self.primary * 2)
    }

    /// The number of gates.
    pub fn gate_count(&self) -> usize {
        self.gates.len()
    }

    /// `and` of the inputs, simplified (LOGIC.md 12.3).
    pub fn and(&mut self, inputs: impl IntoIterator<Item = Bool>) -> Bool {
        let mut xs: Vec<Bool> = Vec::new();
        for x in inputs {
            if x == Bool::FALSE {
                return Bool::FALSE;
            }
            if x != Bool::TRUE {
                xs.push(x);
            }
        }
        xs.sort_unstable();
        xs.dedup();
        // A value and its negation sort next to each other.
        if xs.windows(2).any(|w| w[0].node() == w[1].node()) {
            return Bool::FALSE;
        }
        match xs.len() {
            0 => Bool::TRUE,
            1 => xs[0],
            _ => self.intern(Gate::And(xs)),
        }
    }

    fn intern(&mut self, gate: Gate) -> Bool {
        if let Some(&g) = self.shared.get(&gate) {
            return Bool(g * 2);
        }
        let node = self.primary + 1 + self.gates.len() as u32;
        self.gates.push(gate.clone());
        self.encoded.push(0);
        self.shared.insert(gate, node);
        Bool(node * 2)
    }

    /// `a xor b`, simplified and shared as one gate (LOGIC.md 16.4).
    pub fn xor(&mut self, a: Bool, b: Bool) -> Bool {
        if a == Bool::FALSE {
            return b;
        }
        if b == Bool::FALSE {
            return a;
        }
        if a == Bool::TRUE {
            return !b;
        }
        if b == Bool::TRUE {
            return !a;
        }
        if a == b {
            return Bool::FALSE;
        }
        if a == !b {
            return Bool::TRUE;
        }
        // xor(!x, y) == !xor(x, y): store both inputs positive and sorted.
        let flip = a.negated() ^ b.negated();
        let (mut x, mut y) = (Bool(a.node() * 2), Bool(b.node() * 2));
        if x > y {
            std::mem::swap(&mut x, &mut y);
        }
        let g = self.intern(Gate::Xor(x, y));
        if flip { !g } else { g }
    }

    /// Majority of three values: true when at least two are true (LOGIC.md 16.4).
    pub fn maj(&mut self, a: Bool, b: Bool, c: Bool) -> Bool {
        let mut xs = [a, b, c];
        xs.sort_unstable();
        let [x, y, z] = xs;
        if x == y {
            return x;
        }
        if y == z {
            return y;
        }
        if x == !y {
            return z;
        }
        if y == !z {
            return x;
        }
        if x == Bool::TRUE {
            return self.or([y, z]);
        }
        if x == Bool::FALSE {
            return self.and([y, z]);
        }
        // maj(!x, !y, !z) == !maj(x, y, z): canonicalize the first input positive.
        if x.negated() {
            let mut ys = [!x, !y, !z];
            ys.sort_unstable();
            !self.intern(Gate::Maj(ys[0], ys[1], ys[2]))
        } else {
            self.intern(Gate::Maj(x, y, z))
        }
    }

    /// `or` of the inputs: the `not` of the `and` of their `not`s.
    pub fn or(&mut self, inputs: impl IntoIterator<Item = Bool>) -> Bool {
        !self.and(inputs.into_iter().map(|x| !x))
    }

    /// `a implies b`
    pub fn implies(&mut self, a: Bool, b: Bool) -> Bool {
        self.or([!a, b])
    }

    /// `a iff b`
    pub fn iff(&mut self, a: Bool, b: Bool) -> Bool {
        let both = self.and([a, b]);
        let neither = self.and([!a, !b]);
        self.or([both, neither])
    }

    /// `if c then a else b`
    pub fn ite(&mut self, c: Bool, a: Bool, b: Bool) -> Bool {
        if c == Bool::TRUE || a == b {
            return a;
        }
        if c == Bool::FALSE {
            return b;
        }
        let then = self.and([c, a]);
        let otherwise = self.and([!c, b]);
        self.or([then, otherwise])
    }

    /// The solver literal of a non-constant value.
    pub fn lit(&self, b: Bool) -> Lit {
        debug_assert!(!b.is_constant());
        let var = Var(b.node() - 1);
        if b.negated() {
            Lit::negative(var)
        } else {
            Lit::positive(var)
        }
    }

    /// Makes sure the solver has a variable for every node so far, and the
    /// clauses `root` needs that it lacks, in gate order (LOGIC.md 12.4).
    /// A gate gets the clauses of each polarity it occurs in under `root`,
    /// as Kodkod's Bool2CNFTranslator does (Plaisted and Greenbaum): where
    /// it occurs positively, that it implies each input; negatively, that
    /// its inputs together imply it. Does not assert `root`.
    pub fn encode(&mut self, solver: &mut dyn Solver, root: Bool) {
        const POSITIVE: u8 = 1;
        const NEGATIVE: u8 = 2;
        let nodes = self.primary + self.gates.len() as u32;
        while self.solver_vars < nodes {
            solver.new_var();
            self.solver_vars += 1;
        }
        let gate =
            |b: Bool| (b.node() > self.primary).then(|| (b.node() - self.primary - 1) as usize);
        let flip = |p: u8, b: Bool| {
            if b.negated() {
                (p & 1) << 1 | (p >> 1)
            } else {
                p
            }
        };
        // A gate's inputs are numbered below it, so one pass from the top
        // gives every gate its polarities.
        let mut need = vec![0u8; self.gates.len()];
        let Some(top) = gate(root) else { return };
        need[top] = flip(POSITIVE, root);
        for k in (0..=top).rev() {
            if need[k] == 0 {
                continue;
            }
            match &self.gates[k] {
                Gate::And(xs) => {
                    for &x in xs {
                        if let Some(j) = gate(x) {
                            need[j] |= flip(need[k], x);
                        }
                    }
                }
                Gate::Xor(a, b) => {
                    // Xor uses both inputs in both polarities regardless of output polarity.
                    for &x in &[*a, *b] {
                        if let Some(j) = gate(x) {
                            need[j] |= POSITIVE | NEGATIVE;
                        }
                    }
                }
                Gate::Maj(a, b, c) => {
                    for &x in &[*a, *b, *c] {
                        if let Some(j) = gate(x) {
                            need[j] |= flip(need[k], x);
                        }
                    }
                }
            }
        }
        for (k, &wanted) in need.iter().enumerate().take(top + 1) {
            let missing = wanted & !self.encoded[k];
            if missing == 0 {
                continue;
            }
            self.encoded[k] |= missing;
            let g_lit = self.lit(Bool((self.primary + 1 + k as u32) * 2));
            match &self.gates[k] {
                Gate::And(xs) => {
                    if missing & POSITIVE != 0 {
                        for &x in xs {
                            solver.add_clause(&[!g_lit, self.lit(x)]);
                        }
                    }
                    if missing & NEGATIVE != 0 {
                        let mut long = vec![g_lit];
                        long.extend(xs.iter().map(|&x| !self.lit(x)));
                        solver.add_clause(&long);
                    }
                }
                Gate::Xor(a, b) => {
                    let (la, lb) = (self.lit(*a), self.lit(*b));
                    if missing & POSITIVE != 0 {
                        solver.add_clause(&[!g_lit, la, lb]);
                        solver.add_clause(&[!g_lit, !la, !lb]);
                    }
                    if missing & NEGATIVE != 0 {
                        solver.add_clause(&[g_lit, !la, lb]);
                        solver.add_clause(&[g_lit, la, !lb]);
                    }
                }
                Gate::Maj(a, b, c) => {
                    let (la, lb, lc) = (self.lit(*a), self.lit(*b), self.lit(*c));
                    if missing & POSITIVE != 0 {
                        solver.add_clause(&[!g_lit, la, lb]);
                        solver.add_clause(&[!g_lit, la, lc]);
                        solver.add_clause(&[!g_lit, lb, lc]);
                    }
                    if missing & NEGATIVE != 0 {
                        solver.add_clause(&[g_lit, !la, !lb]);
                        solver.add_clause(&[g_lit, !la, !lc]);
                        solver.add_clause(&[g_lit, !lb, !lc]);
                    }
                }
            }
        }
    }

    /// Encodes `root` and asserts it. Returns false if it is the constant
    /// false.
    pub fn assert(&mut self, solver: &mut dyn Solver, root: Bool) -> bool {
        if root == Bool::FALSE {
            return false;
        }
        self.encode(solver, root);
        if root != Bool::TRUE {
            let l = self.lit(root);
            solver.add_clause(&[l]);
        }
        true
    }

    /// Encodes `b` and asserts `guard => b`, for assumption-based core
    /// extraction.
    pub fn assert_if(&mut self, solver: &mut dyn Solver, guard: Lit, b: Bool) {
        if b == Bool::TRUE {
            return;
        }
        if b == Bool::FALSE {
            solver.add_clause(&[!guard]);
            return;
        }
        self.encode(solver, b);
        let l = self.lit(b);
        solver.add_clause(&[!guard, l]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn simplifications() {
        let mut c = Circuit::new();
        let (a, b, d) = (c.new_var(), c.new_var(), c.new_var());
        assert_eq!(c.and([a, Bool::TRUE]), a);
        assert_eq!(c.and([a, Bool::FALSE]), Bool::FALSE);
        assert_eq!(c.and([a, !a]), Bool::FALSE);
        assert_eq!(c.and([]), Bool::TRUE);
        assert_eq!(c.and([a, a]), a);
        let g = c.and([a, b]);
        assert_eq!(c.and([b, a]), g);
        assert_eq!(c.gate_count(), 1);
        assert_eq!(c.or([a, !a]), Bool::TRUE);
        assert_eq!(c.xor(a, Bool::FALSE), a);
        assert_eq!(c.xor(a, Bool::TRUE), !a);
        assert_eq!(c.xor(a, a), Bool::FALSE);
        assert_eq!(c.xor(a, !a), Bool::TRUE);
        let x = c.xor(a, b);
        assert_eq!(c.xor(b, a), x);
        assert_eq!(c.xor(!a, b), !x);
        assert_eq!(c.xor(!a, !b), x);
        assert_eq!(c.maj(a, a, b), a);
        assert_eq!(c.maj(a, !a, b), b);
        assert_eq!(c.maj(Bool::FALSE, a, b), g);
        assert_eq!(c.maj(Bool::TRUE, a, b), c.or([a, b]));
        let m = c.maj(a, b, d);
        assert_eq!(c.maj(d, a, b), m);
        assert_eq!(c.maj(!a, !b, !d), !m);
    }

    /// Records the clauses it is given.
    #[derive(Default)]
    struct Clauses {
        vars: u32,
        clauses: Vec<Vec<Lit>>,
    }

    impl Solver for Clauses {
        fn new_var(&mut self) -> Var {
            self.vars += 1;
            Var(self.vars - 1)
        }
        fn add_clause(&mut self, clause: &[Lit]) {
            self.clauses.push(clause.to_vec());
        }
        fn solve(&mut self, _: &[Lit], _: &crate::sat::Budget) -> crate::sat::Solved {
            unreachable!("only clauses are recorded")
        }
        fn value(&self, _: Var) -> bool {
            false
        }
    }

    /// LOGIC.md 12.4, by hand: root = and(g, not h), g = and(a, b),
    /// h = and(a, c). The root and g occur positively, h negatively, so the
    /// root gives two clauses, g two (not g or a, not g or b), and h one
    /// (h or not a or not c); with the root's unit clause, six.
    #[test]
    fn clauses_follow_polarity() {
        let mut c = Circuit::new();
        let (a, b, x) = (c.new_var(), c.new_var(), c.new_var());
        let g = c.and([a, b]);
        let h = c.and([a, x]);
        let root = c.and([g, !h]);
        let mut s = Clauses::default();
        assert!(c.assert(&mut s, root));
        let (la, lb, lx, lg, lh, lr) = (
            c.lit(a),
            c.lit(b),
            c.lit(x),
            c.lit(g),
            c.lit(h),
            c.lit(root),
        );
        assert_eq!(
            s.clauses,
            vec![
                vec![!lg, la],
                vec![!lg, lb],
                vec![lh, !la, !lx],
                vec![!lr, lg],
                vec![!lr, !lh],
                vec![lr],
            ]
        );
    }
}