use crate::circuit::{Bool, Circuit};
use crate::translate::{Primary, Translator};
use elinvar_logic::{Bounds, Relation, TupleSet};
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)))
}
#[must_use]
pub fn partition(bounds: &Bounds) -> Vec<Vec<u64>> {
partition_without(bounds, &[])
}
pub(crate) fn partition_without(bounds: &Bounds, skip: &[&Relation]) -> Vec<Vec<u64>> {
let u = bounds.universe();
let n = u.size() as u64;
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
}
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();
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);
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)
}
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)
}