featurechart.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: Chart Parser for Feature-Based Grammars
  3. #
  4. # Copyright (C) 2001-2019 NLTK Project
  5. # Author: Rob Speer <rspeer@mit.edu>
  6. # Peter Ljunglöf <peter.ljunglof@heatherleaf.se>
  7. # URL: <http://nltk.org/>
  8. # For license information, see LICENSE.TXT
  9. """
  10. Extension of chart parsing implementation to handle grammars with
  11. feature structures as nodes.
  12. """
  13. from __future__ import print_function, unicode_literals
  14. from six.moves import range
  15. from nltk.compat import python_2_unicode_compatible
  16. from nltk.featstruct import FeatStruct, unify, TYPE, find_variables
  17. from nltk.sem import logic
  18. from nltk.tree import Tree
  19. from nltk.grammar import (
  20. Nonterminal,
  21. Production,
  22. CFG,
  23. FeatStructNonterminal,
  24. is_nonterminal,
  25. is_terminal,
  26. )
  27. from nltk.parse.chart import (
  28. TreeEdge,
  29. Chart,
  30. ChartParser,
  31. EdgeI,
  32. FundamentalRule,
  33. LeafInitRule,
  34. EmptyPredictRule,
  35. BottomUpPredictRule,
  36. SingleEdgeFundamentalRule,
  37. BottomUpPredictCombineRule,
  38. CachedTopDownPredictRule,
  39. TopDownInitRule,
  40. )
  41. # ////////////////////////////////////////////////////////////
  42. # Tree Edge
  43. # ////////////////////////////////////////////////////////////
  44. @python_2_unicode_compatible
  45. class FeatureTreeEdge(TreeEdge):
  46. """
  47. A specialized tree edge that allows shared variable bindings
  48. between nonterminals on the left-hand side and right-hand side.
  49. Each ``FeatureTreeEdge`` contains a set of ``bindings``, i.e., a
  50. dictionary mapping from variables to values. If the edge is not
  51. complete, then these bindings are simply stored. However, if the
  52. edge is complete, then the constructor applies these bindings to
  53. every nonterminal in the edge whose symbol implements the
  54. interface ``SubstituteBindingsI``.
  55. """
  56. def __init__(self, span, lhs, rhs, dot=0, bindings=None):
  57. """
  58. Construct a new edge. If the edge is incomplete (i.e., if
  59. ``dot<len(rhs)``), then store the bindings as-is. If the edge
  60. is complete (i.e., if ``dot==len(rhs)``), then apply the
  61. bindings to all nonterminals in ``lhs`` and ``rhs``, and then
  62. clear the bindings. See ``TreeEdge`` for a description of
  63. the other arguments.
  64. """
  65. if bindings is None:
  66. bindings = {}
  67. # If the edge is complete, then substitute in the bindings,
  68. # and then throw them away. (If we didn't throw them away, we
  69. # might think that 2 complete edges are different just because
  70. # they have different bindings, even though all bindings have
  71. # already been applied.)
  72. if dot == len(rhs) and bindings:
  73. lhs = self._bind(lhs, bindings)
  74. rhs = [self._bind(elt, bindings) for elt in rhs]
  75. bindings = {}
  76. # Initialize the edge.
  77. TreeEdge.__init__(self, span, lhs, rhs, dot)
  78. self._bindings = bindings
  79. self._comparison_key = (self._comparison_key, tuple(sorted(bindings.items())))
  80. @staticmethod
  81. def from_production(production, index):
  82. """
  83. :return: A new ``TreeEdge`` formed from the given production.
  84. The new edge's left-hand side and right-hand side will
  85. be taken from ``production``; its span will be
  86. ``(index,index)``; and its dot position will be ``0``.
  87. :rtype: TreeEdge
  88. """
  89. return FeatureTreeEdge(
  90. span=(index, index), lhs=production.lhs(), rhs=production.rhs(), dot=0
  91. )
  92. def move_dot_forward(self, new_end, bindings=None):
  93. """
  94. :return: A new ``FeatureTreeEdge`` formed from this edge.
  95. The new edge's dot position is increased by ``1``,
  96. and its end index will be replaced by ``new_end``.
  97. :rtype: FeatureTreeEdge
  98. :param new_end: The new end index.
  99. :type new_end: int
  100. :param bindings: Bindings for the new edge.
  101. :type bindings: dict
  102. """
  103. return FeatureTreeEdge(
  104. span=(self._span[0], new_end),
  105. lhs=self._lhs,
  106. rhs=self._rhs,
  107. dot=self._dot + 1,
  108. bindings=bindings,
  109. )
  110. def _bind(self, nt, bindings):
  111. if not isinstance(nt, FeatStructNonterminal):
  112. return nt
  113. return nt.substitute_bindings(bindings)
  114. def next_with_bindings(self):
  115. return self._bind(self.nextsym(), self._bindings)
  116. def bindings(self):
  117. """
  118. Return a copy of this edge's bindings dictionary.
  119. """
  120. return self._bindings.copy()
  121. def variables(self):
  122. """
  123. :return: The set of variables used by this edge.
  124. :rtype: set(Variable)
  125. """
  126. return find_variables(
  127. [self._lhs]
  128. + list(self._rhs)
  129. + list(self._bindings.keys())
  130. + list(self._bindings.values()),
  131. fs_class=FeatStruct,
  132. )
  133. def __str__(self):
  134. if self.is_complete():
  135. return TreeEdge.__unicode__(self)
  136. else:
  137. bindings = '{%s}' % ', '.join(
  138. '%s: %r' % item for item in sorted(self._bindings.items())
  139. )
  140. return '%s %s' % (TreeEdge.__unicode__(self), bindings)
  141. # ////////////////////////////////////////////////////////////
  142. # A specialized Chart for feature grammars
  143. # ////////////////////////////////////////////////////////////
  144. # TODO: subsumes check when adding new edges
  145. class FeatureChart(Chart):
  146. """
  147. A Chart for feature grammars.
  148. :see: ``Chart`` for more information.
  149. """
  150. def select(self, **restrictions):
  151. """
  152. Returns an iterator over the edges in this chart.
  153. See ``Chart.select`` for more information about the
  154. ``restrictions`` on the edges.
  155. """
  156. # If there are no restrictions, then return all edges.
  157. if restrictions == {}:
  158. return iter(self._edges)
  159. # Find the index corresponding to the given restrictions.
  160. restr_keys = sorted(restrictions.keys())
  161. restr_keys = tuple(restr_keys)
  162. # If it doesn't exist, then create it.
  163. if restr_keys not in self._indexes:
  164. self._add_index(restr_keys)
  165. vals = tuple(
  166. self._get_type_if_possible(restrictions[key]) for key in restr_keys
  167. )
  168. return iter(self._indexes[restr_keys].get(vals, []))
  169. def _add_index(self, restr_keys):
  170. """
  171. A helper function for ``select``, which creates a new index for
  172. a given set of attributes (aka restriction keys).
  173. """
  174. # Make sure it's a valid index.
  175. for key in restr_keys:
  176. if not hasattr(EdgeI, key):
  177. raise ValueError('Bad restriction: %s' % key)
  178. # Create the index.
  179. index = self._indexes[restr_keys] = {}
  180. # Add all existing edges to the index.
  181. for edge in self._edges:
  182. vals = tuple(
  183. self._get_type_if_possible(getattr(edge, key)()) for key in restr_keys
  184. )
  185. index.setdefault(vals, []).append(edge)
  186. def _register_with_indexes(self, edge):
  187. """
  188. A helper function for ``insert``, which registers the new
  189. edge with all existing indexes.
  190. """
  191. for (restr_keys, index) in self._indexes.items():
  192. vals = tuple(
  193. self._get_type_if_possible(getattr(edge, key)()) for key in restr_keys
  194. )
  195. index.setdefault(vals, []).append(edge)
  196. def _get_type_if_possible(self, item):
  197. """
  198. Helper function which returns the ``TYPE`` feature of the ``item``,
  199. if it exists, otherwise it returns the ``item`` itself
  200. """
  201. if isinstance(item, dict) and TYPE in item:
  202. return item[TYPE]
  203. else:
  204. return item
  205. def parses(self, start, tree_class=Tree):
  206. for edge in self.select(start=0, end=self._num_leaves):
  207. if (
  208. (isinstance(edge, FeatureTreeEdge))
  209. and (edge.lhs()[TYPE] == start[TYPE])
  210. and (unify(edge.lhs(), start, rename_vars=True))
  211. ):
  212. for tree in self.trees(edge, complete=True, tree_class=tree_class):
  213. yield tree
  214. # ////////////////////////////////////////////////////////////
  215. # Fundamental Rule
  216. # ////////////////////////////////////////////////////////////
  217. class FeatureFundamentalRule(FundamentalRule):
  218. """
  219. A specialized version of the fundamental rule that operates on
  220. nonterminals whose symbols are ``FeatStructNonterminal``s. Rather
  221. tha simply comparing the nonterminals for equality, they are
  222. unified. Variable bindings from these unifications are collected
  223. and stored in the chart using a ``FeatureTreeEdge``. When a
  224. complete edge is generated, these bindings are applied to all
  225. nonterminals in the edge.
  226. The fundamental rule states that:
  227. - ``[A -> alpha \* B1 beta][i:j]``
  228. - ``[B2 -> gamma \*][j:k]``
  229. licenses the edge:
  230. - ``[A -> alpha B3 \* beta][i:j]``
  231. assuming that B1 and B2 can be unified to generate B3.
  232. """
  233. def apply(self, chart, grammar, left_edge, right_edge):
  234. # Make sure the rule is applicable.
  235. if not (
  236. left_edge.end() == right_edge.start()
  237. and left_edge.is_incomplete()
  238. and right_edge.is_complete()
  239. and isinstance(left_edge, FeatureTreeEdge)
  240. ):
  241. return
  242. found = right_edge.lhs()
  243. nextsym = left_edge.nextsym()
  244. if isinstance(right_edge, FeatureTreeEdge):
  245. if not is_nonterminal(nextsym):
  246. return
  247. if left_edge.nextsym()[TYPE] != right_edge.lhs()[TYPE]:
  248. return
  249. # Create a copy of the bindings.
  250. bindings = left_edge.bindings()
  251. # We rename vars here, because we don't want variables
  252. # from the two different productions to match.
  253. found = found.rename_variables(used_vars=left_edge.variables())
  254. # Unify B1 (left_edge.nextsym) with B2 (right_edge.lhs) to
  255. # generate B3 (result).
  256. result = unify(nextsym, found, bindings, rename_vars=False)
  257. if result is None:
  258. return
  259. else:
  260. if nextsym != found:
  261. return
  262. # Create a copy of the bindings.
  263. bindings = left_edge.bindings()
  264. # Construct the new edge.
  265. new_edge = left_edge.move_dot_forward(right_edge.end(), bindings)
  266. # Add it to the chart, with appropriate child pointers.
  267. if chart.insert_with_backpointer(new_edge, left_edge, right_edge):
  268. yield new_edge
  269. class FeatureSingleEdgeFundamentalRule(SingleEdgeFundamentalRule):
  270. """
  271. A specialized version of the completer / single edge fundamental rule
  272. that operates on nonterminals whose symbols are ``FeatStructNonterminal``s.
  273. Rather than simply comparing the nonterminals for equality, they are
  274. unified.
  275. """
  276. _fundamental_rule = FeatureFundamentalRule()
  277. def _apply_complete(self, chart, grammar, right_edge):
  278. fr = self._fundamental_rule
  279. for left_edge in chart.select(
  280. end=right_edge.start(), is_complete=False, nextsym=right_edge.lhs()
  281. ):
  282. for new_edge in fr.apply(chart, grammar, left_edge, right_edge):
  283. yield new_edge
  284. def _apply_incomplete(self, chart, grammar, left_edge):
  285. fr = self._fundamental_rule
  286. for right_edge in chart.select(
  287. start=left_edge.end(), is_complete=True, lhs=left_edge.nextsym()
  288. ):
  289. for new_edge in fr.apply(chart, grammar, left_edge, right_edge):
  290. yield new_edge
  291. # ////////////////////////////////////////////////////////////
  292. # Top-Down Prediction
  293. # ////////////////////////////////////////////////////////////
  294. class FeatureTopDownInitRule(TopDownInitRule):
  295. def apply(self, chart, grammar):
  296. for prod in grammar.productions(lhs=grammar.start()):
  297. new_edge = FeatureTreeEdge.from_production(prod, 0)
  298. if chart.insert(new_edge, ()):
  299. yield new_edge
  300. class FeatureTopDownPredictRule(CachedTopDownPredictRule):
  301. """
  302. A specialized version of the (cached) top down predict rule that operates
  303. on nonterminals whose symbols are ``FeatStructNonterminal``s. Rather
  304. than simply comparing the nonterminals for equality, they are
  305. unified.
  306. The top down expand rule states that:
  307. - ``[A -> alpha \* B1 beta][i:j]``
  308. licenses the edge:
  309. - ``[B2 -> \* gamma][j:j]``
  310. for each grammar production ``B2 -> gamma``, assuming that B1
  311. and B2 can be unified.
  312. """
  313. def apply(self, chart, grammar, edge):
  314. if edge.is_complete():
  315. return
  316. nextsym, index = edge.nextsym(), edge.end()
  317. if not is_nonterminal(nextsym):
  318. return
  319. # If we've already applied this rule to an edge with the same
  320. # next & end, and the chart & grammar have not changed, then
  321. # just return (no new edges to add).
  322. nextsym_with_bindings = edge.next_with_bindings()
  323. done = self._done.get((nextsym_with_bindings, index), (None, None))
  324. if done[0] is chart and done[1] is grammar:
  325. return
  326. for prod in grammar.productions(lhs=nextsym):
  327. # If the left corner in the predicted production is
  328. # leaf, it must match with the input.
  329. if prod.rhs():
  330. first = prod.rhs()[0]
  331. if is_terminal(first):
  332. if index >= chart.num_leaves():
  333. continue
  334. if first != chart.leaf(index):
  335. continue
  336. # We rename vars here, because we don't want variables
  337. # from the two different productions to match.
  338. if unify(prod.lhs(), nextsym_with_bindings, rename_vars=True):
  339. new_edge = FeatureTreeEdge.from_production(prod, edge.end())
  340. if chart.insert(new_edge, ()):
  341. yield new_edge
  342. # Record the fact that we've applied this rule.
  343. self._done[nextsym_with_bindings, index] = (chart, grammar)
  344. # ////////////////////////////////////////////////////////////
  345. # Bottom-Up Prediction
  346. # ////////////////////////////////////////////////////////////
  347. class FeatureBottomUpPredictRule(BottomUpPredictRule):
  348. def apply(self, chart, grammar, edge):
  349. if edge.is_incomplete():
  350. return
  351. for prod in grammar.productions(rhs=edge.lhs()):
  352. if isinstance(edge, FeatureTreeEdge):
  353. _next = prod.rhs()[0]
  354. if not is_nonterminal(_next):
  355. continue
  356. new_edge = FeatureTreeEdge.from_production(prod, edge.start())
  357. if chart.insert(new_edge, ()):
  358. yield new_edge
  359. class FeatureBottomUpPredictCombineRule(BottomUpPredictCombineRule):
  360. def apply(self, chart, grammar, edge):
  361. if edge.is_incomplete():
  362. return
  363. found = edge.lhs()
  364. for prod in grammar.productions(rhs=found):
  365. bindings = {}
  366. if isinstance(edge, FeatureTreeEdge):
  367. _next = prod.rhs()[0]
  368. if not is_nonterminal(_next):
  369. continue
  370. # We rename vars here, because we don't want variables
  371. # from the two different productions to match.
  372. used_vars = find_variables(
  373. (prod.lhs(),) + prod.rhs(), fs_class=FeatStruct
  374. )
  375. found = found.rename_variables(used_vars=used_vars)
  376. result = unify(_next, found, bindings, rename_vars=False)
  377. if result is None:
  378. continue
  379. new_edge = FeatureTreeEdge.from_production(
  380. prod, edge.start()
  381. ).move_dot_forward(edge.end(), bindings)
  382. if chart.insert(new_edge, (edge,)):
  383. yield new_edge
  384. class FeatureEmptyPredictRule(EmptyPredictRule):
  385. def apply(self, chart, grammar):
  386. for prod in grammar.productions(empty=True):
  387. for index in range(chart.num_leaves() + 1):
  388. new_edge = FeatureTreeEdge.from_production(prod, index)
  389. if chart.insert(new_edge, ()):
  390. yield new_edge
  391. # ////////////////////////////////////////////////////////////
  392. # Feature Chart Parser
  393. # ////////////////////////////////////////////////////////////
  394. TD_FEATURE_STRATEGY = [
  395. LeafInitRule(),
  396. FeatureTopDownInitRule(),
  397. FeatureTopDownPredictRule(),
  398. FeatureSingleEdgeFundamentalRule(),
  399. ]
  400. BU_FEATURE_STRATEGY = [
  401. LeafInitRule(),
  402. FeatureEmptyPredictRule(),
  403. FeatureBottomUpPredictRule(),
  404. FeatureSingleEdgeFundamentalRule(),
  405. ]
  406. BU_LC_FEATURE_STRATEGY = [
  407. LeafInitRule(),
  408. FeatureEmptyPredictRule(),
  409. FeatureBottomUpPredictCombineRule(),
  410. FeatureSingleEdgeFundamentalRule(),
  411. ]
  412. class FeatureChartParser(ChartParser):
  413. def __init__(
  414. self,
  415. grammar,
  416. strategy=BU_LC_FEATURE_STRATEGY,
  417. trace_chart_width=20,
  418. chart_class=FeatureChart,
  419. **parser_args
  420. ):
  421. ChartParser.__init__(
  422. self,
  423. grammar,
  424. strategy=strategy,
  425. trace_chart_width=trace_chart_width,
  426. chart_class=chart_class,
  427. **parser_args
  428. )
  429. class FeatureTopDownChartParser(FeatureChartParser):
  430. def __init__(self, grammar, **parser_args):
  431. FeatureChartParser.__init__(self, grammar, TD_FEATURE_STRATEGY, **parser_args)
  432. class FeatureBottomUpChartParser(FeatureChartParser):
  433. def __init__(self, grammar, **parser_args):
  434. FeatureChartParser.__init__(self, grammar, BU_FEATURE_STRATEGY, **parser_args)
  435. class FeatureBottomUpLeftCornerChartParser(FeatureChartParser):
  436. def __init__(self, grammar, **parser_args):
  437. FeatureChartParser.__init__(
  438. self, grammar, BU_LC_FEATURE_STRATEGY, **parser_args
  439. )
  440. # ////////////////////////////////////////////////////////////
  441. # Instantiate Variable Chart
  442. # ////////////////////////////////////////////////////////////
  443. class InstantiateVarsChart(FeatureChart):
  444. """
  445. A specialized chart that 'instantiates' variables whose names
  446. start with '@', by replacing them with unique new variables.
  447. In particular, whenever a complete edge is added to the chart, any
  448. variables in the edge's ``lhs`` whose names start with '@' will be
  449. replaced by unique new ``Variable``s.
  450. """
  451. def __init__(self, tokens):
  452. FeatureChart.__init__(self, tokens)
  453. def initialize(self):
  454. self._instantiated = set()
  455. FeatureChart.initialize(self)
  456. def insert(self, edge, child_pointer_list):
  457. if edge in self._instantiated:
  458. return False
  459. self.instantiate_edge(edge)
  460. return FeatureChart.insert(self, edge, child_pointer_list)
  461. def instantiate_edge(self, edge):
  462. """
  463. If the edge is a ``FeatureTreeEdge``, and it is complete,
  464. then instantiate all variables whose names start with '@',
  465. by replacing them with unique new variables.
  466. Note that instantiation is done in-place, since the
  467. parsing algorithms might already hold a reference to
  468. the edge for future use.
  469. """
  470. # If the edge is a leaf, or is not complete, or is
  471. # already in the chart, then just return it as-is.
  472. if not isinstance(edge, FeatureTreeEdge):
  473. return
  474. if not edge.is_complete():
  475. return
  476. if edge in self._edge_to_cpls:
  477. return
  478. # Get a list of variables that need to be instantiated.
  479. # If there are none, then return as-is.
  480. inst_vars = self.inst_vars(edge)
  481. if not inst_vars:
  482. return
  483. # Instantiate the edge!
  484. self._instantiated.add(edge)
  485. edge._lhs = edge.lhs().substitute_bindings(inst_vars)
  486. def inst_vars(self, edge):
  487. return dict(
  488. (var, logic.unique_variable())
  489. for var in edge.lhs().variables()
  490. if var.name.startswith('@')
  491. )
  492. # ////////////////////////////////////////////////////////////
  493. # Demo
  494. # ////////////////////////////////////////////////////////////
  495. def demo_grammar():
  496. from nltk.grammar import FeatureGrammar
  497. return FeatureGrammar.fromstring(
  498. """
  499. S -> NP VP
  500. PP -> Prep NP
  501. NP -> NP PP
  502. VP -> VP PP
  503. VP -> Verb NP
  504. VP -> Verb
  505. NP -> Det[pl=?x] Noun[pl=?x]
  506. NP -> "John"
  507. NP -> "I"
  508. Det -> "the"
  509. Det -> "my"
  510. Det[-pl] -> "a"
  511. Noun[-pl] -> "dog"
  512. Noun[-pl] -> "cookie"
  513. Verb -> "ate"
  514. Verb -> "saw"
  515. Prep -> "with"
  516. Prep -> "under"
  517. """
  518. )
  519. def demo(
  520. print_times=True,
  521. print_grammar=True,
  522. print_trees=True,
  523. print_sentence=True,
  524. trace=1,
  525. parser=FeatureChartParser,
  526. sent='I saw John with a dog with my cookie',
  527. ):
  528. import sys, time
  529. print()
  530. grammar = demo_grammar()
  531. if print_grammar:
  532. print(grammar)
  533. print()
  534. print("*", parser.__name__)
  535. if print_sentence:
  536. print("Sentence:", sent)
  537. tokens = sent.split()
  538. t = time.clock()
  539. cp = parser(grammar, trace=trace)
  540. chart = cp.chart_parse(tokens)
  541. trees = list(chart.parses(grammar.start()))
  542. if print_times:
  543. print("Time: %s" % (time.clock() - t))
  544. if print_trees:
  545. for tree in trees:
  546. print(tree)
  547. else:
  548. print("Nr trees:", len(trees))
  549. def run_profile():
  550. import profile
  551. profile.run('for i in range(1): demo()', '/tmp/profile.out')
  552. import pstats
  553. p = pstats.Stats('/tmp/profile.out')
  554. p.strip_dirs().sort_stats('time', 'cum').print_stats(60)
  555. p.strip_dirs().sort_stats('cum', 'time').print_stats(60)
  556. if __name__ == '__main__':
  557. from nltk.data import load
  558. demo()
  559. print()
  560. grammar = load('grammars/book_grammars/feat0.fcfg')
  561. cp = FeatureChartParser(grammar, trace=2)
  562. sent = 'Kim likes children'
  563. tokens = sent.split()
  564. trees = cp.parse(tokens)
  565. for tree in trees:
  566. print(tree)