oxiz-sat 0.2.0

High-performance CDCL SAT Solver for OxiZ
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Binary Implication Graph (BIG) optimization
//!
//! This module implements optimizations for the binary implication graph,
//! including transitive reduction to remove redundant binary clauses and
//! strongly connected component detection for equivalence finding.
//!
//! The binary implication graph represents binary clauses as implications:
//! - Binary clause (a v b) represents two implications: ~a => b and ~b => a
//!
//! References:
//! - "Binary Clause Reasoning in Conflict-Driven Clause Learning" (Bacchus)
//! - "Effective Preprocessing in SAT" (Eén & Biere)
//! - "Bounded Variable Elimination" (Subbarayan & Pradhan)

use crate::clause::ClauseDatabase;
use crate::literal::Lit;
#[allow(unused_imports)]
use crate::prelude::*;

/// Statistics for BIG optimization
#[derive(Debug, Clone, Default)]
pub struct BigStats {
    /// Number of binary clauses analyzed
    pub binary_clauses_analyzed: usize,
    /// Number of redundant binary clauses removed
    pub redundant_removed: usize,
    /// Number of transitive implications found
    pub transitive_found: usize,
    /// Number of SCCs detected
    pub sccs_found: usize,
    /// Number of equivalent literal pairs from SCCs
    pub equivalences_from_sccs: usize,
}

impl BigStats {
    /// Display statistics
    pub fn display(&self) {
        println!("Binary Implication Graph Statistics:");
        println!(
            "  Binary clauses analyzed: {}",
            self.binary_clauses_analyzed
        );
        println!("  Redundant clauses removed: {}", self.redundant_removed);
        println!("  Transitive implications: {}", self.transitive_found);
        println!("  SCCs found: {}", self.sccs_found);
        println!("  Equivalences from SCCs: {}", self.equivalences_from_sccs);
    }
}

/// Binary Implication Graph optimizer
#[derive(Debug)]
pub struct BinaryImplicationGraph {
    /// Adjacency list: implications[lit] = literals implied by lit
    implications: Vec<HashSet<Lit>>,
    /// Reverse adjacency list for SCC detection
    reverse_implications: Vec<HashSet<Lit>>,
    /// Statistics
    stats: BigStats,
}

impl BinaryImplicationGraph {
    /// Create a new BIG optimizer
    #[must_use]
    pub fn new(num_vars: usize) -> Self {
        let size = num_vars * 2;
        Self {
            implications: vec![HashSet::new(); size],
            reverse_implications: vec![HashSet::new(); size],
            stats: BigStats::default(),
        }
    }

    /// Build the implication graph from clause database
    pub fn build(&mut self, clauses: &ClauseDatabase) {
        // Clear existing data
        for imp in &mut self.implications {
            imp.clear();
        }
        for imp in &mut self.reverse_implications {
            imp.clear();
        }
        self.stats.binary_clauses_analyzed = 0;

        // Extract binary clauses
        for cid in clauses.iter_ids() {
            if let Some(clause) = clauses.get(cid)
                && clause.len() == 2
            {
                self.stats.binary_clauses_analyzed += 1;

                let a = clause.lits[0];
                let b = clause.lits[1];

                // Binary clause (a v b) means: ~a => b and ~b => a
                self.add_implication(!a, b);
                self.add_implication(!b, a);
            }
        }
    }

    /// Add a binary implication to the graph
    fn add_implication(&mut self, from: Lit, to: Lit) {
        let from_idx = from.code() as usize;
        let to_idx = to.code() as usize;

        // Ensure capacity
        while from_idx >= self.implications.len() {
            self.implications.push(HashSet::new());
            self.reverse_implications.push(HashSet::new());
        }
        while to_idx >= self.implications.len() {
            self.implications.push(HashSet::new());
            self.reverse_implications.push(HashSet::new());
        }

        self.implications[from_idx].insert(to);
        self.reverse_implications[to_idx].insert(from);
    }

    /// Perform transitive reduction to remove redundant implications
    ///
    /// An edge a => c is redundant if there exists a path a => b => c
    pub fn transitive_reduction(&mut self) -> Vec<(Lit, Lit)> {
        let mut redundant = Vec::new();
        let num_lits = self.implications.len();

        for lit_idx in 0..num_lits {
            let lit = Lit::from_code(lit_idx as u32);
            let direct_implications: Vec<_> = self.implications[lit_idx].iter().copied().collect();

            for &implied in &direct_implications {
                // Check if there's an alternative path from lit to implied
                if self.has_alternative_path(lit, implied) {
                    redundant.push((lit, implied));
                    self.stats.redundant_removed += 1;
                }
            }
        }

        // Remove redundant edges
        for (from, to) in &redundant {
            let from_idx = from.code() as usize;
            let to_idx = to.code() as usize;
            self.implications[from_idx].remove(to);
            self.reverse_implications[to_idx].remove(from);
        }

        redundant
    }

    /// Check if there's a path from 'from' to 'to' without using the direct edge
    fn has_alternative_path(&self, from: Lit, to: Lit) -> bool {
        let from_idx = from.code() as usize;
        if from_idx >= self.implications.len() {
            return false;
        }

        let mut visited = HashSet::new();
        let mut queue = Vec::new();

        // Start BFS from literals implied by 'from', excluding direct edge to 'to'
        for &implied in &self.implications[from_idx] {
            if implied != to {
                queue.push(implied);
            }
        }

        while let Some(lit) = queue.pop() {
            if lit == to {
                return true; // Found alternative path
            }

            let lit_idx = lit.code() as usize;
            if visited.contains(&lit_idx) || lit_idx >= self.implications.len() {
                continue;
            }

            visited.insert(lit_idx);

            for &next in &self.implications[lit_idx] {
                if !visited.contains(&(next.code() as usize)) {
                    queue.push(next);
                }
            }
        }

        false
    }

    /// Detect strongly connected components using Tarjan's algorithm
    ///
    /// Literals in the same SCC are equivalent (mutual implication)
    #[allow(dead_code)]
    pub fn find_sccs(&mut self) -> Vec<Vec<Lit>> {
        let num_lits = self.implications.len();
        let mut index = vec![None; num_lits];
        let mut lowlink = vec![0; num_lits];
        let mut on_stack = vec![false; num_lits];
        let mut stack = Vec::new();
        let mut sccs = Vec::new();
        let mut current_index = 0;

        for lit_idx in 0..num_lits {
            if index[lit_idx].is_none() {
                self.tarjan_scc(
                    lit_idx,
                    &mut index,
                    &mut lowlink,
                    &mut on_stack,
                    &mut stack,
                    &mut sccs,
                    &mut current_index,
                );
            }
        }

        // Filter out trivial SCCs (single nodes)
        self.stats.sccs_found = sccs.iter().filter(|scc| scc.len() > 1).count();
        sccs.into_iter().filter(|scc| scc.len() > 1).collect()
    }

    /// Tarjan's SCC algorithm helper
    #[allow(clippy::too_many_arguments)]
    fn tarjan_scc(
        &self,
        lit_idx: usize,
        index: &mut Vec<Option<usize>>,
        lowlink: &mut Vec<usize>,
        on_stack: &mut Vec<bool>,
        stack: &mut Vec<usize>,
        sccs: &mut Vec<Vec<Lit>>,
        current_index: &mut usize,
    ) {
        index[lit_idx] = Some(*current_index);
        lowlink[lit_idx] = *current_index;
        *current_index += 1;
        stack.push(lit_idx);
        on_stack[lit_idx] = true;

        // Consider successors
        if lit_idx < self.implications.len() {
            for &implied in &self.implications[lit_idx] {
                let impl_idx = implied.code() as usize;

                if index[impl_idx].is_none() {
                    self.tarjan_scc(
                        impl_idx,
                        index,
                        lowlink,
                        on_stack,
                        stack,
                        sccs,
                        current_index,
                    );
                    lowlink[lit_idx] = lowlink[lit_idx].min(lowlink[impl_idx]);
                } else if on_stack[impl_idx] {
                    lowlink[lit_idx] = lowlink[lit_idx]
                        .min(index[impl_idx].expect("index set when on_stack is true"));
                }
            }
        }

        // If lit_idx is a root node, pop the stack to form an SCC
        if lowlink[lit_idx] == index[lit_idx].expect("index set for lit_idx in SCC") {
            let mut scc = Vec::new();
            loop {
                let node = stack.pop().expect("stack non-empty in SCC formation");
                on_stack[node] = false;
                scc.push(Lit::from_code(node as u32));
                if node == lit_idx {
                    break;
                }
            }
            sccs.push(scc);
        }
    }

    /// Apply BIG optimizations to clause database
    ///
    /// Removes redundant binary clauses found through transitive reduction
    pub fn optimize(&mut self, clauses: &mut ClauseDatabase) {
        // Build the graph
        self.build(clauses);

        // Perform transitive reduction
        let redundant = self.transitive_reduction();

        // Remove redundant binary clauses from database
        let clause_ids: Vec<_> = clauses.iter_ids().collect();
        for cid in clause_ids {
            if let Some(clause) = clauses.get(cid)
                && clause.len() == 2
            {
                let a = clause.lits[0];
                let b = clause.lits[1];

                // Check if this binary clause is redundant
                if redundant.contains(&(!a, b)) || redundant.contains(&(!b, a)) {
                    clauses.remove(cid);
                }
            }
        }
    }

    /// Get all implications for a literal
    #[must_use]
    pub fn get_implications(&self, lit: Lit) -> Vec<Lit> {
        let idx = lit.code() as usize;
        if idx < self.implications.len() {
            self.implications[idx].iter().copied().collect()
        } else {
            Vec::new()
        }
    }

    /// Check if literal a implies literal b
    #[must_use]
    pub fn implies(&self, a: Lit, b: Lit) -> bool {
        let idx = a.code() as usize;
        if idx < self.implications.len() {
            self.implications[idx].contains(&b)
        } else {
            false
        }
    }

    /// Get statistics
    #[must_use]
    pub fn stats(&self) -> &BigStats {
        &self.stats
    }

    /// Reset statistics
    pub fn reset_stats(&mut self) {
        self.stats = BigStats::default();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::literal::Var;

    #[test]
    fn test_big_creation() {
        let big = BinaryImplicationGraph::new(10);
        assert_eq!(big.stats().binary_clauses_analyzed, 0);
    }

    #[test]
    fn test_build_from_clauses() {
        let mut big = BinaryImplicationGraph::new(10);
        let mut db = ClauseDatabase::new();

        let a = Lit::pos(Var::new(0));
        let b = Lit::pos(Var::new(1));

        db.add_original(vec![a, b]);
        big.build(&db);

        assert_eq!(big.stats().binary_clauses_analyzed, 1);
        // Should have implications: ~a => b and ~b => a
        assert!(big.implies(!a, b));
        assert!(big.implies(!b, a));
    }

    #[test]
    fn test_transitive_reduction() {
        let mut big = BinaryImplicationGraph::new(10);

        let a = Lit::pos(Var::new(0));
        let b = Lit::pos(Var::new(1));
        let c = Lit::pos(Var::new(2));

        // Add: a => b, b => c, a => c (last one is redundant)
        big.add_implication(a, b);
        big.add_implication(b, c);
        big.add_implication(a, c);

        let redundant = big.transitive_reduction();

        // Should find a => c as redundant
        assert!(!redundant.is_empty());
        assert!(redundant.contains(&(a, c)));
    }

    #[test]
    fn test_find_sccs() {
        let mut big = BinaryImplicationGraph::new(10);

        let a = Lit::pos(Var::new(0));
        let b = Lit::pos(Var::new(1));

        // Create a cycle: a => b, b => a (they're equivalent)
        big.add_implication(a, b);
        big.add_implication(b, a);

        let sccs = big.find_sccs();

        // Should find one SCC containing a and b
        assert!(!sccs.is_empty());
        let scc = &sccs[0];
        assert!(scc.contains(&a));
        assert!(scc.contains(&b));
    }

    #[test]
    fn test_get_implications() {
        let mut big = BinaryImplicationGraph::new(10);

        let a = Lit::pos(Var::new(0));
        let b = Lit::pos(Var::new(1));

        big.add_implication(a, b);

        let implications = big.get_implications(a);
        assert!(implications.contains(&b));
    }

    #[test]
    fn test_optimize() {
        let mut big = BinaryImplicationGraph::new(10);
        let mut db = ClauseDatabase::new();

        let a = Lit::pos(Var::new(0));
        let b = Lit::pos(Var::new(1));
        let c = Lit::pos(Var::new(2));

        // Add three binary clauses creating redundancy
        db.add_original(vec![a, b]); // ~a => b
        db.add_original(vec![b, c]); // ~b => c
        db.add_original(vec![a, c]); // ~a => c (redundant)

        let before = db.len();
        big.optimize(&mut db);
        let after = db.len();

        // Should have removed at least one redundant clause
        assert!(after <= before);
    }
}