Skip to main content

logicaffeine_proof/
pigeonhole.rs

1//! Pigeonhole / bipartite-matching detection for the general solver — the cardinality reasoning
2//! that lets `prove_unsat` win on pigeonhole-shaped formulas in POLYNOMIAL time.
3//!
4//! A conjunction of "each item is in at least one slot" (positive disjunctions) and "each slot
5//! holds at most one item" (pairwise mutual-exclusion clauses) is a bipartite-matching feasibility
6//! question. Encoded as boolean SAT it needs *exponentially* long resolution refutations — the
7//! classic wall for CDCL (ours and Z3's). But the underlying matching is decided in *polynomial*
8//! time with a certified Hall witness ([`crate::matching`]).
9//!
10//! This module recognizes that structure SOUNDLY — a faithful, fully-verified decomposition or it
11//! bails to `None` — and routes the UNSAT case to the matching reasoner. **Soundness:** a
12//! satisfying assignment of (at-least-one rows ∧ fully-encoded at-most-one columns) is *exactly* a
13//! perfect matching of items to slots (each item ≥1 true variable, each slot ≤1), so "no perfect
14//! matching" (a re-verified Hall witness) ⟺ UNSAT. A `true` from [`decide_pigeonhole_unsat`] is
15//! therefore always a genuine, witnessed refutation; everything else falls back to CDCL.
16
17use crate::matching::{assign_or_hall, is_hall_witness, MatchOutcome};
18use crate::ProofExpr;
19use std::collections::{HashMap, HashSet};
20
21/// Decide whether `e` is a clean pigeonhole structure that is UNSAT. Returns `true` ONLY when the
22/// formula decomposes faithfully into at-least-one rows + fully-encoded (clique) at-most-one columns
23/// AND the bipartite matching is infeasible with a RE-VERIFIED Hall witness. `false` otherwise — for
24/// a non-pigeonhole formula, or a feasible one (the caller falls back to CDCL). **Never a false
25/// `true`.**
26pub fn decide_pigeonhole_unsat(e: &ProofExpr) -> bool {
27    let Some((adj, num_slots)) = extract_bipartite(e) else {
28        return false;
29    };
30    match assign_or_hall(&adj, num_slots) {
31        MatchOutcome::Infeasible(w) => is_hall_witness(&adj, &w),
32        MatchOutcome::Feasible(_) => false,
33    }
34}
35
36/// Expose the O(1) counting certificate for any matching-shaped cover, not just literal pigeonhole:
37/// recover the bipartite `(items → slots)` structure and certify UNSAT by the full-set Hall bound
38/// `items > slots`. Fires for pigeonhole *and* clique-coloring (`n` vertices, `k < n` colors) — the
39/// same crush, derived structurally. `None` when there is no such bipartite structure or the full set
40/// does not overflow the slots (a subset-Hall failure is still caught by [`decide_pigeonhole_unsat`]).
41pub fn counting_certificate(e: &ProofExpr) -> Option<CountingCert> {
42    let (adj, num_slots) = extract_bipartite(e)?;
43    certify_pigeonhole_unsat(adj.len() as u128, num_slots as u128)
44}
45
46/// The **full Hall certificate** — the matching symmetry invariant in its complete form. A bipartite
47/// cover is infeasible the moment *some subset* `S` of items reaches fewer than `|S|` slots, even when
48/// the totals balance and the crude `items > slots` bound sees nothing. Returns the violating subset
49/// (re-checked by [`is_hall_witness`]), strictly stronger than [`counting_certificate`]. This is the
50/// witness behind [`decide_pigeonhole_unsat`]'s verdict, surfaced.
51pub fn hall_refutation(e: &ProofExpr) -> Option<crate::matching::HallWitness> {
52    let (adj, num_slots) = extract_bipartite(e)?;
53    match assign_or_hall(&adj, num_slots) {
54        MatchOutcome::Infeasible(w) if is_hall_witness(&adj, &w) => Some(w),
55        _ => None,
56    }
57}
58
59/// The pigeonhole counting certificate — the symmetry break taken to its absolute limit. For the *complete*
60/// bipartite instance `PHP(pigeons → holes)` (every pigeon may use every hole, each hole ≤ 1 pigeon), the
61/// full pigeon set has neighborhood = all `holes` slots, so Hall's condition fails the instant
62/// `pigeons > holes`. That single inequality IS the refutation — sound, `O(1)`, and **scale-free**.
63///
64/// This is the indisputable object. `PHP(n)` over booleans has `n·(n−1)` variables, and *every* resolution
65/// or CDCL refutation has at least `2^Ω(n)` steps (Haken, 1985) — so for `n = 2¹²⁸` the shortest possible
66/// search proof has more steps than a number with `~10³⁷` digits, beyond any computation this universe could
67/// ever run. The counting break decides and certifies the very same fact in one comparison.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub struct CountingCert {
70    pub pigeons: u128,
71    pub holes: u128,
72}
73
74/// Certify `PHP(pigeons → holes)` UNSAT by pure counting, in `O(1)`. `Some` iff `pigeons > holes` (Hall
75/// violated by the full pigeon set); `None` otherwise (feasible — a perfect matching can exist).
76pub fn certify_pigeonhole_unsat(pigeons: u128, holes: u128) -> Option<CountingCert> {
77    (pigeons > holes).then_some(CountingCert { pigeons, holes })
78}
79
80/// Re-check a counting certificate from scratch: it witnesses UNSAT iff `pigeons > holes`. `O(1)`, zero
81/// trust in how it was produced — the whole refutation is one inequality.
82pub fn check_counting_cert(c: &CountingCert) -> bool {
83    c.pigeons > c.holes
84}
85
86/// Recover `(item → reachable slots, slot count)` from `e`, or `None` if `e` is not a faithful
87/// pigeonhole conjunction. Conservative: any clause that is neither an at-least-one row nor a
88/// binary at-most-one exclusion, any variable in two rows, an exclusion over an unknown variable,
89/// or an at-most-one group that is not a full clique → `None`.
90fn extract_bipartite(e: &ProofExpr) -> Option<(Vec<Vec<usize>>, usize)> {
91    let mut clauses = Vec::new();
92    flatten_and(e, &mut clauses);
93    if clauses.is_empty() {
94        return None;
95    }
96
97    let mut rows: Vec<Vec<String>> = Vec::new(); // each item's candidate variables
98    let mut excl: Vec<(String, String)> = Vec::new(); // mutual-exclusion (same-slot) pairs
99    for c in &clauses {
100        if let Some(atoms) = positive_disjunction(c) {
101            if atoms.is_empty() {
102                return None;
103            }
104            rows.push(atoms);
105        } else if let Some(pair) = exclusion_pair(c) {
106            excl.push(pair);
107        } else {
108            return None;
109        }
110    }
111    if rows.is_empty() {
112        return None;
113    }
114
115    // Every variable must appear in EXACTLY ONE row (its item) — a clean item partition.
116    let mut item_of: HashMap<String, usize> = HashMap::new();
117    for (i, row) in rows.iter().enumerate() {
118        for a in row {
119            if item_of.insert(a.clone(), i).is_some() {
120                return None;
121            }
122        }
123    }
124
125    // Union-find over variables joined by exclusion → slot components.
126    let vars: Vec<String> = item_of.keys().cloned().collect();
127    let idx: HashMap<&str, usize> = vars
128        .iter()
129        .enumerate()
130        .map(|(i, v)| (v.as_str(), i))
131        .collect();
132    let mut uf = UnionFind::new(vars.len());
133    for (a, b) in &excl {
134        let (Some(&ia), Some(&ib)) = (idx.get(a.as_str()), idx.get(b.as_str())) else {
135            return None; // exclusion over a variable not in any row
136        };
137        uf.union(ia, ib);
138    }
139
140    // Compact component ids → slots; record members.
141    let mut slot_id: HashMap<usize, usize> = HashMap::new();
142    let mut slot_members: Vec<Vec<usize>> = Vec::new();
143    let mut slot_of: Vec<usize> = vec![0; vars.len()];
144    for v in 0..vars.len() {
145        let root = uf.find(v);
146        let s = *slot_id.entry(root).or_insert_with(|| {
147            slot_members.push(Vec::new());
148            slot_members.len() - 1
149        });
150        slot_of[v] = s;
151        slot_members[s].push(v);
152    }
153
154    // Each multi-member slot must be a FULL clique of exclusions (so "at most one" is genuinely
155    // enforced — otherwise two items could share a slot and infeasibility wouldn't imply UNSAT).
156    let excl_set: HashSet<(usize, usize)> = excl
157        .iter()
158        .filter_map(|(a, b)| {
159            let ia = *idx.get(a.as_str())?;
160            let ib = *idx.get(b.as_str())?;
161            Some((ia.min(ib), ia.max(ib)))
162        })
163        .collect();
164    for members in &slot_members {
165        for i in 0..members.len() {
166            for j in (i + 1)..members.len() {
167                let key = (members[i].min(members[j]), members[i].max(members[j]));
168                if !excl_set.contains(&key) {
169                    return None;
170                }
171            }
172        }
173    }
174
175    // Build item → reachable slots.
176    let num_slots = slot_members.len();
177    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); rows.len()];
178    for (i, row) in rows.iter().enumerate() {
179        for a in row {
180            let s = slot_of[*idx.get(a.as_str()).unwrap()];
181            if !adj[i].contains(&s) {
182                adj[i].push(s);
183            }
184        }
185    }
186    Some((adj, num_slots))
187}
188
189fn flatten_and<'a>(e: &'a ProofExpr, out: &mut Vec<&'a ProofExpr>) {
190    match e {
191        ProofExpr::And(l, r) => {
192            flatten_and(l, out);
193            flatten_and(r, out);
194        }
195        other => out.push(other),
196    }
197}
198
199/// `Some(atoms)` if `e` is a disjunction of POSITIVE atoms (an at-least-one row); else `None`.
200fn positive_disjunction(e: &ProofExpr) -> Option<Vec<String>> {
201    fn walk(e: &ProofExpr, out: &mut Vec<String>) -> bool {
202        match e {
203            ProofExpr::Or(l, r) => walk(l, out) && walk(r, out),
204            ProofExpr::Atom(a) => {
205                out.push(a.clone());
206                true
207            }
208            _ => false,
209        }
210    }
211    let mut atoms = Vec::new();
212    walk(e, &mut atoms).then_some(atoms)
213}
214
215/// `Some((a, b))` if `e` is a binary mutual-exclusion `¬(a ∧ b)` or `(¬a ∨ ¬b)` over atoms.
216fn exclusion_pair(e: &ProofExpr) -> Option<(String, String)> {
217    match e {
218        ProofExpr::Not(inner) => match inner.as_ref() {
219            ProofExpr::And(a, b) => match (a.as_ref(), b.as_ref()) {
220                (ProofExpr::Atom(a), ProofExpr::Atom(b)) => Some((a.clone(), b.clone())),
221                _ => None,
222            },
223            _ => None,
224        },
225        ProofExpr::Or(l, r) => match (l.as_ref(), r.as_ref()) {
226            (ProofExpr::Not(a), ProofExpr::Not(b)) => match (a.as_ref(), b.as_ref()) {
227                (ProofExpr::Atom(a), ProofExpr::Atom(b)) => Some((a.clone(), b.clone())),
228                _ => None,
229            },
230            _ => None,
231        },
232        _ => None,
233    }
234}
235
236struct UnionFind {
237    parent: Vec<usize>,
238}
239impl UnionFind {
240    fn new(n: usize) -> Self {
241        UnionFind {
242            parent: (0..n).collect(),
243        }
244    }
245    fn find(&mut self, x: usize) -> usize {
246        if self.parent[x] != x {
247            let r = self.find(self.parent[x]);
248            self.parent[x] = r;
249        }
250        self.parent[x]
251    }
252    fn union(&mut self, a: usize, b: usize) {
253        let (ra, rb) = (self.find(a), self.find(b));
254        if ra != rb {
255            self.parent[ra] = rb;
256        }
257    }
258}
259
260#[cfg(test)]
261#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/pigeonhole/tests.rs"]
262mod tests;