-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvisualization.py
2187 lines (1973 loc) · 108 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 os.path import getsize, expanduser
from os import listdir
import sys
from nltk.tree import Tree
from utils import inf_none_gen, inf_zero_gen
from utils.file_io import join, isfile, parpath
from utils.pickle_io import pickle_load, pickle_dump
from utils.param_ops import HParams
IOVocab = namedtuple('IOVocab', 'vocabs, IOHead_fields, IOData_fields, threshold')
_IOHead = namedtuple('_IOHead', 'type, tree, token, offset, length')
DataStat = namedtuple('DataStat', 'data, stat')
class TensorVis:
@classmethod
def from_vfile(cls, fpath): # vocabs, IOHead_fields, IOData_fields, threshold
return cls(parpath(fpath), *pickle_load(fpath))
def __init__(self, fpath, vocabs, IOHead_fields, IOData_fields, threshold = None, clean_fn = None, fname = 'vocabs.pkl'):
files = listdir(fpath)
if isinstance(vocabs, dict):
assert (threshold is None) ^ isinstance(threshold, dict)
pkl_vocabs, pkl_thresh = vocabs, threshold
else:
pkl_vocabs = {k: v for k, v in zip(vocabs._fields, vocabs)}
pkl_thresh = {k: v for k, v in zip(threshold._fields, threshold)} if threshold else None
if vfile_exists := (fname in files):
assert isfile(join(fpath, fname))
if callable(clean_fn): # TODO
clean_fn(files)
else:
pickle_dump(join(fpath, fname), IOVocab(pkl_vocabs, IOHead_fields, IOData_fields, pkl_thresh))
self._anew = not vfile_exists
self._fpath = fpath
self._vocabs = HParams(pkl_vocabs)
self._head_type = namedtuple('IOHead', IOHead_fields)
self._data_type = namedtuple('IOData', IOData_fields)
self._threshold = HParams(pkl_thresh) if threshold else None
@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
class DiscontinuousTensorVis(TensorVis):
def __init__(self, fpath, vocabs, thresholds):
common = 'tag, label, right, joint, direc'
IOHead_fields = 'token, ' + common
IOData_fields = f'tree, {common}, batch_segment, segment, 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, tree, token, length):
size = token.shape[1]
pickle_dump(self.join(f'head.{batch_id}_{size}.pkl'), (None, tree, token, 1, length))
def set_data(self, batch_id, epoch, *l_args):
assert len(self._data_type._fields) == len(l_args)
pickle_dump(self.join(f'data.{batch_id}_{epoch}.pkl'), l_args)
# 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 in (0, 1)'
return x
def _frac_(x):
x = float(x)
assert 0 <= x <= 1, 'should be a fraction in [0, 1]'
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, rho, pc_x, pc_y, line_width, offset_x, offset_y, word_width, word_height, yx_ratio, histo_width, scatter_width')
numb_types = NumbList(_font, _frac_, _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
from utils.math_ops import uneven_split, itp
from functools import partial
from utils.file_io import path_folder
from data import NIL
from data.continuous.binary.triangle import triangle_to_layers
from data.continuous.binary.trapezoid import trapezoid_to_layers, inflate
from data.cross import Signal as CS
from data.cross import Signal as DS, draw_str_lines
CS.set_binary()
DS.set_binary()
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, 0, 1, 0.2), (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 (f1 := smy.get('F1')) and not isnan(f1):
summary_fscores[batch_id].append((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:
IOData = self._tvis.IOData
bid, num_word = (int(i) for i in heads[i][5:-4].split('_'))
head = _IOHead(*pickle_load(fpath.join(heads[i])))
if sentiment := (set(polar_vocab := self._tvis.vocabs.label) == set('01234')):
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)
if is_a_conti_task := not (isinstance(head.offset, int) and head.offset == 1): # tri/tra
breakpoint()
is_triangular = head.segment is None and head.label is not None
for sid, tree in enumerate(head.tree):
if sentiment:
negation = any(t.label() in pos_set for t in head.tree[sid].subtrees()) and any(t.label() in neg_set for t in head.tree[sid].subtrees())
else:
negation = False
mark = '*' if negation else ''
mark += f'{sid + 1}'
# if warning_cnt:
# mark += " ◌•▴⨯"[warning_level(warning_cnt)]
mark += '\t'
tokens = ' '.join(tree.leaves() if isinstance(tree, Tree) else (w for _, w, _ in tree[0]))
sentbox.insert(END, mark + tokens)
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)))
self._sent_cache[fname_time] = data_stat = []
if is_a_conti_task: # depend on task senti/parse | tri
if is_triangular:
sample_gen = (inf_none_gen if x is None else x for x in data[:-1])
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_stat.append(DataStat(sample, stat))
else: # trapezoidal
sample_gen = (inf_none_gen if d is None or f in ('segment', 'summary') else d for f,d in zip(IOData._fields, 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_stat.append(DataStat(sample, stat))
else: # discontinuous task
batch_segment = data.batch_segment
joint_segment = [x - 1 for x in batch_segment[:-1]]
sample_gen = (inf_none_gen if f == 'batch_segment' else d for f,d in zip(IOData._fields, 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], batch_segment, batch_segment)
for field in ('joint', 'joint_score'):
values[field] = trapezoid_to_layers(values[field], joint_segment, joint_segment)
values['batch_segment'] = batch_segment
sample = IOData(**values)
stat = SentenceEnergy(num_word, sample.mpc_word, sample.mpc_phrase,
1, None, batch_segment, sample.segment, False)
data_stat.append(DataStat(sample, stat))
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
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)
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)
self._max_all = xmin = np.max(mpc_all, 0)
for i, stat in enumerate(stats):
if is_contiuous:
if i == 0:
lo = offset, length
ct = 0
else:
_len = length - i + 1 # pitari without +1
if _len <= 0 or stat is None:
continue
lo = offset, _len
else: # discontinuous
if i == 0:
lo = 1, seg_length[i]
else:
lo = 1, seg_length[i - 1]
x, _ = stat._without_paddings(lo)
assert x.shape[0] != 0, 'should not be'
_max = np.max(x, 0)
x = x[x[:, 0] > 0]
_min = np.min(x, 0)
invalid = _min < xmin
xmin = np.where(invalid, _min, xmin)
invalid = _max > xmax
xmax = np.where(invalid, _max, xmax)
if lo[1] == 1:
break
self._min_val = xmin
self._max_val = xmax
self._stats = stats
self._word = token
self._phrase = phrase
self._xy_dim = None
self._cache = {}
def histo_max(self, with_padding):
if with_padding:
return self._max_all[0]
return self._max_val[0]
def scatter_min_max(self, with_nil, with_padding):
if with_nil:
_min = self._min_all[self._xy_dim]
else:
_min = self._min_val[self._xy_dim]
if with_padding:
_max = self._max_all[self._xy_dim]
else:
_max = self._max_val[self._xy_dim]
return _min, _max
def make(self, show_paddings, *xy_dims):
key = xy_dims, show_paddings
self._xy_dim = xy_dims = np.asarray(xy_dims)
if key in self._cache:
self._word, self._phrase = self._cache[key]
return
_max = self._max_all if show_paddings else self._max_val
sature_max = 0
for stat in self._stats :
if stat is None:
continue
sature_max = max(sature_max, stat.colorify(_max[0], xy_dims))
if self._word:
self._word = self._word.seal(sature_max)
self._phrase = tuple(s if s is None else s.seal(sature_max) for s in self._phrase)
self._cache[key] = self._word, self._phrase
@property
def token(self):
if self._word:
return self._word
return self._phrase[0]
@property
def tag(self):
return self._phrase[0]
@property
def phrase(self):
return self._phrase
def disp(x):
if x >= 1:
return str(x)[:3]
if x <= -1:
return str(x)[:4]
if x >= 0.01:
return str(x)[1:4]
if x <= -0.01:
return '-' + str(x)[2:5]
if x == 0:
return '0'
return '+0' if x > 0 else '-0'
def make_color(mutable_x,
show_color = False,
inverse_brightness = False,
curve = None,
fallback_color = 'orange'):
if show_color:
v, h, s = mutable_x[:3]
else:
if isinstance(mutable_x, float):
v = mutable_x
else:
v = mutable_x[0] if mutable_x.shape else mutable_x
h = s = 0
if curve is not None:
v = curve(v)
if v < 0 or v > 1:
return fallback_color
if inverse_brightness:
v = 1 - v
def channel(c):
x = hex(int(c * 255))
n = len(x)
if c < 0:
return 'z'
if n == 3:
return '0' + x[-1]
elif n == 4:
return x[2:]
return '#' + ''.join(channel(x) for x in hsv_to_rgb(h, s, v))
def make_histogram(stat_board, offx, offy, width, height,
stat, offset_length, histo_max,
half_word_height,
stat_font,
stat_color,
xlab,
filtered = None,
distance = None,
bin_width = 1):
gaussian = distance and distance > 0
xy, xmin, xmax, coord_x = stat.histo_data(width, gaussian, distance if gaussian else bin_width, histo_max, offset_length, filtered)
if half_word_height and stat_font and xlab:
stat_board.create_text(offx, offy + height + half_word_height,
text = disp(xmin),
fill = stat_color, anchor = W, font = stat_font)
stat_board.create_text(offx + width, offy + height + half_word_height,
text = disp(xmax),
fill = stat_color, anchor = E, font = stat_font)
# base line
stat_board.create_line(offx, offy + height,
offx + width, offy + height,
fill = stat_color)# does not work, width = 0.5)
for x, y in xy:
stat_board.create_line(offx + x, offy + height - y * height,
offx + x, offy + height,
fill = stat_color,
width = 1 if gaussian else bin_width)
return {c:x * width for c, x in coord_x}
def make_scatter(stat_board, offx, offy, width, height, r,
stat, offset_length, scatter_min_max,
stat_color,
half_word_height,
stat_font,
to_color,
background,
xlab, ylab, clab,
filtered = None):
xy, xy_min, xy_max, xy_orig, coord = stat.scatter_data(scatter_min_max, offset_length, filtered)
if half_word_height and stat_font and (xlab or ylab or clab):
xmin, ymin = (disp(i) for i in xy_min)
xmax, ymax = (disp(i) for i in xy_max)
if xlab:
stat_board.create_text(offx, offy + height + half_word_height,
text = xmin, fill = stat_color,
font = stat_font, anchor = W)
stat_board.create_text(offx + width, offy + height + half_word_height,
text = xmax, fill = stat_color,
font = stat_font, anchor = E)
if ylab:
stat_board.create_text(offx - half_word_height * 1.3, offy,
text = ymax, fill = stat_color,
font = stat_font)#, angle = 90)
stat_board.create_text(offx - half_word_height * 1.3, offy + height,
text = ymin, fill = stat_color,
font = stat_font)
if clab:
stat_board.create_text(offx - half_word_height * 1.3, offy + height / 2,
text = f'{len(xy)}•', fill = 'SpringGreen3',
font = stat_font)#, anchor = E)
stat_board.create_rectangle(offx, offy,
offx + width, offy + height,
fill = background, outline = background)
x, y = xy_orig