-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualization.py
2392 lines (2154 loc) · 118 KB
/
visualization.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
#!/usr/bin/env python
import numpy as np
from collections import namedtuple, Counter, defaultdict
from itertools import count
from os.path import getsize, expanduser
from os import listdir, remove
import sys, pdb
from nltk.tree import Tree
from utils.file_io import join, isfile, parpath
from utils.pickle_io import pickle_load, pickle_dump
from utils.param_ops import HParams
inf_none_gen = (None for _ in count())
DiscoThresholds = namedtuple('DiscoThresholds', 'right, joint, direc')
IOVocab = namedtuple('IOVocab', 'vocabs, IOHead_fields, IOData_fields, thresholds')
class TensorVis:
@classmethod
def from_vfile(cls, fpath):
vocabs, IOHead_fields, IOData_fields, thresholds = pickle_load(fpath)
return cls(parpath(fpath), HParams(vocabs), IOHead_fields, IOData_fields, thresholds)
def __init__(self, fpath, vocabs, IOHead_fields, IOData_fields, thresholds = None, clean_fn = None, fname = 'vocabs.pkl'):
files = listdir(fpath)
if fname in files:
assert isfile(join(fpath, fname))
if callable(clean_fn): # TODO
clean_fn(files)
anew = False
else:
assert isinstance(vocabs, HParams)
pickle_dump(join(fpath, fname), IOVocab(vocabs._nested, IOHead_fields, IOData_fields, thresholds))
anew = True
self._anew = anew
self._fpath = fpath
self._vocabs = vocabs
self._head_type = namedtuple('IOHead', IOHead_fields)
self._data_type = namedtuple('IOData', IOData_fields)
self._threshold = thresholds
@property
def is_anew(self):
return self._anew
def join(self, fname):
return join(self._fpath, fname)
@property
def vocabs(self):
return self._vocabs
@property
def IOHead(self):
return self._head_type
@property
def IOData(self):
return self._data_type
@property
def threshold(self):
return self._threshold
from contextlib import ExitStack
class DiscontinuousTensorVis(TensorVis):
def __init__(self, fpath, vocabs, thresholds):
IOHead_fields = 'token, tag, label, right, joint, direc, tree, segment, seg_length'
IOData_fields = 'token, tag, label, right, joint, direc, tree, segment, seg_length, mpc_word, mpc_phrase, warning, scores, tag_score, label_score, right_score, joint_score, direc_score'
super().__init__(fpath, vocabs, IOHead_fields, IOData_fields, thresholds)
def set_head(self, batch_id, size, *args):
assert len(self._head_type._fields) == len(args)
pickle_dump(self.join(f'head.{batch_id}_{size}.pkl'), args)
def set_data(self, batch_id, epoch, *args):
assert len(self._data_type._fields) == len(args)
pickle_dump(self.join(f'data.{batch_id}_{epoch}.pkl'), args)
def tee_trees(join_fn, mode, lengths, trees, batch_id, bin_width):
ftrees = {}
write_all = batch_id is None
write_len = isinstance(bin_width, int)
with ExitStack() as stack:
if write_all:
fh = stack.enter_context(open(join_fn(f'{mode}.tree'), 'a'))
else:
fh = stack.enter_context(open(join_fn(f'{mode}.{batch_id}.tree'), 'w'))
for wlen, tree in zip(lengths, trees):
print(tree, file = fh)
if write_len:
wbin = wlen // bin_width
if wbin in ftrees:
fw = ftrees[wbin]
else:
fw = open(join_fn(f'{mode}.bin_{wbin}.tree'), 'a')
ftrees[wbin] = stack.enter_context(fw)
print(tree, file = fw)
return ftrees.keys()
from data.triangle import head_to_tree as tri_h2t
from data.triangle import data_to_tree as tri_d2t
from data.trapezoid import head_to_tree as tra_h2t
from data.trapezoid import data_to_tree as tra_d2t
from utils.shell_io import parseval, rpt_summary
class ContinuousTensorVis(TensorVis):
def __init__(self, fpath, vocabs):
IOHead_fields = 'offset, length, token, tag, label, right, tree, segment, seg_length'
IOData_fields = 'offset, length, token, tag, label, right, tree, segment, seg_length, mpc_word, mpc_phrase, warning, scores, tag_score, label_score, split_score, summary'
super().__init__(fpath, vocabs, IOHead_fields, IOData_fields)
def set_head(self, fhtree, offset, length, token, tag, label, right, trapezoid_info, *batch_id_size_bin_width):
old_tag = tag
if tag is None:
tag = inf_none_gen
if trapezoid_info is None:
segment = seg_length = None
func_args = zip(offset, length, token, tag, label, right)
func_args = ((*args, self.vocabs) for args in func_args)
head_to_tree = tri_h2t
else:
segment, seg_length = trapezoid_info
func_args = zip(offset, length, token, tag, label, right, seg_length)
func_args = ((*args, segment, self.vocabs) for args in func_args)
head_to_tree = tra_h2t
trees = []
for args in func_args:
tree = str(head_to_tree(*args))
tree = ' '.join(tree.split())
print(tree, file = fhtree)
trees.append(tree)
if batch_id_size_bin_width:
batch_id, size, bin_width = batch_id_size_bin_width
fname = self.join(f'head.{batch_id}_{size}.pkl')
head = self.IOHead(offset, length, token, old_tag, label, right, trees, segment, seg_length)
pickle_dump(fname, tuple(head)) # type check
return tee_trees(self.join, 'head', length, trees, batch_id, bin_width)
def set_void_head(self, batch_id, size, offset, length, token):
fname = self.join(f'head.{batch_id}_{size}.pkl')
head = self.IOHead(offset, length, token, None, None, None, None, None, None)
pickle_dump(fname, tuple(head))
def set_data(self, fdtree, on_error, batch_id, epoch,
offset, length, token, tag, label, right, mpc_word, mpc_phrase,
tag_score, label_score, split_score,
trapezoid_info, size_bin_width_evalb):
tree_kwargs = dict(return_warnings = True, on_error = on_error)
error_prefix = f' [{batch_id} {epoch}'
old_tag = tag
old_tag_s = tag_score
if tag is None: tag = inf_none_gen
if label is None:
label_ = label_score
tree_kwargs['error_root'] = 'NA'
else:
label_ = label
trees = []
batch_warnings = []
if trapezoid_info is None:
segment = seg_length = None
func_args = zip(offset, length, token, tag, label_, right)
func_args = ((*args, self.vocabs) for args in func_args)
data_to_tree = tri_d2t
else:
segment, seg_length = trapezoid_info
func_args = zip(offset, length, token, tag, label_, right, seg_length)
func_args = ((*args, segment, self.vocabs) for args in func_args)
data_to_tree = tra_d2t
for i, args in enumerate(func_args):
tree_kwargs['error_prefix'] = error_prefix + f']-{i} len={args[1]}'
tree, warnings = data_to_tree(*args, **tree_kwargs)
tree = str(tree)
tree = ' '.join(tree.split())
trees.append(tree)
print(tree, file = fdtree) # TODO use stack to protect opened file close and delete
batch_warnings.append(warnings)
if size_bin_width_evalb:
size, bin_width, evalb = size_bin_width_evalb
if label is None: # unlabeled
pickle_dump(self.join(f'data.{batch_id}_{epoch}.pkl'),
(offset, length, token, None, None, right, trees,
segment, seg_length, mpc_word, mpc_phrase,
batch_warnings, None, tag_score, label_score, split_score, None))
return batch_warnings
else: # supervised / labeled
tee_trees(self.join, 'data', length, trees, batch_id, bin_width)
fhead = f'head.{batch_id}_{size}.pkl'
assert isfile(self.join(fhead)), f"Need a head '{fhead}'"
fhead = self.join(f'head.{batch_id}.tree')
fdata = self.join(f'data.{batch_id}.tree')
if evalb is None: # sentiment
# 52VII
from data.stan_types import calc_stan_accuracy
idv, smy, key_score = calc_stan_accuracy(fhead, fdata, error_prefix, on_error)
else: # constituency
proc = parseval(evalb, fhead, fdata)
idv, smy = rpt_summary(proc.stdout.decode(), True, True)
fname = self.join('summary.pkl')
if isfile(fname):
summary = pickle_load(fname)
else:
summary = {}
summary[(batch_id, epoch)] = smy
pickle_dump(fname, summary)
key_score = smy['F1']
fdata = self.join(f'data.{batch_id}_{epoch}.pkl')
data = self.IOData(offset, length, token, old_tag, label, right, trees,
segment, seg_length, mpc_word, mpc_phrase,
batch_warnings, idv, tag_score, label_score, split_score, smy)
pickle_dump(fdata, tuple(data))
return key_score
# dpi_value = master.winfo_fpixels('1i')
# master.tk.call('tk', 'scaling', '-displayof', '.', dpi_value / 72.272)
# screen_shape = master.winfo_screenwidth(), master.winfo_screenheight()
# master.geometry("%dx%d+%d+%d" % (canvas_shape + tuple(s/2-c/2 for s,c in zip(screen_shape, canvas_shape))))
try:
from utils.gui import *
desktop = True
except ImportError:
desktop = False
if desktop:
def _font(x):
font_name, font_min_size, font_max_size = x.split()
font_min_size = int(font_min_size)
font_max_size = int(font_max_size)
assert font_min_size > 0, 'font minimun size should be positive'
assert font_max_size > font_min_size, 'font maximun size should be greather than min size'
return font_name, font_min_size, font_max_size
def _ratio(x):
x = float(x) if '.' in x else int(x)
assert x > 0, 'should be positive'
return x
def _frac(x):
x = float(x)
assert 0 < x < 1, 'should be a fraction'
return x
def _size(x):
x = int(x)
assert x > 0, 'should be positive'
return x
def _dim(x):
x = int(x)
assert 0 < x < 10, 'should be in [1, 9]'
return x
def _offset(x):
return int(x)
def _curve(x):
x = x.strip()
assert 'x' in x, 'should contain variable x'
if ':' not in x:
x = 'lambda x:' + x
curve = eval(x)
assert callable(curve), 'shoule be a function'
assert isinstance(curve(0), float), 'should return a float number'
return curve
BoolList = namedtuple('BoolList', 'delta_shape, show_errors, show_paddings, show_nil, dark_background, inverse_brightness, align_coord, show_color, force_bottom_color, statistics')
CombList = namedtuple('CombList', 'curve, dash, gauss, picker, spotlight')
DynamicSettings = namedtuple('DynamicSettings', BoolList._fields + tuple('apply_' + f for f in CombList._fields) + CombList._fields)
NumbList = namedtuple('NumbList', 'font, pc_x, pc_y, line_width, offset_x, offset_y, word_width, word_height, yx_ratio, histo_width, scatter_width')
numb_types = NumbList(_font, _dim, _dim, _ratio, _offset, _offset, _size, _size, _ratio, _size, _size)
comb_types = CombList(_curve, _frac, _ratio, _ratio, _ratio)
PanelList = namedtuple('PanelList', 'hide_listboxes, detach_viewer')
navi_directions = '⇤↑o↓⇥'
from colorsys import hsv_to_rgb, hls_to_rgb
from tempfile import TemporaryDirectory
from nltk.draw import TreeWidget
from nltk.draw.util import CanvasFrame
from time import time, sleep
from utils.math_ops import uneven_split, itp
from math import exp, sqrt, pi
from functools import partial
from data.delta import warning_level, NIL
from utils.param_ops import more_kwargs
from utils.file_io import path_folder
from concurrent.futures import ProcessPoolExecutor
from data.triangle import triangle_to_layers
from data.trapezoid import trapezoid_to_layers, inflate
from data.cross import draw_str_lines
# from multiprocessing import Pool
class PathWrapper:
def __init__(self, fpath, sftp):
fpath, folder = path_folder(fpath)
self._folder = '/'.join(folder[-2:])
if sftp is not None:
sftp.chdir(fpath)
fpath = TemporaryDirectory()
self._fpath_sftp = fpath, sftp
def join(self, fname):
fpath, sftp = self._fpath_sftp
if sftp is not None:
f = join(fpath.name, fname)
if fname not in listdir(fpath.name):
print('networking for', fname)
start = time()
sftp.get(fname, f)
print('transfered %d KB in %.2f sec.' % (getsize(f) >> 10, time() - start))
else:
print('use cached', fname)
return f
return join(fpath, fname)
@property
def base(self):
fpath, sftp = self._fpath_sftp
if sftp is not None:
return fpath.name
return fpath
@property
def folder(self):
return self._folder
def listdir(self):
fpath, sftp = self._fpath_sftp
if sftp is not None:
return sftp.listdir()
return listdir(fpath)
def __del__(self):
fpath, sftp = self._fpath_sftp
if sftp is not None:
# fpath.cleanup() # auto cleanup
sftp.close()
get_batch_id = lambda x: int(x[5:-4].split('_')[0])
class TreeViewer(Frame):
def __init__(self,
root,
fpath):
super().__init__(root) # To view just symbolic trees ptb or xml.
class TreeExplorer(Frame):
def __init__(self,
root,
fpath,
initial_bools = BoolList(True, False, False, False, False, True, False, True, False, False),
initial_numbs = NumbList('System 6 15', (1, 1, 9, 1), (2, 1, 9, 1), (4, 2, 10, 2), (0, -200, 200, 10), (0, -200, 200, 10), (80, 60, 200, 5), (22, 12, 99, 2), (0.9, 0.5, 2, 0.1), (60, 50, 120, 10), (60, 50, 120, 10)),
initial_panel = PanelList(False, False),
initial_combs = CombList((True, 'x ** 0.5'), (False, (0.5, 0.1, 0.9, 0.1)), (True, (0.04, 0.01, 0.34, 0.01)), (True, (0.2, 0.1, 0.9, 0.1)), (False, (200, 100, 500, 100)))):
vocabs = fpath.join('vocabs.pkl')
if isfile(vocabs):
self._tvis = TensorVis.from_vfile(vocabs)
else:
raise ValueError(f"The folder should at least contains a vocab file '{vocabs}'")
self._fpath_heads = fpath, None
self._last_init_time = None
super().__init__(root)
self.master.title(fpath.folder)
headbox = Listbox(self, relief = SUNKEN, font = 'TkFixedFont')
sentbox = Listbox(self, relief = SUNKEN)
self._boxes = headbox, sentbox
self.initialize_headbox()
self._sent_cache = {}
self._cross_warnings = {}
headbox.bind('<<ListboxSelect>>', self.read_listbox)
sentbox.bind('<<ListboxSelect>>', self.read_listbox)
pack_kwargs = dict(padx = 10, pady = 5)
intr_kwargs = dict(pady = 2)
control = [1 for i in range(len(initial_numbs))]
control[0] = dict(char_width = 17)
control_panel = Frame(self, relief = SUNKEN)
ckb_panel = Frame(control_panel)
etr_panel = Frame(control_panel)
self._checkboxes = make_namedtuple_gui(make_checkbox, ckb_panel, initial_bools, self._change_bool, **intr_kwargs)
self._entries = make_namedtuple_gui(make_entry, etr_panel, initial_numbs, self._change_string, control)
ckb_panel.pack(side = TOP, fill = X, **pack_kwargs)
etr_panel.pack(side = TOP, fill = X, **pack_kwargs) # expand means to pad
self._last_bools = initial_bools
self._last_numbs = NumbList(*(x[0] if isinstance(x, tuple) else x for x in initial_numbs))
comb_panel = Frame(control_panel)
self._checkboxes_entries = make_namedtuple_gui(make_checkbox_entry, comb_panel, initial_combs, (self._change_bool, self._change_string), (2, 1, 1, 1, 1))
comb_panel.pack(side = TOP, fill = X, **pack_kwargs)
self._last_combs = CombList(*((x[0], x[1][0]) if isinstance(x[1], tuple) else x for x in initial_combs))
view_panel = Frame(control_panel)
self._panels = make_namedtuple_gui(make_checkbox, view_panel, initial_panel, self.__update_viewer, **intr_kwargs)
view_panel.pack(side = TOP, fill = X, **pack_kwargs)
self._last_panel_bools = initial_panel
navi_panel = Frame(control_panel)
navi_panel.pack(fill = X)
btns = tuple(Button(navi_panel, text = p) for p in navi_directions)
for btn in btns:
btn.bind("<Button-1>", self._navi)
btn.pack(side = LEFT, fill = X, expand = YES)
self._navi_btns = btns
btn_panel = Frame(control_panel)
btn_panel.pack(side = TOP, fill = X) # no need to expand, because of st? can be bottom
st = Button(btn_panel, text = 'Show Trees', command = self._show_one_tree )
sa = Button(btn_panel, text = '♾', command = self._show_all_trees)
sc = Button(btn_panel, text = '◉', command = self._save_canvas )
st.pack(side = LEFT, fill = X, expand = YES)
sa.pack(side = LEFT, fill = X)
sc.pack(side = LEFT, fill = X)
self._panel_btns = st, sa, sc
self._control_panel = control_panel
control_panel.bind('<Key>', self.shortcuts)
headbox.bind('<Key>', self.shortcuts)
sentbox.bind('<Key>', self.shortcuts)
self._viewer = None
self._selected = tuple()
self._init_time = 0
self.__update_layout(True, True)
def initialize_headbox(self):
fpath = self._fpath_heads[0]
headbox = self._boxes[0]
headbox.delete(0, END)
fnames = fpath.listdir()
heads = [f for f in fnames if f.startswith('head.') and f.endswith('.pkl')]
heads.sort(key = get_batch_id)
if len(heads) == 0:
raise ValueError("'%s' is an invalid dir" % fpath.base)
if 'summary.pkl' in fnames:
from math import isnan
summary = pickle_load(fpath.join('summary.pkl'))
summary_fscores = defaultdict(list)
for (batch_id, epoch), smy in summary.items():
if not isnan(smy['F1']):
summary_fscores[batch_id].append((smy['F1'], smy.get('DF', None)))
else:
summary_fscores = {}
max_id_len = len(str(max(summary_fscores.keys()))) if summary_fscores else 4
for h in heads:
bid = get_batch_id(h)
if bid in summary_fscores:
if len(summary_fscores[bid]) == 1:
f1, df = summary_fscores[bid][0]
fscores = f' {f1:.2f}' if df is None else f' {f1:.2f} ({df:.2f})'
else:
f1, df = max(summary_fscores[bid], key = lambda x: x[0])
fscores = f' ≤{f1:.2f}' if df is None else f' ≤{f1:.2f} ({df:.2f})'
else:
fscores = ''
str_bid, length = h[5:-4].split('_')
length = '≤' + length
headbox.insert(END, str_bid.rjust(max_id_len) + length.rjust(3) + fscores)
self._fpath_heads = fpath, heads
self._last_init_time = time()
# def __del__(self):
# if self._rpt.alabelc:
# print(f'terminate receiving {len(self._rpt.alabelc)} rpt files')
# self._rpt.pool.terminate()
def __update_layout(self, hide_listboxes_changed, detach_viewer_changed):
headbox, sentbox = self._boxes
control_panel = self._control_panel
viewer = self._viewer
if detach_viewer_changed:
if viewer and viewer.winfo_exists():
self._init_time = viewer.time
viewer.destroy()
# widget shall be consumed within a function, or they will be visible!
master = Toplevel(self) if self._last_panel_bools.detach_viewer else self
viewer = ThreadViewer(master, self._tvis, self._change_title)
viewer.bind('<Key>', self.shortcuts)
self._viewer = viewer
if hide_listboxes_changed:
if self._last_panel_bools.hide_listboxes:
headbox.pack_forget()
sentbox.pack_forget()
else:
control_panel.pack_forget()
viewer.pack_forget()
headbox.pack(fill = Y, side = LEFT)
sentbox.pack(fill = BOTH, side = LEFT, expand = YES)
control_panel.pack(fill = Y, side = LEFT)
viewer.pack(fill = BOTH, expand = YES)
self.pack(fill = BOTH, expand = YES)
def _change_title(self, prefix, epoch):
title = [self._fpath_heads[0].folder, prefix]
# bid, _, _, sid = self._selected
# key = f'{bid}_{epoch}'
# if key in self._rpt.sent:
# scores = self._rpt.sent[key][sid]
# if len(scores) == 4:
# scores = ' '.join(i+f'({j:.2f})' for i, j in zip(('5C@R', 'N-P@R', '5C', 'N-P'), scores))
# else:
# scores = tuple(scores[i] for i in (1, 3, 4, 11))
# scores = ' '.join(i+f'({str(j)})' for i, j in zip(('len.', 'P.', 'R.', 'tag.'), scores))
# else:
# r = self._fpath_heads[0].join(f'data.{key}.rpt')
# scores = self._rpt.sent[r[5:-4]] = rpt_summary(r, sents = True)
# title.append(scores)
self.master.title(' | '.join(title))
def read_listbox(self, event):
headbox, sentbox = self._boxes
choice_t = event.widget.curselection()
if choice_t:
fpath, heads = self._fpath_heads
i = int(choice_t[0]) # head/inter-batch id or sentence/intra-batch id
if event.widget is headbox:
IOHead = self._tvis.IOHead
IOData = self._tvis.IOData
head = fpath.join(heads[i])
bid, num_word = (int(i) for i in heads[i][5:-4].split('_'))
head = IOHead(*pickle_load(head))
if head.tag is None and head.label is not None:
polar_vocab = self._tvis.vocabs.polar
neg_set = set(polar_vocab.index(i) for i in '01')
pos_set = set(polar_vocab.index(i) for i in '34')
sentbox.delete(0, END)
is_a_conti_task = 'offset' in IOHead._fields
if is_a_conti_task: # tri/tra
offsets = head.offset
lengths = head.length
is_triangular = head.segment is None and head.label is not None
else: # cross
batch_size = head.token.shape[0]
offsets = (1 for _ in range(batch_size))
lengths = head.seg_length[:, 0]
for sid, (offset, length, words) in enumerate(zip(offsets, lengths, head.token)):
if head.tag is None and head.label is not None:
negation = any(i in head.label[sid] for i in pos_set) and any(i in head.label[sid] for i in neg_set)
else:
negation = False
mark = '*' if negation else ''
mark += f'{sid + 1}'
# if warning_cnt:
# mark += " ◌•▴⨯"[warning_level(warning_cnt)]
mark += '\t'
tokens = '' if head.label is None else ' '
tokens = tokens.join(self._tvis.vocabs.token[idx] for idx in words[offset:offset + length])
sentbox.insert(END, mark + tokens)
head_ = []
if is_a_conti_task: # depend on task senti/parse | tri
if is_triangular:
sample_gen = (inf_none_gen if h is None else h for h in head)
for sample in zip(*sample_gen):
values = []
for field, value in zip(IOHead._fields, sample):
if value is not None and field in ('label', 'right'):
value = triangle_to_layers(value)
values.append(value)
head_.append(IOHead(*values))
prefix, suffix = f'data.{bid}_', '.pkl'
for fname_time in fpath.listdir():
if fname_time.startswith(prefix) and fname_time.endswith(suffix):
if fname_time not in self._sent_cache:
data = IOData(*pickle_load(fpath.join(fname_time)))
sample_gen = (inf_none_gen if x is None else x for x in data[:-1])
data_ = []
for sample in zip(*sample_gen):
values = []
for field, value in zip(IOData._fields, sample): # TODO: open for unsup?
if value is not None and field in ('label', 'right', 'label_score', 'split_score'):
value = triangle_to_layers(value)
values.append(value)
sample = IOData(*values, inf_none_gen)
stat = SentenceEnergy(num_word, sample.mpc_word, sample.mpc_phrase,
sample.offset, sample.length, None, None)
data_.append((sample, stat))
self._sent_cache[fname_time] = data_, data[-1]
else: # trapezoidal
sample_gen = (inf_none_gen if h is None or f == 'segment' else h for f,h in zip(IOHead._fields, head))
for sample in zip(*sample_gen):
values = dict(zip(IOHead._fields, sample))
for field in ('label', 'right'):
if values[field] is not None: # trapezoids for supervised parsing
values[field] = inflate(trapezoid_to_layers(values[field], head.segment, values['seg_length']))
values['segment'] = head.segment
head_.append(IOHead(**values))
prefix, suffix = f'data.{bid}_', '.pkl'
for fname_time in fpath.listdir():
if fname_time.startswith(prefix) and fname_time.endswith(suffix):
if fname_time not in self._sent_cache:
data = IOData(*pickle_load(fpath.join(fname_time)))
sample_gen = (inf_none_gen if d is None or f in ('segment', 'summary') else d for f,d in zip(IOData._fields, data))
data_ = []
for sample in zip(*sample_gen):
values = dict(zip(IOData._fields, sample))
for field in ('label', 'right', 'label_score', 'split_score'):
if field == 'label' and values[field] is None:
values[field] = values['label_score']
if values[field] is not None: # trapezoid for supervised parsing
values[field] = inflate(trapezoid_to_layers(values[field], data.segment, values['seg_length']))
values['segment'] = data.segment
sample = IOData(**values)
stat = SentenceEnergy(num_word, sample.mpc_word, sample.mpc_phrase,
sample.offset, sample.length,
sample.segment, sample.seg_length)
data_.append((sample, stat))
self._sent_cache[fname_time] = data_, data[-1]
else: # discontinuous task
sample_gen = (inf_none_gen if f == 'segment' else h for f,h in zip(IOHead._fields, head))
for sample in zip(*sample_gen):
values = dict(zip(IOHead._fields, sample))
for field in ('label', 'right', 'direc'):
values[field] = trapezoid_to_layers(values[field], head.segment, head.segment, big_endian = False)
joint_segment = (head.segment - 1)[:-1]
values['joint'] = trapezoid_to_layers(values['joint'], joint_segment, joint_segment, big_endian = False)
values['segment'] = head.segment
head_.append(IOHead(**values))
prefix, suffix = f'data.{bid}_', '.pkl'
for fname_time in fpath.listdir():
if fname_time.startswith(prefix) and fname_time.endswith(suffix):
if fname_time not in self._sent_cache:
data = IOData(*pickle_load(fpath.join(fname_time)))
sample_gen = (inf_none_gen if f == 'segment' else d for f,d in zip(IOData._fields, data))
data_ = []
for sample in zip(*sample_gen):
values = dict(zip(IOData._fields, sample))
for field in ('label', 'right', 'direc', 'label_score', 'right_score', 'direc_score'):
values[field] = trapezoid_to_layers(values[field], data.segment, data.segment, big_endian = False)
joint_segment = [x - 1 for x in data.segment[:-1]]
for field in ('joint', 'joint_score'):
values[field] = trapezoid_to_layers(values[field], joint_segment, joint_segment, big_endian = False)
values['segment'] = data.segment
sample = IOData(**values)
stat = SentenceEnergy(num_word, sample.mpc_word, sample.mpc_phrase,
1, None, sample.segment, sample.seg_length, False)
data_.append((sample, stat))
# import pdb; pdb.set_trace()
self._sent_cache[fname_time] = data_, data[-1]
self._selected = bid, num_word, head_
elif event.widget is sentbox:
bid, num_word, head = self._selected[:3]
self._selected = bid, num_word, head, i
self.__update_viewer()
else:
print('nothing', choice_t, event)
def _change_bool(self):
if self._viewer.ready():
self._viewer.minor_change(self.dynamic_settings(), self.static_settings(0, 1, 2, 3, 4, 5))
def _change_string(self, event):
if any(not hasattr(self, attr) for attr in '_entries _panels _checkboxes_entries _checkboxes'.split()):
return
if event is None or event.char in ('\r', '\uf700', '\uf701'):
ss = self.static_settings()
ss_changed = NumbList(*(t != l for t, l in zip(ss, self._last_numbs)))
if any(ss_changed[6:]): # font and PCs will not cause resize
self.__update_viewer(force_resize = True)
elif self._viewer.ready():
self._viewer.minor_change(self.dynamic_settings(), ss[:6])
self._last_numbs = ss
if event and event.char == '\r':
self._control_panel.focus()
def shortcuts(self, key_press_event):
char = key_press_event.char
# self.winfo_toplevel().bind(key, self._navi)
if char == 'w':
self._checkboxes.statistics.ckb.invoke()
sub_state = 'normal' if self._last_bools.statistics else 'disable'
self._checkboxes_entries.gauss.ckb.configure(state = sub_state)
self._checkboxes_entries.gauss.etr.configure(state = sub_state)
elif char == 'n':
self._checkboxes.show_nil.ckb.invoke()
elif char == 'b':
self._checkboxes.show_paddings.ckb.invoke()
elif char == 'e':
self._checkboxes.show_errors.ckb.invoke()
elif char == '|':
self._checkboxes.align_coord.ckb.invoke()
elif char == ',':
self._checkboxes.force_bottom_color.ckb.invoke()
# elif char == 'v':
# self._checkboxes.hard_split.ckb.invoke()
# if self._last_bools.apply_dash:
# self._checkboxes.apply_dash.ckb.invoke()
elif char == '.':
self._checkboxes_entries.dash.ckb.invoke()
# if self._last_bools.hard_split: # turn uni dire off
# self._checkboxes.hard_split.ckb.invoke()
elif char == '\r':
self._checkboxes_entries.curve.etr.icursor("end")
self._checkboxes_entries.curve.etr.focus()
elif char == 'i':
self._checkboxes.dark_background.ckb.invoke()
self._checkboxes.inverse_brightness.ckb.invoke()
elif char == 'u':
self._checkboxes_entries.curve.ckb.invoke()
elif char == 'p':
self._checkboxes_entries.picker.ckb.invoke()
elif char == 'g':
self._checkboxes_entries.gauss.ckb.invoke()
elif char == 'l':
self._checkboxes_entries.spotlight.ckb.invoke()
elif char == 'q':
self._panels.hide_listboxes.ckb.invoke()
elif char == 'z':
self._panel_btns[0].invoke()
elif char == 'x':
self._panel_btns[1].invoke()
elif char == 'c':
self._panel_btns[2].invoke()
elif char == 'a':
self._navi('⇤')
elif char == 's':
self._navi('↑')
elif char == ' ':
self._navi('o')
elif char == 'd':
self._navi('↓')
elif char == 'f':
self._navi('⇥')
else:
print('???', key_press_event)
def __update_viewer(self, force_resize = False):
panel_bools = get_checkbox(self._panels)
changed = (t^l for t, l in zip(panel_bools, self._last_panel_bools))
changed = PanelList(*changed)
self._last_panel_bools = panel_bools
viewer = self._viewer
self.__update_layout(changed.hide_listboxes, changed.detach_viewer or not viewer.winfo_exists())
viewer = self._viewer
if len(self._selected) < 4:
print('selected len:', len(self._selected))
return
bid, num_word, head, sid = self._selected
# import pdb; pdb.set_trace()
prefix = f"data.{bid}_"
suffix = '.pkl'
timeline = []
for fname in self._sent_cache:
if fname.startswith(prefix):
timeline.append(fname)
timeline.sort(key = lambda kv: float(kv[len(prefix):-len(suffix)]))
num_time = len(timeline)
if force_resize or not self._viewer.ready(num_word, num_time):
ds = self.dynamic_settings()
ss = self.static_settings()
viewer.configure(num_word, num_time, ds, ss, self._init_time)
viewer.set_framework(head, {t:self._sent_cache[t] for t in timeline})
viewer.show_sentence(sid)
viewer.update() # manually update canvas
def dynamic_settings(self):
cs = (n for b,n in self._last_combs)
ns = get_entry(self._checkboxes_entries, comb_types, (n for b,n in self._last_combs), 1)
self._last_combs = CombList(*zip(cs, ns))
bs = get_checkbox(self._checkboxes)
ds = bs + get_checkbox(self._checkboxes_entries, 1) + ns
# changed_bs = (t^l for t, l in zip(bs, self._last_bools))
# changed_bs = BoolList(*changed_bs)
self._last_bools = bs
# if bs.show_errors and not bs.show_nil:
# if changed_bs.show_errors:
# self._checkboxes.show_nil.ckb.invoke()
# elif changed_bs.show_nil:
# self._checkboxes.show_errors.ckb.invoke()
return DynamicSettings(*ds)
def static_settings(self, *ids):
if ids:
enties = tuple(self._entries[i] for i in ids)
types = tuple(numb_types[i] for i in ids)
lasts = tuple(self._last_numbs[i] for i in ids)
return get_entry(enties, types, lasts)
return get_entry(self._entries, numb_types, self._last_numbs)
def _show_one_tree(self):
if self._viewer.ready():
self._viewer.show_tree(False)#, self._viewer, self._viewer._boards[0])
def _show_all_trees(self):
if self._viewer.ready():
self._viewer.show_tree(True)
def _navi(self, event):
if self._viewer.ready():
if isinstance(event, str):
self._viewer.navi_to(event)
elif event.widget in self._navi_btns:
self._viewer.navi_to(navi_directions[self._navi_btns.index(event.widget)])
def _save_canvas(self):
if not self._viewer.ready():
return
bid, _, _, i = self._selected
options = dict(filetypes = [('postscript', '.eps')],
initialfile = f'{bid}-{i}-{self._viewer.time}.eps',
parent = self)
filename = filedialog.asksaveasfilename(**options)
if filename:
self._viewer.save(filename)
def _calc_batch(self):
pass
def to_circle(xy, xy_orig = None):
if xy_orig is not None:
xy = xy - xy_orig
x, y = (xy[:, i] for i in (0,1))
reg_angle = np.arctan2(y, x) / np.pi
reg_angle += 1
reg_angle /= 2
reg_power = np.sqrt(np.sum(xy ** 2, axis = 1))
return np.stack([reg_angle, reg_power], axis = 1), np.max(reg_power)
def filter_data_coord(x, offset_length, filtered):
if offset_length is None:
coord = range(x.shape[0])
else:
offset, length = offset_length
end = offset + length
coord = range(offset, end)
x = x[offset:end]
if filtered is not None:
filtered = filtered[offset:end]
if filtered is not None:
x = x[filtered]
coord = (c for c, f in zip(coord, filtered) if f)
return x, coord
class LayerMPCStat:
def __init__(self, mpc):
self._global_data = mpc
self._xy_dims = None
self._histo_cache = {}
self._scatt_cache = {}
def _without_paddings(self, offset_length):
return filter_data_coord(self._global_data, offset_length, None)
def histo_data(self, width, gaussian, distance_or_bin_width, global_xmax = None, offset_length = None, filtered = None):
key = width, gaussian, distance_or_bin_width, global_xmax is None, offset_length is None, filtered is None
if key in self._histo_cache:
return self._histo_cache[key]
x, coord = filter_data_coord(self._global_data[:, 0], offset_length, filtered)
if global_xmax is None:
xmin = np.min(x)
xmax = np.max(x)
else:
xmin = 0
xmax = global_xmax
if xmin == xmax:
xmin -= 0.1
xmax += 0.1
x = x - xmin # new memory, not in-place
x /= xmax - xmin # in range [0, 1]
if gaussian:
a = (2 * distance_or_bin_width ** 2)
yi = np.empty([width])
for i in range(width):
xi = i / width
dx = (xi - x) ** 2
yi[i] = np.sum(1 * np.exp(-dx / a))
yi /= np.max(yi)
xy = tuple(zip(range(width), yi))
else:
num_backle = width // distance_or_bin_width
tick = 1 / num_backle
tock = num_backle + 1
x //= tick # bin_width is float, even for floordiv
x /= tock # discrete x for coord [0, 1), leave 1 for final
x += 0.5 / tock
collapsed_x = Counter(x * width)
ymax = max(collapsed_x.values()) if collapsed_x else 1
xy = tuple((x, y/ymax) for x, y in collapsed_x.items())
# for old_key in self._histo_cache:
# if old_key[1] == gaussian:
# self._histo_cache.pop(old_key)
self._histo_cache[key] = cached = xy, xmin, xmax, tuple(zip(coord, x))
return cached
def scatter_data(self, xy_min_max = None, offset_length = None, filtered = None):
key = xy_min_max is None, offset_length is None, filtered is None
if key in self._scatt_cache:
return self._scatt_cache[key]
xy, coord = filter_data_coord(self._global_data[:, self._xy_dims], offset_length, filtered)
if xy_min_max is None:
xmin = np.min(xy, 0)
xmax = np.max(xy, 0)
else:
xmin, xmax = xy_min_max
g_orig = np.zeros_like(xmin)
invalid = g_orig < xmin
xmin = np.where(invalid, g_orig, xmin)
invalid = g_orig > xmax
xmax = np.where(invalid, g_orig, xmax)
if np.all(xmin == xmax):
xmin -= 0.1
xmax += 0.1
xy = xy - xmin
xy /= xmax - xmin
g_orig -= xmin
g_orig /= xmax - xmin
self._scatt_cache[key] = cached = xy, xmin, xmax, g_orig, tuple(coord)
return cached
# print('xy', xy.shape[0])
# print('seq_len', seq_len if seq_len else 'None')
# print('filtered', f'{sum(filtered)} in {len(filtered)}' if filtered else 'None')
# print('coord', coord)
def colorify(self, m_max, xy_dims):
self._xy_dims = xy_dims
self._global_m_max = m_max
ene = np.expand_dims(self._global_data[:, 0], 1) / m_max
ori, sature_max = to_circle(self._global_data[:, xy_dims])
self._render = np.concatenate([ene, ori], axis = 1)
return sature_max
def seal(self, sature_max):
self._render[:, 2] /= sature_max
return self
def __getitem__(self, idx):
return self._render[idx]
def __len__(self):
return self._global_data.shape[0]
class SentenceEnergy:
def __init__(self, size, mpc_word, mpc_phrase, offset, length, segment, seg_length, is_contiuous = True):
mpc_all = mpc_phrase
if segment is None:
stats = phrase = tuple(LayerMPCStat(l) for l in triangle_to_layers(mpc_phrase))
else:
if is_contiuous:
layers = inflate(trapezoid_to_layers(mpc_phrase, segment, seg_length)) # TODO check seg seg
else:
layers = trapezoid_to_layers(mpc_phrase, segment, segment, big_endian = False)
stats = phrase = tuple(l if l is None else LayerMPCStat(l) for l in layers)
if mpc_word is not None:
mpc_all = np.concatenate([mpc_word, mpc_phrase])
token = LayerMPCStat(mpc_word) # TODO check [offset:offset + length]
stats = (token,) + phrase
else:
token = None
self._min_all = xmax = np.min(mpc_all, 0)