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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! A second brute-force counter, bit-sliced (DESIGN.md section 10, R18).
//!
//! It counts the instances of LOGIC.md section 8 as `elinvar_logic::count`
//! does, but evaluates a block of 4,096 instances at once: every value is a
//! mask with one bit per instance of the block, and each operator is a few
//! bitwise operations on masks, done with SIMD (`macerator`). The plain
//! evaluator stays the definition and the referee (AGENTS.md law 12); this
//! one is a faster check of the solver, and tests require the two agree.
//!
//! It handles static first-order formulas. A formula with a temporal
//! operator, a prime, or a declaration over sets falls back to the plain
//! counter.

use elinvar_logic::{
    Against, BinaryOp, Bounds, Decl, Error, Expr, ExprKind, Formula, FormulaKind, Multiplicity,
    Quantifier, Relation, UnaryOp, Variable, check_formula, count as plain_count,
};
use macerator::{Scalar, Simd, Vector, with_simd};
use std::collections::BTreeMap;

/// Words in a mask: 64 of them, 4,096 instances per block.
const WORDS: usize = 64;
const LANES: u64 = (WORDS * 64) as u64;

#[derive(Clone, PartialEq, Eq)]
struct Mask(Vec<u64>);

#[with_simd]
fn and_words<S: Simd>(dst: &mut [u64], a: &[u64], b: &[u64]) {
    let lanes = u64::lanes::<S>();
    let whole = dst.len() / lanes * lanes;
    for i in (0..whole).step_by(lanes) {
        (Vector::<S, u64>::load(&a[i..]) & Vector::<S, u64>::load(&b[i..])).store(&mut dst[i..]);
    }
    for i in whole..dst.len() {
        dst[i] = a[i] & b[i];
    }
}

#[with_simd]
fn or_words<S: Simd>(dst: &mut [u64], a: &[u64], b: &[u64]) {
    let lanes = u64::lanes::<S>();
    let whole = dst.len() / lanes * lanes;
    for i in (0..whole).step_by(lanes) {
        (Vector::<S, u64>::load(&a[i..]) | Vector::<S, u64>::load(&b[i..])).store(&mut dst[i..]);
    }
    for i in whole..dst.len() {
        dst[i] = a[i] | b[i];
    }
}

#[with_simd]
fn andnot_words<S: Simd>(dst: &mut [u64], a: &[u64], b: &[u64]) {
    let lanes = u64::lanes::<S>();
    let whole = dst.len() / lanes * lanes;
    for i in (0..whole).step_by(lanes) {
        (Vector::<S, u64>::load(&a[i..]) & !Vector::<S, u64>::load(&b[i..])).store(&mut dst[i..]);
    }
    for i in whole..dst.len() {
        dst[i] = a[i] & !b[i];
    }
}

impl Mask {
    fn zeros() -> Mask {
        Mask(vec![0; WORDS])
    }

    fn ones() -> Mask {
        Mask(vec![u64::MAX; WORDS])
    }

    fn and(&self, o: &Mask) -> Mask {
        let mut d = Mask::zeros();
        and_words(&mut d.0, &self.0, &o.0);
        d
    }

    fn or(&self, o: &Mask) -> Mask {
        let mut d = Mask::zeros();
        or_words(&mut d.0, &self.0, &o.0);
        d
    }

    /// `self and not o`
    fn andnot(&self, o: &Mask) -> Mask {
        let mut d = Mask::zeros();
        andnot_words(&mut d.0, &self.0, &o.0);
        d
    }

    fn not(&self) -> Mask {
        Mask::ones().andnot(self)
    }

    fn is_zero(&self) -> bool {
        self.0.iter().all(|&w| w == 0)
    }

    fn count(&self) -> u64 {
        self.0.iter().map(|w| u64::from(w.count_ones())).sum()
    }
}

/// A table: tuple index to the mask of instances that hold it.
type Table = BTreeMap<u64, Mask>;

fn get(t: &Table, i: u64) -> Mask {
    t.get(&i).cloned().unwrap_or_else(Mask::zeros)
}

fn put(t: &mut Table, i: u64, m: Mask) {
    if !m.is_zero() {
        t.insert(i, m);
    }
}

/// Whether the bit-sliced evaluator handles the formula: static and first
/// order.
fn supported(f: &Formula) -> bool {
    fn expr(e: &Expr) -> bool {
        match e.kind() {
            ExprKind::Binary(_, a, b) => expr(a) && expr(b),
            ExprKind::Unary(_, a) => expr(a),
            ExprKind::Comprehension(decls, body) => decls_ok(decls) && formula(body),
            ExprKind::IfThenElse(c, a, b) => formula(c) && expr(a) && expr(b),
            ExprKind::Prime(_) | ExprKind::IntToSet(_) => false,
            ExprKind::Relation(r) => !r.is_changing(),
            ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => true,
        }
    }
    fn decls_ok(decls: &[Decl]) -> bool {
        decls.iter().all(|d| d.is_first_order() && expr(&d.expr))
    }
    fn formula(f: &Formula) -> bool {
        match f.kind() {
            FormulaKind::Constant(_) => true,
            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => expr(a) && expr(b),
            FormulaKind::Multiplicity(_, a) => expr(a),
            FormulaKind::Not(g) => formula(g),
            FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(formula),
            FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => formula(a) && formula(b),
            FormulaKind::Quantified(_, decls, body) => decls_ok(decls) && formula(body),
            FormulaKind::Temporal(..)
            | FormulaKind::TemporalBinary(..)
            | FormulaKind::IntCompare(..) => false,
        }
    }
    formula(f)
}

struct Block<'a> {
    n: u64,
    relations: &'a [(Relation, Table)],
    env: Vec<(Variable, u64)>,
}

impl Block<'_> {
    fn pow(&self, k: usize) -> u64 {
        self.n.pow(k as u32)
    }

    fn arity(e: &Expr) -> usize {
        e.arity().expect("checked before counting")
    }

    fn expr(&mut self, e: &Expr) -> Table {
        let n = self.n;
        let mut out = Table::new();
        match e.kind() {
            ExprKind::Relation(r) => {
                return self
                    .relations
                    .iter()
                    .find(|(s, _)| s == r)
                    .map(|(_, t)| t.clone())
                    .expect("checked before counting");
            }
            ExprKind::Variable(v) => {
                let a = self
                    .env
                    .iter()
                    .rev()
                    .find(|(w, _)| w == v)
                    .map(|(_, a)| *a)
                    .expect("checked before counting");
                out.insert(a, Mask::ones());
            }
            ExprKind::None => {}
            ExprKind::Univ => {
                for a in 0..n {
                    out.insert(a, Mask::ones());
                }
            }
            ExprKind::Iden => {
                for a in 0..n {
                    out.insert(a * n + a, Mask::ones());
                }
            }
            ExprKind::Binary(op, a, b) => {
                let (ta, tb) = (self.expr(a), self.expr(b));
                return self.binary(*op, &ta, &tb, Self::arity(a), Self::arity(b));
            }
            ExprKind::Unary(op, a) => {
                let ta = self.expr(a);
                return match op {
                    UnaryOp::Transpose => ta
                        .into_iter()
                        .map(|(i, m)| ((i % n) * n + i / n, m))
                        .collect(),
                    UnaryOp::Closure => self.closure(&ta),
                    UnaryOp::ReflexiveClosure => {
                        let mut t = self.closure(&ta);
                        for x in 0..n {
                            t.insert(x * n + x, Mask::ones());
                        }
                        t
                    }
                };
            }
            ExprKind::Comprehension(decls, body) => {
                let mut values: Table = Table::new();
                let mut chosen = Vec::new();
                self.bindings(decls, &mut chosen, Mask::ones(), &mut |b, atoms, guard| {
                    let v = guard.and(&b.formula(body));
                    let idx = atoms.iter().fold(0u64, |acc, &x| acc * n + x);
                    let cur = get(&values, idx);
                    put(&mut values, idx, cur.or(&v));
                });
                return values;
            }
            ExprKind::IfThenElse(c, a, b) => {
                let cv = self.formula(c);
                let (ta, tb) = (self.expr(a), self.expr(b));
                let keys: std::collections::BTreeSet<u64> =
                    ta.keys().chain(tb.keys()).copied().collect();
                for i in keys {
                    let v = get(&ta, i).and(&cv).or(&get(&tb, i).andnot(&cv));
                    put(&mut out, i, v);
                }
            }
            ExprKind::Prime(_) | ExprKind::IntToSet(_) => {
                unreachable!("not supported, so not counted here")
            }
        }
        out
    }

    fn join(&self, a: &Table, b: &Table, bk: usize) -> Table {
        let n = self.n;
        let tail = self.pow(bk - 1);
        let mut out = Table::new();
        for (&x, ma) in a {
            for (&y, mb) in b {
                if y / tail == x % n {
                    let i = (x / n) * tail + y % tail;
                    let cur = get(&out, i);
                    put(&mut out, i, cur.or(&ma.and(mb)));
                }
            }
        }
        out
    }

    fn binary(&self, op: BinaryOp, a: &Table, b: &Table, ak: usize, bk: usize) -> Table {
        let n = self.n;
        let mut out = Table::new();
        match op {
            BinaryOp::Union => {
                let keys: std::collections::BTreeSet<u64> =
                    a.keys().chain(b.keys()).copied().collect();
                for i in keys {
                    put(&mut out, i, get(a, i).or(&get(b, i)));
                }
            }
            BinaryOp::Intersection => {
                for (&i, m) in a {
                    put(&mut out, i, m.and(&get(b, i)));
                }
            }
            BinaryOp::Difference => {
                for (&i, m) in a {
                    put(&mut out, i, m.andnot(&get(b, i)));
                }
            }
            BinaryOp::Join => return self.join(a, b, bk),
            BinaryOp::Product => {
                let shift = self.pow(bk);
                for (&x, ma) in a {
                    for (&y, mb) in b {
                        put(&mut out, x * shift + y, ma.and(mb));
                    }
                }
            }
            BinaryOp::Override => {
                // LOGIC.md 3: a tuple of A stays where B has none with its
                // first atom.
                let row = self.pow(ak - 1);
                let mut rows: BTreeMap<u64, Mask> = BTreeMap::new();
                for (&y, m) in b {
                    let cur = rows.get(&(y / row)).cloned().unwrap_or_else(Mask::zeros);
                    rows.insert(y / row, cur.or(m));
                }
                let keys: std::collections::BTreeSet<u64> =
                    a.keys().chain(b.keys()).copied().collect();
                for i in keys {
                    let blocked = rows.get(&(i / row)).cloned().unwrap_or_else(Mask::zeros);
                    put(&mut out, i, get(a, i).andnot(&blocked).or(&get(b, i)));
                }
            }
            BinaryOp::DomainRestriction => {
                let row = self.pow(bk - 1);
                for (&y, m) in b {
                    put(&mut out, y, m.and(&get(a, y / row)));
                }
            }
            BinaryOp::RangeRestriction => {
                for (&x, m) in a {
                    put(&mut out, x, m.and(&get(b, x % n)));
                }
            }
        }
        out
    }

    /// LOGIC.md 7: `T = A`, then `T + T . A` until it stops growing in
    /// every instance.
    fn closure(&self, a: &Table) -> Table {
        let mut t = a.clone();
        loop {
            let step = self.join(&t, a, 2);
            let next = self.binary(BinaryOp::Union, &t, &step, 2, 2);
            if next == t {
                return t;
            }
            t = next;
        }
    }

    fn bindings(
        &mut self,
        decls: &[Decl],
        chosen: &mut Vec<u64>,
        guard: Mask,
        visit: &mut dyn FnMut(&mut Self, &[u64], &Mask),
    ) {
        let k = chosen.len();
        if k == decls.len() {
            visit(self, chosen, &guard);
            return;
        }
        let range = self.expr(&decls[k].expr);
        for (atom, m) in range {
            let g = guard.and(&m);
            if g.is_zero() {
                continue;
            }
            self.env.push((decls[k].var.clone(), atom));
            chosen.push(atom);
            self.bindings(decls, chosen, g, visit);
            chosen.pop();
            self.env.pop();
        }
    }

    /// Per instance: some, no, one, or lone of the values.
    fn count(m: Multiplicity, values: &[Mask]) -> Mask {
        let mut seen = Mask::zeros();
        let mut two = Mask::zeros();
        for v in values {
            two = two.or(&seen.and(v));
            seen = seen.or(v);
        }
        match m {
            Multiplicity::Some => seen,
            Multiplicity::No => seen.not(),
            Multiplicity::Lone => two.not(),
            Multiplicity::One => seen.andnot(&two),
        }
    }

    fn formula(&mut self, f: &Formula) -> Mask {
        match f.kind() {
            FormulaKind::Constant(true) => Mask::ones(),
            FormulaKind::Constant(false) => Mask::zeros(),
            FormulaKind::Subset(a, b) => {
                let (ta, tb) = (self.expr(a), self.expr(b));
                let mut all = Mask::ones();
                for (&i, m) in &ta {
                    all = all.andnot(&m.andnot(&get(&tb, i)));
                }
                all
            }
            FormulaKind::Equal(a, b) => {
                let (ta, tb) = (self.expr(a), self.expr(b));
                let keys: std::collections::BTreeSet<u64> =
                    ta.keys().chain(tb.keys()).copied().collect();
                let mut all = Mask::ones();
                for i in keys {
                    let (x, y) = (get(&ta, i), get(&tb, i));
                    all = all.andnot(&x.andnot(&y)).andnot(&y.andnot(&x));
                }
                all
            }
            FormulaKind::Multiplicity(m, a) => {
                let values: Vec<Mask> = self.expr(a).into_values().collect();
                Self::count(*m, &values)
            }
            FormulaKind::Not(g) => self.formula(g).not(),
            FormulaKind::And(fs) => fs
                .iter()
                .fold(Mask::ones(), |acc, g| acc.and(&self.formula(g))),
            FormulaKind::Or(fs) => fs
                .iter()
                .fold(Mask::zeros(), |acc, g| acc.or(&self.formula(g))),
            FormulaKind::Implies(a, b) => {
                let (x, y) = (self.formula(a), self.formula(b));
                x.not().or(&y)
            }
            FormulaKind::Iff(a, b) => {
                let (x, y) = (self.formula(a), self.formula(b));
                x.and(&y).or(&x.not().and(&y.not()))
            }
            FormulaKind::Quantified(q, decls, body) => {
                let mut cases: Vec<(Mask, Mask)> = Vec::new();
                let mut chosen = Vec::new();
                self.bindings(decls, &mut chosen, Mask::ones(), &mut |b, _, guard| {
                    let v = b.formula(body);
                    cases.push((guard.clone(), v));
                });
                match q {
                    Quantifier::All => cases
                        .iter()
                        .fold(Mask::ones(), |acc, (g, v)| acc.andnot(&g.andnot(v))),
                    _ => {
                        let values: Vec<Mask> = cases.iter().map(|(g, v)| g.and(v)).collect();
                        let m = match q {
                            Quantifier::Some => Multiplicity::Some,
                            Quantifier::No => Multiplicity::No,
                            Quantifier::One => Multiplicity::One,
                            Quantifier::Lone | Quantifier::All => Multiplicity::Lone,
                        };
                        Self::count(m, &values)
                    }
                }
            }
            FormulaKind::Temporal(..)
            | FormulaKind::TemporalBinary(..)
            | FormulaKind::IntCompare(..) => {
                unreachable!("not supported, so not counted here")
            }
        }
    }
}

/// The number of instances within `bounds` under which `formula` is true,
/// as `elinvar_logic::count` gives it (LOGIC.md section 8), with at most
/// `cap` free tuples.
pub fn count_bitsliced(bounds: &Bounds, formula: &Formula, cap: usize) -> Result<u64, Vec<Error>> {
    let errors = check_formula(formula, Against::Bounds(bounds));
    if !errors.is_empty() {
        return Err(errors);
    }
    if !supported(formula) || bounds.relations().any(Relation::is_changing) {
        return plain_count(bounds, formula, cap);
    }
    // The free tuples, in LOGIC.md 8's order.
    let mut free = Vec::new();
    for (pos, (_, lower, upper)) in bounds.entries().enumerate() {
        for i in upper.indices() {
            if !lower.contains_index(i) {
                free.push((pos, i));
            }
        }
    }
    let m = free.len();
    if m > cap || m > 63 {
        return Err(vec![Error::new(
            "enumerate.too_large",
            format!("{m} free tuples, and the cap is {}", cap.min(63)),
        )]);
    }
    let total = 1u64 << m;
    let lane_bits = LANES.trailing_zeros() as usize;
    // Bit `b` of the lane's own number, for the bits a block varies.
    let pattern = |b: usize| -> Mask {
        Mask(
            (0..WORDS)
                .map(|w| {
                    (0..64u64).fold(0u64, |acc, k| {
                        let lane = (w as u64) * 64 + k;
                        acc | (((lane >> b) & 1) << k)
                    })
                })
                .collect(),
        )
    };
    let patterns: Vec<Mask> = (0..lane_bits.min(m)).map(pattern).collect();
    let mut counted = 0u64;
    let mut base = 0u64;
    while base < total {
        let relations: Vec<(Relation, Table)> = bounds
            .entries()
            .enumerate()
            .map(|(pos, (r, lower, _))| {
                let mut t = Table::new();
                for i in lower.indices() {
                    t.insert(i, Mask::ones());
                }
                for (bit, &(p, i)) in free.iter().enumerate() {
                    if p != pos {
                        continue;
                    }
                    let mask = if bit < lane_bits {
                        patterns[bit].clone()
                    } else if (base >> bit) & 1 == 1 {
                        Mask::ones()
                    } else {
                        Mask::zeros()
                    };
                    put(&mut t, i, mask);
                }
                (r.clone(), t)
            })
            .collect();
        let mut block = Block {
            n: bounds.universe().size() as u64,
            relations: &relations,
            env: Vec::new(),
        };
        let mut holds = block.formula(formula);
        // Lanes past the last instance do not count.
        let valid = (total - base).min(LANES);
        if valid < LANES {
            let mut keep = Mask::zeros();
            for lane in 0..valid {
                keep.0[(lane / 64) as usize] |= 1 << (lane % 64);
            }
            holds = holds.and(&keep);
        }
        counted += holds.count();
        base += LANES;
    }
    Ok(counted)
}