-
Notifications
You must be signed in to change notification settings - Fork 93
/
wxncview.py
1032 lines (821 loc) · 34 KB
/
wxncview.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
from __future__ import print_function, division, unicode_literals, absolute_import
import os
import collections
import wx
import netCDF4
import numpy as np
import abipy.gui.awx as awx
import wx.lib.mixins.listctrl as listmix
import wx.lib.agw.flatnotebook as fnb
import wx.lib.dialogs as wxdg
import wx.lib.newevent
from monty.string import list_strings
#def ndcontract_var(var):
# """
# Remove fake dimensions from a Netcdf Variable.
#
# Returns:
# data:
# ndarray
# dimensions:
# list with the name of the dimensions in data.
# """
# shape, dimensions = [], []
# for num, name in zip(var.shape, var.dimensions):
# if num > 1:
# shape.append(num)
# dimensions.append(name)
#
# # Reshape array.
# data = np.reshape(var[:], shape)
#
# return data, dimensions
class AttrDict(dict):
"""
Allows to access dict keys as obj.foo in addition to the traditional way
obj['foo']"
"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
def copy(self):
newd = super(AttrDict, self).copy()
return self.__class__(**newd)
class SimpleTextViewer(awx.Frame):
"""Very simple frame that displays text (string) in read-only mode."""
def __init__(self, parent, text, **kwargs):
super(SimpleTextViewer, self).__init__(parent, **kwargs)
wx.TextCtrl(self, -1, text, style=wx.TE_MULTILINE|wx.TE_LEFT|wx.TE_READONLY)
# Command event used to signal that the value of the selected variable/dimension
# should be plotted as function of the file index.
CompareEvent, EVT_COMPARE = wx.lib.newevent.NewCommandEvent()
def getSelected(wxlist):
"""Gets the selected items from a list object."""
selected = []
item = -1
while True:
item = wxlist.GetNextItem(item, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
if item == -1: break
selected.append(item)
return selected
def getColumnText(wxlist, index, col):
"""Gets the text from the specified column entry in a list."""
item = wxlist.GetItem(index, col)
return item.GetText()
class NcViewerFrame(wx.Frame):
"""
This frame allows the user to inspect the dimensions
and the variables reported in a netcdf file.
"""
def __init__(self, parent, filepaths=(), **kwargs):
"""
Args:
parent:
parent window.
filepaths:
String or list of strings with the path of the nc files to open
Empty tuple if no file should be opened during the initialization of the frame.
"""
if "size" not in kwargs:
kwargs["size"] = (1200, 800)
super(NcViewerFrame, self).__init__(parent, id=-1, **kwargs)
# This combination of options for config seems to work on my Mac.
self.config = wx.FileConfig(appName=self.codename, localFilename=self.codename + ".ini",
style=wx.CONFIG_USE_LOCAL_FILE)
# Build menu, toolbar and status bar.
self.makeMenu()
self.makeToolBar()
self.statusbar = self.CreateStatusBar()
# Open netcdf files.
filepaths, datasets = list_strings(filepaths), []
filepaths = map(os.path.abspath, filepaths)
for path in filepaths:
datasets.append(netCDF4.Dataset(path, mode="r"))
self.AddFileToHistory(path)
# Create the notebook (each file will have its own tab).
panel = wx.Panel(self, -1)
try:
self.notebook = fnb.FlatNotebook(panel, -1, style=fnb.FNB_NAV_BUTTONS_WHEN_NEEDED)
except AttributeError:
self.notebook = fnb.FlatNotebook(panel, -1)
for path, dataset in zip(filepaths, datasets):
tab = NcFileTab(self.notebook, dataset)
self.notebook.AddPage(tab, os.path.basename(path))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.notebook, 1, wx.EXPAND, 5)
panel.SetSizerAndFit(sizer)
self.Bind(wx.EVT_CLOSE, self.OnExit)
# Intercept the command event associated to variable/dimension comparison.
self.Bind(EVT_COMPARE, self.OnCompare)
@property
def codename(self):
"""Name of the application."""
return "wxncview"
@property
def num_tabs(self):
"""Number of tabs in the notebook."""
return self.notebook.GetPageCount()
@property
def datasets(self):
"""List of Netcdf4 `Dataset`"""
datasets = []
for page in range(self.notebook.GetPageCount()):
tab = self.notebook.GetPage(page)
datasets.append(tab.dataset)
return datasets
def makeMenu(self):
"""Creates the main menu."""
self.menu_bar = wx.MenuBar()
self.menu_bar.Append(self.createFileMenu(), "&File")
self.menu_bar.Append(self.createPlotMenu(), "&Plot")
self.menu_bar.Append(self.createHelpMenu(), "&Help")
self.SetMenuBar(self.menu_bar)
def createFileMenu(self):
"""Creates the file menu."""
file_menu = wx.Menu()
# File Menu ID's
self.idOPEN = wx.NewId()
self.idCLOSE = wx.NewId()
self.idEXIT = wx.NewId()
file_menu.Append(self.idOPEN, "&Open", "Open netcdf file")
file_menu.Append(self.idCLOSE, "&Close", "Close netcdf file")
file_history = self.file_history = wx.FileHistory(8)
file_history.Load(self.config)
recent = wx.Menu()
file_history.UseMenu(recent)
file_history.AddFilesToMenu()
file_menu.AppendMenu(-1, "&Recent Files", recent)
self.Bind(wx.EVT_MENU_RANGE, self.OnFileHistory, id=wx.ID_FILE1, id2=wx.ID_FILE9)
file_menu.AppendSeparator()
file_menu.Append(self.idEXIT, "E&xit", "Exit wxnciew")
self.Bind(wx.EVT_MENU, self.OnOpen, id=self.idOPEN)
self.Bind(wx.EVT_MENU, self.OnClose, id=self.idCLOSE)
self.Bind(wx.EVT_MENU, self.OnExit, id=self.idEXIT)
return file_menu
def createPlotMenu(self):
"""Creates the plot menu."""
# Plot Menu ID's
plot_menu = wx.Menu()
# Options for 2D-plots
self.twod_menu = twod_menu = wx.Menu()
for plot_mode in ["line", "scatter"]:
_id = wx.NewId()
twod_menu.AppendRadioItem(_id, plot_mode)
plot_menu.AppendMenu(-1, '2-D plots', twod_menu)
# Options for image plots
self.image_menu = image_menu = wx.Menu()
for image_mode in ["intensity", "contour", "rgb"]:
_id = wx.NewId()
image_menu.AppendRadioItem(_id, image_mode)
plot_menu.AppendMenu(-1, 'Image mode', image_menu)
# Options for complex data.
self.cplx_menu = cplx_menu = wx.Menu()
for cplx_mode in ["None", "Abs", "Real", "Imag"]:
_id = wx.NewId()
cplx_menu.AppendRadioItem(_id, cplx_mode)
plot_menu.AppendMenu(-1, 'Complex', cplx_menu)
return plot_menu
def createHelpMenu(self):
"""Create the help menu."""
# Help Menu ID's
self.idABOUT = wx.NewId()
help_menu = wx.Menu()
help_menu.Append(self.idABOUT, "&About", "About wxncview")
self.Bind(wx.EVT_MENU, self.OnAbout, id=self.idABOUT)
return help_menu
def makeToolBar(self):
"""Creates the toolbar."""
self.toolbar = self.CreateToolBar()
self.toolbar.SetToolBitmapSize(wx.Size(32, 32))
#bitmap = icons.connect.getBitmap()
#self.toolbar.AddSimpleTool(self.idTOOL_CONNECT, bitmap, shortHelpString=_("Normal Connect"))
#bitmap = icons.quick_connect.getBitmap()
#self.dir_entry_box = wx.ComboBox(self.toolbar, self.idTOOL_ENTRYBOX,
# size=wx.Size(350, -1), style=wx.CB_DROPDOWN)
#self.binary_button = wx.RadioButton(self.toolbar, self.idTOOL_BINARY, _("BINARY"))
#self.ascii_button = wx.RadioButton(self.toolbar, self.idTOOL_ASCII, _("ASCII"))
#config = utils.getApplicationConfiguration()
#if config['transfer_type'] == protocol.ProtocolInterface.BINARY:
# self.binary_button.SetValue(True)
#else:
# self.ascii_button.SetValue(True)
#utils.addHorizontalSpaceTool(self.toolbar, 75)
#self.toolbar.AddControl(self.dir_entry_box)
#utils.addHorizontalSpaceTool(self.toolbar, 5)
#self.toolbar.AddControl(self.binary_button)
#utils.addHorizontalSpaceTool(self.toolbar, 5)
#self.toolbar.AddControl(self.ascii_button)
#self.Bind(wx.EVT_TOOL, self.onConnect, id=self.idTOOL_CONNECT)
#self.Bind(wx.EVT_COMBOBOX, self.onComboSelect, id=self.idTOOL_ENTRYBOX)
self.toolbar.Realize()
def AddFileToHistory(self, filepath):
"""Add the absolute filepath to the file history."""
self.file_history.AddFileToHistory(filepath)
self.file_history.Save(self.config)
self.config.Flush()
def GetPlotOptions(self):
"""Returns a dictionary with the options specified in the PlotMenu"""
d = AttrDict()
for radio in self.twod_menu.GetMenuItems():
if radio.IsChecked(): d["plot_mode"] = radio.GetItemLabel()
for radio in self.image_menu.GetMenuItems():
if radio.IsChecked(): d["image_mode"] = radio.GetItemLabel()
for radio in self.cplx_menu.GetMenuItems():
if radio.IsChecked(): d["cplx_mode"] = radio.GetItemLabel()
return d
def OnAbout(self, event):
"""Displays the about window box."""
# TODO
#about = aboutwin.AboutWindow(self)
#ret = about.ShowModal()
#awx.makeAboutBox(codename=self.codename, version=self.VERSION,
# description="", developers="M. Giantomassi")
def read_file(self, filepath):
"""Open a netcdf file, create new tab and save the file in the history."""
try:
notebook = self.notebook
dataset = netCDF4.Dataset(filepath, mode="r")
tab = NcFileTab(notebook, dataset)
notebook.AddPage(tab, os.path.basename(filepath))
# don't know why but this does not work!
notebook.Refresh()
notebook.SetSelection(notebook.GetPageCount())
self.AddFileToHistory(filepath)
except:
raise
def OnOpen(self, event):
"""Open FileDialog to allow the user to select a netcdf file."""
dialog = wx.FileDialog(self, wildcard="*.nc")
if dialog.ShowModal() == wx.ID_CANCEL: return
filepath = os.path.abspath(dialog.GetPath())
self.read_file(filepath)
def OnClose(self, event):
"""
Remove the active tab from the notebook and
close the corresponding netcdf file,
"""
notebook = self.notebook
if notebook.GetPageCount() == 0: return
idx = notebook.GetSelection()
if idx == -1: return None
# Close the file
tab = notebook.GetPage(idx)
tab.dataset.close()
# Remove tab.
notebook.DeletePage(idx)
notebook.Refresh()
def OnExit(self, event):
"""Close the netcdf files and exit the application."""
try:
for index in range(self.notebook.GetPageCount()):
tab = self.notebook.GetPage(index)
try:
tab.dataset.close()
except:
pass
finally:
self.Destroy()
def OnFileHistory(self, event):
"""Open one of the file listed in the file_history."""
fileNum = event.GetId() - wx.ID_FILE1
filepath = self.file_history.GetHistoryFile(fileNum)
self.read_file(filepath)
def OnCompare(self, event):
"""
Callback triggered by the `compare` option in the popup menu of the panels
Plote the netcdf variable/dimension as function of the file index.
"""
# Get the name of the variable.
name, obj = event.name, event.obj
# Define the function to use the get the value of the dimension/variable.
if isinstance(obj, netCDF4.Variable):
def extract(dataset, name):
return dataset.variables[name][:]
elif isinstance(obj, netCDF4.Dimension):
def extract(dataset, name):
return np.array(len(dataset.dimensions[name]))
else:
raise ValueError("Don't know how to handle %s" % repr(obj))
# Extract data. Make sure all the shapes are equal.
data, shape = [], None
for dataset in self.datasets:
v = extract(dataset, name)
data.append(v)
if shape is None:
shape = v.shape
else:
assert shape == v.shape
# Plot data. Two Branches for scalars and arrays.
opts = self.GetPlotOptions()
is_scalar = not shape or (len(shape) == 1 and shape[0] == 1)
#print(shape)
from wxmplot import PlotFrame
if is_scalar:
frame = PlotFrame(parent=self)
xx = range(len(self.datasets))
if opts.plot_mode == "line":
frame.plot(xx, data)
else:
frame.scatterplot(xx, data)
frame.set_xlabel("File index")
frame.set_ylabel(name)
frame.Show()
else:
# Open new frame to allow the user to specify how to handle the array.
ArrayComparisonFrame(self, name, data).Show()
class NcFileTab(wx.Panel):
"""Tab showing information on the netcdf file."""
def __init__(self, parent, dataset, **kwargs):
"""
Args:
parent:
parent window.
dataset:
Netcdf4 `Dataset`.
"""
super(NcFileTab, self).__init__(parent, -1, **kwargs)
self.dataset = dataset
splitter = wx.SplitterWindow(self, -1, style=wx.SP_3DSASH)
self.dims_panel = DimsPanel(splitter, dataset)
self.vars_panel = VarsPanel(splitter, dataset)
splitter.SplitVertically(self.dims_panel, self.vars_panel)
splitter.SetSashGravity(0.1)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(splitter, 1, wx.EXPAND, 5)
self.SetSizerAndFit(sizer)
class BasePanel(wx.Panel, listmix.ColumnSorterMixin):
"""Mixin class providing helper functions."""
@property
def viewer_frame(self):
try:
return self._viewer_frame
except AttributeError:
self._viewer_frame = self.getParentWithType(NcViewerFrame)
return self._viewer_frame
def makePopupMenu(self):
"""
Creates a popup menu containing the list of supported actions for local file objects.
"""
# Popup IDs
self.idPOPUP_GETINFO = wx.NewId()
self.idPOPUP_COMPARE = wx.NewId()
menu = wx.Menu()
menu.Append(self.idPOPUP_GETINFO, "Get Info")
self.Bind(wx.EVT_MENU, self.OnGetInfo, id=self.idPOPUP_GETINFO)
if self.viewer_frame.num_tabs > 1:
menu.Append(self.idPOPUP_COMPARE, "Compare")
self.Bind(wx.EVT_MENU, self.OnCompare, id=self.idPOPUP_COMPARE)
return menu
def OnRightClick(self, event):
"""Creates a popup menu at the location of the right click."""
menu = self.makePopupMenu()
self.PopupMenu(menu, event.GetPosition())
def OnColClick(self, event):
event.Skip()
def GetListCtrl(self):
"""Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py"""
return self.list
def GetPlotOptions(self):
"""
Dictionary with the options for the plots taken from
the MenuBar of the parent `NcViewerFrame`
"""
frame = self.ncview_frame
return frame.GetPlotOptions()
@property
def ncview_frame(self):
"""The parent frame `NcViewFrame`."""
try:
return self._ncview_frame
except AttributeError:
parent = self.GetParent()
while True:
if parent is None:
raise RuntimeError("Cannot find NcViewerFrame, got None parent!")
if isinstance(parent, NcViewerFrame):
break
else:
parent = parent.GetParent()
self._ncview_frame = parent
return self._ncview_frame
def getParentWithType(self, cls):
"""
Returns the first parent window of type cls.
Raises:
RuntimeError if we have reached the head of the linked list.
"""
parent = self.GetParent()
while True:
if parent is None:
raise RuntimeError("Cannot find parent with class %s, reached None parent!" % cls)
if isinstance(parent, cls):
return parent
else:
parent = parent.GetParent()
class DimsPanel(BasePanel):
"""Panel with the netcdf dimensions."""
def __init__(self, parent, dataset, **kwargs):
"""
Args:
parent:
Parent window.
dataset:
Netcdf4 `Dataset`.
"""
super(DimsPanel, self).__init__(parent, -1, **kwargs)
self.dataset = dataset
text = wx.StaticText(self, -1, "Number of dimensions: %d" % len(dataset.dimensions))
columns = ["name", "value"]
self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
for col, name in enumerate(columns):
self.list.InsertColumn(col, name)
# Used to store the Max width in pixels for the data in the column.
column_widths = [awx.get_width_height(self, s)[0] for s in columns]
self.id2entry = {}
for idx, (name, dim) in enumerate(dataset.dimensions.items()):
entry = map(str, [name, len(dim)])
self.list.Append(entry)
self.list.SetItemData(idx, idx)
self.id2entry[idx] = entry
w = [awx.get_width_height(self, s)[0] for s in entry]
column_widths = map(max, zip(w, column_widths))
for index, col in enumerate(columns):
self.list.SetColumnWidth(index, column_widths[index])
# Now that the list exists we can init the other base class, see wx/lib/mixins/listctrl.py
self.itemDataMap = self.id2entry
listmix.ColumnSorterMixin.__init__(self, len(columns))
self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(text, 0, wx.EXPAND, 5)
sizer.Add(self.list, 1, wx.EXPAND, 5)
self.SetSizerAndFit(sizer)
# Connect the events.
self.list.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnRightClick)
self.list.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
def OnItemActivated(self, event):
"""NoP"""
def OnCompare(self, event):
"""Trigger CompareEvent."""
item = getSelected(self.list)[0]
name = getColumnText(self.list, item, 0)
dim = self.dataset.dimensions[name]
# Create and post the event to trigger the refresh of the GUI
event = CompareEvent(id=-1, name=name, obj=dim)
wx.PostEvent(self.viewer_frame, event)
def OnGetInfo(self, event):
"""Show extra information on the selected variables."""
selected = getSelected(self.list)
lines = []
for item in selected:
var_name = getColumnText(self.list, item, 0)
var = self.dataset.dimensions[var_name]
lines.append(str(var))
#lines.append(ncvar_info(var))
wxdg.ScrolledMessageDialog(self, "\n".join(lines), caption="Variable Metadata", style=wx.MAXIMIZE_BOX).Show()
class VarsPanel(BasePanel):
"""
Panel with the netcdf variables.
Provides popup menu to inspect/plot the selected variable.
"""
def __init__(self, parent, dataset, **kwargs):
"""
Args:
parent:
Parent window.
dataset:
Netcdf4 `Dataset`.
"""
super(VarsPanel, self).__init__(parent, -1, **kwargs)
self.dataset = dataset
text = wx.StaticText(self, -1, "Number of variables: %d" % len(dataset.variables))
columns = ["name", "dtype", "shape", "value", "dimensions"]
self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
for col, name in enumerate(columns):
self.list.InsertColumn(col, name)
# Used to store the Max width in pixels for the data in the column.
column_widths = [awx.get_width_height(self, s)[0] for s in columns]
self.id2entry = {}
for idx, (name, var) in enumerate(dataset.variables.items()):
# Show the value of scalars.
if not var.shape:
value = str(var[:]).replace("[", "").replace("]", "").strip()
else:
value = "[...]"
entry = map(str, [name, var.dtype, var.shape, value, var.dimensions])
self.list.Append(entry)
self.list.SetItemData(idx, idx)
self.id2entry[idx] = entry
w = [awx.get_width_height(self, s)[0] for s in entry]
column_widths = map(max, zip(w, column_widths))
for index, col in enumerate(columns):
self.list.SetColumnWidth(index, column_widths[index])
# Now that the list exists we can init the other base class, see wx/lib/mixins/listctrl.py
self.itemDataMap = self.id2entry
listmix.ColumnSorterMixin.__init__(self, len(columns))
self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(text, 0, wx.EXPAND, 5)
sizer.Add(self.list, 1, wx.EXPAND, 5)
self.SetSizerAndFit(sizer)
# Connect the events whose callback will be set by the client code.
self.list.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnRightClick)
self.list.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
def makePopupMenu(self):
"""
Creates a popup menu containing the list of
supported actions for local file objects.
"""
# Menu of the base class
menu = super(VarsPanel, self).makePopupMenu()
self.idPOPUP_VAR_SHOW = wx.NewId()
menu.Append(self.idPOPUP_VAR_SHOW, "Show")
# Extend base class.
#menu.AppendSeparator()
self.idPOPUP_VAR_EXPORT = wx.NewId()
menu.Append(self.idPOPUP_VAR_EXPORT, "Export")
# Extra Popup IDs for arrays
#self.idPOPUP_ARR_SLICE = wx.NewId()
#menu.Append(self.idPOPUP_ARR_SLICE, "Slice array")
#self.Bind(wx.EVT_MENU, self.OnArraySlice, id=self.idPOPUP_ARR_SLICE)
# Associate menu/toolbar items with their handlers.
menu_handlers = [
(self.idPOPUP_VAR_SHOW, self.onVarShow),
(self.idPOPUP_VAR_EXPORT, self.onVarExport),
]
for combo in menu_handlers:
mid, handler = combo[:2]
self.Bind(wx.EVT_MENU, handler, id=mid)
return menu
#def GetNameVarFromEvent(self, event):
# currentItem = event.m_itemIndex
# entry = self.id2entry[self.list.GetItemData(currentItem)]
# name = entry[0]
# return name, self.dataset.variables[name]
def OnGetInfo(self, event):
"""Show extra information on the selected variables."""
selected = getSelected(self.list)
lines = []
for item in selected:
name = getColumnText(self.list, item, 0)
var = self.dataset.variables[name]
lines.append(str(var))
#lines.append(ncvar_info(var))
wxdg.ScrolledMessageDialog(self, "\n".join(lines), caption="Variable Metadata", style=wx.MAXIMIZE_BOX).Show()
def onVarShow(self, event):
item = getSelected(self.list)[0]
name = getColumnText(self.list, item, 0)
var = self.dataset.variables[name]
text = str(var[:])
SimpleTextViewer(self, text=text).Show()
def onVarExport(self, event):
"""Export the selected variable to txt format and save it to file."""
item = getSelected(self.list)[0]
name = getColumnText(self.list, item, 0)
var = self.dataset.variables[name]
dialog = wx.FileDialog(self, message="Save text file", defaultDir="", defaultFile="",
wildcard="", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dialog.ShowModal() == wx.ID_CANCEL: return
# save the current contents in the file
path = dialog.GetPath()
# Save self to a text file. See :func:`np.savetext` for the description of the variables
np.savetxt(path, var[:], fmt='%.18e')
def OnCompare(self, event):
"""Trigger CompareEvent."""
item = getSelected(self.list)[0]
name = getColumnText(self.list, item, 0)
var = self.dataset.variables[name]
# Create and post the event to trigger the comparison.
event = CompareEvent(id=-1, name=name, obj=var)
wx.PostEvent(self.viewer_frame, event)
def OnItemActivated(self, event):
"""Use `wxmplot` to plot the selected variables."""
selected = getSelected(self.list)
for item in selected:
name = getColumnText(self.list, item, 0)
var = self.dataset.variables[name]
self.plot_variable(name, var, self.dataset)
def plot_variable(self, var_name, var, dataset):
"""
Use `wxmplot` to plot the selected variables.
Args:
var_name:
Name of the variable
var:
Netcdf4 `Variable`.
dataset:
Netcdf4 `Dataset`.
"""
# Remove fake dimensions.
shape, dimensions = [], []
for num, name in zip(var.shape, var.dimensions):
if num > 1:
shape.append(num)
dimensions.append(name)
# Get data to plot.
data = np.reshape(var[:], shape)
opts = self.GetPlotOptions()
cplx_mode = opts.cplx_mode
if cplx_mode != "None":
if shape[-1] != 2:
err_msg = "cplx_mode: %s. Expecting 2 as last dimensions but got %d" % (
cplx_mode, shape[-1])
raise ValueError(err_msg)
# Convert to complex then change shape and dimensions
data = data[..., 0] + 1j*data[..., 1]
shape = shape[:-1]
dimensions = dimensions[:-1]
if cplx_mode == "Abs":
data = np.abs(data)
elif cplx_mode == "Real":
data = data.real
elif cplx_mode == "Imag":
data = data.imag
else:
raise ValueError("Wrong value for cplx_mode %s" % cplx_mode)
# Plotting a scalar?
if not shape: return
ndim = len(shape)
if ndim == 1:
# Vector
dim_name = dimensions[0]
xx = range(len(dataset.dimensions[dim_name]))
from wxmplot import PlotFrame
frame = PlotFrame(parent=self)
if opts.plot_mode == "line":
frame.plot(xx, data)
else:
frame.scatterplot(xx, data)
frame.set_xlabel(dim_name)
frame.set_ylabel(var_name)
frame.Show()
elif ndim == 2:
# Two dimensional array.
dim_namex, dim_namey = dimensions
xx, yy = range(len(dataset.dimensions[dim_namex])), range(len(dataset.dimensions[dim_namey]))
mode = opts.image_mode
if False:
# 3d plot
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X, Y = np.meshgrid(xx, yy, sparse=False, indexing='ij')
print(X.shape, Y.shape, data.shape)
ax.plot_surface(X, Y, data) # rstride=8, cstride=8, alpha=0.3)
plt.show()
from wxmplot import ImageFrame
frame = ImageFrame(parent=self)
frame.display(data, title=var_name, style=mode, x=xx, y=yy, xlabel=dim_namex, ylabel=dim_namey)
frame.Show()
else:
raise NotImplementedError()
#def OnArraySlice(self, event):
# print("Onslice")
# item = getSelected(self.list)[0]
# name = getColumnText(self.list, item, 0)
# var = self.dataset.variables[name]
# ArraySlicerFrame(self, name, var).Show()
class ArrayComparisonFrame(wx.Frame):
"""This frame allows the user to specify how to handle array comparison."""
def __init__(self, parent, name, data, **kwargs):
super(ArrayComparisonFrame, self).__init__(parent, -1, **kwargs)
self.name, self.data = name, data
self.panel = ArrayComparisonPanel(self)
main_sizer = wx.BoxSizer(wx.VERTICAL)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
plot_button = wx.Button(self, -1, "Plot")
hsizer.Add(plot_button, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
plot_button.Bind(wx.EVT_BUTTON, self.onPlotData)
main_sizer.Add(hsizer, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)
main_sizer.Add(self.panel, 1, wx.EXPAND, 5)
self.SetSizerAndFit(main_sizer)
def onPlotData(self, event):
operators = self.panel.GetSelectedOperators()
from wxmplot import PlotFrame
frame = PlotFrame(parent=self)
xx = range(len(self.data))
for oname, op in operators.items():
#print(oname)
values = [op(arr) for arr in self.data]
frame.oplot(xx, values, label=oname)
#if opts.plot_mode == "line":
# frame.oplot(xx, values)
#else:
# frame.scatterplot(xx, values)
frame.set_xlabel("File index")
frame.set_ylabel(self.name)
frame.Show()
class ArrayComparisonPanel(wx.Panel):
"""A panel with checkboxes used to select the scalar quantities to compare."""
def __init__(self, parent, **kwargs):
"""
Args:
parent:
Parent window.
"""
super(ArrayComparisonPanel, self).__init__(parent, -1, **kwargs)
main_sizer = wx.BoxSizer(wx.VERTICAL)
static_sizer = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Array contractions"), wx.VERTICAL)
operators = [
("max", np.max),
("min", np.min),
("mean", np.mean),
("std", np.std),
#("median", np.median),
]
self.operators = collections.OrderedDict(operators)
self.check_boxes = collections.OrderedDict()
for oname, _ in self.operators.items():
cbox = wx.CheckBox(self, -1, oname, wx.DefaultPosition, wx.DefaultSize, 0)
cbox.SetValue(True)
static_sizer.Add(cbox, 0, wx.ALL | wx.EXPAND, 5)
self.check_boxes[oname] = cbox
main_sizer.Add(static_sizer, 1, wx.EXPAND, 5)
# Add buttons to (select|deselect) all checkboxes.
hsizer = wx.BoxSizer(wx.HORIZONTAL)
all_button = wx.Button(self, -1, "Select all")
all_button.Bind(wx.EVT_BUTTON, self.OnSelectAll)
hsizer.Add(all_button, 0, wx.ALL, 5)
deselect_button = wx.Button(self, -1, "Deselect all")
deselect_button.Bind(wx.EVT_BUTTON, self.OnDeselectAll)
hsizer.Add(deselect_button, 0, wx.ALL, 5)
main_sizer.Add(hsizer, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)
self.SetSizerAndFit(main_sizer)
def OnSelectAll(self, event):
"""Select all the check boxes."""
for cbox in self.check_boxes.values():
cbox.SetValue(True)
def OnDeselectAll(self, event):
"""Deselect all the check boxes."""
for cbox in self.check_boxes.values():
cbox.SetValue(False)
def GetSelectedOperators(self):
"""
Return the list of operators selected by the user.
"""
ops = collections.OrderedDict()
for oname, cbox in self.check_boxes.items():
if cbox.GetValue():
ops[oname] = self.operators[oname]
return ops
#class ArraySlicerFrame(wx.Frame):
#
# def __init__(self, parent, name, var, **kwargs):
# super(ArraySlicerFrame, self).__init__(parent, -1, **kwargs)
# self.name, self.var = name, var
#
# self.panel_1d = Slice1dPanel(self, name, var)
# #self.panel_2d = Slice1dPanel(self, name, arr)
# #self.panel_3d = Slice1dPanel(self, name, arr)
#
# main_sizer = wx.BoxSizer(wx.VERTICAL)
# main_sizer.Add(self.panel_1d, 1, wx.EXPAND, 5)
# self.SetSizer(main_sizer)
#
#
#class Slice1dPanel(wx.Panel):
# """A panel plotting for 1D slices."""
# def __init__(self, parent, name, var, **kwargs):
# """
# Args:
# parent:
# Parent window.
# """
# super(Slice1dPanel, self).__init__(parent, -1, **kwargs)
# self.name, self.var = name, var
#
# label = wx.StaticText(self, -1, "Axis:")
# label.Wrap(-1)
# self.axis_choice = wx.ComboBox(self, -1, choices=var.dimensions)
#
# hsz1 = wx.BoxSizer(wx.HORIZONTAL)
# hsz1.Add(label, 0, wx.ALL, 5)