forked from UCLA-Plasma-Simulation-Group/pyVisOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathosh5visipy.py
More file actions
1986 lines (1779 loc) · 107 KB
/
osh5visipy.py
File metadata and controls
1986 lines (1779 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
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
"""
osh5visipy.py
=============
Vis tools for the OSIRIS HDF5 data.
"""
from __future__ import print_function
from functools import partial
from ipywidgets import interact, Layout, Output
import ipywidgets as widgets
from IPython.display import display, FileLink, clear_output
import numpy as np
import osh5vis
import osh5io
import glob
import os
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm, Normalize, PowerNorm, SymLogNorm
from matplotlib._pylab_helpers import Gcf as pylab_gcf
import subprocess
from datetime import datetime
import time
import re
print("Importing osh5visipy. Please use `%matplotlib notebook' in your jupyter/ipython notebook;")
print("use `%matplotlib widget' if you are using newer version of matplotlib (3.0) + jupyterlab (0.35)")
do_nothing = lambda x : x
_items_layout = Layout(flex='1 1 auto', width='auto')
_get_delete_btn = lambda tp : widgets.Button(description='', tooltip='delete %s' % tp, icon='times', layout=Layout(width='32px'))
__2dplot_param_doc = """
2D plot with widgets
:param data: (list of) 2D H5Data
:param args: arguments passed to 2d plotting widgets. reserved for future use
:param show: whether to show the widgets
:param grid: a tuple (row, column) specifying the layout of subplots. Must be set when plotting more than one subplot
:param kwargs: keyword arguments passed to 2d plotting widgets. reserved for future use
:return: if show == True return None otherwise return a list of widgets
"""
__2dplot_example_doc = """
example usage:
os%s_w(filename) # filename is a string, display %s of the file with filename
os%s_w(data) # data is a H5Data variable, display %s of data
os%s_w((filename1, filename2, filename3), grid=(3,1)) # display %s of 3 files in 3 rows
os%s_w((data1, data2, data3, data4), grid=(2,2)) # display %s of 4 H5Data variables in a 2 by 2 grid
"""
def os2dplot_w(data, *args, pltfunc=osh5vis.osimshow, show=True, grid=None, **kwargs):
"""%s""" % (__2dplot_param_doc + (__2dplot_example_doc % (('pltfunc', ) * 8)))
if isinstance(data, str):
h5data = osh5io.read_h5(data)
wl = Generic2DPlotCtrl(h5data, *args, pltfunc=pltfunc, **kwargs).widgets_list
elif isinstance(data, (tuple, list)):
if not grid:
raise ValueError('Specify the grid layout when plotting more than one quantity!')
if isinstance(data[0], str):
data = [osh5io.read_h5(n) for n in data]
wl = MultiPanelCtrl((Generic2DPlotCtrl,) * len(data), data, grid, **kwargs).widgets_list
else:
wl = Generic2DPlotCtrl(data, *args, pltfunc=pltfunc, **kwargs).widgets_list
if show:
display(*wl)
else:
return wl
osimshow_w = partial(os2dplot_w, pltfunc=osh5vis.osimshow)
osimshow_w.__doc__ = """%s""" % (__2dplot_param_doc + (__2dplot_example_doc % (('imshow',) * 8)))
oscontour_w = partial(os2dplot_w, pltfunc=osh5vis.oscontour)
oscontour_w.__doc__ = """%s""" % (__2dplot_param_doc + (__2dplot_example_doc % (('contour',) * 8)))
oscontourf_w = partial(os2dplot_w, pltfunc=osh5vis.oscontourf)
oscontourf_w.__doc__ = """%s""" % (__2dplot_param_doc + (__2dplot_example_doc % (('contourf',) * 8)))
def slicer_w(data, *args, show=True, slider_only=False, **kwargs):
"""
A slider for 3D data
:param data: (a list of) 3D H5Data or directory name (a string)
:param args: arguments passed to plotting widgets. reserved for future use
:param show: whether to show the widgets
:param slider_only: if True only show the slider otherwise show also other plot control (aka 'the tab')
:param kwargs: keyword arguments passed to 2d plotting widgets. reserved for future use
:return: whatever widgets that are not shown
example usage:
slicer_w(dirname) # dirname is the name of a directory, display the quantity inside dirname,
# slider bar let you choose which file to display
slicer_w(data) # data is a 3d H5Data variable, slider bar let you choose the position along certain axis
slicer_w((dirname1, dirname2, dirname3, dirname4), grid=(2, 2)) # display 4 subplots in a 2 by 2 grid,
# slider bar let you choose which time step to display,
# number of files in dirname# should be the same
"""
if isinstance(data, str):
wl = DirSlicer(data, *args, **kwargs).widgets_list
elif isinstance(data, (tuple, list)):
if isinstance(data[0], (str, tuple, list)):
wl = MPDirSlicer(data, *args, **kwargs).widgets_list
else:
raise NotImplementedError('Unexpected data. Cannot process input parameters')
else:
wl = Slicer(data, *args, **kwargs).widgets_list
tab, slider = wl[0], widgets.HBox(wl[1:-1], layout=_items_layout)
if show:
if slider_only:
display(slider, wl[-1])
return tab
else:
display(tab, slider, wl[-1])
else:
return wl
def animation_w(data, *args, **kwargs):
wl = Animation(data, *args, **kwargs).widgets_list
display(widgets.VBox([wl[0], widgets.HBox(wl[1:4]), widgets.HBox(wl[4:-2]), widgets.VBox(wl[-2:])]))
class FigureManager(object):
def __init__(self):
self.managers, self.figures = self.refresh()
self.refreshbtn = widgets.Button(description='refresh', disabled=False, tooltip='get all currently opened figures', icon='refresh')
self.deletebtn = widgets.Button(description='delete', tooltip='delete this figure', icon='trash', button_style='danger')
self.selection = widgets.ToggleButtons(options=list(range(len(self.figures))), description='Figures:', value=None)
# layout=_items_layout, style={'description_width': 'initial', "button_width": 'initial'})
self.display = Output()
self.selection.observe(self.display_figure, 'value')
self.refreshbtn.on_click(self.refresh_wgt)
self.deletebtn.on_click(self.delete)
self._widget = widgets.VBox([widgets.HBox([self.refreshbtn, self.deletebtn]), self.selection])
with self.display:
display(self._widget)
def display_figure(self, change):
self.display.clear_output(wait=True)
with self.display:
display(self._widget)
if isinstance(change['new'], int):
display(self.figures[change['new']])
@property
def widget(self):
return self.display
# @widget.setter
# def widget(self, value):
# self._widget = value
def refresh(self):
mngr = [manager for manager in pylab_gcf.get_all_fig_managers()]
f = [m.canvas.figure for m in mngr]
return mngr, f
def refresh_wgt(self, *_):
self.managers, self.figures = self.refresh()
self.selection.options, self.selection.value = list(range(len(self.figures))), 0
# self._widget = widgets.VBox([widgets.HBox([self.refreshbtn, self.deletebtn]), self.selection, self.display])
def delete(self, *_):
plt.close(self.figures[self.selection.value])
self.refresh_wgt()
def _get_downloadable_url(filename):
return '<a href="files%s" download="%s"> %s </a>' % (os.path.abspath(filename),
os.path.basename(filename), filename)
class Generic2DPlotCtrl(object):
tab_contents = ['Data', 'Axes', 'Overlay', 'Colorbar', 'Save', 'Figure']
eps = 1e-40
colormaps_available = sorted(c for c in plt.colormaps() if not c.endswith("_r"))
def __init__(self, data, pltfunc=osh5vis.osimshow, slcs=(slice(None, ), slice(None, )), title=None, norm='',
fig=None, figsize=None, time_in_title=True, phys_time=False, ax=None, output_widget=None,
xlabel=None, ylabel=None, onDestruction=do_nothing,
convert_xaxis=False, convert_yaxis=False, register_callbacks=None, **kwargs):
self._data, self._slcs, self.im_xlt, self.time_in_title, self.pltfunc, self.onDestruction = \
data, slcs, None, time_in_title, pltfunc, onDestruction
self.callbacks = {} if register_callbacks is None else register_callbacks
user_cmap, show_colorbar = kwargs.pop('cmap', 'jet'), kwargs.pop('colorbar', True)
tab = []
# # # -------------------- Tab0 --------------------------
# title
if not title:
title = osh5vis.default_title(data, show_time=False)
t_in_axis = data.has_axis('t')
self.if_reset_title = widgets.Checkbox(value=True, description='Auto', layout=_items_layout)
self.datalabel = widgets.Text(value=title, placeholder='data', continuous_update=False,
description='Data Name:', disabled=self.if_reset_title.value, layout=_items_layout)
self.if_show_time = widgets.Checkbox(value=time_in_title and not t_in_axis, description='Time in title, ', layout=_items_layout)
self.time_in_phys = widgets.Checkbox(value=phys_time, description='time in physical unit',
layout={'width': 'initial'}, style={'description_width': 'initial'})
lognorm = norm == 'Log'
self.__pp = np.abs if lognorm else do_nothing
if 'clim' in kwargs:
if kwargs['clim'][0] is not None:
vmin, auto_vmin = kwargs['clim'][0], False
logvmin = vmin if lognorm else self.eps
else:
vmin, logvmin, auto_vmin = np.min(data), self.eps, True
if kwargs['clim'][1] is not None:
vmax, auto_vmax = kwargs['clim'][1], False
else:
vmax, auto_vmax = np.max(data), True
else:
vmin, logvmin, vmax, auto_vmin, auto_vmax = np.min(data), self.eps, np.max(data), True, True
# normalization
# general parameters: vmin, vmax, clip
self.if_vmin_auto = widgets.Checkbox(value=auto_vmin, description='Auto', layout=_items_layout, style={'description_width': 'initial'})
self.if_vmax_auto = widgets.Checkbox(value=auto_vmax, description='Auto', layout=_items_layout, style={'description_width': 'initial'})
self.vmin_wgt = widgets.FloatText(value=vmin, description='vmin:', continuous_update=False,
disabled=self.if_vmin_auto.value, layout=_items_layout, style={'description_width': 'initial'})
self.vlogmin_wgt = widgets.FloatText(value=logvmin, description='vmin:', continuous_update=False,
disabled=self.if_vmin_auto.value, layout=_items_layout, style={'description_width': 'initial'})
self.vmax_wgt = widgets.FloatText(value=vmax, description='vmax:', continuous_update=False,
disabled=self.if_vmax_auto.value, layout=_items_layout, style={'description_width': 'initial'})
self.if_clip_cm = widgets.Checkbox(value=True, description='Clip', layout=_items_layout, style={'description_width': 'initial'})
# PowerNorm specific
self.gamma = widgets.FloatText(value=1, description='gamma:', continuous_update=False,
layout=_items_layout, style={'description_width': 'initial'})
# SymLogNorm specific
self.linthresh = widgets.FloatText(value=self.eps, description='linthresh:', continuous_update=False,
layout=_items_layout, style={'description_width': 'initial'})
self.linscale = widgets.FloatText(value=1.0, description='linscale:', continuous_update=False,
layout=_items_layout, style={'description_width': 'initial'})
# build the widgets tuple
ln_wgt = (LogNorm, widgets.VBox([widgets.HBox([self.vmax_wgt, self.if_vmax_auto]),
widgets.HBox([self.vlogmin_wgt, self.if_vmin_auto]), self.if_clip_cm]))
n_wgt = (Normalize, widgets.VBox([widgets.HBox([self.vmax_wgt, self.if_vmax_auto]),
widgets.HBox([self.vmin_wgt, self.if_vmin_auto]), self.if_clip_cm]))
pn_wgt = (PowerNorm, widgets.VBox([widgets.HBox([self.vmax_wgt, self.if_vmax_auto]),
widgets.HBox([self.vmin_wgt, self.if_vmin_auto]), self.if_clip_cm,
self.gamma]))
sln_wgt = (SymLogNorm, widgets.VBox(
[widgets.HBox([self.vmax_wgt, self.if_vmax_auto]),
widgets.HBox([self.vmin_wgt, self.if_vmin_auto]), self.if_clip_cm, self.linthresh, self.linscale]))
# find out default value for norm_selector
norm_avail = {'Log': ln_wgt, 'Normalize': n_wgt, 'Power': pn_wgt, 'SymLog': sln_wgt}
self.norm_selector = widgets.Dropdown(options=norm_avail, style={'description_width': 'initial'},
value=norm_avail.get(norm, n_wgt), description='Normalization:')
self.__old_norm = self.norm_selector.value
# additional care for LorNorm()
self.__handle_lognorm()
# self.vmin_wgt.value, self.vlogmin_wgt.value, self.vmax_wgt.value = vmin, logvmin, vmax
# re-plot button
self.norm_btn_wgt = widgets.Button(description='Apply', disabled=False, tooltip='Update normalization', icon='refresh')
tab.append(self.get_tab_data())
# # # -------------------- Tab1 --------------------------
self.if_xrange_auto = widgets.Checkbox(value=True, description='Auto xrange', layout=_items_layout, style={'description_width': 'initial'})
self.if_yrange_auto = widgets.Checkbox(value=True, description='Auto yrange', layout=_items_layout, style={'description_width': 'initial'})
self.apply_range_btn = widgets.Button(description='Apply', disabled=False, \
tooltip='set range. (* this will delete all overlaid plots *)', icon='refresh')
self.axis_lim_wgt = widgets.HBox([self.if_xrange_auto, self.if_yrange_auto, self.apply_range_btn])
# x axis
xmin, xmax, xinc, ymin, ymax, yinc = self.__get_xy_minmax_delta()
if convert_xaxis:
self.xconv, xunit = data.axes[1].punit_convert_factor()
else:
self.xconv, xunit = 1.0, data.axes[1].units
self.x_min_wgt = widgets.BoundedFloatText(value=xmin * self.xconv, min=xmin * self.xconv, max=xmax * self.xconv, step=xinc * self.xconv/2, description='xmin:',
disabled=True, layout=_items_layout, style={'description_width': 'initial'})
self.x_max_wgt = widgets.BoundedFloatText(value=xmax * self.xconv, min=xmin * self.xconv, max=xmax * self.xconv, step=xinc * self.xconv/2, description='xmax:',
disabled=True, layout=_items_layout, style={'description_width': 'initial'})
self.x_step_wgt = widgets.BoundedFloatText(value=xinc * self.xconv, step=xinc * self.xconv, disabled=True,
description='$\Delta x$:', layout=_items_layout, style={'description_width': 'initial'})
widgets.jslink((self.x_min_wgt, 'max'), (self.x_max_wgt, 'value'))
widgets.jslink((self.x_max_wgt, 'min'), (self.x_min_wgt, 'value'))
widgets.jslink((self.x_min_wgt, 'disabled'), (self.if_xrange_auto, 'value'))
widgets.jslink((self.x_max_wgt, 'disabled'), (self.if_xrange_auto, 'value'))
widgets.jslink((self.x_step_wgt, 'disabled'), (self.if_xrange_auto, 'value'))
# x label
self.if_reset_xlabel = widgets.Checkbox(value=True, description='Auto', layout=_items_layout, style={'description_width': 'initial'})
self.if_x_phys_unit = widgets.Checkbox(value=convert_xaxis, description='phys unit; ', layout={'width': 'initial'}, style={'description_width': 'initial'})
if xlabel is False:
self._xlabel = None
self.if_reset_xlabel.value = False
elif isinstance(xlabel, str):
self._xlabel = xlabel
else:
self._xlabel = osh5vis.axis_format(data.axes[1].long_name, xunit)
self.xlabel = widgets.Text(value=self._xlabel,
placeholder='x', continuous_update=False,
description='X label:', disabled=self.if_reset_xlabel.value)
widgets.jslink((self.xlabel, 'disabled'), (self.if_reset_xlabel, 'value'))
self.xaxis_lim_wgt = widgets.HBox([self.if_x_phys_unit, self.x_min_wgt, self.x_max_wgt, self.x_step_wgt,
widgets.HBox([self.xlabel, self.if_reset_xlabel], layout=Layout(border='solid 1px'))])
# y axis
if convert_yaxis:
self.yconv, yunit = data.axes[0].punit_convert_factor()
else:
self.yconv, yunit = 1.0, data.axes[0].units
self.y_min_wgt = widgets.BoundedFloatText(value=ymin * self.yconv, min=ymin * self.yconv, max=ymax * self.yconv, step=yinc * self.yconv/2, description='ymin:',
disabled=True, layout=_items_layout, style={'description_width': 'initial'})
self.y_max_wgt = widgets.BoundedFloatText(value=ymax * self.yconv, min=ymin * self.yconv, max=ymax * self.yconv, step=yinc * self.yconv/2, description='ymax:',
disabled=True, layout=_items_layout, style={'description_width': 'initial'})
self.y_step_wgt = widgets.BoundedFloatText(value=yinc * self.yconv, step=yinc * self.yconv, disabled=True, description='$\Delta y$:',
layout=_items_layout, style={'description_width': 'initial'})
widgets.jslink((self.y_min_wgt, 'max'), (self.y_max_wgt, 'value'))
widgets.jslink((self.y_max_wgt, 'min'), (self.y_min_wgt, 'value'))
widgets.jslink((self.y_min_wgt, 'disabled'), (self.if_yrange_auto, 'value'))
widgets.jslink((self.y_max_wgt, 'disabled'), (self.if_yrange_auto, 'value'))
widgets.jslink((self.y_step_wgt, 'disabled'), (self.if_xrange_auto, 'value'))
# y label
self.if_reset_ylabel = widgets.Checkbox(value=True, description='Auto', layout=_items_layout, style={'description_width': 'initial'})
self.if_y_phys_unit = widgets.Checkbox(value=convert_yaxis, description='phys unit; ', layout={'width': 'initial'}, style={'description_width': 'initial'})
if ylabel is False:
self._ylabel = None
self.if_reset_ylabel.value = False
elif isinstance(ylabel, str):
self._ylabel = ylabel
else:
self._ylabel = osh5vis.axis_format(data.axes[0].long_name, yunit)
self.ylabel = widgets.Text(value=self._ylabel,
placeholder='y', continuous_update=False,
description='Y label:', disabled=self.if_reset_ylabel.value)
widgets.jslink((self.ylabel, 'disabled'), (self.if_reset_ylabel, 'value'))
self.yaxis_lim_wgt = widgets.HBox([self.if_y_phys_unit, self.y_min_wgt, self.y_max_wgt, self.y_step_wgt,
widgets.HBox([self.ylabel, self.if_reset_ylabel], layout=Layout(border='solid 1px'))])
tab.append(widgets.VBox([self.axis_lim_wgt, self.xaxis_lim_wgt, self.yaxis_lim_wgt]))
# # # -------------------- Tab2 --------------------------
overlay_item_layout = Layout(display='flex', flex_flow='row wrap', width='auto')
self.__analysis_def = {'Average': {'Simple': lambda x, a : np.mean(x, axis=a), 'RMS': lambda x, a : np.sqrt(np.mean(x*x, axis=a))},
'Sum': {'Simple': lambda x, a : np.sum(x, axis=a), 'Square': lambda x, a : np.sum(x*x, axis=a),
'ABS': lambda x, a : np.sum(np.abs(x, axis=a))},
'Min': {'Simple': lambda x, a : np.min(x, axis=a), 'ABS': lambda x, a : np.min(np.abs(x), axis=a)},
'Max': {'Simple': lambda x, a : np.max(x, axis=a), 'ABS': lambda x, a : np.max(np.abs(x), axis=a)}} #TODO: envelope
analist = [k for k in self.__analysis_def.keys()]
# x lineout
self.xlineout_wgt = widgets.BoundedFloatText(value=ymin, min=ymin, max=ymax, style={'description_width': 'initial'},
step=yinc, description=self.ylabel.value, layout={'width': 'initial'})
widgets.jslink((self.xlineout_wgt, 'description'), (self.ylabel, 'value'))
widgets.jslink((self.xlineout_wgt, 'min'), (self.y_min_wgt, 'value'))
widgets.jslink((self.xlineout_wgt, 'max'), (self.y_max_wgt, 'value'))
widgets.jslink((self.xlineout_wgt, 'step'), (self.y_step_wgt, 'value'))
self.add_xlineout_btn = widgets.Button(description='Lineout', tooltip='Add x-lines', layout={'width': 'initial'})
# simple analysis in x direction
self.xananame = widgets.Dropdown(options=analist, value=analist[0], description='Analysis:',
layout={'width': 'initial'}, style={'description_width': 'initial'})
xanaoptlist = [k for k in self.__analysis_def[analist[0]].keys()]
self.xanaopts = widgets.Dropdown(options=xanaoptlist, value=xanaoptlist[0], description='',
layout={'width': 'initial'}, style={'description_width': 'initial'})
self.anaxmin = widgets.BoundedFloatText(value=ymin, min=ymin, max=ymax, step=yinc, description='from',
layout={'width': 'initial'}, style={'description_width': 'initial'})
self.anaxmax = widgets.BoundedFloatText(value=ymax, min=ymin, max=ymax, step=yinc, description='to',
layout={'width': 'initial'}, style={'description_width': 'initial'})
widgets.jslink((self.anaxmin, 'min'), (self.y_min_wgt, 'value'))
widgets.jslink((self.anaxmin, 'max'), (self.anaxmax, 'value'))
widgets.jslink((self.anaxmin, 'step'), (self.y_step_wgt, 'value'))
widgets.jslink((self.anaxmax, 'min'), (self.anaxmin, 'value'))
widgets.jslink((self.anaxmax, 'max'), (self.y_max_wgt, 'value'))
widgets.jslink((self.anaxmax, 'step'), (self.y_step_wgt, 'value'))
self.xana_add = widgets.Button(description='Add', tooltip='Add analysis as x line plot', layout={'width': 'initial'})
xlinegroup = widgets.HBox([self.xananame, self.xanaopts, self.anaxmin, self.anaxmax, self.xana_add], layout=Layout(border='solid 1px'))
# list of x lines plotted
self.xlineout_list_wgt = widgets.Box(children=[], layout=overlay_item_layout, style={'description_width': 'initial'})
self.xlineout_tab = widgets.VBox([widgets.HBox([widgets.HBox([self.xlineout_wgt, self.add_xlineout_btn],
layout=Layout(border='solid 1px', flex='1 1 auto', width='auto')),
xlinegroup]), self.xlineout_list_wgt])
# y lineout
self.ylineout_wgt = widgets.BoundedFloatText(value=xmin, min=xmin, max=xmax, style={'description_width': 'initial'},
step=xinc, description=self.xlabel.value, layout={'width': 'initial'})
widgets.jslink((self.ylineout_wgt, 'description'), (self.xlabel, 'value'))
widgets.jslink((self.ylineout_wgt, 'min'), (self.x_min_wgt, 'value'))
widgets.jslink((self.ylineout_wgt, 'max'), (self.x_max_wgt, 'value'))
widgets.jslink((self.ylineout_wgt, 'step'), (self.x_step_wgt, 'value'))
self.add_ylineout_btn = widgets.Button(description='Lineout', tooltip='Add y-lines', layout={'width': 'initial'})
# simple analysis in x direction
self.yananame = widgets.Dropdown(options=analist, value=analist[0], description='Analysis:',
layout={'width': 'initial'}, style={'description_width': 'initial'})
yanaoptlist = [k for k in self.__analysis_def[analist[0]].keys()]
self.yanaopts = widgets.Dropdown(options=yanaoptlist, value=yanaoptlist[0], description='',
layout={'width': 'initial'}, style={'description_width': 'initial'})
self.anaymin = widgets.BoundedFloatText(value=xmin, min=xmin, max=xmax, step=xinc, description='from',
layout={'width': 'initial'}, style={'description_width': 'initial'})
self.anaymax = widgets.BoundedFloatText(value=xmax, min=xmin, max=xmax, step=xinc, description='to',
layout={'width': 'initial'}, style={'description_width': 'initial'})
widgets.jslink((self.anaymin, 'min'), (self.x_min_wgt, 'value'))
widgets.jslink((self.anaymin, 'max'), (self.anaymax, 'value'))
widgets.jslink((self.anaymin, 'step'), (self.x_step_wgt, 'value'))
widgets.jslink((self.anaymax, 'min'), (self.anaymin, 'value'))
widgets.jslink((self.anaymax, 'max'), (self.x_max_wgt, 'value'))
widgets.jslink((self.anaymax, 'step'), (self.x_step_wgt, 'value'))
self.yana_add = widgets.Button(description='Add', tooltip='Add analysis as y line plot', layout={'width': 'initial'})
ylinegroup = widgets.HBox([self.yananame, self.yanaopts, self.anaymin, self.anaymax, self.yana_add],
layout=Layout(width='initial', border='solid 1px'))
# list of x lines plotted
self.ylineout_list_wgt = widgets.Box(children=[], layout=overlay_item_layout)
self.ylineout_tab = widgets.VBox([widgets.HBox([widgets.HBox([self.ylineout_wgt, self.add_ylineout_btn],
layout=Layout(border='solid 1px', flex='1 1 auto', width='auto')),
ylinegroup]), self.ylineout_list_wgt])
# self.ct_alpha = widgets.BoundedFloatText(value=1.0, min=0., max=1., step=0.01, layout={'width': 'initial'}, style={'description_width': 'initial'})
self.ct_auto_color = widgets.ToggleButtons(options=['colormap', 'manual', 'same'], description='Color:', value='colormap',
tooltips=['use selected colormap', 'set each level indevidually', 'monochromatic, same as the last level'],
layout=_items_layout, style={'description_width': 'initial', "button_width": 'initial'})
self.ct_antialiased = widgets.Checkbox(value=False, description='antialiased; ', layout=_items_layout, style={'description_width': 'initial'})
self.ct_if_clabel = widgets.Checkbox(value=False, description='clabels ', layout=_items_layout, style={'description_width': 'initial'})
self.ct_if_inline_clabel = widgets.Checkbox(value=False, description='inline; ', disabled=True,
layout=_items_layout, style={'description_width': 'initial'})
self.ct_cmap_selector = widgets.Dropdown(options=self.colormaps_available, value=user_cmap, description=' colormap:',
disabled=(self.ct_auto_color.value != 'colormap'), layout={'width': 'initial'}, style={'description_width': 'initial'})
self.ct_cmap_reverse = widgets.Checkbox(value=False, description='Reverse; ', disabled=self.ct_cmap_selector.disabled,
layout=_items_layout, style={'description_width': 'initial'})
widgets.jslink((self.ct_cmap_reverse, 'disabled'), (self.ct_cmap_selector, 'disabled'))
self.ct_method = widgets.Dropdown(options=['contour', 'contourf'], value='contour', description='', layout=_items_layout, style={'description_width': 'initial'})
self.ct_plot_btn = widgets.Button(description='Plot', tooltip='plot overlay', style={'description_width': 'initial'}, layout={'width': 'initial'})
self.ct_opts_list, self.ct_wgt_list = widgets.Box(children=[], layout=overlay_item_layout), widgets.Box(children=[], layout=overlay_item_layout)
self.ct_opts_dict, self.ct_plot_dict = {}, {} # dict to keep track of the overlaid plots
self.ct_num_levels_opts = widgets.ToggleButtons(options=['auto', 'option', 'fixed:'], description=' number of levels:', value='auto',
tooltips=['let the plotter decide how many levels to plot', 'same number of levels as the level options added below',
'excact number of levels (some of the level options added below may not be used)'],
layout=_items_layout, style={'description_width': 'initial', "button_width": 'initial'})
self.ct_num_levels = widgets.BoundedIntText(value=8, min=1, max=plt.MaxNLocator.MAXTICKS, description='', disabled=(self.ct_num_levels_opts.value != 'fixed:'),
layout={'width': 'initial'}, style={'description_width': 'initial'})
self.ct_level = widgets.Text(value='0.0', placeholder='0.0, 0.01, 10', description='Levels=', disabled=(self.ct_num_levels_opts.value != 'option'),
layout=_items_layout, style={'description_width': 'initial'})
self.ct_colorpicker = widgets.ColorPicker(concise=False, description='; color:', value='black', disabled=(self.ct_auto_color.value == 'colormap'),
style={'description_width': 'initial'}, layout={'width': '200px'})
self.ct_linestyle = widgets.Dropdown(options=[None, 'solid', 'dashed', 'dashdot', 'dotted'], value=None, description='; linestyle:',
style={'description_width': 'initial'}, layout={'width': 'initial'})
self.ct_add_lvl_btn = widgets.Button(description='Add', tooltip='Add level options. Will use default settings if no option is added',
style={'description_width': 'initial'}, layout={'width': 'initial'})
self.ct_info_output = Output()
self.ct_tab = widgets.VBox([widgets.HBox([self.ct_antialiased, self.ct_if_clabel, self.ct_if_inline_clabel, self.ct_auto_color,
self.ct_cmap_selector, self.ct_cmap_reverse, self.ct_num_levels_opts, self.ct_num_levels]),
widgets.HBox([self.ct_level, self.ct_colorpicker, self.ct_add_lvl_btn, self.ct_method, self.ct_linestyle, self.ct_plot_btn]),
self.ct_opts_list, self.ct_info_output, self.ct_wgt_list])
self.overlay = widgets.Tab(children=[self.xlineout_tab, self.ylineout_tab, self.ct_tab])
[self.overlay.set_title(i, tt) for i, tt in enumerate(['x-lines', 'y-lines', 'contours'])]
tab.append(self.overlay)
# # # -------------------- Tab3 --------------------------
self.colorbar = widgets.Checkbox(value=show_colorbar, description='Show colorbar')
self.cmap_selector = widgets.Dropdown(options=self.colormaps_available, value=user_cmap,
description='Colormap:', disabled=not show_colorbar)
self.cmap_reverse = widgets.Checkbox(value=False, description='Reverse', disabled=not show_colorbar)
# colorbar
self.if_reset_cbar = widgets.Checkbox(value=True, description='Auto', disabled=not show_colorbar)
self.cbar = widgets.Text(value=data.units.tex(), placeholder='a.u.', continuous_update=False,
description='Colorbar:', disabled=self.if_reset_cbar.value or not show_colorbar)
tab.append(widgets.VBox([self.colorbar,
widgets.HBox([self.cmap_selector, self.cmap_reverse], layout=_items_layout),
widgets.HBox([self.cbar, self.if_reset_cbar])], layout=_items_layout))
# # # -------------------- Tab4 --------------------------
self.saveas = widgets.Button(description='Save current plot', tooltip='save current plot', button_style='')
self.dlink = widgets.HTML(value='', description='')
self.figname = widgets.Text(value='figure.eps', description='Figure name:', placeholder='figure name')
self.dpi = widgets.BoundedIntText(value=300, min=4, max=3000, description='DPI:')
tab.append(self.get_tab_save())
# # # -------------------- Tab5 --------------------------
width, height = figsize or plt.rcParams.get('figure.figsize')
self.figwidth = widgets.BoundedFloatText(value=width, min=0.1, step=0.01, description='Width:')
self.figheight = widgets.BoundedFloatText(value=height, min=0.1, step=0.01, description='Height:')
self.resize_btn = widgets.Button(description='Adjust figure', tooltip='Update figure', icon='refresh')
self.destroy_fig_btn = widgets.Button(description='Close figure', tooltip='close figure and destroy this widget', icon='trash')
tab.append(widgets.VBox([widgets.HBox([self.figwidth, self.figheight, self.resize_btn], layout=_items_layout),
self.destroy_fig_btn]))
# construct the tab
self.tab = widgets.Tab(layout=_items_layout)
self.tab.children = tab
[self.tab.set_title(i, tt) for i, tt in enumerate(self.tab_contents)]
# plotting and then setting normalization colors
# self.vmin_wgt.value, self.vlogmin_wgt.value, self.vmax_wgt.value = vmin, logvmin, vmax
self.out_main = output_widget or Output()
self.observer_thrd, self.cb = None, None
# if not fig:
# ax = None
with self.out_main:
self.fig = fig or plt.figure(figsize=[width, height], constrained_layout=True)
self.ax = ax or self.fig.add_subplot(111)
self.im, self.cb = self.plot_data(vminmax_from_widget=True)
# vmin, vmax = self.__get_vminmax(from_widgets=True)
# self.im.set_clim(vmin, vmax)
# plt.show()
self.axx, self.axy, self._xlineouts, self._ylineouts, self.im2 = None, None, {}, {}, []
# link and activate the widgets
self.if_reset_title.observe(self.__update_title, 'value')
self.if_reset_xlabel.observe(self.__update_xlabel, 'value')
self.if_reset_ylabel.observe(self.__update_ylabel, 'value')
self.if_x_phys_unit.observe(self._update_xconverter, 'value')
self.if_y_phys_unit.observe(self._update_yconverter, 'value')
self.if_reset_cbar.observe(self.__update_cbar, 'value')
self.norm_btn_wgt.on_click(self.update_norm)
self.if_vmin_auto.observe(self.__update_vmin, 'value')
self.if_vmax_auto.observe(self.__update_vmax, 'value')
self.norm_selector.observe(self.__update_norm_wgt, 'value')
self.cmap_selector.observe(self.update_cmap, 'value')
self.cmap_reverse.observe(self.update_cmap, 'value')
self.datalabel.observe(self.update_title, 'value')
self.if_show_time.observe(self.update_title, 'value')
self.time_in_phys.observe(self.update_title, 'value')
self.xlabel.observe(self.update_xlabel, 'value')
self.ylabel.observe(self.update_ylabel, 'value')
self.cbar.observe(self.update_cbar, 'value')
self.apply_range_btn.on_click(self.update_plot_area)
self.figname.observe(self.__reset_save_button, 'value')
self.saveas.on_click(self.__try_savefig)
self.colorbar.observe(self.__toggle_colorbar, 'value')
self.resize_btn.on_click(self.adjust_figure)
self.add_xlineout_btn.on_click(self.__add_xlineout)
self.add_ylineout_btn.on_click(self.__add_ylineout)
self.xananame.observe(self.__update_xanaopts, 'value')
self.xana_add.on_click(self.__add_xana)
self.yananame.observe(self.__update_yanaopts, 'value')
self.yana_add.on_click(self.__add_yana)
self.destroy_fig_btn.on_click(self.self_destruct)
self.ct_auto_color.observe(self._on_ct_auto_color_wgt_change, 'value')
self.ct_num_levels_opts.observe(self._on_ct_num_lvl_opts_wgt_change, 'value')
self.ct_add_lvl_btn.on_click(self._add_contour_lvl_opts)
self.ct_plot_btn.on_click(self._add_contour_plot)
self.ct_if_clabel.observe(self._on_clabel_toggle, 'value')
self.ct_method.observe(self._on_ct_method_change, 'value')
self.if_xrange_auto.observe(self.reset_xrange_step, 'value')
self.if_yrange_auto.observe(self.reset_yrange_step, 'value')
@property
def widgets_list(self):
return self.tab, self.out_main
@property
def widget(self):
return widgets.VBox([self.tab, self.out_main])
def get_dataname(self):
return self._data.name
def get_time_label(self, convert_tunit=False):
return osh5vis.time_format(self._data.run_attrs['TIME'][0], self._data.run_attrs['TIME UNITS'], convert_tunit=convert_tunit)
def update_data(self, data, slcs):
self._data, self._slcs = data, slcs
self._xlabel, self._ylabel = osh5vis.axis_format(data.axes[1].long_name, data.axes[1].units), \
osh5vis.axis_format(data.axes[0].long_name, data.axes[0].units)
self.__update_title()
self.__update_xlabel({'new': True})
self.__update_ylabel({'new': True})
def reset_plot_area(self):
self.x_min_wgt.min, self.x_max_wgt.max, xstep, \
self.y_min_wgt.min, self.y_max_wgt.max, ystep = self.__get_xy_minmax_delta()
self.x_min_wgt.value, self.x_max_wgt.value, self.y_min_wgt.value, self.y_max_wgt.value = \
self.x_min_wgt.min, self.x_max_wgt.max, self.y_min_wgt.min, self.y_max_wgt.max
self.x_step_wgt.value, self.y_step_wgt.value = xstep / 2, ystep / 2
self.__destroy_all_xlineout()
self.__destroy_all_ylineout()
self._ct_destroy_all()
def redraw(self, data=None, update_vminmax=False, newfile=False):
# set new extent if necessary
if newfile:
no_need_to_update = np.allclose((self._data.axes[0].min, self._data.axes[0].max, self._data.axes[1].min, self._data.axes[1].max),
(data.axes[0].min, data.axes[0].max, data.axes[1].min, data.axes[1].max))
no_need_to_update = False
if data is not None:
self._data = data
if self.pltfunc is osh5vis.osimshow:
"if the size of the data is the same we can just redraw part of figure"
processed_data = self.__pp(self._data[self._slcs]).view(np.ndarray)
self.im.set_data(processed_data)
if newfile and (not no_need_to_update):
xvmm, yvmm = (None, None) if self.if_xrange_auto.value else self.ax.get_xbound(), (None, None) if self.if_yrange_auto.value else self.ax.get_ybound()
xmm, _, ymm, _ = osh5vis.get_extent_and_unit(data[self._slcs], convert_xaxis=self.if_x_phys_unit.value, convert_yaxis=self.if_y_phys_unit.value)
Generic2DPlotCtrl.update_axis_units('xy', self, (xmm[0], xmm[1], ymm[0], ymm[1]), xconv=self.xconv, yconv=self.yconv)
self.ax.set_xbound(xmm)
self.ax.set_ybound(ymm)
self.fig.canvas.toolbar.update()
self.fig.canvas.toolbar.push_current()
# zoom-in, back to previous view
self.ax.set_xbound(xvmm)
self.ax.set_ybound(yvmm)
if update_vminmax:
self.__handle_lognorm()
vmin, vmax = self.__get_vminmax(from_widgets=True)
# vmin = np.min(processed_data) if self.if_vmin_auto.value else None
# vmax = np.max(processed_data) if self.if_vmax_auto.value else None
# if vmin is not None:
# self.current_vmin = vmin
# if vmax is not None:
# self.vmax_wgt.value = vmax
self.im.set_clim(vmin, vmax)
self.fig.canvas.draw_idle()
else:
"for contour/contourf we have to do a full replot"
self._replot_contour()
def _replot_contour(self):
for col in self.im.collections:
col.remove()
self.replot_axes()
def update_title(self, *_):
self.ax.axes.set_title(self.get_plot_title())
def update_xlabel(self, change):
self.ax.axes.xaxis.set_label_text(change['new'])
def update_ylabel(self, change):
self.ax.axes.yaxis.set_label_text(change['new'])
def update_cbar(self, change):
self.im.colorbar.set_label(change['new'])
def update_cmap(self, _change):
cmap = self.cmap_selector.value if not self.cmap_reverse.value else self.cmap_selector.value + '_r'
self.im.set_cmap(cmap)
self.cb.set_cmap(cmap)
# def update_time_label(self):
# self._time = osh5vis.time_format(self._data.run_attrs['TIME'][0], self._data.run_attrs['TIME UNITS'])
def adjust_figure(self, *_):
with self.out_main:
self.out_main.clear_output(wait=True)
# this dosen't work in all scenarios. it could be a bug in matplotlib/jupyterlab
self.fig.set_size_inches(self.figwidth.value, self.figheight.value)
def register_callbacks(self, others):
keys = self.callbacks.keys()
for k in others.keys():
if k in keys:
self.callbacks[k] += others[k]
else:
self.callbacks[k] = others[k]
def replot_axes(self):
# self.fig.delaxes(self.ax)
# # self.fig.clear()
# self.ax = self.fig.add_subplot(111)
self.ax.cla()
# self.im.remove()
self.im, cb = self.plot_data(colorbar=self.colorbar.value)
if self.colorbar.value:
self.cb.remove()
self.cb = cb
# self.fig.subplots_adjust() # does not compatible with constrained_layout in Matplotlib 3.0
def __get_xy_minmax_delta(self):
# return (float('%.2g' % self._data.axes[1].min), float('%.2g' % self._data.axes[1].ax.max()), float('%.2g' % self._data.axes[1].increment),
# float('%.2g' % self._data.axes[0].min), float('%.2g' % self._data.axes[0].ax.max()), float('%.2g' % self._data.axes[0].increment))
return (self._data.axes[1].min, self._data.axes[1].ax.max(), self._data.axes[1].increment,
self._data.axes[0].min, self._data.axes[0].ax.max(), self._data.axes[0].increment)
def _update_xy_minmaxstep_wgt(self, d):
xmin, xmax, xstep, ymin, ymax, ystep = self.__get_xy_minmax_delta()
if 'x' in d:
self.x_min_wgt.min, self.x_max_wgt.max, self.x_step_wgt.value = xmin * self.xconv, xmax * self.xconv, xstep * self.xconv * 0.5
self.x_min_wgt.value, self.x_max_wgt.value = self.x_min_wgt.min, self.x_max_wgt.max
if 'y' in d:
self.y_min_wgt.min, self.y_max_wgt.max, self.y_step_wgt.value = ymin * self.yconv, ymax * self.yconv, ystep * self.yconv * 0.5
self.y_min_wgt.value, self.y_max_wgt.value = self.y_min_wgt.min, self.y_max_wgt.max
def reset_xrange_step(self, change):
if change['new']:
self._update_xy_minmaxstep_wgt('x')
def reset_yrange_step(self, change):
if change['new']:
self._update_xy_minmaxstep_wgt('y')
def update_plot_area(self, *_):
bnd = [(self.y_min_wgt.value / self.yconv, self.y_max_wgt.value / self.yconv, self.y_step_wgt.value / self.yconv),
(self.x_min_wgt.value / self.xconv, self.x_max_wgt.value / self.xconv, self.x_step_wgt.value / self.xconv)]
self._slcs = tuple(slice(*self._data.get_index_slice(self._data.axes[i], bd)) for i, bd in enumerate(bnd))
#TODO: maybe we can keep some of the overlaid plots but replot_axes will generate new axes.
# for now delete everything for simplicity
self.__destroy_all_xlineout()
self.__destroy_all_ylineout()
# self._ct_destroy_all()
self.replot_axes()
self.update_contours()
def refresh_tab_wgt(self, update_list):
"""
the tab.children is a tuple so we have to reconstruct the whole tab widget when
addition/deletion of children widgets happens
"""
tmp = self.tab.children
newtab = [tmp[i] if not t else t for i, t in enumerate(update_list)]
self.tab.children = tuple(newtab)
def current_norm(self, vminmax_from_widget=False):
return self.norm_selector.value[0](**self.__get_norm(vminmax_from_widget=vminmax_from_widget))
def plot_data(self, vminmax_from_widget=False, **passthrough):
ifcolorbar = passthrough.pop('colorbar', self.colorbar.value)
return self.pltfunc(self.__pp(self._data[self._slcs]), cmap=self.cmap_selector.value,
norm=self.current_norm(vminmax_from_widget), title=self.get_plot_title(),
xlabel=self.xlabel.value, ylabel=self.ylabel.value, cblabel=self.cbar.value,
ax=self.ax, fig=self.fig, colorbar=ifcolorbar,
convert_xaxis=self.if_x_phys_unit.value, convert_yaxis=self.if_y_phys_unit.value, **passthrough)
def self_destruct(self, *_):
plt.close(self.fig)
for w in self.widgets_list:
w.close()
self.onDestruction()
def get_plot_title(self):
if self.datalabel.value:
return self.datalabel.value + ((', ' + self.get_time_label(self.time_in_phys.value)) if self.if_show_time.value else '')
else:
return self.get_time_label(self.time_in_phys.value) if self.if_show_time.value else ''
def get_tab_data(self):
return widgets.HBox([widgets.VBox([self.norm_selector, self.norm_selector.value[1]]), self.norm_btn_wgt,
widgets.VBox([widgets.HBox([self.datalabel, self.if_reset_title]),
widgets.HBox([self.if_show_time, self.time_in_phys])])])
def get_tab_save(self):
return widgets.VBox([widgets.HBox([self.figname, self.dpi, self.saveas], layout=_items_layout),
self.dlink], layout=_items_layout)
def extract_lineout_params(self, s):
l = s.split()
# we put all params in the tooltip of the delete button
if "~" in l: # this is analysis
return int(l[2]), int(l[4]), l[5], l[6]
else:
return (float(l[1]), )
def update_lineouts(self, dim='xy', description_only=False, xconv=None, yconv=None):
# update x lineouts/analysis
if 'x' in dim:
vminl, vmaxl = [], []
xaxis = self._data[self._slcs].axes[1].ax
for wgt in self.xlineout_list_wgt.children:
cpk, nw = wgt.children
params = self.extract_lineout_params(nw.tooltip)
if len(params) > 1:
data, posstr, _ = self._get_xana_data_descr(*params, description_only=description_only)
else:
data, posstr, _ = self.get_xlineout_data_and_index(params[0])
cpk.description = posstr
if description_only:
continue
self._xlineouts[cpk].set_ydata(data)
vminl.append(np.min(data)[0])
vmaxl.append(np.max(data)[0])
if xconv is not None:
self._xlineouts[cpk].set_xdata(xconv * xaxis)
if (not description_only) and len(self.xlineout_list_wgt.children) != 0:
vmin, vmax = self.__get_vminmax()
vmin, vmax = vmin if vmin else np.min(vminl), vmax if vmax else np.max(vmaxl)
padding = 0.05 * (vmax - vmin)
args = {'bottom': vmin - padding, 'top': vmax + padding}
self.axx.set_ylim(**args)
# update y lineouts/analysis
if 'y' in dim:
vminl, vmaxl = [], []
yaxis = self._data[self._slcs].axes[0].ax
for wgt in self.ylineout_list_wgt.children:
cpk, nw = wgt.children
params = self.extract_lineout_params(nw.tooltip)
if len(params) > 1:
data, posstr, _ = self._get_yana_data_descr(*params, description_only=description_only)
else:
data, posstr, _ = self.get_ylineout_data_and_index(params[0])
cpk.description = posstr
if description_only:
continue
self._ylineouts[cpk].set_xdata(data)
vminl.append(np.min(data)[0])
vmaxl.append(np.max(data)[0])
if yconv is not None:
self._ylineouts[cpk].set_ydata(yconv * yaxis)
if (not description_only) and len(self.ylineout_list_wgt.children) != 0:
vmin, vmax = self.__get_vminmax()
vmin, vmax = vmin if vmin else np.min(vminl), vmax if vmax else np.max(vmaxl)
padding = 0.05 * (vmax - vmin)
args = {'left': vmin - padding, 'right': vmax + padding}
self.axy.set_xlim(**args)
def update_contours(self):
for wgt in self.ct_wgt_list.children:
_, _, db = wgt.children
w, kwargs, im = self.ct_plot_dict[db]
# reconstruct the contour
self.im2.remove(im)
# free up resources
for c in im[0].collections:
c.remove()
for l in im[1]:
l.remove()
# _ct_plot will append im2 with the new plot
tmp = kwargs.copy()
self._ct_plot(None, None, None, tmp)
self.ct_plot_dict[db][-1] = self.im2[-1]
def _on_clabel_toggle(self, change):
self.ct_if_inline_clabel.disabled = not change['new']
@staticmethod
def update_axis_units(dim, thisclass, ext, xconv=None, yconv=None, xunit=None, yunit=None, xconv_now=None, yconv_now=None):
if xconv_now is not None:
thisclass.xconv = xconv_now
if yconv_now is not None:
thisclass.yconv = yconv_now
thisclass.im.set_extent(ext)
#TODO: contour/contourf do not have set_extent?? Have to reconstruct from scratch
thisclass.update_contours()
thisclass._update_xy_minmaxstep_wgt(d=dim)
thisclass.update_lineouts(dim=dim, xconv=xconv, yconv=yconv)
if 'x' in dim:
if thisclass.if_reset_xlabel.value and xunit is not None:
thisclass._xlabel = osh5vis.axis_format(thisclass._data.axes[1].long_name, xunit)
# toggle the reset checkbox
thisclass.if_reset_xlabel.value = False
thisclass.if_reset_xlabel.value = True
if 'y' in dim:
if thisclass.if_reset_ylabel.value and yunit is not None:
thisclass._ylabel = osh5vis.axis_format(thisclass._data.axes[0].long_name, yunit)
# toggle the reset checkbox
thisclass.if_reset_ylabel.value = False
thisclass.if_reset_ylabel.value = True
def get_extent_and_unit(self):
return osh5vis.get_extent_and_unit(self._data[self._slcs], convert_xaxis=self.if_x_phys_unit.value, convert_yaxis=self.if_y_phys_unit.value)
def _update_xconverter(self, change):
#TODO: In general handling share axes this way is combersome. Maybe we should shift all controls to MultiPanelCtrl.
if change['new']:
xconv, xunit = self._data.axes[1].punit_convert_factor()
else:
xconv, xunit = 1.0, self._data.axes[1].units
if xconv == self.xconv:
return
else:
self.xconv, xconv = xconv, self.xconv
xconv = 1./xconv if self.xconv == 1.0 else self.xconv
xmm, _, ymm, _ = self.get_extent_and_unit()
xvmm, yvmm = self.ax.get_xbound(), self.ax.get_ybound()
# set new extent, zoom out to full scale, update it as the "home view"
#TODO: there might be finer control over the view if we dig deeper into matplotlib interactive backend
# but I don't know how stable those APIs are.
Generic2DPlotCtrl.update_axis_units('x', self, (xmm[0], xmm[1], ymm[0], ymm[1]), xconv=self.xconv, xunit=xunit)
sharedx, sharedy, not_shared = self.callbacks.get('sharedx', tuple()), self.callbacks.get('sharedy', tuple()), []
for i, w in enumerate(sharedx):
_, _, oymm, _ = w.get_extent_and_unit()
if w not in sharedy:
not_shared.append((i, w.ax.get_ybound()))
w.ax.set_ybound(oymm)
Generic2DPlotCtrl.update_axis_units('x', w, (xmm[0], xmm[1], oymm[0], oymm[1]), xconv=self.xconv, xunit=xunit, xconv_now=self.xconv)
w.if_x_phys_unit.unobserve(w._update_xconverter, 'value')
w.if_x_phys_unit.value = change['new']
w.if_x_phys_unit.observe(w._update_xconverter, 'value')
self.ax.set_xbound(xmm)
self.ax.set_ybound(ymm)
self.fig.canvas.toolbar.update()
self.fig.canvas.toolbar.push_current()
# zoom-in, back to previous view
self.ax.set_xbound((xvmm[0] * xconv, xvmm[1] * xconv))
self.ax.set_ybound(yvmm)
for i, v in not_shared:
sharedx[i].ax.set_ybound(v)
def _update_yconverter(self, change):
if change['new']:
yconv, yunit = self._data.axes[0].punit_convert_factor()
else:
yconv, yunit = 1.0, self._data.axes[0].units
if yconv == self.yconv:
return
else:
self.yconv, yconv = yconv, self.yconv
yconv = 1./yconv if self.yconv == 1.0 else self.yconv
data = self._data[self._slcs]
xmm, _, ymm, _ = self.get_extent_and_unit()
xvmm, yvmm = self.ax.get_xbound(), self.ax.get_ybound()
Generic2DPlotCtrl.update_axis_units('y', self, (xmm[0], xmm[1], ymm[0], ymm[1]), yconv=self.yconv, yunit=yunit)
sharedx, sharedy, not_shared = self.callbacks.get('sharedx', tuple()), self.callbacks.get('sharedy', tuple()), []
for i, w in enumerate(sharedy):
oxmm, _, _, _ = w.get_extent_and_unit()
if w not in sharedx:
not_shared.append((i, w.ax.get_xbound()))
w.ax.set_xbound(oxvmm)
Generic2DPlotCtrl.update_axis_units('y', w, (oxmm[0], oxmm[1], ymm[0], ymm[1]), yconv=self.yconv, yunit=yunit, yconv_now=self.yconv)
w.if_y_phys_unit.unobserve(w._update_yconverter, 'value')
w.if_y_phys_unit.value = change['new']
w.if_y_phys_unit.observe(w._update_yconverter, 'value')
self.ax.set_xbound(xmm)
self.ax.set_ybound(ymm)
self.fig.canvas.toolbar.update()
self.fig.canvas.toolbar.push_current()
# zoom-in, back to previous view
self.ax.set_ybound((yvmm[0] * yconv, yvmm[1] * yconv))
self.ax.set_xbound(xvmm)
for i, v in not_shared:
sharedy[i].ax.set_xbound(v)
def _on_ct_auto_color_wgt_change(self, change):
if change['new'] == 'colormap':
self.ct_cmap_selector.disabled, self.ct_colorpicker.disabled = False, True
else:
self.ct_cmap_selector.disabled, self.ct_colorpicker.disabled = True, False
def _on_ct_method_change(self, change):
# linestyle keyword only applies to contour
self.ct_linestyle.disabled = change['new'] != 'contour'
def _on_ct_num_lvl_opts_wgt_change(self, change):
self.ct_num_levels.disabled = False if change['new'] == 'fixed:' else True
self.ct_level.disabled = True if change['new'] != 'option' else False
def _get_contour_opt_wgt(self, lvl, color, txt_wgt_width='initial', cp_wgt_width='initial'):
return (widgets.FloatText(value=lvl, description='level=', disabled=(self.ct_num_levels_opts.value != 'option'),
style={'description_width': 'initial'}, layout={'width': txt_wgt_width}),
widgets.ColorPicker(concise=False, description='; color:', value=color, disabled=(self.ct_auto_color.value == 'colormap'),
style={'description_width': 'initial'}, layout={'width': cp_wgt_width}), _get_delete_btn('level %f' % lvl))
def _remove_ct_lvl_opt(self, btn):
lvl_wgt = self.ct_opts_dict.pop(btn)
# remove level widgets from ct_opts_list
tmp = list(self.ct_opts_list.children)
tmp.remove(lvl_wgt)
self.ct_opts_list.children = tuple(tmp)
lvl_wgt.close()
def _print_ct_info(self, msg, timeout=8):
with self.ct_info_output:
print(msg)
time.sleep(timeout)
self.ct_info_output.clear_output()
def _extract_ct_kwargs_from_wgt(self):
levels, colors = [], []
for w in self.ct_opts_list.children:
lvl, cp, db = w.children
levels.append(lvl.value)
colors.append(cp.value)
lvl.close()
cp.close()
db.close()
w.close()
kwargs = {'antialiased': self.ct_antialiased.value}
if self.ct_auto_color.value == 'colormap':
kwargs['colors'] = None
kwargs['cmap'] = self.ct_cmap_selector.value + ('_r' if self.ct_cmap_reverse.value else '')
kwargs['norm'] = self.norm_selector.value[0](**self.__get_norm())
elif self.ct_auto_color.value == 'manual':
kwargs['colors'] = colors or None
else:
kwargs['colors'] = None if not colors else (colors[-1], ) * len(colors)
if not self.ct_linestyle.disabled:
kwargs['linestyles'] = self.ct_linestyle.value
if self.ct_num_levels_opts.value == 'fixed:':
kwargs['levels'] = self.ct_num_levels.value
elif self.ct_num_levels_opts.value == 'option':
if levels:
if len(levels) > len(set(levels)):
if self.ct_auto_color.value == 'manual':
self._print_ct_info('Found duplicated levels, last appearance takes precedence')
tmp = dict(zip(levels, kwargs['colors'])) # use dict to get rid of duplicates
levels, kwargs['colors'] = list(tmp.keys()), list(tmp.values())
else:
levels = list(set(levels)) # use dict to get rid of duplicates
kwargs['levels'] = sorted(levels)
if kwargs['colors'] is not None:
ii = sorted(range(len(levels)), key=lambda k: levels[k])
c = kwargs['colors']
kwargs['colors'] = list(c[i] for i in ii)
else:
self._print_ct_info('number of levels = option: but no option is added, fall back to auto')
if self.ct_auto_color.value == 'colormap' and self.ct_num_levels_opts.value == 'auto' and self.ct_opts_list.children:
self._print_ct_info('Level options have no effect.', 2)
return kwargs
def _ct_plot(self, pltfunc, if_clabel, if_inline_clabel, kwargs):
vext = self.im.get_extent()
if kwargs: # this is called to replot for new data, kwargs contain all necessary info to generate the contour, kwargs will be altered
pltfunc = kwargs.pop('method', 'contour')
if_clabel = kwargs.pop('if_clabel', self.ct_if_clabel.value)
if_inline_clabel = kwargs.pop('inline', self.ct_if_inline_clabel) and if_clabel
else: # this is called when user press the plot button, kwargs will return keywords for the contour plot
kwargs.update(self._extract_ct_kwargs_from_wgt())
if pltfunc == 'contour':
im2, _ = osh5vis.oscontour(self.__pp(self._data[self._slcs]), ax=self.ax, fig=self.fig, colorbar=False,