api.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. # Natural Language Toolkit: Classifier Interface
  2. #
  3. # Author: Ewan Klein <ewan@inf.ed.ac.uk>
  4. # Dan Garrette <dhgarrette@gmail.com>
  5. #
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. """
  9. Interfaces and base classes for theorem provers and model builders.
  10. ``Prover`` is a standard interface for a theorem prover which tries to prove a goal from a
  11. list of assumptions.
  12. ``ModelBuilder`` is a standard interface for a model builder. Given just a set of assumptions.
  13. the model builder tries to build a model for the assumptions. Given a set of assumptions and a
  14. goal *G*, the model builder tries to find a counter-model, in the sense of a model that will satisfy
  15. the assumptions plus the negation of *G*.
  16. """
  17. from __future__ import print_function
  18. from abc import ABCMeta, abstractmethod
  19. import threading
  20. import time
  21. from six import add_metaclass
  22. @add_metaclass(ABCMeta)
  23. class Prover(object):
  24. """
  25. Interface for trying to prove a goal from assumptions. Both the goal and
  26. the assumptions are constrained to be formulas of ``logic.Expression``.
  27. """
  28. def prove(self, goal=None, assumptions=None, verbose=False):
  29. """
  30. :return: Whether the proof was successful or not.
  31. :rtype: bool
  32. """
  33. return self._prove(goal, assumptions, verbose)[0]
  34. @abstractmethod
  35. def _prove(self, goal=None, assumptions=None, verbose=False):
  36. """
  37. :return: Whether the proof was successful or not, along with the proof
  38. :rtype: tuple: (bool, str)
  39. """
  40. @add_metaclass(ABCMeta)
  41. class ModelBuilder(object):
  42. """
  43. Interface for trying to build a model of set of formulas.
  44. Open formulas are assumed to be universally quantified.
  45. Both the goal and the assumptions are constrained to be formulas
  46. of ``logic.Expression``.
  47. """
  48. def build_model(self, goal=None, assumptions=None, verbose=False):
  49. """
  50. Perform the actual model building.
  51. :return: Whether a model was generated
  52. :rtype: bool
  53. """
  54. return self._build_model(goal, assumptions, verbose)[0]
  55. @abstractmethod
  56. def _build_model(self, goal=None, assumptions=None, verbose=False):
  57. """
  58. Perform the actual model building.
  59. :return: Whether a model was generated, and the model itself
  60. :rtype: tuple(bool, sem.Valuation)
  61. """
  62. @add_metaclass(ABCMeta)
  63. class TheoremToolCommand(object):
  64. """
  65. This class holds a goal and a list of assumptions to be used in proving
  66. or model building.
  67. """
  68. @abstractmethod
  69. def add_assumptions(self, new_assumptions):
  70. """
  71. Add new assumptions to the assumption list.
  72. :param new_assumptions: new assumptions
  73. :type new_assumptions: list(sem.Expression)
  74. """
  75. @abstractmethod
  76. def retract_assumptions(self, retracted, debug=False):
  77. """
  78. Retract assumptions from the assumption list.
  79. :param debug: If True, give warning when ``retracted`` is not present on
  80. assumptions list.
  81. :type debug: bool
  82. :param retracted: assumptions to be retracted
  83. :type retracted: list(sem.Expression)
  84. """
  85. @abstractmethod
  86. def assumptions(self):
  87. """
  88. List the current assumptions.
  89. :return: list of ``Expression``
  90. """
  91. @abstractmethod
  92. def goal(self):
  93. """
  94. Return the goal
  95. :return: ``Expression``
  96. """
  97. @abstractmethod
  98. def print_assumptions(self):
  99. """
  100. Print the list of the current assumptions.
  101. """
  102. class ProverCommand(TheoremToolCommand):
  103. """
  104. This class holds a ``Prover``, a goal, and a list of assumptions. When
  105. prove() is called, the ``Prover`` is executed with the goal and assumptions.
  106. """
  107. @abstractmethod
  108. def prove(self, verbose=False):
  109. """
  110. Perform the actual proof.
  111. """
  112. @abstractmethod
  113. def proof(self, simplify=True):
  114. """
  115. Return the proof string
  116. :param simplify: bool simplify the proof?
  117. :return: str
  118. """
  119. @abstractmethod
  120. def get_prover(self):
  121. """
  122. Return the prover object
  123. :return: ``Prover``
  124. """
  125. class ModelBuilderCommand(TheoremToolCommand):
  126. """
  127. This class holds a ``ModelBuilder``, a goal, and a list of assumptions.
  128. When build_model() is called, the ``ModelBuilder`` is executed with the goal
  129. and assumptions.
  130. """
  131. @abstractmethod
  132. def build_model(self, verbose=False):
  133. """
  134. Perform the actual model building.
  135. :return: A model if one is generated; None otherwise.
  136. :rtype: sem.Valuation
  137. """
  138. @abstractmethod
  139. def model(self, format=None):
  140. """
  141. Return a string representation of the model
  142. :param simplify: bool simplify the proof?
  143. :return: str
  144. """
  145. @abstractmethod
  146. def get_model_builder(self):
  147. """
  148. Return the model builder object
  149. :return: ``ModelBuilder``
  150. """
  151. class BaseTheoremToolCommand(TheoremToolCommand):
  152. """
  153. This class holds a goal and a list of assumptions to be used in proving
  154. or model building.
  155. """
  156. def __init__(self, goal=None, assumptions=None):
  157. """
  158. :param goal: Input expression to prove
  159. :type goal: sem.Expression
  160. :param assumptions: Input expressions to use as assumptions in
  161. the proof.
  162. :type assumptions: list(sem.Expression)
  163. """
  164. self._goal = goal
  165. if not assumptions:
  166. self._assumptions = []
  167. else:
  168. self._assumptions = list(assumptions)
  169. self._result = None
  170. """A holder for the result, to prevent unnecessary re-proving"""
  171. def add_assumptions(self, new_assumptions):
  172. """
  173. Add new assumptions to the assumption list.
  174. :param new_assumptions: new assumptions
  175. :type new_assumptions: list(sem.Expression)
  176. """
  177. self._assumptions.extend(new_assumptions)
  178. self._result = None
  179. def retract_assumptions(self, retracted, debug=False):
  180. """
  181. Retract assumptions from the assumption list.
  182. :param debug: If True, give warning when ``retracted`` is not present on
  183. assumptions list.
  184. :type debug: bool
  185. :param retracted: assumptions to be retracted
  186. :type retracted: list(sem.Expression)
  187. """
  188. retracted = set(retracted)
  189. result_list = list(filter(lambda a: a not in retracted, self._assumptions))
  190. if debug and result_list == self._assumptions:
  191. print(Warning("Assumptions list has not been changed:"))
  192. self.print_assumptions()
  193. self._assumptions = result_list
  194. self._result = None
  195. def assumptions(self):
  196. """
  197. List the current assumptions.
  198. :return: list of ``Expression``
  199. """
  200. return self._assumptions
  201. def goal(self):
  202. """
  203. Return the goal
  204. :return: ``Expression``
  205. """
  206. return self._goal
  207. def print_assumptions(self):
  208. """
  209. Print the list of the current assumptions.
  210. """
  211. for a in self.assumptions():
  212. print(a)
  213. class BaseProverCommand(BaseTheoremToolCommand, ProverCommand):
  214. """
  215. This class holds a ``Prover``, a goal, and a list of assumptions. When
  216. prove() is called, the ``Prover`` is executed with the goal and assumptions.
  217. """
  218. def __init__(self, prover, goal=None, assumptions=None):
  219. """
  220. :param prover: The theorem tool to execute with the assumptions
  221. :type prover: Prover
  222. :see: ``BaseTheoremToolCommand``
  223. """
  224. self._prover = prover
  225. """The theorem tool to execute with the assumptions"""
  226. BaseTheoremToolCommand.__init__(self, goal, assumptions)
  227. self._proof = None
  228. def prove(self, verbose=False):
  229. """
  230. Perform the actual proof. Store the result to prevent unnecessary
  231. re-proving.
  232. """
  233. if self._result is None:
  234. self._result, self._proof = self._prover._prove(
  235. self.goal(), self.assumptions(), verbose
  236. )
  237. return self._result
  238. def proof(self, simplify=True):
  239. """
  240. Return the proof string
  241. :param simplify: bool simplify the proof?
  242. :return: str
  243. """
  244. if self._result is None:
  245. raise LookupError("You have to call prove() first to get a proof!")
  246. else:
  247. return self.decorate_proof(self._proof, simplify)
  248. def decorate_proof(self, proof_string, simplify=True):
  249. """
  250. Modify and return the proof string
  251. :param proof_string: str the proof to decorate
  252. :param simplify: bool simplify the proof?
  253. :return: str
  254. """
  255. return proof_string
  256. def get_prover(self):
  257. return self._prover
  258. class BaseModelBuilderCommand(BaseTheoremToolCommand, ModelBuilderCommand):
  259. """
  260. This class holds a ``ModelBuilder``, a goal, and a list of assumptions. When
  261. build_model() is called, the ``ModelBuilder`` is executed with the goal and
  262. assumptions.
  263. """
  264. def __init__(self, modelbuilder, goal=None, assumptions=None):
  265. """
  266. :param modelbuilder: The theorem tool to execute with the assumptions
  267. :type modelbuilder: ModelBuilder
  268. :see: ``BaseTheoremToolCommand``
  269. """
  270. self._modelbuilder = modelbuilder
  271. """The theorem tool to execute with the assumptions"""
  272. BaseTheoremToolCommand.__init__(self, goal, assumptions)
  273. self._model = None
  274. def build_model(self, verbose=False):
  275. """
  276. Attempt to build a model. Store the result to prevent unnecessary
  277. re-building.
  278. """
  279. if self._result is None:
  280. self._result, self._model = self._modelbuilder._build_model(
  281. self.goal(), self.assumptions(), verbose
  282. )
  283. return self._result
  284. def model(self, format=None):
  285. """
  286. Return a string representation of the model
  287. :param simplify: bool simplify the proof?
  288. :return: str
  289. """
  290. if self._result is None:
  291. raise LookupError('You have to call build_model() first to ' 'get a model!')
  292. else:
  293. return self._decorate_model(self._model, format)
  294. def _decorate_model(self, valuation_str, format=None):
  295. """
  296. :param valuation_str: str with the model builder's output
  297. :param format: str indicating the format for displaying
  298. :return: str
  299. """
  300. return valuation_str
  301. def get_model_builder(self):
  302. return self._modelbuilder
  303. class TheoremToolCommandDecorator(TheoremToolCommand):
  304. """
  305. A base decorator for the ``ProverCommandDecorator`` and
  306. ``ModelBuilderCommandDecorator`` classes from which decorators can extend.
  307. """
  308. def __init__(self, command):
  309. """
  310. :param command: ``TheoremToolCommand`` to decorate
  311. """
  312. self._command = command
  313. # The decorator has its own versions of 'result' different from the
  314. # underlying command
  315. self._result = None
  316. def assumptions(self):
  317. return self._command.assumptions()
  318. def goal(self):
  319. return self._command.goal()
  320. def add_assumptions(self, new_assumptions):
  321. self._command.add_assumptions(new_assumptions)
  322. self._result = None
  323. def retract_assumptions(self, retracted, debug=False):
  324. self._command.retract_assumptions(retracted, debug)
  325. self._result = None
  326. def print_assumptions(self):
  327. self._command.print_assumptions()
  328. class ProverCommandDecorator(TheoremToolCommandDecorator, ProverCommand):
  329. """
  330. A base decorator for the ``ProverCommand`` class from which other
  331. prover command decorators can extend.
  332. """
  333. def __init__(self, proverCommand):
  334. """
  335. :param proverCommand: ``ProverCommand`` to decorate
  336. """
  337. TheoremToolCommandDecorator.__init__(self, proverCommand)
  338. # The decorator has its own versions of 'result' and 'proof'
  339. # because they may be different from the underlying command
  340. self._proof = None
  341. def prove(self, verbose=False):
  342. if self._result is None:
  343. prover = self.get_prover()
  344. self._result, self._proof = prover._prove(
  345. self.goal(), self.assumptions(), verbose
  346. )
  347. return self._result
  348. def proof(self, simplify=True):
  349. """
  350. Return the proof string
  351. :param simplify: bool simplify the proof?
  352. :return: str
  353. """
  354. if self._result is None:
  355. raise LookupError("You have to call prove() first to get a proof!")
  356. else:
  357. return self.decorate_proof(self._proof, simplify)
  358. def decorate_proof(self, proof_string, simplify=True):
  359. """
  360. Modify and return the proof string
  361. :param proof_string: str the proof to decorate
  362. :param simplify: bool simplify the proof?
  363. :return: str
  364. """
  365. return self._command.decorate_proof(proof_string, simplify)
  366. def get_prover(self):
  367. return self._command.get_prover()
  368. class ModelBuilderCommandDecorator(TheoremToolCommandDecorator, ModelBuilderCommand):
  369. """
  370. A base decorator for the ``ModelBuilderCommand`` class from which other
  371. prover command decorators can extend.
  372. """
  373. def __init__(self, modelBuilderCommand):
  374. """
  375. :param modelBuilderCommand: ``ModelBuilderCommand`` to decorate
  376. """
  377. TheoremToolCommandDecorator.__init__(self, modelBuilderCommand)
  378. # The decorator has its own versions of 'result' and 'valuation'
  379. # because they may be different from the underlying command
  380. self._model = None
  381. def build_model(self, verbose=False):
  382. """
  383. Attempt to build a model. Store the result to prevent unnecessary
  384. re-building.
  385. """
  386. if self._result is None:
  387. modelbuilder = self.get_model_builder()
  388. self._result, self._model = modelbuilder._build_model(
  389. self.goal(), self.assumptions(), verbose
  390. )
  391. return self._result
  392. def model(self, format=None):
  393. """
  394. Return a string representation of the model
  395. :param simplify: bool simplify the proof?
  396. :return: str
  397. """
  398. if self._result is None:
  399. raise LookupError('You have to call build_model() first to ' 'get a model!')
  400. else:
  401. return self._decorate_model(self._model, format)
  402. def _decorate_model(self, valuation_str, format=None):
  403. """
  404. Modify and return the proof string
  405. :param valuation_str: str with the model builder's output
  406. :param format: str indicating the format for displaying
  407. :return: str
  408. """
  409. return self._command._decorate_model(valuation_str, format)
  410. def get_model_builder(self):
  411. return self._command.get_prover()
  412. class ParallelProverBuilder(Prover, ModelBuilder):
  413. """
  414. This class stores both a prover and a model builder and when either
  415. prove() or build_model() is called, then both theorem tools are run in
  416. parallel. Whichever finishes first, the prover or the model builder, is the
  417. result that will be used.
  418. """
  419. def __init__(self, prover, modelbuilder):
  420. self._prover = prover
  421. self._modelbuilder = modelbuilder
  422. def _prove(self, goal=None, assumptions=None, verbose=False):
  423. return self._run(goal, assumptions, verbose), ''
  424. def _build_model(self, goal=None, assumptions=None, verbose=False):
  425. return not self._run(goal, assumptions, verbose), ''
  426. def _run(self, goal, assumptions, verbose):
  427. # Set up two thread, Prover and ModelBuilder to run in parallel
  428. tp_thread = TheoremToolThread(
  429. lambda: self._prover.prove(goal, assumptions, verbose), verbose, 'TP'
  430. )
  431. mb_thread = TheoremToolThread(
  432. lambda: self._modelbuilder.build_model(goal, assumptions, verbose),
  433. verbose,
  434. 'MB',
  435. )
  436. tp_thread.start()
  437. mb_thread.start()
  438. while tp_thread.isAlive() and mb_thread.isAlive():
  439. # wait until either the prover or the model builder is done
  440. pass
  441. if tp_thread.result is not None:
  442. return tp_thread.result
  443. elif mb_thread.result is not None:
  444. return not mb_thread.result
  445. else:
  446. return None
  447. class ParallelProverBuilderCommand(BaseProverCommand, BaseModelBuilderCommand):
  448. """
  449. This command stores both a prover and a model builder and when either
  450. prove() or build_model() is called, then both theorem tools are run in
  451. parallel. Whichever finishes first, the prover or the model builder, is the
  452. result that will be used.
  453. Because the theorem prover result is the opposite of the model builder
  454. result, we will treat self._result as meaning "proof found/no model found".
  455. """
  456. def __init__(self, prover, modelbuilder, goal=None, assumptions=None):
  457. BaseProverCommand.__init__(self, prover, goal, assumptions)
  458. BaseModelBuilderCommand.__init__(self, modelbuilder, goal, assumptions)
  459. def prove(self, verbose=False):
  460. return self._run(verbose)
  461. def build_model(self, verbose=False):
  462. return not self._run(verbose)
  463. def _run(self, verbose):
  464. # Set up two thread, Prover and ModelBuilder to run in parallel
  465. tp_thread = TheoremToolThread(
  466. lambda: BaseProverCommand.prove(self, verbose), verbose, 'TP'
  467. )
  468. mb_thread = TheoremToolThread(
  469. lambda: BaseModelBuilderCommand.build_model(self, verbose), verbose, 'MB'
  470. )
  471. tp_thread.start()
  472. mb_thread.start()
  473. while tp_thread.isAlive() and mb_thread.isAlive():
  474. # wait until either the prover or the model builder is done
  475. pass
  476. if tp_thread.result is not None:
  477. self._result = tp_thread.result
  478. elif mb_thread.result is not None:
  479. self._result = not mb_thread.result
  480. return self._result
  481. class TheoremToolThread(threading.Thread):
  482. def __init__(self, command, verbose, name=None):
  483. threading.Thread.__init__(self)
  484. self._command = command
  485. self._result = None
  486. self._verbose = verbose
  487. self._name = name
  488. def run(self):
  489. try:
  490. self._result = self._command()
  491. if self._verbose:
  492. print(
  493. 'Thread %s finished with result %s at %s'
  494. % (self._name, self._result, time.localtime(time.time()))
  495. )
  496. except Exception as e:
  497. print(e)
  498. print('Thread %s completed abnormally' % (self._name))
  499. @property
  500. def result(self):
  501. return self._result