elinvar-engine 0.1.1

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
Documentation
//! Symmetry breaking (LOGIC.md section 12.5).

use crate::circuit::{Bool, Circuit};
use crate::translate::{Primary, Translator};
use elinvar_logic::{Bounds, Relation, TupleSet};

/// The predicate compares at most this many entries per pair of atoms by
/// default, as Kodkod and Alloy do.
pub const PREDICATE_LENGTH: usize = 20;

fn swap_index(n: u64, arity: usize, mut i: u64, a: u64, b: u64) -> u64 {
    let mut out = 0u64;
    let mut mul = 1u64;
    for _ in 0..arity {
        let mut atom = i % n;
        i /= n;
        if atom == a {
            atom = b;
        } else if atom == b {
            atom = a;
        }
        out += atom * mul;
        mul *= n;
    }
    out
}

fn preserved(set: &TupleSet, n: u64, a: u64, b: u64) -> bool {
    set.indices()
        .all(|i| set.contains_index(swap_index(n, set.arity(), i, a, b)))
}

/// The parts of the universe: atoms that no bound tells apart, each part in
/// atom order, parts in the order of their first atom.
#[must_use]
pub fn partition(bounds: &Bounds) -> Vec<Vec<u64>> {
    partition_without(bounds, &[])
}

/// The parts of the universe as `partition` gives them, with the bounds of
/// `skip` left out.
pub(crate) fn partition_without(bounds: &Bounds, skip: &[&Relation]) -> Vec<Vec<u64>> {
    let u = bounds.universe();
    let n = u.size() as u64;
    // LOGIC.md 16.4: an integer atom is told apart by its integer.
    let plain = |a: u64| u.int_of(a as usize).is_none();
    let swappable = |a: u64, b: u64| {
        plain(a)
            && plain(b)
            && bounds
                .entries()
                .filter(|(r, _, _)| !skip.contains(r))
                .all(|(_, lower, upper)| preserved(lower, n, a, b) && preserved(upper, n, a, b))
    };
    let mut parts: Vec<Vec<u64>> = Vec::new();
    for a in 0..n {
        match parts.iter_mut().find(|p| swappable(p[0], a)) {
            Some(p) => p.push(a),
            None => parts.push(vec![a]),
        }
    }
    parts
}

/// The lex-leader predicate over the primary variables.
pub fn predicate(
    tr: &mut Translator<'_>,
    bounds: &Bounds,
    primaries: &[Primary],
    length: usize,
) -> Bool {
    let n = bounds.universe().size() as u64;
    let relations: Vec<_> = bounds.relations().cloned().collect();
    // LOGIC.md 12.5: relations by arity, then name, as Kodkod orders them
    // (SymmetryBreaker.relParts at 6e80244); within one, in number order.
    let mut order: Vec<&Primary> = primaries.iter().collect();
    order.sort_by(|p, q| {
        let (r, s) = (&relations[p.relation], &relations[q.relation]);
        (r.arity(), p.relation).cmp(&(s.arity(), q.relation))
    });
    let mut parts_out = Vec::new();
    for part in partition(bounds) {
        for pair in part.windows(2) {
            let (a, b) = (pair[0], pair[1]);
            let mut xs = Vec::new();
            let mut ys = Vec::new();
            for p in order.iter().copied() {
                if xs.len() == length {
                    break;
                }
                let r = &relations[p.relation];
                let image = swap_index(n, r.arity(), p.tuple, a, b);
                if image == p.tuple {
                    continue;
                }
                let y = tr.relation_table_in(r, p.state).get(image);
                // A pair already compared the other way round adds nothing:
                // it matters only once the two are equal (Kodkod's
                // atSameIndex).
                if xs
                    .iter()
                    .zip(&ys)
                    .any(|(&x0, &y0)| x0 == y && y0 == p.value)
                {
                    continue;
                }
                xs.push(p.value);
                ys.push(y);
            }
            parts_out.push(lex_leq(tr.circuit, &xs, &ys));
        }
    }
    tr.circuit.and(parts_out)
}

/// `xs <= ys` in lexicographic order, false before true.
fn lex_leq(c: &mut Circuit, xs: &[Bool], ys: &[Bool]) -> Bool {
    let len = xs.len().min(ys.len());
    let mut parts = Vec::with_capacity(len);
    let mut equal_so_far = Bool::TRUE;
    for (idx, (&x, &y)) in xs.iter().zip(ys).enumerate() {
        parts.push(c.or([!equal_so_far, !x, y]));
        if idx + 1 < len {
            let same = !c.xor(x, y);
            equal_so_far = c.and([equal_so_far, same]);
        }
    }
    c.and(parts)
}