resolution.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. # Natural Language Toolkit: First-order Resolution-based Theorem Prover
  2. #
  3. # Author: Dan Garrette <dhgarrette@gmail.com>
  4. #
  5. # Copyright (C) 2001-2020 NLTK Project
  6. # URL: <http://nltk.org>
  7. # For license information, see LICENSE.TXT
  8. """
  9. Module for a resolution-based First Order theorem prover.
  10. """
  11. import operator
  12. from collections import defaultdict
  13. from functools import reduce
  14. from nltk.sem import skolemize
  15. from nltk.sem.logic import (
  16. VariableExpression,
  17. EqualityExpression,
  18. ApplicationExpression,
  19. Expression,
  20. NegatedExpression,
  21. Variable,
  22. AndExpression,
  23. unique_variable,
  24. OrExpression,
  25. is_indvar,
  26. IndividualVariableExpression,
  27. Expression,
  28. )
  29. from nltk.inference.api import Prover, BaseProverCommand
  30. class ProverParseError(Exception):
  31. pass
  32. class ResolutionProver(Prover):
  33. ANSWER_KEY = "ANSWER"
  34. _assume_false = True
  35. def _prove(self, goal=None, assumptions=None, verbose=False):
  36. """
  37. :param goal: Input expression to prove
  38. :type goal: sem.Expression
  39. :param assumptions: Input expressions to use as assumptions in the proof
  40. :type assumptions: list(sem.Expression)
  41. """
  42. if not assumptions:
  43. assumptions = []
  44. result = None
  45. try:
  46. clauses = []
  47. if goal:
  48. clauses.extend(clausify(-goal))
  49. for a in assumptions:
  50. clauses.extend(clausify(a))
  51. result, clauses = self._attempt_proof(clauses)
  52. if verbose:
  53. print(ResolutionProverCommand._decorate_clauses(clauses))
  54. except RuntimeError as e:
  55. if self._assume_false and str(e).startswith(
  56. "maximum recursion depth exceeded"
  57. ):
  58. result = False
  59. clauses = []
  60. else:
  61. if verbose:
  62. print(e)
  63. else:
  64. raise e
  65. return (result, clauses)
  66. def _attempt_proof(self, clauses):
  67. # map indices to lists of indices, to store attempted unifications
  68. tried = defaultdict(list)
  69. i = 0
  70. while i < len(clauses):
  71. if not clauses[i].is_tautology():
  72. # since we try clauses in order, we should start after the last
  73. # index tried
  74. if tried[i]:
  75. j = tried[i][-1] + 1
  76. else:
  77. j = i + 1 # nothing tried yet for 'i', so start with the next
  78. while j < len(clauses):
  79. # don't: 1) unify a clause with itself,
  80. # 2) use tautologies
  81. if i != j and j and not clauses[j].is_tautology():
  82. tried[i].append(j)
  83. newclauses = clauses[i].unify(clauses[j])
  84. if newclauses:
  85. for newclause in newclauses:
  86. newclause._parents = (i + 1, j + 1)
  87. clauses.append(newclause)
  88. if not len(newclause): # if there's an empty clause
  89. return (True, clauses)
  90. i = -1 # since we added a new clause, restart from the top
  91. break
  92. j += 1
  93. i += 1
  94. return (False, clauses)
  95. class ResolutionProverCommand(BaseProverCommand):
  96. def __init__(self, goal=None, assumptions=None, prover=None):
  97. """
  98. :param goal: Input expression to prove
  99. :type goal: sem.Expression
  100. :param assumptions: Input expressions to use as assumptions in
  101. the proof.
  102. :type assumptions: list(sem.Expression)
  103. """
  104. if prover is not None:
  105. assert isinstance(prover, ResolutionProver)
  106. else:
  107. prover = ResolutionProver()
  108. BaseProverCommand.__init__(self, prover, goal, assumptions)
  109. self._clauses = None
  110. def prove(self, verbose=False):
  111. """
  112. Perform the actual proof. Store the result to prevent unnecessary
  113. re-proving.
  114. """
  115. if self._result is None:
  116. self._result, clauses = self._prover._prove(
  117. self.goal(), self.assumptions(), verbose
  118. )
  119. self._clauses = clauses
  120. self._proof = ResolutionProverCommand._decorate_clauses(clauses)
  121. return self._result
  122. def find_answers(self, verbose=False):
  123. self.prove(verbose)
  124. answers = set()
  125. answer_ex = VariableExpression(Variable(ResolutionProver.ANSWER_KEY))
  126. for clause in self._clauses:
  127. for term in clause:
  128. if (
  129. isinstance(term, ApplicationExpression)
  130. and term.function == answer_ex
  131. and not isinstance(term.argument, IndividualVariableExpression)
  132. ):
  133. answers.add(term.argument)
  134. return answers
  135. @staticmethod
  136. def _decorate_clauses(clauses):
  137. """
  138. Decorate the proof output.
  139. """
  140. out = ""
  141. max_clause_len = max([len(str(clause)) for clause in clauses])
  142. max_seq_len = len(str(len(clauses)))
  143. for i in range(len(clauses)):
  144. parents = "A"
  145. taut = ""
  146. if clauses[i].is_tautology():
  147. taut = "Tautology"
  148. if clauses[i]._parents:
  149. parents = str(clauses[i]._parents)
  150. parents = " " * (max_clause_len - len(str(clauses[i])) + 1) + parents
  151. seq = " " * (max_seq_len - len(str(i + 1))) + str(i + 1)
  152. out += "[%s] %s %s %s\n" % (seq, clauses[i], parents, taut)
  153. return out
  154. class Clause(list):
  155. def __init__(self, data):
  156. list.__init__(self, data)
  157. self._is_tautology = None
  158. self._parents = None
  159. def unify(self, other, bindings=None, used=None, skipped=None, debug=False):
  160. """
  161. Attempt to unify this Clause with the other, returning a list of
  162. resulting, unified, Clauses.
  163. :param other: ``Clause`` with which to unify
  164. :param bindings: ``BindingDict`` containing bindings that should be used
  165. during the unification
  166. :param used: tuple of two lists of atoms. The first lists the
  167. atoms from 'self' that were successfully unified with atoms from
  168. 'other'. The second lists the atoms from 'other' that were successfully
  169. unified with atoms from 'self'.
  170. :param skipped: tuple of two ``Clause`` objects. The first is a list of all
  171. the atoms from the 'self' Clause that have not been unified with
  172. anything on the path. The second is same thing for the 'other' Clause.
  173. :param debug: bool indicating whether debug statements should print
  174. :return: list containing all the resulting ``Clause`` objects that could be
  175. obtained by unification
  176. """
  177. if bindings is None:
  178. bindings = BindingDict()
  179. if used is None:
  180. used = ([], [])
  181. if skipped is None:
  182. skipped = ([], [])
  183. if isinstance(debug, bool):
  184. debug = DebugObject(debug)
  185. newclauses = _iterate_first(
  186. self, other, bindings, used, skipped, _complete_unify_path, debug
  187. )
  188. # remove subsumed clauses. make a list of all indices of subsumed
  189. # clauses, and then remove them from the list
  190. subsumed = []
  191. for i, c1 in enumerate(newclauses):
  192. if i not in subsumed:
  193. for j, c2 in enumerate(newclauses):
  194. if i != j and j not in subsumed and c1.subsumes(c2):
  195. subsumed.append(j)
  196. result = []
  197. for i in range(len(newclauses)):
  198. if i not in subsumed:
  199. result.append(newclauses[i])
  200. return result
  201. def isSubsetOf(self, other):
  202. """
  203. Return True iff every term in 'self' is a term in 'other'.
  204. :param other: ``Clause``
  205. :return: bool
  206. """
  207. for a in self:
  208. if a not in other:
  209. return False
  210. return True
  211. def subsumes(self, other):
  212. """
  213. Return True iff 'self' subsumes 'other', this is, if there is a
  214. substitution such that every term in 'self' can be unified with a term
  215. in 'other'.
  216. :param other: ``Clause``
  217. :return: bool
  218. """
  219. negatedother = []
  220. for atom in other:
  221. if isinstance(atom, NegatedExpression):
  222. negatedother.append(atom.term)
  223. else:
  224. negatedother.append(-atom)
  225. negatedotherClause = Clause(negatedother)
  226. bindings = BindingDict()
  227. used = ([], [])
  228. skipped = ([], [])
  229. debug = DebugObject(False)
  230. return (
  231. len(
  232. _iterate_first(
  233. self,
  234. negatedotherClause,
  235. bindings,
  236. used,
  237. skipped,
  238. _subsumes_finalize,
  239. debug,
  240. )
  241. )
  242. > 0
  243. )
  244. def __getslice__(self, start, end):
  245. return Clause(list.__getslice__(self, start, end))
  246. def __sub__(self, other):
  247. return Clause([a for a in self if a not in other])
  248. def __add__(self, other):
  249. return Clause(list.__add__(self, other))
  250. def is_tautology(self):
  251. """
  252. Self is a tautology if it contains ground terms P and -P. The ground
  253. term, P, must be an exact match, ie, not using unification.
  254. """
  255. if self._is_tautology is not None:
  256. return self._is_tautology
  257. for i, a in enumerate(self):
  258. if not isinstance(a, EqualityExpression):
  259. j = len(self) - 1
  260. while j > i:
  261. b = self[j]
  262. if isinstance(a, NegatedExpression):
  263. if a.term == b:
  264. self._is_tautology = True
  265. return True
  266. elif isinstance(b, NegatedExpression):
  267. if a == b.term:
  268. self._is_tautology = True
  269. return True
  270. j -= 1
  271. self._is_tautology = False
  272. return False
  273. def free(self):
  274. return reduce(operator.or_, ((atom.free() | atom.constants()) for atom in self))
  275. def replace(self, variable, expression):
  276. """
  277. Replace every instance of variable with expression across every atom
  278. in the clause
  279. :param variable: ``Variable``
  280. :param expression: ``Expression``
  281. """
  282. return Clause([atom.replace(variable, expression) for atom in self])
  283. def substitute_bindings(self, bindings):
  284. """
  285. Replace every binding
  286. :param bindings: A list of tuples mapping Variable Expressions to the
  287. Expressions to which they are bound
  288. :return: ``Clause``
  289. """
  290. return Clause([atom.substitute_bindings(bindings) for atom in self])
  291. def __str__(self):
  292. return "{" + ", ".join("%s" % item for item in self) + "}"
  293. def __repr__(self):
  294. return "%s" % self
  295. def _iterate_first(first, second, bindings, used, skipped, finalize_method, debug):
  296. """
  297. This method facilitates movement through the terms of 'self'
  298. """
  299. debug.line("unify(%s,%s) %s" % (first, second, bindings))
  300. if not len(first) or not len(second): # if no more recursions can be performed
  301. return finalize_method(first, second, bindings, used, skipped, debug)
  302. else:
  303. # explore this 'self' atom
  304. result = _iterate_second(
  305. first, second, bindings, used, skipped, finalize_method, debug + 1
  306. )
  307. # skip this possible 'self' atom
  308. newskipped = (skipped[0] + [first[0]], skipped[1])
  309. result += _iterate_first(
  310. first[1:], second, bindings, used, newskipped, finalize_method, debug + 1
  311. )
  312. try:
  313. newbindings, newused, unused = _unify_terms(
  314. first[0], second[0], bindings, used
  315. )
  316. # Unification found, so progress with this line of unification
  317. # put skipped and unused terms back into play for later unification.
  318. newfirst = first[1:] + skipped[0] + unused[0]
  319. newsecond = second[1:] + skipped[1] + unused[1]
  320. result += _iterate_first(
  321. newfirst,
  322. newsecond,
  323. newbindings,
  324. newused,
  325. ([], []),
  326. finalize_method,
  327. debug + 1,
  328. )
  329. except BindingException:
  330. # the atoms could not be unified,
  331. pass
  332. return result
  333. def _iterate_second(first, second, bindings, used, skipped, finalize_method, debug):
  334. """
  335. This method facilitates movement through the terms of 'other'
  336. """
  337. debug.line("unify(%s,%s) %s" % (first, second, bindings))
  338. if not len(first) or not len(second): # if no more recursions can be performed
  339. return finalize_method(first, second, bindings, used, skipped, debug)
  340. else:
  341. # skip this possible pairing and move to the next
  342. newskipped = (skipped[0], skipped[1] + [second[0]])
  343. result = _iterate_second(
  344. first, second[1:], bindings, used, newskipped, finalize_method, debug + 1
  345. )
  346. try:
  347. newbindings, newused, unused = _unify_terms(
  348. first[0], second[0], bindings, used
  349. )
  350. # Unification found, so progress with this line of unification
  351. # put skipped and unused terms back into play for later unification.
  352. newfirst = first[1:] + skipped[0] + unused[0]
  353. newsecond = second[1:] + skipped[1] + unused[1]
  354. result += _iterate_second(
  355. newfirst,
  356. newsecond,
  357. newbindings,
  358. newused,
  359. ([], []),
  360. finalize_method,
  361. debug + 1,
  362. )
  363. except BindingException:
  364. # the atoms could not be unified,
  365. pass
  366. return result
  367. def _unify_terms(a, b, bindings=None, used=None):
  368. """
  369. This method attempts to unify two terms. Two expressions are unifiable
  370. if there exists a substitution function S such that S(a) == S(-b).
  371. :param a: ``Expression``
  372. :param b: ``Expression``
  373. :param bindings: ``BindingDict`` a starting set of bindings with which
  374. the unification must be consistent
  375. :return: ``BindingDict`` A dictionary of the bindings required to unify
  376. :raise ``BindingException``: If the terms cannot be unified
  377. """
  378. assert isinstance(a, Expression)
  379. assert isinstance(b, Expression)
  380. if bindings is None:
  381. bindings = BindingDict()
  382. if used is None:
  383. used = ([], [])
  384. # Use resolution
  385. if isinstance(a, NegatedExpression) and isinstance(b, ApplicationExpression):
  386. newbindings = most_general_unification(a.term, b, bindings)
  387. newused = (used[0] + [a], used[1] + [b])
  388. unused = ([], [])
  389. elif isinstance(a, ApplicationExpression) and isinstance(b, NegatedExpression):
  390. newbindings = most_general_unification(a, b.term, bindings)
  391. newused = (used[0] + [a], used[1] + [b])
  392. unused = ([], [])
  393. # Use demodulation
  394. elif isinstance(a, EqualityExpression):
  395. newbindings = BindingDict([(a.first.variable, a.second)])
  396. newused = (used[0] + [a], used[1])
  397. unused = ([], [b])
  398. elif isinstance(b, EqualityExpression):
  399. newbindings = BindingDict([(b.first.variable, b.second)])
  400. newused = (used[0], used[1] + [b])
  401. unused = ([a], [])
  402. else:
  403. raise BindingException((a, b))
  404. return newbindings, newused, unused
  405. def _complete_unify_path(first, second, bindings, used, skipped, debug):
  406. if used[0] or used[1]: # if bindings were made along the path
  407. newclause = Clause(skipped[0] + skipped[1] + first + second)
  408. debug.line(" -> New Clause: %s" % newclause)
  409. return [newclause.substitute_bindings(bindings)]
  410. else: # no bindings made means no unification occurred. so no result
  411. debug.line(" -> End")
  412. return []
  413. def _subsumes_finalize(first, second, bindings, used, skipped, debug):
  414. if not len(skipped[0]) and not len(first):
  415. # If there are no skipped terms and no terms left in 'first', then
  416. # all of the terms in the original 'self' were unified with terms
  417. # in 'other'. Therefore, there exists a binding (this one) such that
  418. # every term in self can be unified with a term in other, which
  419. # is the definition of subsumption.
  420. return [True]
  421. else:
  422. return []
  423. def clausify(expression):
  424. """
  425. Skolemize, clausify, and standardize the variables apart.
  426. """
  427. clause_list = []
  428. for clause in _clausify(skolemize(expression)):
  429. for free in clause.free():
  430. if is_indvar(free.name):
  431. newvar = VariableExpression(unique_variable())
  432. clause = clause.replace(free, newvar)
  433. clause_list.append(clause)
  434. return clause_list
  435. def _clausify(expression):
  436. """
  437. :param expression: a skolemized expression in CNF
  438. """
  439. if isinstance(expression, AndExpression):
  440. return _clausify(expression.first) + _clausify(expression.second)
  441. elif isinstance(expression, OrExpression):
  442. first = _clausify(expression.first)
  443. second = _clausify(expression.second)
  444. assert len(first) == 1
  445. assert len(second) == 1
  446. return [first[0] + second[0]]
  447. elif isinstance(expression, EqualityExpression):
  448. return [Clause([expression])]
  449. elif isinstance(expression, ApplicationExpression):
  450. return [Clause([expression])]
  451. elif isinstance(expression, NegatedExpression):
  452. if isinstance(expression.term, ApplicationExpression):
  453. return [Clause([expression])]
  454. elif isinstance(expression.term, EqualityExpression):
  455. return [Clause([expression])]
  456. raise ProverParseError()
  457. class BindingDict(object):
  458. def __init__(self, binding_list=None):
  459. """
  460. :param binding_list: list of (``AbstractVariableExpression``, ``AtomicExpression``) to initialize the dictionary
  461. """
  462. self.d = {}
  463. if binding_list:
  464. for (v, b) in binding_list:
  465. self[v] = b
  466. def __setitem__(self, variable, binding):
  467. """
  468. A binding is consistent with the dict if its variable is not already bound, OR if its
  469. variable is already bound to its argument.
  470. :param variable: ``Variable`` The variable to bind
  471. :param binding: ``Expression`` The atomic to which 'variable' should be bound
  472. :raise BindingException: If the variable cannot be bound in this dictionary
  473. """
  474. assert isinstance(variable, Variable)
  475. assert isinstance(binding, Expression)
  476. try:
  477. existing = self[variable]
  478. except KeyError:
  479. existing = None
  480. if not existing or binding == existing:
  481. self.d[variable] = binding
  482. elif isinstance(binding, IndividualVariableExpression):
  483. # Since variable is already bound, try to bind binding to variable
  484. try:
  485. existing = self[binding.variable]
  486. except KeyError:
  487. existing = None
  488. binding2 = VariableExpression(variable)
  489. if not existing or binding2 == existing:
  490. self.d[binding.variable] = binding2
  491. else:
  492. raise BindingException(
  493. "Variable %s already bound to another " "value" % (variable)
  494. )
  495. else:
  496. raise BindingException(
  497. "Variable %s already bound to another " "value" % (variable)
  498. )
  499. def __getitem__(self, variable):
  500. """
  501. Return the expression to which 'variable' is bound
  502. """
  503. assert isinstance(variable, Variable)
  504. intermediate = self.d[variable]
  505. while intermediate:
  506. try:
  507. intermediate = self.d[intermediate]
  508. except KeyError:
  509. return intermediate
  510. def __contains__(self, item):
  511. return item in self.d
  512. def __add__(self, other):
  513. """
  514. :param other: ``BindingDict`` The dict with which to combine self
  515. :return: ``BindingDict`` A new dict containing all the elements of both parameters
  516. :raise BindingException: If the parameter dictionaries are not consistent with each other
  517. """
  518. try:
  519. combined = BindingDict()
  520. for v in self.d:
  521. combined[v] = self.d[v]
  522. for v in other.d:
  523. combined[v] = other.d[v]
  524. return combined
  525. except BindingException:
  526. raise BindingException(
  527. "Attempting to add two contradicting "
  528. "BindingDicts: '%s' and '%s'" % (self, other)
  529. )
  530. def __len__(self):
  531. return len(self.d)
  532. def __str__(self):
  533. data_str = ", ".join("%s: %s" % (v, self.d[v]) for v in sorted(self.d.keys()))
  534. return "{" + data_str + "}"
  535. def __repr__(self):
  536. return "%s" % self
  537. def most_general_unification(a, b, bindings=None):
  538. """
  539. Find the most general unification of the two given expressions
  540. :param a: ``Expression``
  541. :param b: ``Expression``
  542. :param bindings: ``BindingDict`` a starting set of bindings with which the
  543. unification must be consistent
  544. :return: a list of bindings
  545. :raise BindingException: if the Expressions cannot be unified
  546. """
  547. if bindings is None:
  548. bindings = BindingDict()
  549. if a == b:
  550. return bindings
  551. elif isinstance(a, IndividualVariableExpression):
  552. return _mgu_var(a, b, bindings)
  553. elif isinstance(b, IndividualVariableExpression):
  554. return _mgu_var(b, a, bindings)
  555. elif isinstance(a, ApplicationExpression) and isinstance(b, ApplicationExpression):
  556. return most_general_unification(
  557. a.function, b.function, bindings
  558. ) + most_general_unification(a.argument, b.argument, bindings)
  559. raise BindingException((a, b))
  560. def _mgu_var(var, expression, bindings):
  561. if var.variable in expression.free() | expression.constants():
  562. raise BindingException((var, expression))
  563. else:
  564. return BindingDict([(var.variable, expression)]) + bindings
  565. class BindingException(Exception):
  566. def __init__(self, arg):
  567. if isinstance(arg, tuple):
  568. Exception.__init__(self, "'%s' cannot be bound to '%s'" % arg)
  569. else:
  570. Exception.__init__(self, arg)
  571. class UnificationException(Exception):
  572. def __init__(self, a, b):
  573. Exception.__init__(self, "'%s' cannot unify with '%s'" % (a, b))
  574. class DebugObject(object):
  575. def __init__(self, enabled=True, indent=0):
  576. self.enabled = enabled
  577. self.indent = indent
  578. def __add__(self, i):
  579. return DebugObject(self.enabled, self.indent + i)
  580. def line(self, line):
  581. if self.enabled:
  582. print(" " * self.indent + line)
  583. def testResolutionProver():
  584. resolution_test(r"man(x)")
  585. resolution_test(r"(man(x) -> man(x))")
  586. resolution_test(r"(man(x) -> --man(x))")
  587. resolution_test(r"-(man(x) and -man(x))")
  588. resolution_test(r"(man(x) or -man(x))")
  589. resolution_test(r"(man(x) -> man(x))")
  590. resolution_test(r"-(man(x) and -man(x))")
  591. resolution_test(r"(man(x) or -man(x))")
  592. resolution_test(r"(man(x) -> man(x))")
  593. resolution_test(r"(man(x) iff man(x))")
  594. resolution_test(r"-(man(x) iff -man(x))")
  595. resolution_test("all x.man(x)")
  596. resolution_test("-all x.some y.F(x,y) & some x.all y.(-F(x,y))")
  597. resolution_test("some x.all y.sees(x,y)")
  598. p1 = Expression.fromstring(r"all x.(man(x) -> mortal(x))")
  599. p2 = Expression.fromstring(r"man(Socrates)")
  600. c = Expression.fromstring(r"mortal(Socrates)")
  601. print("%s, %s |- %s: %s" % (p1, p2, c, ResolutionProver().prove(c, [p1, p2])))
  602. p1 = Expression.fromstring(r"all x.(man(x) -> walks(x))")
  603. p2 = Expression.fromstring(r"man(John)")
  604. c = Expression.fromstring(r"some y.walks(y)")
  605. print("%s, %s |- %s: %s" % (p1, p2, c, ResolutionProver().prove(c, [p1, p2])))
  606. p = Expression.fromstring(r"some e1.some e2.(believe(e1,john,e2) & walk(e2,mary))")
  607. c = Expression.fromstring(r"some e0.walk(e0,mary)")
  608. print("%s |- %s: %s" % (p, c, ResolutionProver().prove(c, [p])))
  609. def resolution_test(e):
  610. f = Expression.fromstring(e)
  611. t = ResolutionProver().prove(f)
  612. print("|- %s: %s" % (f, t))
  613. def test_clausify():
  614. lexpr = Expression.fromstring
  615. print(clausify(lexpr("P(x) | Q(x)")))
  616. print(clausify(lexpr("(P(x) & Q(x)) | R(x)")))
  617. print(clausify(lexpr("P(x) | (Q(x) & R(x))")))
  618. print(clausify(lexpr("(P(x) & Q(x)) | (R(x) & S(x))")))
  619. print(clausify(lexpr("P(x) | Q(x) | R(x)")))
  620. print(clausify(lexpr("P(x) | (Q(x) & R(x)) | S(x)")))
  621. print(clausify(lexpr("exists x.P(x) | Q(x)")))
  622. print(clausify(lexpr("-(-P(x) & Q(x))")))
  623. print(clausify(lexpr("P(x) <-> Q(x)")))
  624. print(clausify(lexpr("-(P(x) <-> Q(x))")))
  625. print(clausify(lexpr("-(all x.P(x))")))
  626. print(clausify(lexpr("-(some x.P(x))")))
  627. print(clausify(lexpr("some x.P(x)")))
  628. print(clausify(lexpr("some x.all y.P(x,y)")))
  629. print(clausify(lexpr("all y.some x.P(x,y)")))
  630. print(clausify(lexpr("all z.all y.some x.P(x,y,z)")))
  631. print(clausify(lexpr("all x.(all y.P(x,y) -> -all y.(Q(x,y) -> R(x,y)))")))
  632. def demo():
  633. test_clausify()
  634. print()
  635. testResolutionProver()
  636. print()
  637. p = Expression.fromstring("man(x)")
  638. print(ResolutionProverCommand(p, [p]).prove())
  639. if __name__ == "__main__":
  640. demo()