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