/
chartparser_app.py
2569 lines (2174 loc) · 83.6 KB
/
chartparser_app.py
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Natural Language Toolkit: Chart Parser Application
#
# Copyright (C) 2001-2021 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# Jean Mark Gawron <gawron@mail.sdsu.edu>
# Steven Bird <stevenbird1@gmail.com>
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
A graphical tool for exploring chart parsing.
Chart parsing is a flexible parsing algorithm that uses a data
structure called a "chart" to record hypotheses about syntactic
constituents. Each hypothesis is represented by a single "edge" on
the chart. A set of "chart rules" determine when new edges can be
added to the chart. This set of rules controls the overall behavior
of the parser (e.g. whether it parses top-down or bottom-up).
The chart parsing tool demonstrates the process of parsing a single
sentence, with a given grammar and lexicon. Its display is divided
into three sections: the bottom section displays the chart; the middle
section displays the sentence; and the top section displays the
partial syntax tree corresponding to the selected edge. Buttons along
the bottom of the window are used to control the execution of the
algorithm.
The chart parsing tool allows for flexible control of the parsing
algorithm. At each step of the algorithm, you can select which rule
or strategy you wish to apply. This allows you to experiment with
mixing different strategies (e.g. top-down and bottom-up). You can
exercise fine-grained control over the algorithm by selecting which
edge you wish to apply a rule to.
"""
# At some point, we should rewrite this tool to use the new canvas
# widget system.
import os.path
import pickle
from tkinter import (
Button,
Canvas,
Checkbutton,
Frame,
IntVar,
Label,
Menu,
Scrollbar,
Tk,
Toplevel,
)
from tkinter.filedialog import askopenfilename, asksaveasfilename
from tkinter.font import Font
from tkinter.messagebox import showerror, showinfo
from nltk.draw import CFGEditor, TreeSegmentWidget, tree_to_treesegment
from nltk.draw.util import (
CanvasFrame,
ColorizedList,
EntryDialog,
MutableOptionMenu,
ShowText,
SymbolWidget,
)
from nltk.grammar import CFG, Nonterminal
from nltk.parse.chart import (
BottomUpPredictCombineRule,
BottomUpPredictRule,
Chart,
LeafEdge,
LeafInitRule,
SingleEdgeFundamentalRule,
SteppingChartParser,
TopDownInitRule,
TopDownPredictRule,
TreeEdge,
)
from nltk.tree import Tree
from nltk.util import in_idle
# Known bug: ChartView doesn't handle edges generated by epsilon
# productions (e.g., [Production: PP -> ]) very well.
#######################################################################
# Edge List
#######################################################################
class EdgeList(ColorizedList):
ARROW = SymbolWidget.SYMBOLS["rightarrow"]
def _init_colortags(self, textwidget, options):
textwidget.tag_config("terminal", foreground="#006000")
textwidget.tag_config("arrow", font="symbol", underline="0")
textwidget.tag_config("dot", foreground="#000000")
textwidget.tag_config(
"nonterminal", foreground="blue", font=("helvetica", -12, "bold")
)
def _item_repr(self, item):
contents = []
contents.append(("%s\t" % item.lhs(), "nonterminal"))
contents.append((self.ARROW, "arrow"))
for i, elt in enumerate(item.rhs()):
if i == item.dot():
contents.append((" *", "dot"))
if isinstance(elt, Nonterminal):
contents.append((" %s" % elt.symbol(), "nonterminal"))
else:
contents.append((" %r" % elt, "terminal"))
if item.is_complete():
contents.append((" *", "dot"))
return contents
#######################################################################
# Chart Matrix View
#######################################################################
class ChartMatrixView:
"""
A view of a chart that displays the contents of the corresponding matrix.
"""
def __init__(
self, parent, chart, toplevel=True, title="Chart Matrix", show_numedges=False
):
self._chart = chart
self._cells = []
self._marks = []
self._selected_cell = None
if toplevel:
self._root = Toplevel(parent)
self._root.title(title)
self._root.bind("<Control-q>", self.destroy)
self._init_quit(self._root)
else:
self._root = Frame(parent)
self._init_matrix(self._root)
self._init_list(self._root)
if show_numedges:
self._init_numedges(self._root)
else:
self._numedges_label = None
self._callbacks = {}
self._num_edges = 0
self.draw()
def _init_quit(self, root):
quit = Button(root, text="Quit", command=self.destroy)
quit.pack(side="bottom", expand=0, fill="none")
def _init_matrix(self, root):
cframe = Frame(root, border=2, relief="sunken")
cframe.pack(expand=0, fill="none", padx=1, pady=3, side="top")
self._canvas = Canvas(cframe, width=200, height=200, background="white")
self._canvas.pack(expand=0, fill="none")
def _init_numedges(self, root):
self._numedges_label = Label(root, text="0 edges")
self._numedges_label.pack(expand=0, fill="none", side="top")
def _init_list(self, root):
self._list = EdgeList(root, [], width=20, height=5)
self._list.pack(side="top", expand=1, fill="both", pady=3)
def cb(edge, self=self):
self._fire_callbacks("select", edge)
self._list.add_callback("select", cb)
self._list.focus()
def destroy(self, *e):
if self._root is None:
return
try:
self._root.destroy()
except:
pass
self._root = None
def set_chart(self, chart):
if chart is not self._chart:
self._chart = chart
self._num_edges = 0
self.draw()
def update(self):
if self._root is None:
return
# Count the edges in each cell
N = len(self._cells)
cell_edges = [[0 for i in range(N)] for j in range(N)]
for edge in self._chart:
cell_edges[edge.start()][edge.end()] += 1
# Color the cells correspondingly.
for i in range(N):
for j in range(i, N):
if cell_edges[i][j] == 0:
color = "gray20"
else:
color = "#00{:02x}{:02x}".format(
min(255, 50 + 128 * cell_edges[i][j] / 10),
max(0, 128 - 128 * cell_edges[i][j] / 10),
)
cell_tag = self._cells[i][j]
self._canvas.itemconfig(cell_tag, fill=color)
if (i, j) == self._selected_cell:
self._canvas.itemconfig(cell_tag, outline="#00ffff", width=3)
self._canvas.tag_raise(cell_tag)
else:
self._canvas.itemconfig(cell_tag, outline="black", width=1)
# Update the edge list.
edges = list(self._chart.select(span=self._selected_cell))
self._list.set(edges)
# Update our edge count.
self._num_edges = self._chart.num_edges()
if self._numedges_label is not None:
self._numedges_label["text"] = "%d edges" % self._num_edges
def activate(self):
self._canvas.itemconfig("inactivebox", state="hidden")
self.update()
def inactivate(self):
self._canvas.itemconfig("inactivebox", state="normal")
self.update()
def add_callback(self, event, func):
self._callbacks.setdefault(event, {})[func] = 1
def remove_callback(self, event, func=None):
if func is None:
del self._callbacks[event]
else:
try:
del self._callbacks[event][func]
except:
pass
def _fire_callbacks(self, event, *args):
if event not in self._callbacks:
return
for cb_func in list(self._callbacks[event].keys()):
cb_func(*args)
def select_cell(self, i, j):
if self._root is None:
return
# If the cell is already selected (and the chart contents
# haven't changed), then do nothing.
if (i, j) == self._selected_cell and self._chart.num_edges() == self._num_edges:
return
self._selected_cell = (i, j)
self.update()
# Fire the callback.
self._fire_callbacks("select_cell", i, j)
def deselect_cell(self):
if self._root is None:
return
self._selected_cell = None
self._list.set([])
self.update()
def _click_cell(self, i, j):
if self._selected_cell == (i, j):
self.deselect_cell()
else:
self.select_cell(i, j)
def view_edge(self, edge):
self.select_cell(*edge.span())
self._list.view(edge)
def mark_edge(self, edge):
if self._root is None:
return
self.select_cell(*edge.span())
self._list.mark(edge)
def unmark_edge(self, edge=None):
if self._root is None:
return
self._list.unmark(edge)
def markonly_edge(self, edge):
if self._root is None:
return
self.select_cell(*edge.span())
self._list.markonly(edge)
def draw(self):
if self._root is None:
return
LEFT_MARGIN = BOT_MARGIN = 15
TOP_MARGIN = 5
c = self._canvas
c.delete("all")
N = self._chart.num_leaves() + 1
dx = (int(c["width"]) - LEFT_MARGIN) / N
dy = (int(c["height"]) - TOP_MARGIN - BOT_MARGIN) / N
c.delete("all")
# Labels and dotted lines
for i in range(N):
c.create_text(
LEFT_MARGIN - 2, i * dy + dy / 2 + TOP_MARGIN, text=repr(i), anchor="e"
)
c.create_text(
i * dx + dx / 2 + LEFT_MARGIN,
N * dy + TOP_MARGIN + 1,
text=repr(i),
anchor="n",
)
c.create_line(
LEFT_MARGIN,
dy * (i + 1) + TOP_MARGIN,
dx * N + LEFT_MARGIN,
dy * (i + 1) + TOP_MARGIN,
dash=".",
)
c.create_line(
dx * i + LEFT_MARGIN,
TOP_MARGIN,
dx * i + LEFT_MARGIN,
dy * N + TOP_MARGIN,
dash=".",
)
# A box around the whole thing
c.create_rectangle(
LEFT_MARGIN, TOP_MARGIN, LEFT_MARGIN + dx * N, dy * N + TOP_MARGIN, width=2
)
# Cells
self._cells = [[None for i in range(N)] for j in range(N)]
for i in range(N):
for j in range(i, N):
t = c.create_rectangle(
j * dx + LEFT_MARGIN,
i * dy + TOP_MARGIN,
(j + 1) * dx + LEFT_MARGIN,
(i + 1) * dy + TOP_MARGIN,
fill="gray20",
)
self._cells[i][j] = t
def cb(event, self=self, i=i, j=j):
self._click_cell(i, j)
c.tag_bind(t, "<Button-1>", cb)
# Inactive box
xmax, ymax = int(c["width"]), int(c["height"])
t = c.create_rectangle(
-100,
-100,
xmax + 100,
ymax + 100,
fill="gray50",
state="hidden",
tag="inactivebox",
)
c.tag_lower(t)
# Update the cells.
self.update()
def pack(self, *args, **kwargs):
self._root.pack(*args, **kwargs)
#######################################################################
# Chart Results View
#######################################################################
class ChartResultsView:
def __init__(self, parent, chart, grammar, toplevel=True):
self._chart = chart
self._grammar = grammar
self._trees = []
self._y = 10
self._treewidgets = []
self._selection = None
self._selectbox = None
if toplevel:
self._root = Toplevel(parent)
self._root.title("Chart Parser Application: Results")
self._root.bind("<Control-q>", self.destroy)
else:
self._root = Frame(parent)
# Buttons
if toplevel:
buttons = Frame(self._root)
buttons.pack(side="bottom", expand=0, fill="x")
Button(buttons, text="Quit", command=self.destroy).pack(side="right")
Button(buttons, text="Print All", command=self.print_all).pack(side="left")
Button(buttons, text="Print Selection", command=self.print_selection).pack(
side="left"
)
# Canvas frame.
self._cframe = CanvasFrame(self._root, closeenough=20)
self._cframe.pack(side="top", expand=1, fill="both")
# Initial update
self.update()
def update(self, edge=None):
if self._root is None:
return
# If the edge isn't a parse edge, do nothing.
if edge is not None:
if edge.lhs() != self._grammar.start():
return
if edge.span() != (0, self._chart.num_leaves()):
return
for parse in self._chart.parses(self._grammar.start()):
if parse not in self._trees:
self._add(parse)
def _add(self, parse):
# Add it to self._trees.
self._trees.append(parse)
# Create a widget for it.
c = self._cframe.canvas()
treewidget = tree_to_treesegment(c, parse)
# Add it to the canvas frame.
self._treewidgets.append(treewidget)
self._cframe.add_widget(treewidget, 10, self._y)
# Register callbacks.
treewidget.bind_click(self._click)
# Update y.
self._y = treewidget.bbox()[3] + 10
def _click(self, widget):
c = self._cframe.canvas()
if self._selection is not None:
c.delete(self._selectbox)
self._selection = widget
(x1, y1, x2, y2) = widget.bbox()
self._selectbox = c.create_rectangle(x1, y1, x2, y2, width=2, outline="#088")
def _color(self, treewidget, color):
treewidget.label()["color"] = color
for child in treewidget.subtrees():
if isinstance(child, TreeSegmentWidget):
self._color(child, color)
else:
child["color"] = color
def print_all(self, *e):
if self._root is None:
return
self._cframe.print_to_file()
def print_selection(self, *e):
if self._root is None:
return
if self._selection is None:
showerror("Print Error", "No tree selected")
else:
c = self._cframe.canvas()
for widget in self._treewidgets:
if widget is not self._selection:
self._cframe.destroy_widget(widget)
c.delete(self._selectbox)
(x1, y1, x2, y2) = self._selection.bbox()
self._selection.move(10 - x1, 10 - y1)
c["scrollregion"] = f"0 0 {x2 - x1 + 20} {y2 - y1 + 20}"
self._cframe.print_to_file()
# Restore our state.
self._treewidgets = [self._selection]
self.clear()
self.update()
def clear(self):
if self._root is None:
return
for treewidget in self._treewidgets:
self._cframe.destroy_widget(treewidget)
self._trees = []
self._treewidgets = []
if self._selection is not None:
self._cframe.canvas().delete(self._selectbox)
self._selection = None
self._y = 10
def set_chart(self, chart):
self.clear()
self._chart = chart
self.update()
def set_grammar(self, grammar):
self.clear()
self._grammar = grammar
self.update()
def destroy(self, *e):
if self._root is None:
return
try:
self._root.destroy()
except:
pass
self._root = None
def pack(self, *args, **kwargs):
self._root.pack(*args, **kwargs)
#######################################################################
# Chart Comparer
#######################################################################
class ChartComparer:
"""
:ivar _root: The root window
:ivar _charts: A dictionary mapping names to charts. When
charts are loaded, they are added to this dictionary.
:ivar _left_chart: The left ``Chart``.
:ivar _left_name: The name ``_left_chart`` (derived from filename)
:ivar _left_matrix: The ``ChartMatrixView`` for ``_left_chart``
:ivar _left_selector: The drop-down ``MutableOptionsMenu`` used
to select ``_left_chart``.
:ivar _right_chart: The right ``Chart``.
:ivar _right_name: The name ``_right_chart`` (derived from filename)
:ivar _right_matrix: The ``ChartMatrixView`` for ``_right_chart``
:ivar _right_selector: The drop-down ``MutableOptionsMenu`` used
to select ``_right_chart``.
:ivar _out_chart: The out ``Chart``.
:ivar _out_name: The name ``_out_chart`` (derived from filename)
:ivar _out_matrix: The ``ChartMatrixView`` for ``_out_chart``
:ivar _out_label: The label for ``_out_chart``.
:ivar _op_label: A Label containing the most recent operation.
"""
_OPSYMBOL = {
"-": "-",
"and": SymbolWidget.SYMBOLS["intersection"],
"or": SymbolWidget.SYMBOLS["union"],
}
def __init__(self, *chart_filenames):
# This chart is displayed when we don't have a value (eg
# before any chart is loaded).
faketok = [""] * 8
self._emptychart = Chart(faketok)
# The left & right charts start out empty.
self._left_name = "None"
self._right_name = "None"
self._left_chart = self._emptychart
self._right_chart = self._emptychart
# The charts that have been loaded.
self._charts = {"None": self._emptychart}
# The output chart.
self._out_chart = self._emptychart
# The most recent operation
self._operator = None
# Set up the root window.
self._root = Tk()
self._root.title("Chart Comparison")
self._root.bind("<Control-q>", self.destroy)
self._root.bind("<Control-x>", self.destroy)
# Initialize all widgets, etc.
self._init_menubar(self._root)
self._init_chartviews(self._root)
self._init_divider(self._root)
self._init_buttons(self._root)
self._init_bindings(self._root)
# Load any specified charts.
for filename in chart_filenames:
self.load_chart(filename)
def destroy(self, *e):
if self._root is None:
return
try:
self._root.destroy()
except:
pass
self._root = None
def mainloop(self, *args, **kwargs):
return
self._root.mainloop(*args, **kwargs)
# ////////////////////////////////////////////////////////////
# Initialization
# ////////////////////////////////////////////////////////////
def _init_menubar(self, root):
menubar = Menu(root)
# File menu
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(
label="Load Chart",
accelerator="Ctrl-o",
underline=0,
command=self.load_chart_dialog,
)
filemenu.add_command(
label="Save Output",
accelerator="Ctrl-s",
underline=0,
command=self.save_chart_dialog,
)
filemenu.add_separator()
filemenu.add_command(
label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
)
menubar.add_cascade(label="File", underline=0, menu=filemenu)
# Compare menu
opmenu = Menu(menubar, tearoff=0)
opmenu.add_command(
label="Intersection", command=self._intersection, accelerator="+"
)
opmenu.add_command(label="Union", command=self._union, accelerator="*")
opmenu.add_command(
label="Difference", command=self._difference, accelerator="-"
)
opmenu.add_separator()
opmenu.add_command(label="Swap Charts", command=self._swapcharts)
menubar.add_cascade(label="Compare", underline=0, menu=opmenu)
# Add the menu
self._root.config(menu=menubar)
def _init_divider(self, root):
divider = Frame(root, border=2, relief="sunken")
divider.pack(side="top", fill="x", ipady=2)
def _init_chartviews(self, root):
opfont = ("symbol", -36) # Font for operator.
eqfont = ("helvetica", -36) # Font for equals sign.
frame = Frame(root, background="#c0c0c0")
frame.pack(side="top", expand=1, fill="both")
# The left matrix.
cv1_frame = Frame(frame, border=3, relief="groove")
cv1_frame.pack(side="left", padx=8, pady=7, expand=1, fill="both")
self._left_selector = MutableOptionMenu(
cv1_frame, list(self._charts.keys()), command=self._select_left
)
self._left_selector.pack(side="top", pady=5, fill="x")
self._left_matrix = ChartMatrixView(
cv1_frame, self._emptychart, toplevel=False, show_numedges=True
)
self._left_matrix.pack(side="bottom", padx=5, pady=5, expand=1, fill="both")
self._left_matrix.add_callback("select", self.select_edge)
self._left_matrix.add_callback("select_cell", self.select_cell)
self._left_matrix.inactivate()
# The operator.
self._op_label = Label(
frame, text=" ", width=3, background="#c0c0c0", font=opfont
)
self._op_label.pack(side="left", padx=5, pady=5)
# The right matrix.
cv2_frame = Frame(frame, border=3, relief="groove")
cv2_frame.pack(side="left", padx=8, pady=7, expand=1, fill="both")
self._right_selector = MutableOptionMenu(
cv2_frame, list(self._charts.keys()), command=self._select_right
)
self._right_selector.pack(side="top", pady=5, fill="x")
self._right_matrix = ChartMatrixView(
cv2_frame, self._emptychart, toplevel=False, show_numedges=True
)
self._right_matrix.pack(side="bottom", padx=5, pady=5, expand=1, fill="both")
self._right_matrix.add_callback("select", self.select_edge)
self._right_matrix.add_callback("select_cell", self.select_cell)
self._right_matrix.inactivate()
# The equals sign
Label(frame, text="=", width=3, background="#c0c0c0", font=eqfont).pack(
side="left", padx=5, pady=5
)
# The output matrix.
out_frame = Frame(frame, border=3, relief="groove")
out_frame.pack(side="left", padx=8, pady=7, expand=1, fill="both")
self._out_label = Label(out_frame, text="Output")
self._out_label.pack(side="top", pady=9)
self._out_matrix = ChartMatrixView(
out_frame, self._emptychart, toplevel=False, show_numedges=True
)
self._out_matrix.pack(side="bottom", padx=5, pady=5, expand=1, fill="both")
self._out_matrix.add_callback("select", self.select_edge)
self._out_matrix.add_callback("select_cell", self.select_cell)
self._out_matrix.inactivate()
def _init_buttons(self, root):
buttons = Frame(root)
buttons.pack(side="bottom", pady=5, fill="x", expand=0)
Button(buttons, text="Intersection", command=self._intersection).pack(
side="left"
)
Button(buttons, text="Union", command=self._union).pack(side="left")
Button(buttons, text="Difference", command=self._difference).pack(side="left")
Frame(buttons, width=20).pack(side="left")
Button(buttons, text="Swap Charts", command=self._swapcharts).pack(side="left")
Button(buttons, text="Detach Output", command=self._detach_out).pack(
side="right"
)
def _init_bindings(self, root):
# root.bind('<Control-s>', self.save_chart)
root.bind("<Control-o>", self.load_chart_dialog)
# root.bind('<Control-r>', self.reset)
# ////////////////////////////////////////////////////////////
# Input Handling
# ////////////////////////////////////////////////////////////
def _select_left(self, name):
self._left_name = name
self._left_chart = self._charts[name]
self._left_matrix.set_chart(self._left_chart)
if name == "None":
self._left_matrix.inactivate()
self._apply_op()
def _select_right(self, name):
self._right_name = name
self._right_chart = self._charts[name]
self._right_matrix.set_chart(self._right_chart)
if name == "None":
self._right_matrix.inactivate()
self._apply_op()
def _apply_op(self):
if self._operator == "-":
self._difference()
elif self._operator == "or":
self._union()
elif self._operator == "and":
self._intersection()
# ////////////////////////////////////////////////////////////
# File
# ////////////////////////////////////////////////////////////
CHART_FILE_TYPES = [("Pickle file", ".pickle"), ("All files", "*")]
def save_chart_dialog(self, *args):
filename = asksaveasfilename(
filetypes=self.CHART_FILE_TYPES, defaultextension=".pickle"
)
if not filename:
return
try:
with open(filename, "wb") as outfile:
pickle.dump(self._out_chart, outfile)
except Exception as e:
showerror("Error Saving Chart", f"Unable to open file: {filename!r}\n{e}")
def load_chart_dialog(self, *args):
filename = askopenfilename(
filetypes=self.CHART_FILE_TYPES, defaultextension=".pickle"
)
if not filename:
return
try:
self.load_chart(filename)
except Exception as e:
showerror("Error Loading Chart", f"Unable to open file: {filename!r}\n{e}")
def load_chart(self, filename):
with open(filename, "rb") as infile:
chart = pickle.load(infile)
name = os.path.basename(filename)
if name.endswith(".pickle"):
name = name[:-7]
if name.endswith(".chart"):
name = name[:-6]
self._charts[name] = chart
self._left_selector.add(name)
self._right_selector.add(name)
# If either left_matrix or right_matrix is empty, then
# display the new chart.
if self._left_chart is self._emptychart:
self._left_selector.set(name)
elif self._right_chart is self._emptychart:
self._right_selector.set(name)
def _update_chartviews(self):
self._left_matrix.update()
self._right_matrix.update()
self._out_matrix.update()
# ////////////////////////////////////////////////////////////
# Selection
# ////////////////////////////////////////////////////////////
def select_edge(self, edge):
if edge in self._left_chart:
self._left_matrix.markonly_edge(edge)
else:
self._left_matrix.unmark_edge()
if edge in self._right_chart:
self._right_matrix.markonly_edge(edge)
else:
self._right_matrix.unmark_edge()
if edge in self._out_chart:
self._out_matrix.markonly_edge(edge)
else:
self._out_matrix.unmark_edge()
def select_cell(self, i, j):
self._left_matrix.select_cell(i, j)
self._right_matrix.select_cell(i, j)
self._out_matrix.select_cell(i, j)
# ////////////////////////////////////////////////////////////
# Operations
# ////////////////////////////////////////////////////////////
def _difference(self):
if not self._checkcompat():
return
out_chart = Chart(self._left_chart.tokens())
for edge in self._left_chart:
if edge not in self._right_chart:
out_chart.insert(edge, [])
self._update("-", out_chart)
def _intersection(self):
if not self._checkcompat():
return
out_chart = Chart(self._left_chart.tokens())
for edge in self._left_chart:
if edge in self._right_chart:
out_chart.insert(edge, [])
self._update("and", out_chart)
def _union(self):
if not self._checkcompat():
return
out_chart = Chart(self._left_chart.tokens())
for edge in self._left_chart:
out_chart.insert(edge, [])
for edge in self._right_chart:
out_chart.insert(edge, [])
self._update("or", out_chart)
def _swapcharts(self):
left, right = self._left_name, self._right_name
self._left_selector.set(right)
self._right_selector.set(left)
def _checkcompat(self):
if (
self._left_chart.tokens() != self._right_chart.tokens()
or self._left_chart.property_names() != self._right_chart.property_names()
or self._left_chart == self._emptychart
or self._right_chart == self._emptychart
):
# Clear & inactivate the output chart.
self._out_chart = self._emptychart
self._out_matrix.set_chart(self._out_chart)
self._out_matrix.inactivate()
self._out_label["text"] = "Output"
# Issue some other warning?
return False
else:
return True
def _update(self, operator, out_chart):
self._operator = operator
self._op_label["text"] = self._OPSYMBOL[operator]
self._out_chart = out_chart
self._out_matrix.set_chart(out_chart)
self._out_label["text"] = "{} {} {}".format(
self._left_name,
self._operator,
self._right_name,
)
def _clear_out_chart(self):
self._out_chart = self._emptychart
self._out_matrix.set_chart(self._out_chart)
self._op_label["text"] = " "
self._out_matrix.inactivate()
def _detach_out(self):
ChartMatrixView(self._root, self._out_chart, title=self._out_label["text"])
#######################################################################
# Chart View
#######################################################################
class ChartView:
"""
A component for viewing charts. This is used by ``ChartParserApp`` to
allow students to interactively experiment with various chart
parsing techniques. It is also used by ``Chart.draw()``.
:ivar _chart: The chart that we are giving a view of. This chart
may be modified; after it is modified, you should call
``update``.
:ivar _sentence: The list of tokens that the chart spans.
:ivar _root: The root window.
:ivar _chart_canvas: The canvas we're using to display the chart
itself.
:ivar _tree_canvas: The canvas we're using to display the tree
that each edge spans. May be None, if we're not displaying
trees.
:ivar _sentence_canvas: The canvas we're using to display the sentence
text. May be None, if we're not displaying the sentence text.
:ivar _edgetags: A dictionary mapping from edges to the tags of
the canvas elements (lines, etc) used to display that edge.
The values of this dictionary have the form
``(linetag, rhstag1, dottag, rhstag2, lhstag)``.
:ivar _treetags: A list of all the tags that make up the tree;
used to erase the tree (without erasing the loclines).
:ivar _chart_height: The height of the chart canvas.
:ivar _sentence_height: The height of the sentence canvas.
:ivar _tree_height: The height of the tree
:ivar _text_height: The height of a text string (in the normal
font).
:ivar _edgelevels: A list of edges at each level of the chart (the
top level is the 0th element). This list is used to remember
where edges should be drawn; and to make sure that no edges
are overlapping on the chart view.
:ivar _unitsize: Pixel size of one unit (from the location). This
is determined by the span of the chart's location, and the
width of the chart display canvas.
:ivar _fontsize: The current font size
:ivar _marks: A dictionary from edges to marks. Marks are
strings, specifying colors (e.g. 'green').
"""
_LEAF_SPACING = 10
_MARGIN = 10
_TREE_LEVEL_SIZE = 12
_CHART_LEVEL_SIZE = 40
def __init__(self, chart, root=None, **kw):
"""
Construct a new ``Chart`` display.