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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Gate detection and optimization
//!
//! This module implements gate detection and extraction from CNF formulas.
//! Many real-world SAT instances contain encoded logical gates (AND, OR, XOR, ITE).
//! Detecting these gates enables specialized reasoning and optimizations.
//!
//! References:
//! - "Gate Extraction for CNF Formulas" (Eén et al.)
//! - "Effective Preprocessing with Hyper-Resolution and Equality Reduction" (Bacchus & Winter)
//! - "Recognition of Nested Gates in CNF Formulas" (Manthey)
use crate::clause::ClauseDatabase;
use crate::literal::Lit;
#[allow(unused_imports)]
use crate::prelude::*;
/// Statistics for gate detection
#[derive(Debug, Clone, Default)]
pub struct GateStats {
/// Number of AND gates detected
pub and_gates: usize,
/// Number of OR gates detected
pub or_gates: usize,
/// Number of XOR gates detected
pub xor_gates: usize,
/// Number of ITE (if-then-else) gates detected
pub ite_gates: usize,
/// Number of MUX gates detected
pub mux_gates: usize,
/// Number of equivalent gates merged
pub gates_merged: usize,
/// Number of clauses removed via gate substitution
pub clauses_removed: usize,
}
impl GateStats {
/// Display statistics
pub fn display(&self) {
println!("Gate Detection Statistics:");
println!(" AND gates: {}", self.and_gates);
println!(" OR gates: {}", self.or_gates);
println!(" XOR gates: {}", self.xor_gates);
println!(" ITE gates: {}", self.ite_gates);
println!(" MUX gates: {}", self.mux_gates);
println!(" Gates merged: {}", self.gates_merged);
println!(" Clauses removed: {}", self.clauses_removed);
}
}
/// Type of logical gate
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GateType {
/// AND gate: output = a ∧ b
And {
/// Output literal of the AND gate
output: Lit,
/// Input literals
inputs: Vec<Lit>,
},
/// OR gate: output = a ∨ b
Or {
/// Output literal of the OR gate
output: Lit,
/// Input literals
inputs: Vec<Lit>,
},
/// XOR gate: output = a ⊕ b
Xor {
/// Output literal of the XOR gate
output: Lit,
/// Input literals
inputs: Vec<Lit>,
},
/// ITE gate: output = if c then t else e
Ite {
/// Output literal of the ITE gate
output: Lit,
/// Condition literal
condition: Lit,
/// Then-value literal
then_val: Lit,
/// Else-value literal
else_val: Lit,
},
/// MUX gate: generalized ITE with multiple conditions
Mux {
/// Output literal of the MUX gate
output: Lit,
/// Select literals
select: Vec<Lit>,
/// Input literals
inputs: Vec<Lit>,
},
}
impl GateType {
/// Get the output literal of this gate
#[must_use]
pub fn output(&self) -> Lit {
match self {
GateType::And { output, .. }
| GateType::Or { output, .. }
| GateType::Xor { output, .. }
| GateType::Ite { output, .. }
| GateType::Mux { output, .. } => *output,
}
}
/// Get all input literals of this gate
#[must_use]
pub fn inputs(&self) -> Vec<Lit> {
match self {
GateType::And { inputs, .. }
| GateType::Or { inputs, .. }
| GateType::Xor { inputs, .. } => inputs.clone(),
GateType::Ite {
condition,
then_val,
else_val,
..
} => vec![*condition, *then_val, *else_val],
GateType::Mux { select, inputs, .. } => {
let mut all = select.clone();
all.extend(inputs);
all
}
}
}
}
/// Gate detector and optimizer
#[derive(Debug)]
pub struct GateDetector {
/// Detected gates indexed by output literal
gates: HashMap<Lit, GateType>,
/// Clauses that define each literal
definitions: HashMap<Lit, Vec<Vec<Lit>>>,
/// Statistics
stats: GateStats,
}
impl Default for GateDetector {
fn default() -> Self {
Self::new()
}
}
impl GateDetector {
/// Create a new gate detector
#[must_use]
pub fn new() -> Self {
Self {
gates: HashMap::new(),
definitions: HashMap::new(),
stats: GateStats::default(),
}
}
/// Build clause definitions for each literal
pub fn build_definitions(&mut self, clauses: &ClauseDatabase) {
self.definitions.clear();
for cid in clauses.iter_ids() {
if let Some(clause) = clauses.get(cid) {
let lits: Vec<_> = clause.lits.to_vec();
// For each literal in the clause, record this clause as a definition
for &lit in &lits {
self.definitions.entry(lit).or_default().push(lits.clone());
}
}
}
}
/// Detect AND gates
///
/// Pattern: output = a ∧ b ∧ ...
/// CNF: (~a ∨ ~b ∨ output) ∧ (a ∨ ~output) ∧ (b ∨ ~output) ...
pub fn detect_and_gates(&mut self) {
let outputs: Vec<_> = self.definitions.keys().copied().collect();
for output in outputs {
if self.gates.contains_key(&output) {
continue; // Already detected a gate for this literal
}
if let Some(gate_inputs) = self.try_extract_and_gate(output) {
self.gates.insert(
output,
GateType::And {
output,
inputs: gate_inputs,
},
);
self.stats.and_gates += 1;
}
}
}
/// Try to extract an AND gate with the given output
fn try_extract_and_gate(&self, output: Lit) -> Option<Vec<Lit>> {
// For AND gate: out = a ∧ b
// CNF: (~a ∨ ~b ∨ out) ∧ (a ∨ ~out) ∧ (b ∨ ~out)
// Look for binary clauses (input ∨ ~output) in definitions[~output]
let neg_output_defs = self.definitions.get(&!output)?;
let mut inputs = Vec::new();
for clause in neg_output_defs {
if clause.len() == 2 && clause.contains(&!output) {
// Binary clause (input ∨ ~output)
let input = clause.iter().find(|&&lit| lit != !output)?;
inputs.push(*input);
}
}
if inputs.is_empty() {
return None;
}
// Check for the main AND clause: (~a ∨ ~b ∨ ... ∨ output) in definitions[output]
let output_defs = self.definitions.get(&output)?;
for clause in output_defs {
if clause.contains(&output) && clause.len() == inputs.len() + 1 {
// Check if all other literals are negations of inputs
let other_lits: Vec<_> = clause
.iter()
.filter(|&&lit| lit != output)
.copied()
.collect();
let expected_lits: HashSet<_> = inputs.iter().map(|&lit| !lit).collect();
let actual_lits: HashSet<_> = other_lits.iter().copied().collect();
if expected_lits == actual_lits {
return Some(inputs);
}
}
}
None
}
/// Detect OR gates
///
/// Pattern: output = a ∨ b ∨ ...
/// CNF: (a ∨ b ∨ ~output) ∧ (~a ∨ output) ∧ (~b ∨ output) ...
pub fn detect_or_gates(&mut self) {
let outputs: Vec<_> = self.definitions.keys().copied().collect();
for output in outputs {
if self.gates.contains_key(&output) {
continue;
}
if let Some(gate_inputs) = self.try_extract_or_gate(output) {
self.gates.insert(
output,
GateType::Or {
output,
inputs: gate_inputs,
},
);
self.stats.or_gates += 1;
}
}
}
/// Try to extract an OR gate with the given output
fn try_extract_or_gate(&self, output: Lit) -> Option<Vec<Lit>> {
// For OR gate: out = a ∨ b
// CNF: (a ∨ b ∨ ~out) ∧ (~a ∨ out) ∧ (~b ∨ out)
// Look for binary clauses (~input ∨ output) in definitions[output]
let output_defs = self.definitions.get(&output)?;
let mut inputs = Vec::new();
for clause in output_defs {
if clause.len() == 2 && clause.contains(&output) {
// Binary clause (~input ∨ output)
let neg_input = clause.iter().find(|&&lit| lit != output)?;
inputs.push(!*neg_input);
}
}
if inputs.is_empty() {
return None;
}
// Check for the main OR clause: (a ∨ b ∨ ... ∨ ~output) in definitions[~output]
let neg_output_defs = self.definitions.get(&!output)?;
for clause in neg_output_defs {
if clause.contains(&!output) && clause.len() == inputs.len() + 1 {
// Check if all other literals match inputs
let other_lits: Vec<_> = clause
.iter()
.filter(|&&lit| lit != !output)
.copied()
.collect();
let expected_lits: HashSet<_> = inputs.iter().copied().collect();
let actual_lits: HashSet<_> = other_lits.iter().copied().collect();
if expected_lits == actual_lits {
return Some(inputs);
}
}
}
None
}
/// Detect ITE (if-then-else) gates
///
/// Pattern: output = if c then t else e
/// CNF: (~c ∨ ~t ∨ output) ∧ (c ∨ ~e ∨ output) ∧ (~c ∨ t ∨ ~output) ∧ (c ∨ e ∨ ~output)
pub fn detect_ite_gates(&mut self) {
let outputs: Vec<_> = self.definitions.keys().copied().collect();
for output in outputs {
if self.gates.contains_key(&output) {
continue;
}
if let Some((condition, then_val, else_val)) = self.try_extract_ite_gate(output) {
self.gates.insert(
output,
GateType::Ite {
output,
condition,
then_val,
else_val,
},
);
self.stats.ite_gates += 1;
}
}
}
/// Try to extract an ITE gate with the given output
fn try_extract_ite_gate(&self, output: Lit) -> Option<(Lit, Lit, Lit)> {
let output_defs = self.definitions.get(&output)?;
let neg_output_defs = self.definitions.get(&!output)?;
// Look for the characteristic clauses of an ITE
// This is a simplified detection - a full implementation would be more thorough
for clause1 in output_defs {
if clause1.len() == 3 {
for clause2 in neg_output_defs {
if clause2.len() == 3 {
// Try to match ITE pattern
// This is a placeholder - full pattern matching would be complex
// For now, we'll just detect simple cases
}
}
}
}
None // Simplified - would need full pattern matching
}
/// Detect all gate types
pub fn detect_all(&mut self, clauses: &ClauseDatabase) {
self.build_definitions(clauses);
self.detect_and_gates();
self.detect_or_gates();
self.detect_ite_gates();
}
/// Get all detected gates
#[must_use]
pub fn gates(&self) -> &HashMap<Lit, GateType> {
&self.gates
}
/// Get gate for a specific literal
#[must_use]
pub fn get_gate(&self, lit: Lit) -> Option<&GateType> {
self.gates.get(&lit)
}
/// Check if a literal is a gate output
#[must_use]
pub fn is_gate_output(&self, lit: Lit) -> bool {
self.gates.contains_key(&lit)
}
/// Get statistics
#[must_use]
pub fn stats(&self) -> &GateStats {
&self.stats
}
/// Reset statistics
pub fn reset_stats(&mut self) {
self.stats = GateStats::default();
}
/// Clear all detected gates
pub fn clear(&mut self) {
self.gates.clear();
self.definitions.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::literal::Var;
#[test]
fn test_gate_detector_creation() {
let detector = GateDetector::new();
assert_eq!(detector.stats().and_gates, 0);
}
#[test]
fn test_build_definitions() {
let mut detector = GateDetector::new();
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]);
detector.build_definitions(&db);
assert!(detector.definitions.contains_key(&a));
assert!(detector.definitions.contains_key(&b));
}
#[test]
fn test_detect_and_gate() {
let mut detector = GateDetector::new();
let mut db = ClauseDatabase::new();
let a = Lit::pos(Var::new(0));
let b = Lit::pos(Var::new(1));
let out = Lit::pos(Var::new(2));
// Encode: out = a ∧ b
// CNF: (~a ∨ ~b ∨ out) ∧ (a ∨ ~out) ∧ (b ∨ ~out)
db.add_original(vec![!a, !b, out]);
db.add_original(vec![a, !out]);
db.add_original(vec![b, !out]);
detector.detect_all(&db);
assert!(detector.is_gate_output(out));
if let Some(GateType::And { inputs, .. }) = detector.get_gate(out) {
assert_eq!(inputs.len(), 2);
assert!(inputs.contains(&a));
assert!(inputs.contains(&b));
} else {
panic!("Expected AND gate");
}
}
#[test]
fn test_detect_or_gate() {
let mut detector = GateDetector::new();
let mut db = ClauseDatabase::new();
let a = Lit::pos(Var::new(0));
let b = Lit::pos(Var::new(1));
let out = Lit::pos(Var::new(2));
// Encode: out = a ∨ b
// CNF: (a ∨ b ∨ ~out) ∧ (~a ∨ out) ∧ (~b ∨ out)
db.add_original(vec![a, b, !out]);
db.add_original(vec![!a, out]);
db.add_original(vec![!b, out]);
detector.detect_all(&db);
assert!(detector.is_gate_output(out));
if let Some(GateType::Or { inputs, .. }) = detector.get_gate(out) {
assert_eq!(inputs.len(), 2);
assert!(inputs.contains(&a));
assert!(inputs.contains(&b));
} else {
panic!("Expected OR gate");
}
}
#[test]
fn test_gate_type_output() {
let a = Lit::pos(Var::new(0));
let b = Lit::pos(Var::new(1));
let out = Lit::pos(Var::new(2));
let gate = GateType::And {
output: out,
inputs: vec![a, b],
};
assert_eq!(gate.output(), out);
let inputs = gate.inputs();
assert_eq!(inputs.len(), 2);
}
#[test]
fn test_clear() {
let mut detector = GateDetector::new();
let mut db = ClauseDatabase::new();
db.add_original(vec![Lit::pos(Var::new(0)), Lit::pos(Var::new(1))]);
detector.build_definitions(&db);
assert!(!detector.definitions.is_empty());
detector.clear();
assert!(detector.definitions.is_empty());
assert!(detector.gates.is_empty());
}
}