discourse.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. # Natural Language Toolkit: Discourse Processing
  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. Module for incrementally developing simple discourses, and checking for semantic ambiguity,
  10. consistency and informativeness.
  11. Many of the ideas are based on the CURT family of programs of Blackburn and Bos
  12. (see http://homepages.inf.ed.ac.uk/jbos/comsem/book1.html).
  13. Consistency checking is carried out by using the ``mace`` module to call the Mace4 model builder.
  14. Informativeness checking is carried out with a call to ``Prover.prove()`` from
  15. the ``inference`` module.
  16. ``DiscourseTester`` is a constructor for discourses.
  17. The basic data structure is a list of sentences, stored as ``self._sentences``. Each sentence in the list
  18. is assigned a "sentence ID" (``sid``) of the form ``s``\ *i*. For example::
  19. s0: A boxer walks
  20. s1: Every boxer chases a girl
  21. Each sentence can be ambiguous between a number of readings, each of which receives a
  22. "reading ID" (``rid``) of the form ``s``\ *i* -``r``\ *j*. For example::
  23. s0 readings:
  24. s0-r1: some x.(boxer(x) & walk(x))
  25. s0-r0: some x.(boxerdog(x) & walk(x))
  26. A "thread" is a list of readings, represented as a list of ``rid``\ s.
  27. Each thread receives a "thread ID" (``tid``) of the form ``d``\ *i*.
  28. For example::
  29. d0: ['s0-r0', 's1-r0']
  30. The set of all threads for a discourse is the Cartesian product of all the readings of the sequences of sentences.
  31. (This is not intended to scale beyond very short discourses!) The method ``readings(filter=True)`` will only show
  32. those threads which are consistent (taking into account any background assumptions).
  33. """
  34. import os
  35. from abc import ABCMeta, abstractmethod
  36. from operator import and_, add
  37. from functools import reduce
  38. from nltk.data import show_cfg
  39. from nltk.tag import RegexpTagger
  40. from nltk.parse import load_parser
  41. from nltk.parse.malt import MaltParser
  42. from nltk.sem.drt import resolve_anaphora, AnaphoraResolutionException
  43. from nltk.sem.glue import DrtGlue
  44. from nltk.sem.logic import Expression
  45. from nltk.inference.mace import MaceCommand
  46. from nltk.inference.prover9 import Prover9Command
  47. class ReadingCommand(metaclass=ABCMeta):
  48. @abstractmethod
  49. def parse_to_readings(self, sentence):
  50. """
  51. :param sentence: the sentence to read
  52. :type sentence: str
  53. """
  54. def process_thread(self, sentence_readings):
  55. """
  56. This method should be used to handle dependencies between readings such
  57. as resolving anaphora.
  58. :param sentence_readings: readings to process
  59. :type sentence_readings: list(Expression)
  60. :return: the list of readings after processing
  61. :rtype: list(Expression)
  62. """
  63. return sentence_readings
  64. @abstractmethod
  65. def combine_readings(self, readings):
  66. """
  67. :param readings: readings to combine
  68. :type readings: list(Expression)
  69. :return: one combined reading
  70. :rtype: Expression
  71. """
  72. @abstractmethod
  73. def to_fol(self, expression):
  74. """
  75. Convert this expression into a First-Order Logic expression.
  76. :param expression: an expression
  77. :type expression: Expression
  78. :return: a FOL version of the input expression
  79. :rtype: Expression
  80. """
  81. class CfgReadingCommand(ReadingCommand):
  82. def __init__(self, gramfile=None):
  83. """
  84. :param gramfile: name of file where grammar can be loaded
  85. :type gramfile: str
  86. """
  87. self._gramfile = (
  88. gramfile if gramfile else "grammars/book_grammars/discourse.fcfg"
  89. )
  90. self._parser = load_parser(self._gramfile)
  91. def parse_to_readings(self, sentence):
  92. """:see: ReadingCommand.parse_to_readings()"""
  93. from nltk.sem import root_semrep
  94. tokens = sentence.split()
  95. trees = self._parser.parse(tokens)
  96. return [root_semrep(tree) for tree in trees]
  97. def combine_readings(self, readings):
  98. """:see: ReadingCommand.combine_readings()"""
  99. return reduce(and_, readings)
  100. def to_fol(self, expression):
  101. """:see: ReadingCommand.to_fol()"""
  102. return expression
  103. class DrtGlueReadingCommand(ReadingCommand):
  104. def __init__(self, semtype_file=None, remove_duplicates=False, depparser=None):
  105. """
  106. :param semtype_file: name of file where grammar can be loaded
  107. :param remove_duplicates: should duplicates be removed?
  108. :param depparser: the dependency parser
  109. """
  110. if semtype_file is None:
  111. semtype_file = os.path.join(
  112. "grammars", "sample_grammars", "drt_glue.semtype"
  113. )
  114. self._glue = DrtGlue(
  115. semtype_file=semtype_file,
  116. remove_duplicates=remove_duplicates,
  117. depparser=depparser,
  118. )
  119. def parse_to_readings(self, sentence):
  120. """:see: ReadingCommand.parse_to_readings()"""
  121. return self._glue.parse_to_meaning(sentence)
  122. def process_thread(self, sentence_readings):
  123. """:see: ReadingCommand.process_thread()"""
  124. try:
  125. return [self.combine_readings(sentence_readings)]
  126. except AnaphoraResolutionException:
  127. return []
  128. def combine_readings(self, readings):
  129. """:see: ReadingCommand.combine_readings()"""
  130. thread_reading = reduce(add, readings)
  131. return resolve_anaphora(thread_reading.simplify())
  132. def to_fol(self, expression):
  133. """:see: ReadingCommand.to_fol()"""
  134. return expression.fol()
  135. class DiscourseTester(object):
  136. """
  137. Check properties of an ongoing discourse.
  138. """
  139. def __init__(self, input, reading_command=None, background=None):
  140. """
  141. Initialize a ``DiscourseTester``.
  142. :param input: the discourse sentences
  143. :type input: list of str
  144. :param background: Formulas which express background assumptions
  145. :type background: list(Expression)
  146. """
  147. self._input = input
  148. self._sentences = dict([("s%s" % i, sent) for i, sent in enumerate(input)])
  149. self._models = None
  150. self._readings = {}
  151. self._reading_command = (
  152. reading_command if reading_command else CfgReadingCommand()
  153. )
  154. self._threads = {}
  155. self._filtered_threads = {}
  156. if background is not None:
  157. from nltk.sem.logic import Expression
  158. for e in background:
  159. assert isinstance(e, Expression)
  160. self._background = background
  161. else:
  162. self._background = []
  163. ###############################
  164. # Sentences
  165. ###############################
  166. def sentences(self):
  167. """
  168. Display the list of sentences in the current discourse.
  169. """
  170. for id in sorted(self._sentences):
  171. print("%s: %s" % (id, self._sentences[id]))
  172. def add_sentence(self, sentence, informchk=False, consistchk=False):
  173. """
  174. Add a sentence to the current discourse.
  175. Updates ``self._input`` and ``self._sentences``.
  176. :param sentence: An input sentence
  177. :type sentence: str
  178. :param informchk: if ``True``, check that the result of adding the sentence is thread-informative. Updates ``self._readings``.
  179. :param consistchk: if ``True``, check that the result of adding the sentence is thread-consistent. Updates ``self._readings``.
  180. """
  181. # check whether the new sentence is informative (i.e. not entailed by the previous discourse)
  182. if informchk:
  183. self.readings(verbose=False)
  184. for tid in sorted(self._threads):
  185. assumptions = [reading for (rid, reading) in self.expand_threads(tid)]
  186. assumptions += self._background
  187. for sent_reading in self._get_readings(sentence):
  188. tp = Prover9Command(goal=sent_reading, assumptions=assumptions)
  189. if tp.prove():
  190. print(
  191. "Sentence '%s' under reading '%s':"
  192. % (sentence, str(sent_reading))
  193. )
  194. print("Not informative relative to thread '%s'" % tid)
  195. self._input.append(sentence)
  196. self._sentences = dict(
  197. [("s%s" % i, sent) for i, sent in enumerate(self._input)]
  198. )
  199. # check whether adding the new sentence to the discourse preserves consistency (i.e. a model can be found for the combined set of
  200. # of assumptions
  201. if consistchk:
  202. self.readings(verbose=False)
  203. self.models(show=False)
  204. def retract_sentence(self, sentence, verbose=True):
  205. """
  206. Remove a sentence from the current discourse.
  207. Updates ``self._input``, ``self._sentences`` and ``self._readings``.
  208. :param sentence: An input sentence
  209. :type sentence: str
  210. :param verbose: If ``True``, report on the updated list of sentences.
  211. """
  212. try:
  213. self._input.remove(sentence)
  214. except ValueError:
  215. print(
  216. "Retraction failed. The sentence '%s' is not part of the current discourse:"
  217. % sentence
  218. )
  219. self.sentences()
  220. return None
  221. self._sentences = dict(
  222. [("s%s" % i, sent) for i, sent in enumerate(self._input)]
  223. )
  224. self.readings(verbose=False)
  225. if verbose:
  226. print("Current sentences are ")
  227. self.sentences()
  228. def grammar(self):
  229. """
  230. Print out the grammar in use for parsing input sentences
  231. """
  232. show_cfg(self._reading_command._gramfile)
  233. ###############################
  234. # Readings and Threads
  235. ###############################
  236. def _get_readings(self, sentence):
  237. """
  238. Build a list of semantic readings for a sentence.
  239. :rtype: list(Expression)
  240. """
  241. return self._reading_command.parse_to_readings(sentence)
  242. def _construct_readings(self):
  243. """
  244. Use ``self._sentences`` to construct a value for ``self._readings``.
  245. """
  246. # re-initialize self._readings in case we have retracted a sentence
  247. self._readings = {}
  248. for sid in sorted(self._sentences):
  249. sentence = self._sentences[sid]
  250. readings = self._get_readings(sentence)
  251. self._readings[sid] = dict(
  252. [
  253. ("%s-r%s" % (sid, rid), reading.simplify())
  254. for rid, reading in enumerate(sorted(readings, key=str))
  255. ]
  256. )
  257. def _construct_threads(self):
  258. """
  259. Use ``self._readings`` to construct a value for ``self._threads``
  260. and use the model builder to construct a value for ``self._filtered_threads``
  261. """
  262. thread_list = [[]]
  263. for sid in sorted(self._readings):
  264. thread_list = self.multiply(thread_list, sorted(self._readings[sid]))
  265. self._threads = dict(
  266. [("d%s" % tid, thread) for tid, thread in enumerate(thread_list)]
  267. )
  268. # re-initialize the filtered threads
  269. self._filtered_threads = {}
  270. # keep the same ids, but only include threads which get models
  271. consistency_checked = self._check_consistency(self._threads)
  272. for (tid, thread) in self._threads.items():
  273. if (tid, True) in consistency_checked:
  274. self._filtered_threads[tid] = thread
  275. def _show_readings(self, sentence=None):
  276. """
  277. Print out the readings for the discourse (or a single sentence).
  278. """
  279. if sentence is not None:
  280. print("The sentence '%s' has these readings:" % sentence)
  281. for r in [str(reading) for reading in (self._get_readings(sentence))]:
  282. print(" %s" % r)
  283. else:
  284. for sid in sorted(self._readings):
  285. print()
  286. print("%s readings:" % sid)
  287. print() #'-' * 30
  288. for rid in sorted(self._readings[sid]):
  289. lf = self._readings[sid][rid]
  290. print("%s: %s" % (rid, lf.normalize()))
  291. def _show_threads(self, filter=False, show_thread_readings=False):
  292. """
  293. Print out the value of ``self._threads`` or ``self._filtered_hreads``
  294. """
  295. threads = self._filtered_threads if filter else self._threads
  296. for tid in sorted(threads):
  297. if show_thread_readings:
  298. readings = [
  299. self._readings[rid.split("-")[0]][rid] for rid in self._threads[tid]
  300. ]
  301. try:
  302. thread_reading = (
  303. ": %s"
  304. % self._reading_command.combine_readings(readings).normalize()
  305. )
  306. except Exception as e:
  307. thread_reading = ": INVALID: %s" % e.__class__.__name__
  308. else:
  309. thread_reading = ""
  310. print("%s:" % tid, self._threads[tid], thread_reading)
  311. def readings(
  312. self,
  313. sentence=None,
  314. threaded=False,
  315. verbose=True,
  316. filter=False,
  317. show_thread_readings=False,
  318. ):
  319. """
  320. Construct and show the readings of the discourse (or of a single sentence).
  321. :param sentence: test just this sentence
  322. :type sentence: str
  323. :param threaded: if ``True``, print out each thread ID and the corresponding thread.
  324. :param filter: if ``True``, only print out consistent thread IDs and threads.
  325. """
  326. self._construct_readings()
  327. self._construct_threads()
  328. # if we are filtering or showing thread readings, show threads
  329. if filter or show_thread_readings:
  330. threaded = True
  331. if verbose:
  332. if not threaded:
  333. self._show_readings(sentence=sentence)
  334. else:
  335. self._show_threads(
  336. filter=filter, show_thread_readings=show_thread_readings
  337. )
  338. def expand_threads(self, thread_id, threads=None):
  339. """
  340. Given a thread ID, find the list of ``logic.Expression`` objects corresponding to the reading IDs in that thread.
  341. :param thread_id: thread ID
  342. :type thread_id: str
  343. :param threads: a mapping from thread IDs to lists of reading IDs
  344. :type threads: dict
  345. :return: A list of pairs ``(rid, reading)`` where reading is the ``logic.Expression`` associated with a reading ID
  346. :rtype: list of tuple
  347. """
  348. if threads is None:
  349. threads = self._threads
  350. return [
  351. (rid, self._readings[sid][rid])
  352. for rid in threads[thread_id]
  353. for sid in rid.split("-")[:1]
  354. ]
  355. ###############################
  356. # Models and Background
  357. ###############################
  358. def _check_consistency(self, threads, show=False, verbose=False):
  359. results = []
  360. for tid in sorted(threads):
  361. assumptions = [
  362. reading for (rid, reading) in self.expand_threads(tid, threads=threads)
  363. ]
  364. assumptions = list(
  365. map(
  366. self._reading_command.to_fol,
  367. self._reading_command.process_thread(assumptions),
  368. )
  369. )
  370. if assumptions:
  371. assumptions += self._background
  372. # if Mace4 finds a model, it always seems to find it quickly
  373. mb = MaceCommand(None, assumptions, max_models=20)
  374. modelfound = mb.build_model()
  375. else:
  376. modelfound = False
  377. results.append((tid, modelfound))
  378. if show:
  379. spacer(80)
  380. print("Model for Discourse Thread %s" % tid)
  381. spacer(80)
  382. if verbose:
  383. for a in assumptions:
  384. print(a)
  385. spacer(80)
  386. if modelfound:
  387. print(mb.model(format="cooked"))
  388. else:
  389. print("No model found!\n")
  390. return results
  391. def models(self, thread_id=None, show=True, verbose=False):
  392. """
  393. Call Mace4 to build a model for each current discourse thread.
  394. :param thread_id: thread ID
  395. :type thread_id: str
  396. :param show: If ``True``, display the model that has been found.
  397. """
  398. self._construct_readings()
  399. self._construct_threads()
  400. threads = {thread_id: self._threads[thread_id]} if thread_id else self._threads
  401. for (tid, modelfound) in self._check_consistency(
  402. threads, show=show, verbose=verbose
  403. ):
  404. idlist = [rid for rid in threads[tid]]
  405. if not modelfound:
  406. print("Inconsistent discourse: %s %s:" % (tid, idlist))
  407. for rid, reading in self.expand_threads(tid):
  408. print(" %s: %s" % (rid, reading.normalize()))
  409. print()
  410. else:
  411. print("Consistent discourse: %s %s:" % (tid, idlist))
  412. for rid, reading in self.expand_threads(tid):
  413. print(" %s: %s" % (rid, reading.normalize()))
  414. print()
  415. def add_background(self, background, verbose=False):
  416. """
  417. Add a list of background assumptions for reasoning about the discourse.
  418. When called, this method also updates the discourse model's set of readings and threads.
  419. :param background: Formulas which contain background information
  420. :type background: list(Expression)
  421. """
  422. from nltk.sem.logic import Expression
  423. for (count, e) in enumerate(background):
  424. assert isinstance(e, Expression)
  425. if verbose:
  426. print("Adding assumption %s to background" % count)
  427. self._background.append(e)
  428. # update the state
  429. self._construct_readings()
  430. self._construct_threads()
  431. def background(self):
  432. """
  433. Show the current background assumptions.
  434. """
  435. for e in self._background:
  436. print(str(e))
  437. ###############################
  438. # Misc
  439. ###############################
  440. @staticmethod
  441. def multiply(discourse, readings):
  442. """
  443. Multiply every thread in ``discourse`` by every reading in ``readings``.
  444. Given discourse = [['A'], ['B']], readings = ['a', 'b', 'c'] , returns
  445. [['A', 'a'], ['A', 'b'], ['A', 'c'], ['B', 'a'], ['B', 'b'], ['B', 'c']]
  446. :param discourse: the current list of readings
  447. :type discourse: list of lists
  448. :param readings: an additional list of readings
  449. :type readings: list(Expression)
  450. :rtype: A list of lists
  451. """
  452. result = []
  453. for sublist in discourse:
  454. for r in readings:
  455. new = []
  456. new += sublist
  457. new.append(r)
  458. result.append(new)
  459. return result
  460. def load_fol(s):
  461. """
  462. Temporarily duplicated from ``nltk.sem.util``.
  463. Convert a file of first order formulas into a list of ``Expression`` objects.
  464. :param s: the contents of the file
  465. :type s: str
  466. :return: a list of parsed formulas.
  467. :rtype: list(Expression)
  468. """
  469. statements = []
  470. for linenum, line in enumerate(s.splitlines()):
  471. line = line.strip()
  472. if line.startswith("#") or line == "":
  473. continue
  474. try:
  475. statements.append(Expression.fromstring(line))
  476. except Exception:
  477. raise ValueError("Unable to parse line %s: %s" % (linenum, line))
  478. return statements
  479. ###############################
  480. # Demo
  481. ###############################
  482. def discourse_demo(reading_command=None):
  483. """
  484. Illustrate the various methods of ``DiscourseTester``
  485. """
  486. dt = DiscourseTester(
  487. ["A boxer walks", "Every boxer chases a girl"], reading_command
  488. )
  489. dt.models()
  490. print()
  491. # dt.grammar()
  492. print()
  493. dt.sentences()
  494. print()
  495. dt.readings()
  496. print()
  497. dt.readings(threaded=True)
  498. print()
  499. dt.models("d1")
  500. dt.add_sentence("John is a boxer")
  501. print()
  502. dt.sentences()
  503. print()
  504. dt.readings(threaded=True)
  505. print()
  506. dt = DiscourseTester(
  507. ["A student dances", "Every student is a person"], reading_command
  508. )
  509. print()
  510. dt.add_sentence("No person dances", consistchk=True)
  511. print()
  512. dt.readings()
  513. print()
  514. dt.retract_sentence("No person dances", verbose=True)
  515. print()
  516. dt.models()
  517. print()
  518. dt.readings("A person dances")
  519. print()
  520. dt.add_sentence("A person dances", informchk=True)
  521. dt = DiscourseTester(
  522. ["Vincent is a boxer", "Fido is a boxer", "Vincent is married", "Fido barks"],
  523. reading_command,
  524. )
  525. dt.readings(filter=True)
  526. import nltk.data
  527. background_file = os.path.join("grammars", "book_grammars", "background.fol")
  528. background = nltk.data.load(background_file)
  529. print()
  530. dt.add_background(background, verbose=False)
  531. dt.background()
  532. print()
  533. dt.readings(filter=True)
  534. print()
  535. dt.models()
  536. def drt_discourse_demo(reading_command=None):
  537. """
  538. Illustrate the various methods of ``DiscourseTester``
  539. """
  540. dt = DiscourseTester(["every dog chases a boy", "he runs"], reading_command)
  541. dt.models()
  542. print()
  543. dt.sentences()
  544. print()
  545. dt.readings()
  546. print()
  547. dt.readings(show_thread_readings=True)
  548. print()
  549. dt.readings(filter=True, show_thread_readings=True)
  550. def spacer(num=30):
  551. print("-" * num)
  552. def demo():
  553. discourse_demo()
  554. tagger = RegexpTagger(
  555. [
  556. ("^(chases|runs)$", "VB"),
  557. ("^(a)$", "ex_quant"),
  558. ("^(every)$", "univ_quant"),
  559. ("^(dog|boy)$", "NN"),
  560. ("^(he)$", "PRP"),
  561. ]
  562. )
  563. depparser = MaltParser(tagger=tagger)
  564. drt_discourse_demo(
  565. DrtGlueReadingCommand(remove_duplicates=False, depparser=depparser)
  566. )
  567. if __name__ == "__main__":
  568. demo()