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
//! A `Theory` is a set of alternative `PropositionalFormula`s, which corresponds to a branch in a
//! tableau tree.

use std::collections::{HashMap, HashSet};

use crate::formula::PropositionalFormula;

use log::debug;

/// A `Theory` is a set of alternative `PropositionalFormula`s.
///
/// It corresponds to one particular branch of the tableau tree.
#[derive(Debug, PartialEq, Clone)]
pub struct Theory {
	formulas: HashSet<PropositionalFormula>,
}

impl Theory {
	/// Construct an empty theory.
	pub fn new() -> Self {
		Self {
			formulas: HashSet::new(),
		}
	}

	/// Construct a `Theory` from a given propositional formula.
	pub fn from_propositional_formula(formula: PropositionalFormula) -> Self {
		let mut formulas: HashSet<PropositionalFormula> = HashSet::new();
		formulas.insert(formula);

		Self { formulas }
	}

	/// Get the formulas.
	pub fn formulas(&self) -> impl Iterator<Item = &PropositionalFormula> {
		self.formulas.iter()
	}

	/// Add a propositional formula to the theory iff the theory does not already contain the
	/// formula.
	pub fn add(&mut self, formula: PropositionalFormula) {
		self.formulas.insert(formula);
	}

	/// Checks if the `Theory` is _fully expanded_, i.e. each propositional_formula in the given
	/// `Theory` is a _literal_ (e.g. `p`, `-(p)`, a propositional variable or its negation).
	pub fn is_fully_expanded(&self) -> bool {
		self.formulas.iter().all(PropositionalFormula::is_literal)
	}

	/// Checks if a `Theory` contains _contradictions_. That is, if the `Theory` contains a literal
	/// `p` AND its negation `-p`.
	///
	/// # Space and Time Complexity
	///
	/// This function uses a [`HashMap`] (specifically, a map from some `&str` to the tuple
	/// `(has_literal, has_negation): (bool, bool)`. As soon as we encounter the case where
	/// `has_literal && has_negation` then we have found a _contradiction_.
	///
	/// - Worst-case time complexity: `O(n)` because we iterate through all of the formulas
	///   for the given theory.
	/// - Worst-case space complexity: `O(k)` for `k` propositional variables appearing in literals.
	///
	/// [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
	pub fn has_contradictions(&self) -> bool {
		// Mapping from the variable name `&str` to `(has_literal, has_negation)`.
		let mut literal_occurrence_map: HashMap<&str, (bool, bool)> = HashMap::new();

		for formula in &self.formulas {
			if self.check_formula(formula, &mut literal_occurrence_map) {
				return true;
			}
		}

		debug!("for the formulas:\n{:#?}", &self.formulas);
		debug!("construct the HashSet:\n{:#?}", &literal_occurrence_map);
		debug!("the theory contains no contradictions:\n{:#?}", &self);

		// We've gone through the entire collection of formulas in the `Theory` and did not find any
		// contradictions.
		false
	}

	fn check_formula<'a>(
		&self,
		formula: &'a PropositionalFormula,
		literal_occurrence_map: &mut HashMap<&'a str, (bool, bool)>,
	) -> bool {
		match formula {
			PropositionalFormula::Variable(v) => {
				if let Some((has_literal, has_negation)) = literal_occurrence_map.get_mut(v.name())
				{
					if *has_negation {
						// We've already seen the negated literal, and now we have the literal, so
						// we've found a contradiction.
						true
					} else {
						*has_literal = true;
						false
					}
				} else {
					literal_occurrence_map.insert(v.name(), (true, false));
					false
				}
			}
			PropositionalFormula::Negation(Some(f)) => match &**f {
				PropositionalFormula::Variable(v) => {
					if let Some((has_literal, has_negation)) =
						literal_occurrence_map.get_mut(v.name())
					{
						if *has_literal {
							// We've already seen the literal, and now we have the negation, so
							// we've found a contradiction.
							true
						} else {
							*has_negation = true;
							false
						}
					} else {
						literal_occurrence_map.insert(v.name(), (false, true));
						false
					}
				}
				PropositionalFormula::Negation(Some(ref g)) => {
					// Now (-(-A)) == A so we've covered the base cases and we can simply
					// recursively call `self.check_formula()` to handle the inductive cases with
					// deeply nested negated literals.
					self.check_formula(g, literal_occurrence_map)
				}
				_ => false,
			},
			_ => false,
		}
	}

	/// Get a non-literal formula (not a propositional variable or its negation) from the current
	/// `Theory`.
	pub fn get_non_literal_formula(&mut self) -> Option<PropositionalFormula> {
		self.formulas.iter().cloned().find(|f| !f.is_literal())
	}

	/// Replace existing formula with a new formula.
	pub fn swap_formula(
		&mut self,
		existing: &PropositionalFormula,
		replacement: PropositionalFormula,
	) {
		if self.formulas.remove(existing) {
			self.formulas.insert(replacement);
		}
	}

	/// Replace existing formula with two new formulas.
	pub fn swap_formula2(
		&mut self,
		existing: &PropositionalFormula,
		replacements: (PropositionalFormula, PropositionalFormula),
	) {
		if self.formulas.remove(existing) {
			self.formulas.insert(replacements.0);
			self.formulas.insert(replacements.1);
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::formula::Variable;
	use assert2::check;

	#[test]
	fn test_construction() {
		let theory =
			Theory::from_propositional_formula(PropositionalFormula::variable(Variable::new("a")));

		check!(theory.formulas().count() == 1);
	}

	#[test]
	fn test_get_formulas() {
		let formula_1 = PropositionalFormula::variable(Variable::new("a"));
		let formula_2 = PropositionalFormula::variable(Variable::new("b"));

		let mut theory = Theory::new();
		theory.add(formula_1);
		theory.add(formula_2);

		check!(theory.formulas().count() == 2);
	}

	#[test]
	fn test_add_fresh_formula() {
		let formula_1 = PropositionalFormula::variable(Variable::new("a"));

		let mut theory = Theory::new();
		check!(theory.formulas().count() == 0);

		theory.add(formula_1);
		check!(theory.formulas().count() == 1);
	}

	#[test]
	fn test_add_duplicate_formula() {
		let formula_1 = PropositionalFormula::variable(Variable::new("a"));

		let mut theory = Theory::new();
		check!(theory.formulas().count() == 0);

		theory.add(formula_1.clone());
		check!(theory.formulas().count() == 1);

		theory.add(formula_1.clone());
		check!(theory.formulas().count() == 1);
	}

	#[test]
	fn test_all_fully_expanded() {
		let formula_1 = PropositionalFormula::variable(Variable::new("a"));
		let formula_2 = PropositionalFormula::negated(Box::new(PropositionalFormula::variable(
			Variable::new("b"),
		)));
		let formula_3 = PropositionalFormula::variable(Variable::new("a"));

		let mut theory = Theory::new();
		theory.add(formula_1);
		theory.add(formula_2);
		theory.add(formula_3);

		check!(theory.is_fully_expanded());
	}

	#[test]
	fn test_partially_expanded() {
		let formula_1 = PropositionalFormula::variable(Variable::new("a"));
		let formula_2 = PropositionalFormula::negated(Box::new(PropositionalFormula::conjunction(
			Box::new(PropositionalFormula::variable(Variable::new("b"))),
			Box::new(PropositionalFormula::variable(Variable::new("c"))),
		)));
		let formula_3 = PropositionalFormula::variable(Variable::new("d"));

		let mut theory = Theory::new();
		theory.add(formula_1);
		theory.add(formula_2);
		theory.add(formula_3);

		check!(!theory.is_fully_expanded());
	}

	#[test]
	fn test_none_fully_expanded() {
		let formula_1 =
			PropositionalFormula::negated(Box::new(PropositionalFormula::biimplication(
				Box::new(PropositionalFormula::variable(Variable::new("e"))),
				Box::new(PropositionalFormula::variable(Variable::new("a"))),
			)));
		let formula_2 = PropositionalFormula::negated(Box::new(PropositionalFormula::conjunction(
			Box::new(PropositionalFormula::variable(Variable::new("b"))),
			Box::new(PropositionalFormula::variable(Variable::new("c"))),
		)));
		let formula_3 = PropositionalFormula::negated(Box::new(PropositionalFormula::negated(
			Box::new(PropositionalFormula::variable(Variable::new("f"))),
		)));

		let mut theory = Theory::new();
		theory.add(formula_1);
		theory.add(formula_2);
		theory.add(formula_3);

		check!(!theory.is_fully_expanded());
	}

	#[test]
	fn test_simple_has_contradictions() {
		let literal_a = PropositionalFormula::variable(Variable::new("a"));
		let negated_literal_a = PropositionalFormula::negated(Box::new(literal_a.clone()));

		let mut theory = Theory::new();
		theory.add(literal_a);
		theory.add(negated_literal_a);

		check!(theory.has_contradictions());
	}

	#[test]
	fn test_simple_has_no_contradictions() {
		let literal_a = PropositionalFormula::variable(Variable::new("a"));
		let literal_b = PropositionalFormula::variable(Variable::new("b"));

		let mut theory = Theory::new();
		theory.add(literal_a);
		theory.add(literal_b);

		check!(!theory.has_contradictions());
	}

	#[test]
	fn test_complex_has_contradictions() {
		let literal_a = PropositionalFormula::variable(Variable::new("a"));
		let non_literal_1 =
			PropositionalFormula::negated(Box::new(PropositionalFormula::conjunction(
				Box::new(PropositionalFormula::variable(Variable::new("b"))),
				Box::new(PropositionalFormula::variable(Variable::new("c"))),
			)));
		let literal_d = PropositionalFormula::variable(Variable::new("d"));
		let negated_literal_a = PropositionalFormula::negated(Box::new(
			PropositionalFormula::variable(Variable::new("a")),
		));

		let mut theory = Theory::new();
		theory.add(literal_a);
		theory.add(non_literal_1);
		theory.add(literal_d);
		theory.add(negated_literal_a);

		check!(theory.has_contradictions());
	}

	#[test]
	fn test_complex_has_no_contradictions() {
		let literal_a = PropositionalFormula::variable(Variable::new("a"));
		let non_literal_1 =
			PropositionalFormula::negated(Box::new(PropositionalFormula::conjunction(
				Box::new(PropositionalFormula::variable(Variable::new("b"))),
				Box::new(PropositionalFormula::variable(Variable::new("c"))),
			)));
		let literal_d = PropositionalFormula::variable(Variable::new("d"));
		let negated_literal_f = PropositionalFormula::negated(Box::new(
			PropositionalFormula::variable(Variable::new("f")),
		));

		let mut theory = Theory::new();
		theory.add(literal_a);
		theory.add(non_literal_1);
		theory.add(literal_d);
		theory.add(negated_literal_f);

		check!(!theory.has_contradictions());
	}

	#[test]
	fn test_double_negation_no_contradiction() {
		// { a, --a } should have no contradictions
		let literal_a = PropositionalFormula::variable(Variable::new("a"));
		let double_negated_literal_a =
			PropositionalFormula::negated(Box::new(PropositionalFormula::negated(Box::new(
				PropositionalFormula::variable(Variable::new("a")),
			))));

		let mut theory = Theory::new();
		theory.add(literal_a);
		theory.add(double_negated_literal_a);

		check!(!theory.has_contradictions());
	}

	#[test]
	fn test_recursive_negation_no_contradictions() {
		// { -a, ---a } should have no contradictions
		let negated_literal_a = PropositionalFormula::negated(Box::new(
			PropositionalFormula::variable(Variable::new("a")),
		));
		let triple_negated_literal_a = PropositionalFormula::negated(Box::new(
			PropositionalFormula::negated(Box::new(PropositionalFormula::negated(Box::new(
				PropositionalFormula::variable(Variable::new("a")),
			)))),
		));

		let mut theory = Theory::new();
		theory.add(negated_literal_a);
		theory.add(triple_negated_literal_a);

		check!(!theory.has_contradictions());
	}

	#[test]
	fn test_recursive_negation_has_contradictions() {
		// { -a, ----a } should have contradictions
		let negated_literal_a = PropositionalFormula::negated(Box::new(
			PropositionalFormula::variable(Variable::new("a")),
		));
		let quad_negated_literal_a =
			PropositionalFormula::negated(Box::new(PropositionalFormula::negated(Box::new(
				PropositionalFormula::negated(Box::new(PropositionalFormula::negated(Box::new(
					PropositionalFormula::variable(Variable::new("a")),
				)))),
			))));

		let mut theory = Theory::new();
		theory.add(negated_literal_a);
		theory.add(quad_negated_literal_a);

		check!(theory.has_contradictions());
	}
}