semitone 0.0.49

SeMiTONE is a Satisfiability Modulo TheOries NEtwork, allowing the creation of variables and constraints in different underlying theories.
Documentation
use crate::{dl_theory::DlVar, rational::InfRational, sat_solver::Lit};

#[cfg_attr(not(feature = "dl"), allow(dead_code))]
pub(crate) enum RouteResult {
    Const(Lit),
    Dl(DlVar, DlVar, InfRational),
    Lra,
}

#[cfg_attr(not(feature = "dl"), allow(dead_code))]
#[derive(Clone, Copy)]
pub(crate) struct IneqFlags {
    pub(crate) is_upper_bound: bool,
    pub(crate) strict: bool,
    pub(crate) is_level0: bool,
}

#[cfg(feature = "dl")]
mod imp {
    use super::{IneqFlags, RouteResult};
    use crate::{
        dl_theory::{DlTheory, DlVar},
        lra_theory::{ArithVar, LraTheory, SparseRow},
        rational::{InfRational, Rational},
        sat_solver::{Lit, SatSolver},
    };
    use rustc_hash::{FxHashMap, FxHashSet};

    #[derive(Clone)]
    struct DlEdge {
        lit: Lit,
        from: DlVar,
        to: DlVar,
        bound: InfRational,
    }

    pub(crate) struct ArithRouter {
        /// Reference zero variable in `DlTheory` (allocated lazily so pure `DlVar` tests keep `DlVar(0)`).
        dl_zero: Option<DlVar>,
        arith_to_dl: FxHashMap<ArithVar, DlVar>,
        dl_to_arith: FxHashMap<DlVar, ArithVar>,
        /// Variables that participate in general LRA constraints (or are coupled to them via DL edges).
        lra_vars: FxHashSet<ArithVar>,
        /// Adjacency list of DL constraints among `ArithVar`s for transitive promotion to LRA.
        dl_neighbors: FxHashMap<ArithVar, Vec<ArithVar>>,
        /// Recorded DL edges per `ArithVar` so already-assigned DL literals can be replayed into LRA on promotion.
        dl_edges_by_var: FxHashMap<ArithVar, Vec<DlEdge>>,
        recorded_lits: FxHashSet<Lit>,
        queued_replay: FxHashSet<Lit>,
        pending_lra_replay: Vec<DlEdge>,
        /// Edges replayed into LRA at a decision level higher than their SAT assignment level.
        out_of_order_replays: Vec<(usize, DlEdge)>,
    }

    impl ArithRouter {
        pub(crate) fn new() -> Self {
            Self {
                dl_zero: None,
                arith_to_dl: FxHashMap::default(),
                dl_to_arith: FxHashMap::default(),
                lra_vars: FxHashSet::default(),
                dl_neighbors: FxHashMap::default(),
                dl_edges_by_var: FxHashMap::default(),
                recorded_lits: FxHashSet::default(),
                queued_replay: FxHashSet::default(),
                pending_lra_replay: Vec::new(),
                out_of_order_replays: Vec::new(),
            }
        }

        fn ensure_zero(&mut self, dl: &mut DlTheory) -> DlVar {
            *self.dl_zero.get_or_insert_with(|| dl.mk_var())
        }

        fn ensure_dl_var(&mut self, dl: &mut DlTheory, var: ArithVar) -> DlVar {
            // Allocate reference zero first so it always takes `DlVar(0)` in pure-arith problems.
            self.ensure_zero(dl);
            if let Some(&dv) = self.arith_to_dl.get(&var) {
                dv
            } else {
                let dv = dl.mk_var();
                self.arith_to_dl.insert(var, dv);
                self.dl_to_arith.insert(dv, var);
                dv
            }
        }

        /// Attempts to route a normalized inequality (`sum(vars) + const_term <= 0` or `>= 0`) to `DlTheory`.
        /// Handles 1-var real bounds (`x <= c`, `x >= c`) and 2-var opposite-coefficient real bounds (`x - y <= c`).
        /// Falls back to `RouteResult::Lra` for integer vars, >= 3 vars, non-difference coeffs, or vars already in LRA.
        pub(crate) fn try_as_dl(&mut self, dl: &mut DlTheory, lra: &LraTheory, vars: &SparseRow, const_term: &rug::Rational, flags: IneqFlags) -> RouteResult {
            let IneqFlags { is_upper_bound, strict, is_level0 } = flags;
            match vars.len() {
                1 => {
                    let (var, coeff) = &vars.terms[0];
                    if lra.is_int_var(*var) || self.lra_vars.contains(var) {
                        return RouteResult::Lra;
                    }

                    let is_upper_for_var = is_upper_bound == coeff.is_positive();
                    let val = rug::Rational::from(-const_term) / coeff;

                    if is_level0 && let Some(&dv) = self.arith_to_dl.get(var) {
                        let v_eps = if strict { rug::Rational::from(if is_upper_for_var { -1 } else { 1 }) } else { rug::Rational::from(0) };
                        let v_bound = InfRational::new(Rational::Finite(val.clone()), v_eps);
                        if is_upper_for_var {
                            if dl.ub(dv) <= v_bound {
                                return RouteResult::Const(Lit::TRUE);
                            }
                            if dl.lb(dv) > v_bound {
                                return RouteResult::Const(Lit::FALSE);
                            }
                        } else {
                            if dl.lb(dv) >= v_bound {
                                return RouteResult::Const(Lit::TRUE);
                            }
                            if dl.ub(dv) < v_bound {
                                return RouteResult::Const(Lit::FALSE);
                            }
                        }
                    }

                    let zero = self.ensure_zero(dl);
                    let dv = self.ensure_dl_var(dl, *var);
                    let delta = rug::Rational::from(if strict { -1 } else { 0 });

                    if is_upper_for_var {
                        // dv - zero <= (val, delta)
                        RouteResult::Dl(zero, dv, InfRational::new(Rational::Finite(val), delta))
                    } else {
                        // zero - dv <= (-val, delta)
                        RouteResult::Dl(dv, zero, InfRational::new(Rational::Finite(-val), delta))
                    }
                }
                2 => {
                    let (v1, c1) = &vars.terms[0];
                    let (v2, c2) = &vars.terms[1];
                    if lra.is_int_var(*v1) || lra.is_int_var(*v2) || self.lra_vars.contains(v1) || self.lra_vars.contains(v2) {
                        return RouteResult::Lra;
                    }
                    if !rug::Rational::from(c1 + c2).is_zero() {
                        return RouteResult::Lra;
                    }

                    let mag = if c1.is_positive() { c1 } else { c2 };
                    let rhs = if is_upper_bound { rug::Rational::from(-const_term) / mag } else { rug::Rational::from(const_term / mag) };
                    let delta = rug::Rational::from(if strict { -1 } else { 0 });
                    let bound = InfRational::new(Rational::Finite(rhs), delta);

                    let dl_v1 = self.ensure_dl_var(dl, *v1);
                    let dl_v2 = self.ensure_dl_var(dl, *v2);
                    let v1_is_to = is_upper_bound == c1.is_positive();
                    let (from, to) = if v1_is_to { (dl_v2, dl_v1) } else { (dl_v1, dl_v2) };

                    RouteResult::Dl(from, to, bound)
                }
                _ => RouteResult::Lra,
            }
        }

        /// Registers a newly routed `DlLeq` proxy so it can be replayed into LRA if either endpoint is promoted later.
        pub(crate) fn on_dl_proxy(&mut self, lit: Lit, from: DlVar, to: DlVar, bound: InfRational) {
            if !self.recorded_lits.insert(lit) {
                return;
            }
            let a_from = self.dl_to_arith.get(&from).copied();
            let a_to = self.dl_to_arith.get(&to).copied();
            let edge = DlEdge { lit, from, to, bound };

            if let Some(u) = a_from {
                self.dl_edges_by_var.entry(u).or_default().push(edge.clone());
            }
            if let Some(v) = a_to {
                self.dl_edges_by_var.entry(v).or_default().push(edge);
            }
            if let (Some(u), Some(v)) = (a_from, a_to) {
                self.dl_neighbors.entry(u).or_default().push(v);
                self.dl_neighbors.entry(v).or_default().push(u);
            }
        }

        /// Marks variables entering a general LRA constraint (and their connected DL component) as mixed,
        /// queuing previously created DL proxies for replay into `LraTheory`.
        pub(crate) fn mark_lra_vars(&mut self, vars: &SparseRow) {
            let mut stack: Vec<ArithVar> = Vec::new();
            for &v in vars.keys() {
                if self.lra_vars.insert(v) {
                    stack.push(v);
                }
            }

            while let Some(v) = stack.pop() {
                if let Some(edges) = self.dl_edges_by_var.get(&v) {
                    for edge in edges {
                        if self.queued_replay.insert(edge.lit) {
                            self.pending_lra_replay.push(edge.clone());
                        }
                    }
                }
                if let Some(neighbors) = self.dl_neighbors.get(&v) {
                    for &n in neighbors {
                        if self.lra_vars.insert(n) {
                            stack.push(n);
                        }
                    }
                }
            }
        }

        /// Replays already-assigned DL literals whose variables were promoted to LRA.
        /// Returns `Ok(true)` if any LRA bound was tightened.
        pub(crate) fn flush_pending_to_lra(&mut self, sat: &SatSolver, lra: &mut LraTheory) -> Result<bool, Vec<Lit>> {
            let cur_lvl = sat.decision_level();
            let mut changed = false;

            while let Some(edge) = self.pending_lra_replay.pop() {
                let Some(val) = sat.lit_value(edge.lit) else {
                    continue;
                };
                let lit_lvl = sat.lit_level(edge.lit).unwrap_or(0);
                let (guard, negated) = if val { (edge.lit, false) } else { (!edge.lit, true) };

                match self.apply_dl_edge_to_lra(lra, edge.from, edge.to, &edge.bound, guard, negated) {
                    Ok(c) => {
                        changed |= c;
                        if lit_lvl < cur_lvl {
                            self.out_of_order_replays.push((cur_lvl, edge));
                        }
                    }
                    Err(lemma) => {
                        if lit_lvl < cur_lvl {
                            self.pending_lra_replay.push(edge);
                        }
                        return Err(lemma);
                    }
                }
            }
            Ok(changed)
        }

        /// Re-queues out-of-order replays undone by `LraTheory::cancel_until(level)`.
        pub(crate) fn on_cancel_until(&mut self, level: usize) {
            let mut i = 0;
            while i < self.out_of_order_replays.len() {
                if self.out_of_order_replays[i].0 > level {
                    let (_, edge) = self.out_of_order_replays.swap_remove(i);
                    self.pending_lra_replay.push(edge);
                } else {
                    i += 1;
                }
            }
        }

        /// Mirrors a propagated `DlLeq(from, to, bound)` into `LraTheory` if either endpoint is mixed.
        pub(crate) fn mirror_dl_to_lra(&self, lra: &mut LraTheory, from: DlVar, to: DlVar, bound: &InfRational, lit: Lit, negated: bool) -> Result<bool, Vec<Lit>> {
            let a_from = self.dl_to_arith.get(&from).copied();
            let a_to = self.dl_to_arith.get(&to).copied();
            let is_mixed = a_from.is_some_and(|v| self.lra_vars.contains(&v)) || a_to.is_some_and(|v| self.lra_vars.contains(&v));
            if !is_mixed {
                return Ok(false);
            }
            self.apply_dl_edge_to_lra(lra, from, to, bound, lit, negated)
        }

        fn apply_dl_edge_to_lra(&self, lra: &mut LraTheory, from: DlVar, to: DlVar, bound: &InfRational, guard: Lit, negated: bool) -> Result<bool, Vec<Lit>> {
            let a_from = self.dl_to_arith.get(&from).copied();
            let a_to = self.dl_to_arith.get(&to).copied();

            match (a_from, a_to) {
                // to - zero <= bound  <=>  to <= bound
                (None, Some(v)) => {
                    if !negated {
                        lra.set_ub(Some(guard), v, bound.clone())
                    } else {
                        let eps = rug::Rational::from(if bound.infinitesimal_part().is_negative() { 0 } else { 1 });
                        let lb = InfRational::new(bound.rational_part().clone(), eps);
                        lra.set_lb(Some(guard), v, lb)
                    }
                }
                // zero - from <= bound  <=>  from >= -bound
                (Some(v), None) => {
                    let neg_bound = -bound.clone();
                    if !negated {
                        lra.set_lb(Some(guard), v, neg_bound)
                    } else {
                        let eps = rug::Rational::from(if neg_bound.infinitesimal_part().is_positive() { 0 } else { -1 });
                        let ub = InfRational::new(neg_bound.rational_part().clone(), eps);
                        lra.set_ub(Some(guard), v, ub)
                    }
                }
                // to - from <= bound
                (Some(v_from), Some(v_to)) => {
                    let mut row = SparseRow::new();
                    row.insert(v_to, rug::Rational::from(1));
                    row.insert(v_from, rug::Rational::from(-1));
                    let slack = lra.get_or_create_slack(row);
                    if !negated {
                        lra.set_ub(Some(guard), slack, bound.clone())
                    } else {
                        let eps = rug::Rational::from(if bound.infinitesimal_part().is_negative() { 0 } else { 1 });
                        let lb = InfRational::new(bound.rational_part().clone(), eps);
                        lra.set_lb(Some(guard), slack, lb)
                    }
                }
                (None, None) => Ok(false),
            }
        }

        pub(crate) fn get_real_val(&self, var: ArithVar, lra: &LraTheory, dl: &DlTheory) -> InfRational {
            if !self.lra_vars.contains(&var)
                && let Some(&dv) = self.arith_to_dl.get(&var)
            {
                return dl.value(dv);
            }
            lra.value(var).clone()
        }

        pub(crate) fn get_real_bounds(&self, var: ArithVar, lra: &LraTheory, dl: &DlTheory) -> (InfRational, InfRational) {
            if let Some(&dv) = self.arith_to_dl.get(&var) {
                let (dl_lb, dl_ub) = (dl.lb(dv), dl.ub(dv));
                if !self.lra_vars.contains(&var) {
                    return (dl_lb, dl_ub);
                }
                let lb = if lra.lb(var) > &dl_lb { lra.lb(var).clone() } else { dl_lb };
                let ub = if lra.ub(var) < &dl_ub { lra.ub(var).clone() } else { dl_ub };
                return (lb, ub);
            }
            (lra.lb(var).clone(), lra.ub(var).clone())
        }
    }
}

#[cfg(not(feature = "dl"))]
mod imp {
    use super::{IneqFlags, RouteResult};
    use crate::{
        dl_theory::{DlTheory, DlVar},
        lra_theory::{ArithVar, LraTheory, SparseRow},
        rational::InfRational,
        sat_solver::{Lit, SatSolver},
    };

    pub(crate) struct ArithRouter;

    impl ArithRouter {
        #[inline(always)]
        pub(crate) fn new() -> Self {
            Self
        }
        #[inline(always)]
        pub(crate) fn try_as_dl(&mut self, _: &mut DlTheory, _: &LraTheory, _: &SparseRow, _: &rug::Rational, _: IneqFlags) -> RouteResult {
            RouteResult::Lra
        }
        #[inline(always)]
        pub(crate) fn on_dl_proxy(&mut self, _: Lit, _: DlVar, _: DlVar, _: InfRational) {}
        #[inline(always)]
        pub(crate) fn mark_lra_vars(&mut self, _: &SparseRow) {}
        #[inline(always)]
        pub(crate) fn flush_pending_to_lra(&mut self, _: &SatSolver, _: &mut LraTheory) -> Result<bool, Vec<Lit>> {
            Ok(false)
        }
        #[inline(always)]
        pub(crate) fn on_cancel_until(&mut self, _: usize) {}
        #[inline(always)]
        pub(crate) fn mirror_dl_to_lra(&self, _: &mut LraTheory, _: DlVar, _: DlVar, _: &InfRational, _: Lit, _: bool) -> Result<bool, Vec<Lit>> {
            Ok(false)
        }
        #[inline(always)]
        pub(crate) fn get_real_val(&self, var: ArithVar, lra: &LraTheory, _: &DlTheory) -> InfRational {
            lra.value(var).clone()
        }
        #[inline(always)]
        pub(crate) fn get_real_bounds(&self, var: ArithVar, lra: &LraTheory, _: &DlTheory) -> (InfRational, InfRational) {
            (lra.lb(var).clone(), lra.ub(var).clone())
        }
    }
}

pub(crate) use imp::ArithRouter;