hole.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. # Natural Language Toolkit: Logic
  2. #
  3. # Author: Peter Wang
  4. # Updated by: Dan Garrette <dhgarrette@gmail.com>
  5. #
  6. # Copyright (C) 2001-2019 NLTK Project
  7. # URL: <http://nltk.org>
  8. # For license information, see LICENSE.TXT
  9. """
  10. An implementation of the Hole Semantics model, following Blackburn and Bos,
  11. Representation and Inference for Natural Language (CSLI, 2005).
  12. The semantic representations are built by the grammar hole.fcfg.
  13. This module contains driver code to read in sentences and parse them
  14. according to a hole semantics grammar.
  15. After parsing, the semantic representation is in the form of an underspecified
  16. representation that is not easy to read. We use a "plugging" algorithm to
  17. convert that representation into first-order logic formulas.
  18. """
  19. from __future__ import print_function, unicode_literals
  20. from functools import reduce
  21. from six import itervalues
  22. from nltk import compat
  23. from nltk.parse import load_parser
  24. from nltk.sem.skolemize import skolemize
  25. from nltk.sem.logic import (
  26. AllExpression,
  27. AndExpression,
  28. ApplicationExpression,
  29. ExistsExpression,
  30. IffExpression,
  31. ImpExpression,
  32. LambdaExpression,
  33. NegatedExpression,
  34. OrExpression,
  35. )
  36. # Note that in this code there may be multiple types of trees being referred to:
  37. #
  38. # 1. parse trees
  39. # 2. the underspecified representation
  40. # 3. first-order logic formula trees
  41. # 4. the search space when plugging (search tree)
  42. #
  43. class Constants(object):
  44. ALL = 'ALL'
  45. EXISTS = 'EXISTS'
  46. NOT = 'NOT'
  47. AND = 'AND'
  48. OR = 'OR'
  49. IMP = 'IMP'
  50. IFF = 'IFF'
  51. PRED = 'PRED'
  52. LEQ = 'LEQ'
  53. HOLE = 'HOLE'
  54. LABEL = 'LABEL'
  55. MAP = {
  56. ALL: lambda v, e: AllExpression(v.variable, e),
  57. EXISTS: lambda v, e: ExistsExpression(v.variable, e),
  58. NOT: NegatedExpression,
  59. AND: AndExpression,
  60. OR: OrExpression,
  61. IMP: ImpExpression,
  62. IFF: IffExpression,
  63. PRED: ApplicationExpression,
  64. }
  65. class HoleSemantics(object):
  66. """
  67. This class holds the broken-down components of a hole semantics, i.e. it
  68. extracts the holes, labels, logic formula fragments and constraints out of
  69. a big conjunction of such as produced by the hole semantics grammar. It
  70. then provides some operations on the semantics dealing with holes, labels
  71. and finding legal ways to plug holes with labels.
  72. """
  73. def __init__(self, usr):
  74. """
  75. Constructor. `usr' is a ``sem.Expression`` representing an
  76. Underspecified Representation Structure (USR). A USR has the following
  77. special predicates:
  78. ALL(l,v,n),
  79. EXISTS(l,v,n),
  80. AND(l,n,n),
  81. OR(l,n,n),
  82. IMP(l,n,n),
  83. IFF(l,n,n),
  84. PRED(l,v,n,v[,v]*) where the brackets and star indicate zero or more repetitions,
  85. LEQ(n,n),
  86. HOLE(n),
  87. LABEL(n)
  88. where l is the label of the node described by the predicate, n is either
  89. a label or a hole, and v is a variable.
  90. """
  91. self.holes = set()
  92. self.labels = set()
  93. self.fragments = {} # mapping of label -> formula fragment
  94. self.constraints = set() # set of Constraints
  95. self._break_down(usr)
  96. self.top_most_labels = self._find_top_most_labels()
  97. self.top_hole = self._find_top_hole()
  98. def is_node(self, x):
  99. """
  100. Return true if x is a node (label or hole) in this semantic
  101. representation.
  102. """
  103. return x in (self.labels | self.holes)
  104. def _break_down(self, usr):
  105. """
  106. Extract holes, labels, formula fragments and constraints from the hole
  107. semantics underspecified representation (USR).
  108. """
  109. if isinstance(usr, AndExpression):
  110. self._break_down(usr.first)
  111. self._break_down(usr.second)
  112. elif isinstance(usr, ApplicationExpression):
  113. func, args = usr.uncurry()
  114. if func.variable.name == Constants.LEQ:
  115. self.constraints.add(Constraint(args[0], args[1]))
  116. elif func.variable.name == Constants.HOLE:
  117. self.holes.add(args[0])
  118. elif func.variable.name == Constants.LABEL:
  119. self.labels.add(args[0])
  120. else:
  121. label = args[0]
  122. assert label not in self.fragments
  123. self.fragments[label] = (func, args[1:])
  124. else:
  125. raise ValueError(usr.label())
  126. def _find_top_nodes(self, node_list):
  127. top_nodes = node_list.copy()
  128. for f in itervalues(self.fragments):
  129. # the label is the first argument of the predicate
  130. args = f[1]
  131. for arg in args:
  132. if arg in node_list:
  133. top_nodes.discard(arg)
  134. return top_nodes
  135. def _find_top_most_labels(self):
  136. """
  137. Return the set of labels which are not referenced directly as part of
  138. another formula fragment. These will be the top-most labels for the
  139. subtree that they are part of.
  140. """
  141. return self._find_top_nodes(self.labels)
  142. def _find_top_hole(self):
  143. """
  144. Return the hole that will be the top of the formula tree.
  145. """
  146. top_holes = self._find_top_nodes(self.holes)
  147. assert len(top_holes) == 1 # it must be unique
  148. return top_holes.pop()
  149. def pluggings(self):
  150. """
  151. Calculate and return all the legal pluggings (mappings of labels to
  152. holes) of this semantics given the constraints.
  153. """
  154. record = []
  155. self._plug_nodes([(self.top_hole, [])], self.top_most_labels, {}, record)
  156. return record
  157. def _plug_nodes(self, queue, potential_labels, plug_acc, record):
  158. """
  159. Plug the nodes in `queue' with the labels in `potential_labels'.
  160. Each element of `queue' is a tuple of the node to plug and the list of
  161. ancestor holes from the root of the graph to that node.
  162. `potential_labels' is a set of the labels which are still available for
  163. plugging.
  164. `plug_acc' is the incomplete mapping of holes to labels made on the
  165. current branch of the search tree so far.
  166. `record' is a list of all the complete pluggings that we have found in
  167. total so far. It is the only parameter that is destructively updated.
  168. """
  169. if queue != []:
  170. (node, ancestors) = queue[0]
  171. if node in self.holes:
  172. # The node is a hole, try to plug it.
  173. self._plug_hole(
  174. node, ancestors, queue[1:], potential_labels, plug_acc, record
  175. )
  176. else:
  177. assert node in self.labels
  178. # The node is a label. Replace it in the queue by the holes and
  179. # labels in the formula fragment named by that label.
  180. args = self.fragments[node][1]
  181. head = [(a, ancestors) for a in args if self.is_node(a)]
  182. self._plug_nodes(head + queue[1:], potential_labels, plug_acc, record)
  183. else:
  184. raise Exception('queue empty')
  185. def _plug_hole(self, hole, ancestors0, queue, potential_labels0, plug_acc0, record):
  186. """
  187. Try all possible ways of plugging a single hole.
  188. See _plug_nodes for the meanings of the parameters.
  189. """
  190. # Add the current hole we're trying to plug into the list of ancestors.
  191. assert hole not in ancestors0
  192. ancestors = [hole] + ancestors0
  193. # Try each potential label in this hole in turn.
  194. for l in potential_labels0:
  195. # Is the label valid in this hole?
  196. if self._violates_constraints(l, ancestors):
  197. continue
  198. plug_acc = plug_acc0.copy()
  199. plug_acc[hole] = l
  200. potential_labels = potential_labels0.copy()
  201. potential_labels.remove(l)
  202. if len(potential_labels) == 0:
  203. # No more potential labels. That must mean all the holes have
  204. # been filled so we have found a legal plugging so remember it.
  205. #
  206. # Note that the queue might not be empty because there might
  207. # be labels on there that point to formula fragments with
  208. # no holes in them. _sanity_check_plugging will make sure
  209. # all holes are filled.
  210. self._sanity_check_plugging(plug_acc, self.top_hole, [])
  211. record.append(plug_acc)
  212. else:
  213. # Recursively try to fill in the rest of the holes in the
  214. # queue. The label we just plugged into the hole could have
  215. # holes of its own so at the end of the queue. Putting it on
  216. # the end of the queue gives us a breadth-first search, so that
  217. # all the holes at level i of the formula tree are filled
  218. # before filling level i+1.
  219. # A depth-first search would work as well since the trees must
  220. # be finite but the bookkeeping would be harder.
  221. self._plug_nodes(
  222. queue + [(l, ancestors)], potential_labels, plug_acc, record
  223. )
  224. def _violates_constraints(self, label, ancestors):
  225. """
  226. Return True if the `label' cannot be placed underneath the holes given
  227. by the set `ancestors' because it would violate the constraints imposed
  228. on it.
  229. """
  230. for c in self.constraints:
  231. if c.lhs == label:
  232. if c.rhs not in ancestors:
  233. return True
  234. return False
  235. def _sanity_check_plugging(self, plugging, node, ancestors):
  236. """
  237. Make sure that a given plugging is legal. We recursively go through
  238. each node and make sure that no constraints are violated.
  239. We also check that all holes have been filled.
  240. """
  241. if node in self.holes:
  242. ancestors = [node] + ancestors
  243. label = plugging[node]
  244. else:
  245. label = node
  246. assert label in self.labels
  247. for c in self.constraints:
  248. if c.lhs == label:
  249. assert c.rhs in ancestors
  250. args = self.fragments[label][1]
  251. for arg in args:
  252. if self.is_node(arg):
  253. self._sanity_check_plugging(plugging, arg, [label] + ancestors)
  254. def formula_tree(self, plugging):
  255. """
  256. Return the first-order logic formula tree for this underspecified
  257. representation using the plugging given.
  258. """
  259. return self._formula_tree(plugging, self.top_hole)
  260. def _formula_tree(self, plugging, node):
  261. if node in plugging:
  262. return self._formula_tree(plugging, plugging[node])
  263. elif node in self.fragments:
  264. pred, args = self.fragments[node]
  265. children = [self._formula_tree(plugging, arg) for arg in args]
  266. return reduce(Constants.MAP[pred.variable.name], children)
  267. else:
  268. return node
  269. @compat.python_2_unicode_compatible
  270. class Constraint(object):
  271. """
  272. This class represents a constraint of the form (L =< N),
  273. where L is a label and N is a node (a label or a hole).
  274. """
  275. def __init__(self, lhs, rhs):
  276. self.lhs = lhs
  277. self.rhs = rhs
  278. def __eq__(self, other):
  279. if self.__class__ == other.__class__:
  280. return self.lhs == other.lhs and self.rhs == other.rhs
  281. else:
  282. return False
  283. def __ne__(self, other):
  284. return not (self == other)
  285. def __hash__(self):
  286. return hash(repr(self))
  287. def __repr__(self):
  288. return '(%s < %s)' % (self.lhs, self.rhs)
  289. def hole_readings(sentence, grammar_filename=None, verbose=False):
  290. if not grammar_filename:
  291. grammar_filename = 'grammars/sample_grammars/hole.fcfg'
  292. if verbose:
  293. print('Reading grammar file', grammar_filename)
  294. parser = load_parser(grammar_filename)
  295. # Parse the sentence.
  296. tokens = sentence.split()
  297. trees = list(parser.parse(tokens))
  298. if verbose:
  299. print('Got %d different parses' % len(trees))
  300. all_readings = []
  301. for tree in trees:
  302. # Get the semantic feature from the top of the parse tree.
  303. sem = tree.label()['SEM'].simplify()
  304. # Print the raw semantic representation.
  305. if verbose:
  306. print('Raw: ', sem)
  307. # Skolemize away all quantifiers. All variables become unique.
  308. while isinstance(sem, LambdaExpression):
  309. sem = sem.term
  310. skolemized = skolemize(sem)
  311. if verbose:
  312. print('Skolemized:', skolemized)
  313. # Break the hole semantics representation down into its components
  314. # i.e. holes, labels, formula fragments and constraints.
  315. hole_sem = HoleSemantics(skolemized)
  316. # Maybe show the details of the semantic representation.
  317. if verbose:
  318. print('Holes: ', hole_sem.holes)
  319. print('Labels: ', hole_sem.labels)
  320. print('Constraints: ', hole_sem.constraints)
  321. print('Top hole: ', hole_sem.top_hole)
  322. print('Top labels: ', hole_sem.top_most_labels)
  323. print('Fragments:')
  324. for l, f in hole_sem.fragments.items():
  325. print('\t%s: %s' % (l, f))
  326. # Find all the possible ways to plug the formulas together.
  327. pluggings = hole_sem.pluggings()
  328. # Build FOL formula trees using the pluggings.
  329. readings = list(map(hole_sem.formula_tree, pluggings))
  330. # Print out the formulas in a textual format.
  331. if verbose:
  332. for i, r in enumerate(readings):
  333. print()
  334. print('%d. %s' % (i, r))
  335. print()
  336. all_readings.extend(readings)
  337. return all_readings
  338. if __name__ == '__main__':
  339. for r in hole_readings('a dog barks'):
  340. print(r)
  341. print()
  342. for r in hole_readings('every girl chases a dog'):
  343. print(r)