|
| 1 | +//! Not-All-Equal Boolean Satisfiability (NAE-SAT) problem implementation. |
| 2 | +//! |
| 3 | +//! NAE-SAT asks whether a CNF formula has an assignment such that each clause |
| 4 | +//! contains at least one true literal and at least one false literal. |
| 5 | +
|
| 6 | +use crate::registry::{FieldInfo, ProblemSchemaEntry}; |
| 7 | +use crate::traits::{Problem, SatisfactionProblem}; |
| 8 | +use serde::{Deserialize, Serialize}; |
| 9 | + |
| 10 | +use super::CNFClause; |
| 11 | + |
| 12 | +inventory::submit! { |
| 13 | + ProblemSchemaEntry { |
| 14 | + name: "NAESatisfiability", |
| 15 | + display_name: "Not-All-Equal Satisfiability", |
| 16 | + aliases: &["NAESAT"], |
| 17 | + dimensions: &[], |
| 18 | + module_path: module_path!(), |
| 19 | + description: "Find an assignment where every CNF clause has both a true and a false literal", |
| 20 | + fields: &[ |
| 21 | + FieldInfo { name: "num_vars", type_name: "usize", description: "Number of Boolean variables" }, |
| 22 | + FieldInfo { name: "clauses", type_name: "Vec<CNFClause>", description: "Clauses in conjunctive normal form with at least two literals each" }, |
| 23 | + ], |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +/// Not-All-Equal Boolean Satisfiability (NAE-SAT) in CNF form. |
| 28 | +/// |
| 29 | +/// Given a Boolean formula in conjunctive normal form (CNF), determine whether |
| 30 | +/// there exists an assignment such that every clause contains at least one |
| 31 | +/// true literal and at least one false literal. |
| 32 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 33 | +#[serde(try_from = "NAESatisfiabilityDef")] |
| 34 | +pub struct NAESatisfiability { |
| 35 | + /// Number of variables. |
| 36 | + num_vars: usize, |
| 37 | + /// Clauses in CNF, each with at least two literals. |
| 38 | + clauses: Vec<CNFClause>, |
| 39 | +} |
| 40 | + |
| 41 | +impl NAESatisfiability { |
| 42 | + /// Create a new NAE-SAT problem. |
| 43 | + /// |
| 44 | + /// # Panics |
| 45 | + /// Panics if any clause has fewer than two literals. |
| 46 | + pub fn new(num_vars: usize, clauses: Vec<CNFClause>) -> Self { |
| 47 | + Self::try_new(num_vars, clauses).unwrap_or_else(|err| panic!("{err}")) |
| 48 | + } |
| 49 | + |
| 50 | + /// Create a new NAE-SAT problem, returning an error instead of panicking |
| 51 | + /// when a clause has fewer than two literals. |
| 52 | + pub fn try_new(num_vars: usize, clauses: Vec<CNFClause>) -> Result<Self, String> { |
| 53 | + validate_clause_lengths(&clauses)?; |
| 54 | + Ok(Self { num_vars, clauses }) |
| 55 | + } |
| 56 | + |
| 57 | + /// Get the number of variables. |
| 58 | + pub fn num_vars(&self) -> usize { |
| 59 | + self.num_vars |
| 60 | + } |
| 61 | + |
| 62 | + /// Get the number of clauses. |
| 63 | + pub fn num_clauses(&self) -> usize { |
| 64 | + self.clauses.len() |
| 65 | + } |
| 66 | + |
| 67 | + /// Get the total number of literal occurrences across all clauses. |
| 68 | + pub fn num_literals(&self) -> usize { |
| 69 | + self.clauses.iter().map(|c| c.len()).sum() |
| 70 | + } |
| 71 | + |
| 72 | + /// Get the clauses. |
| 73 | + pub fn clauses(&self) -> &[CNFClause] { |
| 74 | + &self.clauses |
| 75 | + } |
| 76 | + |
| 77 | + /// Get a specific clause. |
| 78 | + pub fn get_clause(&self, index: usize) -> Option<&CNFClause> { |
| 79 | + self.clauses.get(index) |
| 80 | + } |
| 81 | + |
| 82 | + /// Count how many clauses satisfy the NAE condition under an assignment. |
| 83 | + pub fn count_nae_satisfied(&self, assignment: &[bool]) -> usize { |
| 84 | + self.clauses |
| 85 | + .iter() |
| 86 | + .filter(|clause| Self::clause_is_nae_satisfied(clause, assignment)) |
| 87 | + .count() |
| 88 | + } |
| 89 | + |
| 90 | + /// Check whether all clauses satisfy the NAE condition under an assignment. |
| 91 | + pub fn is_nae_satisfying(&self, assignment: &[bool]) -> bool { |
| 92 | + self.clauses |
| 93 | + .iter() |
| 94 | + .all(|clause| Self::clause_is_nae_satisfied(clause, assignment)) |
| 95 | + } |
| 96 | + |
| 97 | + /// Check if a solution (config) is valid. |
| 98 | + pub fn is_valid_solution(&self, config: &[usize]) -> bool { |
| 99 | + self.evaluate(config) |
| 100 | + } |
| 101 | + |
| 102 | + fn config_to_assignment(config: &[usize]) -> Vec<bool> { |
| 103 | + config.iter().map(|&v| v == 1).collect() |
| 104 | + } |
| 105 | + |
| 106 | + fn literal_value(lit: i32, assignment: &[bool]) -> bool { |
| 107 | + let var = lit.unsigned_abs() as usize - 1; |
| 108 | + let value = assignment.get(var).copied().unwrap_or(false); |
| 109 | + if lit > 0 { |
| 110 | + value |
| 111 | + } else { |
| 112 | + !value |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + fn clause_is_nae_satisfied(clause: &CNFClause, assignment: &[bool]) -> bool { |
| 117 | + let mut has_true = false; |
| 118 | + let mut has_false = false; |
| 119 | + |
| 120 | + for &lit in &clause.literals { |
| 121 | + if Self::literal_value(lit, assignment) { |
| 122 | + has_true = true; |
| 123 | + } else { |
| 124 | + has_false = true; |
| 125 | + } |
| 126 | + |
| 127 | + if has_true && has_false { |
| 128 | + return true; |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + false |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +impl Problem for NAESatisfiability { |
| 137 | + const NAME: &'static str = "NAESatisfiability"; |
| 138 | + type Metric = bool; |
| 139 | + |
| 140 | + fn dims(&self) -> Vec<usize> { |
| 141 | + vec![2; self.num_vars] |
| 142 | + } |
| 143 | + |
| 144 | + fn evaluate(&self, config: &[usize]) -> bool { |
| 145 | + let assignment = Self::config_to_assignment(config); |
| 146 | + self.is_nae_satisfying(&assignment) |
| 147 | + } |
| 148 | + |
| 149 | + fn variant() -> Vec<(&'static str, &'static str)> { |
| 150 | + crate::variant_params![] |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +impl SatisfactionProblem for NAESatisfiability {} |
| 155 | + |
| 156 | +crate::declare_variants! { |
| 157 | + default sat NAESatisfiability => "2^num_variables", |
| 158 | +} |
| 159 | + |
| 160 | +#[derive(Debug, Clone, Deserialize)] |
| 161 | +struct NAESatisfiabilityDef { |
| 162 | + num_vars: usize, |
| 163 | + clauses: Vec<CNFClause>, |
| 164 | +} |
| 165 | + |
| 166 | +impl TryFrom<NAESatisfiabilityDef> for NAESatisfiability { |
| 167 | + type Error = String; |
| 168 | + |
| 169 | + fn try_from(value: NAESatisfiabilityDef) -> Result<Self, Self::Error> { |
| 170 | + Self::try_new(value.num_vars, value.clauses) |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +fn validate_clause_lengths(clauses: &[CNFClause]) -> Result<(), String> { |
| 175 | + for (index, clause) in clauses.iter().enumerate() { |
| 176 | + if clause.len() < 2 { |
| 177 | + return Err(format!( |
| 178 | + "Clause {} has {} literals, expected at least 2", |
| 179 | + index, |
| 180 | + clause.len() |
| 181 | + )); |
| 182 | + } |
| 183 | + } |
| 184 | + Ok(()) |
| 185 | +} |
| 186 | + |
| 187 | +#[cfg(feature = "example-db")] |
| 188 | +pub(crate) fn canonical_model_example_specs() -> Vec<crate::example_db::specs::ModelExampleSpec> { |
| 189 | + vec![crate::example_db::specs::ModelExampleSpec { |
| 190 | + id: "nae_satisfiability", |
| 191 | + instance: Box::new(NAESatisfiability::new( |
| 192 | + 5, |
| 193 | + vec![ |
| 194 | + CNFClause::new(vec![1, 2, -3]), |
| 195 | + CNFClause::new(vec![-1, 3, 4]), |
| 196 | + CNFClause::new(vec![2, -4, 5]), |
| 197 | + CNFClause::new(vec![-2, 3, -5]), |
| 198 | + CNFClause::new(vec![1, -3, 5]), |
| 199 | + ], |
| 200 | + )), |
| 201 | + optimal_config: vec![0, 0, 0, 1, 1], |
| 202 | + optimal_value: serde_json::json!(true), |
| 203 | + }] |
| 204 | +} |
| 205 | + |
| 206 | +#[cfg(test)] |
| 207 | +#[path = "../../unit_tests/models/formula/nae_satisfiability.rs"] |
| 208 | +mod tests; |
0 commit comments