resolution.py 26 KB

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