semitone 0.0.52

SeMiTONE is a Satisfiability Modulo TheOries NEtwork, allowing the creation of variables and constraints in different underlying theories.
Documentation
use crate::proxy::TheoryConstraint;
use std::{fmt, time::Duration};

#[cfg(feature = "profiling")]
mod timer {
    use std::time::{Duration, Instant};

    #[derive(Clone, Copy)]
    pub(crate) struct Span(Instant);

    #[inline(always)]
    pub(crate) fn start() -> Span {
        Span(Instant::now())
    }

    #[inline(always)]
    pub(crate) fn record(dst: &mut Duration, span: Span) {
        *dst += span.0.elapsed();
    }
}

#[cfg(not(feature = "profiling"))]
mod timer {
    use std::time::Duration;

    #[derive(Clone, Copy)]
    pub(crate) struct Span;

    #[inline(always)]
    pub(crate) fn start() -> Span {
        Span
    }

    #[inline(always)]
    pub(crate) fn record(_dst: &mut Duration, _span: Span) {}
}

pub(crate) use timer::Span;

#[derive(Clone, Copy)]
pub(crate) enum TheoryKind {
    Lra,
    Dl,
    Enum,
    Other,
}

impl TheoryKind {
    #[inline]
    pub(crate) fn of(c: &TheoryConstraint) -> Self {
        match c {
            TheoryConstraint::LraLb(..) | TheoryConstraint::LraUb(..) => Self::Lra,
            TheoryConstraint::DlLeq(..) => Self::Dl,
            TheoryConstraint::EnumEq(..) => Self::Enum,
            _ => Self::Other,
        }
    }
}

/// Breakdown of cumulative wall-clock time spent across solver phases.
///
/// Populated only when the `profiling` feature is enabled; otherwise
/// [`SmtStats::timing`] is `None`.
#[derive(Debug, Clone, Copy, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TimingStats {
    /// Total wall-clock time spent inside [`crate::SeMiTONE::propagate`]
    /// (including calls made internally by [`crate::SeMiTONE::probe_implied`]).
    pub prop_total: Duration,
    /// Time spent in SAT Boolean Constraint Propagation (`SatSolver::propagate`),
    /// including SAT-level 1-UIP conflict analysis on propositional conflicts.
    pub sat_prop: Duration,
    /// Time spent asserting individual LRA lower/upper bounds during trail notification.
    pub lra_bound: Duration,
    /// Time spent asserting Difference Logic edges and mirroring them to LRA when needed.
    pub dl: Duration,
    /// Time spent asserting equality and disequality constraints in the finite-domain enum theory.
    pub enum_theory: Duration,
    /// Time spent in the LRA Simplex feasibility check (`LraTheory::check`).
    pub lra_check: Duration,
    /// Time spent in SAT 1-UIP conflict analysis triggered by theory-level conflict lemmas.
    pub analyze: Duration,
    /// Time spent inserting and simplifying clauses via [`crate::SeMiTONE::add_clause`]
    /// and [`crate::SeMiTONE::add_learnt_clause`] (including LBD-based database reductions).
    pub add_clause: Duration,
    /// Time spent backtracking SAT and all theory states in [`crate::SeMiTONE::cancel_until`].
    pub cancel: Duration,
}

impl TimingStats {
    /// Time spent inside `SeMiTONE::propagate` outside SAT/theory/analysis sub-timers.
    pub fn prop_other(&self) -> Duration {
        let inner = self.sat_prop + self.lra_bound + self.dl + self.enum_theory + self.lra_check + self.analyze;
        self.prop_total.saturating_sub(inner)
    }
}

/// Structured runtime statistics snapshot for [`crate::SeMiTONE`].
///
/// Counters reflect either the current solver state (e.g. `num_vars`, `num_clauses`,
/// tableau dimensions) or cumulative totals since solver creation (e.g. conflicts,
/// reductions, pivots). Phase timings are recorded in [`Self::timing`] when the
/// `profiling` feature is enabled.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SmtStats {
    /// Cumulative number of calls to [`crate::SeMiTONE::propagate`]
    /// (including propagation rounds executed inside [`crate::SeMiTONE::probe_implied`]).
    pub prop_calls: usize,

    /// Current number of allocated SAT Boolean variables, including both
    /// user-created variables and internal theory/Tseitin proxy variables.
    pub num_vars: usize,

    /// Current total number of multi-literal clauses stored in the SAT database
    /// (permanent problem clauses plus currently retained learnt clauses).
    /// Unit clauses are absorbed directly into the assignment trail and are not counted here.
    pub num_clauses: usize,

    /// Current number of learnt clauses retained in the SAT database (a subset of [`Self::num_clauses`]).
    pub num_learnts: usize,

    /// Cumulative number of LBD-based learnt-clause database reductions performed so far.
    pub db_reductions: usize,

    /// Cumulative number of learnt clauses removed by database reductions.
    pub clauses_deleted: usize,

    /// Cumulative number of propositional conflicts detected during SAT unit propagation.
    pub sat_conflicts: usize,

    /// Cumulative number of immediate bound conflicts (e.g., `lb > ub`) detected
    /// while notifying the LRA theory of individual bound literals.
    pub lra_bound_conflicts: usize,

    /// Cumulative number of linear infeasibility conflicts detected by the
    /// LRA Simplex feasibility check.
    pub lra_check_conflicts: usize,

    /// Cumulative number of negative-cycle conflicts detected by the Difference Logic theory.
    pub dl_conflicts: usize,

    /// Cumulative number of domain-wipeout conflicts detected by the finite-domain enum theory.
    pub enum_conflicts: usize,

    /// Cumulative number of multi-literal learnt clauses added via [`crate::SeMiTONE::add_learnt_clause`].
    /// Serves as the denominator for [`Self::avg_learnt_len`] and [`Self::avg_learnt_lbd`].
    pub learnt_added: usize,

    /// Cumulative sum of literal counts across all learnt clauses counted in [`Self::learnt_added`].
    pub learnt_lits_sum: usize,

    /// Cumulative sum of initial Literal Block Distance (LBD) scores across all
    /// learnt clauses counted in [`Self::learnt_added`].
    pub learnt_lbd_sum: usize,

    /// Cumulative number of Simplex pivots executed by the LRA theory during
    /// feasibility checks and optimization.
    pub lra_pivots: usize,

    /// Current number of active basic rows in the LRA Simplex tableau.
    pub lra_rows: usize,

    /// Current total number of non-zero coefficients across all active LRA tableau rows.
    pub lra_nnz: usize,

    /// Current maximum number of non-zero terms in any single active LRA tableau row.
    pub lra_max_row: usize,

    /// Optional wall-clock phase timings; `Some(_)` when built with the `profiling` feature,
    /// `None` otherwise.
    pub timing: Option<TimingStats>,
}

impl SmtStats {
    /// Returns the average number of literals per learnt clause, or `0.0` if no learnt clauses have been added yet.
    pub fn avg_learnt_len(&self) -> f64 {
        if self.learnt_added == 0 { 0.0 } else { self.learnt_lits_sum as f64 / self.learnt_added as f64 }
    }

    /// Returns the average initial LBD score per learnt clause, or `0.0` if no learnt clauses have been added yet.
    pub fn avg_learnt_lbd(&self) -> f64 {
        if self.learnt_added == 0 { 0.0 } else { self.learnt_lbd_sum as f64 / self.learnt_added as f64 }
    }
}

impl fmt::Display for SmtStats {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "calls={} vars={} cl={}(lrn={}, red={}, del={}) sat_c={} lra_b_c={} lra_chk_c={} dl_c={} enum_c={} avg_len={:.1} avg_lbd={:.1} | pivots={} rows={} nnz={} max_row={}",
            self.prop_calls,
            self.num_vars,
            self.num_clauses,
            self.num_learnts,
            self.db_reductions,
            self.clauses_deleted,
            self.sat_conflicts,
            self.lra_bound_conflicts,
            self.lra_check_conflicts,
            self.dl_conflicts,
            self.enum_conflicts,
            self.avg_learnt_len(),
            self.avg_learnt_lbd(),
            self.lra_pivots,
            self.lra_rows,
            self.lra_nnz,
            self.lra_max_row,
        )?;
        if let Some(t) = &self.timing {
            write!(f, " | prop_tot={:.2?} sat={:.2?} lra_b={:.2?} dl={:.2?} enum={:.2?} lra_chk={:.2?} analyze={:.2?} other={:.2?} add_cl={:.2?} cancel={:.2?}", t.prop_total, t.sat_prop, t.lra_bound, t.dl, t.enum_theory, t.lra_check, t.analyze, t.prop_other(), t.add_clause, t.cancel,)?;
        }
        Ok(())
    }
}

#[derive(Default)]
pub(crate) struct SmtProf {
    prop_calls: usize,
    sat_conflicts: usize,
    lra_bound_conflicts: usize,
    lra_check_conflicts: usize,
    dl_conflicts: usize,
    enum_conflicts: usize,
    timing: TimingStats,
}

impl SmtProf {
    #[inline(always)]
    pub(crate) fn start() -> Span {
        timer::start()
    }
    #[inline(always)]
    pub(crate) fn on_prop_call(&mut self) {
        self.prop_calls += 1;
    }
    #[inline(always)]
    pub(crate) fn stop_sat_prop(&mut self, t: Span) {
        timer::record(&mut self.timing.sat_prop, t);
    }
    #[inline(always)]
    pub(crate) fn on_sat_conflict(&mut self) {
        self.sat_conflicts += 1;
    }
    #[inline(always)]
    pub(crate) fn stop_notify(&mut self, t: Span, kind: TheoryKind) {
        match kind {
            TheoryKind::Lra => timer::record(&mut self.timing.lra_bound, t),
            TheoryKind::Dl => timer::record(&mut self.timing.dl, t),
            TheoryKind::Enum => timer::record(&mut self.timing.enum_theory, t),
            TheoryKind::Other => {}
        }
    }
    #[inline(always)]
    pub(crate) fn on_notify_conflict(&mut self, kind: TheoryKind) {
        match kind {
            TheoryKind::Lra => self.lra_bound_conflicts += 1,
            TheoryKind::Dl => self.dl_conflicts += 1,
            TheoryKind::Enum => self.enum_conflicts += 1,
            TheoryKind::Other => {}
        }
    }
    #[inline(always)]
    pub(crate) fn stop_lra_check(&mut self, t: Span) {
        timer::record(&mut self.timing.lra_check, t);
    }
    #[inline(always)]
    pub(crate) fn on_lra_check_conflict(&mut self) {
        self.lra_check_conflicts += 1;
    }
    #[inline(always)]
    pub(crate) fn stop_analyze(&mut self, t: Span) {
        timer::record(&mut self.timing.analyze, t);
    }
    #[inline(always)]
    pub(crate) fn stop_cancel(&mut self, t: Span) {
        timer::record(&mut self.timing.cancel, t);
    }
    #[inline(always)]
    pub(crate) fn stop_prop_total(&mut self, t: Span) {
        timer::record(&mut self.timing.prop_total, t);
    }
    #[inline(always)]
    pub(crate) fn stop_add_clause(&mut self, t: Span) {
        timer::record(&mut self.timing.add_clause, t);
    }

    pub(crate) fn snapshot(&self, num_vars: usize, (num_clauses, num_learnts, db_reductions, clauses_deleted, learnt_added, learnt_lits_sum, learnt_lbd_sum): (usize, usize, usize, usize, usize, usize, usize), lra_pivots: usize, (lra_rows, lra_nnz, lra_max_row): (usize, usize, usize)) -> SmtStats {
        #[cfg(feature = "profiling")]
        let timing = Some(self.timing);
        #[cfg(not(feature = "profiling"))]
        let timing = None;

        SmtStats {
            prop_calls: self.prop_calls,
            num_vars,
            num_clauses,
            num_learnts,
            db_reductions,
            clauses_deleted,
            sat_conflicts: self.sat_conflicts,
            lra_bound_conflicts: self.lra_bound_conflicts,
            lra_check_conflicts: self.lra_check_conflicts,
            dl_conflicts: self.dl_conflicts,
            enum_conflicts: self.enum_conflicts,
            learnt_added,
            learnt_lits_sum,
            learnt_lbd_sum,
            lra_pivots,
            lra_rows,
            lra_nnz,
            lra_max_row,
            timing,
        }
    }
}