hole.py 14 KB

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