discourse.py 22 KB

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