-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathplot_gui.py
More file actions
1746 lines (1355 loc) · 69.9 KB
/
plot_gui.py
File metadata and controls
1746 lines (1355 loc) · 69.9 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Modelon AB
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import matplotlib
matplotlib.interactive(True)
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure
from matplotlib import rcParams
import fnmatch
import re
import os
#GUI modules
try:
import wx
import wx.lib.agw.customtreectrl as wxCustom
import wx.lib.agw.aui as aui
except ImportError:
print("WX-Python not found. The GUI will not work.")
from pyfmi.common.io import ResultDymolaTextual
from pyfmi.common.io import ResultDymolaBinary
from pyfmi.common.io import ResultCSVTextual
from pyfmi.common.io import JIOError
ID_GRID = 15001
ID_LICENSE = 15002
ID_LABELS = 15003
ID_AXIS = 15004
ID_MOVE = 15005
ID_ZOOM = 15006
ID_RESIZE = 15007
ID_LINES = 15008
ID_CLEAR = 15009
def convert_filter(expression):
"""
Convert a filter based on unix filename pattern matching to a
list of regular expressions.
"""
regexp = []
if isinstance(expression,str):
regex = fnmatch.translate(expression)
regexp = [re.compile(regex)]
elif isinstance(expression,list):
for i in expression:
regex = fnmatch.translate(i)
regexp.append(re.compile(regex))
else:
raise Exception("Unknown input.")
return regexp
def match(name, filter_list):
found = False
for j in range(len(filter_list)):
if re.match(filter_list[j], name):
found = True
break
return found
class MainGUI(wx.Frame):
sizeHeightDefault=900
sizeLengthDefault=675
sizeHeightMin=100
sizeLengthMin=130
sizeTreeMin=200
sizeTreeDefault=sizeTreeMin+40
def __init__(self, parent, ID, filename=None):
self.title = "PyFMI Plot GUI"
wx.Frame.__init__(self, parent, ID, self.title,
wx.DefaultPosition, wx.Size(self.sizeHeightDefault, self.sizeLengthDefault))
#Handle idle events
#wx.IdleEvent.SetMode(wx.IDLE_PROCESS_SPECIFIED)
#Variables for the results
self.ResultFiles = [] #Contains all the result files
self.PlotVariables = [[]] #Contains all the variables for the different plots
self.ResultIndex = 0 #Index of the result file
self.PlotIndex = 0 #Index of the plot variables connected to the different plots
#Settings variables
self.grid = True
self.zoom = True
self.move = False
#Create menus and status bars
self.CreateStatusBar() #Create a statusbar at the bottom
self.CreateMenu() #Create the normal menu
#Create the main window
self.verticalSplitter = wx.SplitterWindow(self, -1, style = wx.CLIP_CHILDREN | wx.SP_LIVE_UPDATE | wx.SP_3D)
#Create the positioners
self.leftPanel = wx.Panel(self.verticalSplitter)
self.leftSizer = wx.BoxSizer(wx.VERTICAL)
self.rightPanel = wx.Panel(self.verticalSplitter)
self.rightSizer = wx.BoxSizer(wx.VERTICAL)
#Create the panels (Tree and Plot)
if wx.VERSION < (2,8,11,0):
self.noteBook = aui.AuiNotebook(self.rightPanel, style= aui.AUI_NB_TOP | aui.AUI_NB_TAB_SPLIT | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_SCROLL_BUTTONS | aui.AUI_NB_CLOSE_ON_ACTIVE_TAB | aui.AUI_NB_DRAW_DND_TAB)
self.tree = VariableTree(self.noteBook, self.leftPanel,style = wx.SUNKEN_BORDER | wxCustom.TR_HAS_BUTTONS | wxCustom.TR_HAS_VARIABLE_ROW_HEIGHT | wxCustom.TR_HIDE_ROOT | wxCustom.TR_ALIGN_WINDOWS)
else:
self.noteBook = aui.AuiNotebook(self.rightPanel, agwStyle= aui.AUI_NB_TOP | aui.AUI_NB_TAB_SPLIT | aui.AUI_NB_TAB_MOVE | aui.AUI_NB_SCROLL_BUTTONS | aui.AUI_NB_CLOSE_ON_ACTIVE_TAB | aui.AUI_NB_DRAW_DND_TAB)
self.tree = VariableTree(self.noteBook, self.leftPanel,style = wx.SUNKEN_BORDER, agwStyle = wxCustom.TR_HAS_BUTTONS | wxCustom.TR_HAS_VARIABLE_ROW_HEIGHT | wxCustom.TR_HIDE_ROOT | wxCustom.TR_ALIGN_WINDOWS)
self.plotPanels = [PlotPanel(self.noteBook,self.grid, move=self.move, zoom=self.zoom)]
self.noteBook.AddPage(self.plotPanels[0],"Plot 1")
self.filterPanel = FilterPanel(self, self.leftPanel, self.tree)
#Add the panels to the positioners
self.leftSizer.Add(self.tree,1,wx.EXPAND)
self.leftSizer.Add(self.filterPanel,0,wx.EXPAND)
self.rightSizer.Add(self.noteBook,1,wx.EXPAND)
self.verticalSplitter.SplitVertically(self.leftPanel, self.rightPanel,self.sizeTreeDefault)
#self.verticalSplitter.SetMinimumPaneSize(self.sizeTreeMin)
self.verticalSplitter.SetMinimumPaneSize(self.filterPanel.GetBestSize()[0])
#Position the main windows
self.leftPanel.SetSizer(self.leftSizer)
self.rightPanel.SetSizer(self.rightSizer)
self.mainSizer = wx.BoxSizer() #Create the main positioner
self.mainSizer.Add(self.verticalSplitter, 1, wx.EXPAND) #Add the vertical splitter
self.SetSizer(self.mainSizer) #Set the positioner to the main window
self.SetMinSize((self.sizeHeightMin,self.sizeLengthMin)) #Set minimum sizes
#Bind the exit event from the "cross"
self.Bind(wx.EVT_CLOSE, self.OnMenuExit)
#Bind the tree item checked event
self.tree.Bind(wxCustom.EVT_TREE_ITEM_CHECKED, self.OnTreeItemChecked)
#Bind the key press event
self.tree.Bind(wx.EVT_KEY_DOWN, self.OnKeyPress)
#Bind the closing of a tab
self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnCloseTab, self.noteBook)
#Bind the changing of a tab
self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGING, self.OnTabChanging, self.noteBook)
#Bind the changed of a tab
self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnTabChanged, self.noteBook)
if filename is not None:
self._OpenFile(filename)
self.Centre(True) #Position the GUI in the centre of the screen
self.Show(True) #Show the Plot GUI
def CreateMenu(self):
#Creating the menu
filemenu = wx.Menu()
helpmenu = wx.Menu()
editmenu = wx.Menu()
viewmenu = wx.Menu()
menuBar = wx.MenuBar()
#Create the menu options
# Main
self.menuOpen = filemenu.Append(wx.ID_OPEN, "&Open\tCtrl+O","Open a result.")
self.menuSaveFig = filemenu.Append(wx.ID_SAVE, "&Save\tCtrl+S", "Save the current figure.")
filemenu.AppendSeparator() #Append a seperator between Open and Exit
self.menuExit = filemenu.Append(wx.ID_EXIT,"E&xit\tCtrl+X"," Terminate the program.")
# Edit
self.editAdd = editmenu.Append(wx.ID_ADD,"A&dd Plot","Add a plot window.")
self.editClear = editmenu.Append(wx.ID_CLEAR, "Clear Plot", "Clear the current plot window.")
editmenu.AppendSeparator()
self.editAxisLabels = editmenu.Append(ID_AXIS,"Axis / Labels", "Edit the axis and labels of the current plot.")
self.editLinesLegends = editmenu.Append(ID_LINES, "Lines / Legends", "Edit the lines and the legend of the current plot.")
# View
self.viewGrid = viewmenu.Append(ID_GRID,"&Grid","Show/Hide Grid.",kind=wx.ITEM_CHECK)
viewmenu.AppendSeparator() #Append a seperator
self.viewMove = viewmenu.Append(ID_MOVE,"Move","Use the mouse to move the plot.",kind=wx.ITEM_RADIO)
self.viewZoom = viewmenu.Append(ID_ZOOM,"Zoom","Use the mouse for zooming.",kind=wx.ITEM_RADIO)
viewmenu.AppendSeparator()
self.viewResize = viewmenu.Append(ID_RESIZE, "Resize", "Resize the current plot.")
#Check items
viewmenu.Check(ID_GRID, self.grid)
viewmenu.Check(ID_ZOOM, self.zoom)
viewmenu.Check(ID_MOVE, self.move)
# Help
self.helpLicense = helpmenu.Append(ID_LICENSE, "License","Show the license.")
self.helpAbout = helpmenu.Append(wx.ID_ABOUT, "&About"," Information about this program.")
#Setting up the menu
menuBar.Append(filemenu,"&File") #Adding the "filemenu" to the MenuBar
menuBar.Append(editmenu,"&Edit") #Adding the "editmenu" to the MenuBar
menuBar.Append(viewmenu,"&View") #Adding the "viewmenu" to the MenuBar
menuBar.Append(helpmenu,"&Help") #Adding the "helpmenu" to the MenuBar
#Binding the events
self.Bind(wx.EVT_MENU, self.OnMenuOpen, self.menuOpen)
self.Bind(wx.EVT_MENU, self.OnMenuSaveFig, self.menuSaveFig)
self.Bind(wx.EVT_MENU, self.OnMenuExit, self.menuExit)
self.Bind(wx.EVT_MENU, self.OnMenuAdd, self.editAdd)
self.Bind(wx.EVT_MENU, self.OnMenuClear, self.editClear)
self.Bind(wx.EVT_MENU, self.OnMenuAxisLabels, self.editAxisLabels)
self.Bind(wx.EVT_MENU, self.OnMenuLinesLegends, self.editLinesLegends)
self.Bind(wx.EVT_MENU, self.OnMenuResize, self.viewResize)
self.Bind(wx.EVT_MENU, self.OnMenuGrid, self.viewGrid)
self.Bind(wx.EVT_MENU, self.OnMenuMove, self.viewMove)
self.Bind(wx.EVT_MENU, self.OnMenuZoom, self.viewZoom)
self.Bind(wx.EVT_MENU, self.OnMenuLicense, self.helpLicense)
self.Bind(wx.EVT_MENU, self.OnMenuAbout, self.helpAbout)
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
#Set keyboard shortcuts
hotKeysTable = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord("O"), self.menuOpen.GetId()),
(wx.ACCEL_CTRL, ord("S"), self.menuSaveFig.GetId()),
(wx.ACCEL_CTRL, ord("X"), self.menuExit.GetId())])
self.SetAcceleratorTable(hotKeysTable)
#Disable Lines and Legends
self.editLinesLegends.Enable(False)
def OnMenuMove(self, event):
self.move = True
self.zoom = False
for i in range(self.noteBook.GetPageCount()):
self.noteBook.GetPage(i).UpdateSettings(move = self.move,
zoom = self.zoom)
def OnMenuZoom(self, event):
self.move = False
self.zoom = True
for i in range(self.noteBook.GetPageCount()):
self.noteBook.GetPage(i).UpdateSettings(move = self.move,
zoom = self.zoom)
def OnMenuExit(self, event):
self.Destroy() #Close the GUI
def OnMenuAbout(self, event):
dlg = wx.MessageDialog(self, 'PyFMI Plot GUI.\n', 'About',
wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def OnMenuResize(self, event):
IDPlot = self.noteBook.GetSelection()
self.noteBook.GetPage(IDPlot).ReSize()
def OnMenuOpen(self, event):
#Open the file window
dlg = wx.FileDialog(self, "Open result file(s)",
wildcard="Supported files (.txt, .mat, .csv)|*.txt;*.mat;*.csv|Text files (.txt)|*.txt|MATLAB files (.mat)|*.mat|Comma-Separated Values files (.csv)|*.csv|All files (*.*)|*.*",
style=wx.FD_MULTIPLE)
#If OK load the results
if dlg.ShowModal() == wx.ID_OK:
for n in dlg.GetFilenames():
self._OpenFile(os.path.join(dlg.GetDirectory(),n))
dlg.Destroy() #Destroy the popup window
def OnMenuSaveFig(self, event):
#Open the file window
dlg = wx.FileDialog(self, "Choose a filename to save to",wildcard="Portable Network Graphics (*.png)|*.png|" \
"Encapsulated Postscript (*.eps)|*.eps|" \
"Enhanced Metafile (*.emf)|*.emf|" \
"Portable Document Format (*.pdf)|*.pdf|" \
"Postscript (*.ps)|*.ps|" \
"Raw RGBA bitmap (*.raw *.rgba)|*.raw;*.rgba|" \
"Scalable Vector Graphics (*.svg *.svgz)|*.svg;*.svgz",
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
#If OK save the figure
if dlg.ShowModal() == wx.ID_OK:
self.SetStatusText("Saving figure...") #Change the statusbar
IDPlot = self.noteBook.GetSelection()
self.noteBook.GetPage(IDPlot).Save(dlg.GetPath())
self.SetStatusText("") #Change the statusbar
dlg.Destroy() #Destroy the popup window
def OnMenuAdd(self, event):
#Add a new list for the plot variables connect to the plot
self.PlotVariables.append([])
self.PlotIndex += 1
#Add a new plot panel to the notebook
self.plotPanels.append(PlotPanel(self.noteBook,self.grid,move=self.move, zoom=self.zoom))
self.noteBook.AddPage(self.plotPanels[-1],"Plot "+str(self.PlotIndex+1))
#Enable labels and axis options
self.editAxisLabels.Enable(True)
def OnMenuClear(self, event):
#Clear the current activated plot window
IDPlot = self.noteBook.GetSelection()
if IDPlot != -1:
plotWindow = self.noteBook.GetPage(IDPlot)
#Uncheck all variables
for i,var in enumerate(self.noteBook.GetPage(IDPlot).GetPlotVariables()):
self.tree.CheckItem2(var[1],checked=False,torefresh=True)
#Delete all variables
plotWindow.DeleteAllPlotVariables()
#Disable Lines and Legends
self.editLinesLegends.Enable(False)
plotWindow.SetDefaultSettings()
plotWindow.UpdateSettings(axes=[0.0,1.0,0.0,1.0])
plotWindow.Draw()
plotWindow.UpdateSettings(axes=[None,None,None,None])
def OnMenuLinesLegends(self, event):
IDPlot = self.noteBook.GetSelection()
plotWindow = self.noteBook.GetPage(IDPlot)
#Create the axis dialog
dlg = DialogLinesLegends(self,self.noteBook.GetPage(IDPlot))
#Open the dialog and update options if OK
if dlg.ShowModal() == wx.ID_OK:
dlg.ApplyChanges() #Apply Changes
legend = dlg.GetValues()
plotWindow.UpdateSettings(legendposition=legend)
plotWindow.Draw()
#Destroy the dialog
dlg.Destroy()
def OnMenuAxisLabels(self, event):
IDPlot = self.noteBook.GetSelection()
plotWindow = self.noteBook.GetPage(IDPlot)
#Create the axis dialog
dlg = DialogAxisLabels(self,self.noteBook.GetPage(IDPlot))
#Open the dialog and update options if OK
if dlg.ShowModal() == wx.ID_OK:
xmax,xmin,ymax,ymin,title,xlabel,ylabel,xscale,yscale = dlg.GetValues()
try:
xmax=float(xmax)
except ValueError:
xmax=None
try:
xmin=float(xmin)
except ValueError:
xmin=None
try:
ymax=float(ymax)
except ValueError:
ymax=None
try:
ymin=float(ymin)
except ValueError:
ymin=None
plotWindow.UpdateSettings(axes=[xmin,xmax,ymin,ymax],
title=title,xlabel=xlabel,ylabel=ylabel,
xscale=xscale, yscale=yscale)
plotWindow.DrawSettings()
#Destroy the dialog
dlg.Destroy()
def OnMenuGrid(self, event):
self.grid = not self.grid
for i in range(self.noteBook.GetPageCount()):
self.noteBook.GetPage(i).UpdateSettings(grid = self.grid)
self.noteBook.GetPage(i).DrawSettings()
def OnTreeItemChecked(self, event):
self.SetStatusText("Drawing figure...")
item = event.GetItem()
#ID = self.tree.FindIndexParent(item)
ID = -1 #Not used
IDPlot = self.noteBook.GetSelection()
if IDPlot != -1: #If there exist a plot window
data = self.tree.GetPyData(item)
#print "Variable: ", data["variable_id"], item
#Store plot variables or "unstore"
if self.tree.IsItemChecked(item): #Draw
#Add to Plot panel
self.noteBook.GetPage(IDPlot).AddPlotVariable(ID,item,data)
data["item_checked"] = IDPlot
else: #Undraw
#Remove from panel
self.noteBook.GetPage(IDPlot).DeletePlotVariable(data["variable_id"])
data["item_checked"] = None
self.noteBook.GetPage(IDPlot).Draw()
lines = self.noteBook.GetPage(IDPlot).GetLines()
if len(lines) != 0:
#Enable Lines and Legends
self.editLinesLegends.Enable(True)
else:
#Disable Lines and Legends
self.editLinesLegends.Enable(False)
else: #Dont allow an item to be checked if there exist no plot window
self.tree.CheckItem2(item,checked=False,torefresh=True)
self.SetStatusText("")
def OnKeyPress(self, event):
keycode = event.GetKeyCode() #Get the key pressed
#If the key is Delete
if keycode == wx.WXK_DELETE:
self.SetStatusText("Deleting Result...")
ID = self.tree.FindIndexParent(self.tree.GetSelection())
data = self.tree.GetPyData(self.tree.GetSelection())
IDPlot = self.noteBook.GetSelection()
if ID >= 0: #If id is less then 0, no item is selected
self.ResultFiles.pop(ID) #Delete the result object from the list
self.tree.DeleteParent(self.tree.GetSelection())
#Redraw
for i in range(self.noteBook.GetPageCount()):
self.noteBook.GetPage(i).DeletePlotVariable(global_id=data["result_id"])
self.noteBook.GetPage(i).Draw()
self.SetStatusText("")
def OnCloseTab(self, event):
self.OnTabChanging(event)
self.PlotVariables.pop(event.GetSelection()) #Delete the plot
self.plotPanels.pop(event.GetSelection()) #MAYBE!
#variables associated with the current plot
#Disable changing of labels and axis if there is no Plot
if self.noteBook.GetPageCount() == 1:
self.editAxisLabels.Enable(False)
self.editLinesLegends.Enable(False)
def OnTabChanging(self, event):
#print "Changing: ", self.noteBook.GetSelection()
self.UpdateCheckedItemTree(check=False)
def OnTabChanged(self,event):
#print "Changed: ", self.noteBook.GetSelection()
self.UpdateCheckedItemTree(check=True)
def UpdateCheckedItemTree(self, check=True):
#print "Update: ", self.noteBook.GetSelection()
IDPlot = self.noteBook.GetSelection()
#Check the items related to the previous plot
if IDPlot != -1:
for i,var in enumerate(self.noteBook.GetPage(IDPlot).GetPlotVariables()):
self.tree.CheckItem2(var[1],checked=check,torefresh=True)
lines = self.noteBook.GetPage(IDPlot).GetLines()
if len(lines) != 0:
#Enable Lines and Legends
self.editLinesLegends.Enable(True)
else:
#Disable Lines and Legends
self.editLinesLegends.Enable(False)
def OnMenuLicense(self, event):
desc = "Copyright (C) 2011 Modelon AB\n\n"\
"This program is free software: you can redistribute it and/or modify "\
"it under the terms of the GNU Lesser General Public License as published by "\
"the Free Software Foundation, version 3 of the License.\n\n"\
"This program is distributed in the hope that it will be useful, "\
"but WITHOUT ANY WARRANTY; without even the implied warranty of "\
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the "\
"GNU Lesser General Public License for more details.\n\n"\
"You should have received a copy of the GNU Lesser General Public License "\
"along with this program. If not, see <http://www.gnu.org/licenses/>. "
dlg = wx.MessageDialog(self, desc, 'License', wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def _OpenFile(self,filename):
# Extract filename and result name
n = str(filename)
if n.find('\\') > n.find('/'):
res_name = n.split('\\')[-1]
else:
res_name = n.split('/')[-1]
failToLoad = False
self.SetStatusText("Loading "+n+"...") #Change the statusbar
#Find out if the result is a textual or binary file
if n.lower().endswith(".txt"): #Textual file
try:
self.ResultFiles.append((res_name,ResultDymolaTextual(n)))
except (JIOError, IOError):
self.SetStatusText("Could not load "+n+".") #Change the statusbar
failToLoad = True
elif n.lower().endswith(".mat"): #Binary file
try:
self.ResultFiles.append((res_name,ResultDymolaBinary(n)))
except (TypeError, IOError):
self.SetStatusText("Could not load "+n+".") #Change the statusbar
failToLoad = True
elif n.lower().endswith(".csv"): #Binary file
try:
self.ResultFiles.append((res_name,ResultCSVTextual(n)))
except (TypeError, IOError, ValueError):
self.SetStatusText("Could not load "+n+". Trying with delimiter ','.") #Change the statusbar
try:
self.ResultFiles.append((res_name,ResultCSVTextual(n,delimiter=",")))
except (TypeError, IOError, ValueError):
self.SetStatusText("Could not load "+n+".") #Change the statusbar
failToLoad = True
else:
self.SetStatusText("Could not load "+n+".") #Change the statusbar
failToLoad = True
if failToLoad:
self.SetStatusText("Could not open file '" + n + "'!\n")
else:
self.SetStatusText("Populating tree for " +n+"...")
self.tree.AddTreeNode(self.ResultFiles[-1][1], self.ResultFiles[-1][0],
self.filterPanel.checkBoxTimeVarying.GetValue(),
self.filterPanel.checkBoxParametersConstants.GetValue(),
self.filterPanel.GetFilter())
self.ResultIndex += 1 #Increment the index
self.SetStatusText("") #Change the statusbar
class VariableTree(wxCustom.CustomTreeCtrl):
def __init__(self, noteBook, *args, **kwargs):
super(VariableTree, self).__init__(*args, **kwargs)
self.noteBook = noteBook
#Add the root item
self.root = self.AddRoot("Result(s)")
#Root have children
self.SetItemHasChildren(self.root)
#Internal counter for all children
self.global_id = 0 #Global ID for each loaded results (unique for each results
self.local_id = 0 #Local ID for each loaded variable (unique for each variable and results)
self.node_id = 0 #Node ID for each node with childrens
#List of hidden children
self.hidden_children = []
self.hidden_nodes = {}
self.nodes = {}
#Internal flags
self._update_top_siblings = True
def RefreshSelectedUnder(self, item):
"""
Refreshes the selected items under the given item.
:param `item`: an instance of L{GenericTreeItem}.
"""
if self._freezeCount:
return
if item.IsSelected():
self.RefreshLine(item)
children = item.GetChildren()
for child in children:
if child.IsSelected():
self.RefreshLine(child)
# Workaround for bug in customtreectrl in wx making
# this function not work there
def SortChildren(self, item):
children = item.GetChildren()
if len(children) > 1:
self._dirty = True
from functools import cmp_to_key
children.sort(key=cmp_to_key(self.OnCompareItems))
def AddTreeNode(self, resultObject, name,timeVarying=None,parametersConstants=None,filter=None):
#Freeze the window temporarely
self.Freeze()
#Add a new dictionary for the nodes
self.nodes[self.global_id] = {}
self._update_top_siblings = True
child = self.AppendItem(self.root, name, data={"result_id":self.global_id, "node_id": self.node_id})
self.SetItemHasChildren(child,True)
self.nodes[self.global_id][self.node_id] = {"node":child, "node_id":self.node_id, "name":name, "parent_node":self.root, "parent_node_id": -1}
self.nodes[self.global_id][-1] = {"node":child, "node_id":self.node_id, "name":name, "parent_node":self.root, "parent_node_id": -2}
self.node_id = self.node_id + 1 #Increment the nodes
rec = {"root":child}
for item in resultObject.name:
spl = item.split(".")
#Python object for storing data related to the variable
data={}
data["timevarying"] = None #resultObject.is_variable(item)
data["traj"] = resultObject
data["name"] = item
data["full_name"] = item
data["result_id"] = self.global_id
data["variable_id"] = self.local_id = self.local_id + 1
data["result_object"] = resultObject
data["item_checked"] = None
if len(spl)==1:
data["parents"] = child
data["child"] = item
data["node_id"] = self.GetPyData(child)["node_id"]
self.AppendItem(child, item,ct_type=1, data=data)
else:
#Handle variables of type der(---.---.x)
if spl[0].startswith("der(") and spl[-1].endswith(")"):
spl[0]=spl[0][4:]
spl[-1] = "der("+spl[-1]
tmp_str = ""
tmp_str_old = ""
for i in range(len(spl)-1):
#See if the sub directory already been added, else add
tmp_str_old = tmp_str
tmp_str += spl[i]
try:
rec[tmp_str]
except KeyError:
local_data = {"result_id":self.global_id, "node_id":self.node_id}
if i==0:
rec[tmp_str] = self.AppendItem(child, spl[i], data=local_data)
local_dict = {"node":rec[tmp_str], "node_id":self.node_id, "name":spl[i], "parent_node":child, "parent_node_id": -1}
self.nodes[self.global_id][self.node_id] = local_dict
else:
rec[tmp_str] = self.AppendItem(rec[tmp_str_old], spl[i], data=local_data)
local_dict = {"node":rec[tmp_str], "node_id":self.node_id, "name":spl[i], "parent_node":rec[tmp_str_old], "parent_node_id": self.GetPyData(rec[tmp_str_old])["node_id"]}
self.nodes[self.global_id][self.node_id] = local_dict
self.SetItemHasChildren(rec[tmp_str],True)
self.node_id = self.node_id + 1 #Increment the nodes
else:
data["parents"] = rec[tmp_str]
data["child"] = spl[-1]
data["node_id"] = self.GetPyData(rec[tmp_str],)["node_id"]
self.AppendItem(rec[tmp_str], spl[-1], ct_type=1, data=data)
self.SortChildren(child)
#Increment global id
self.global_id = self.global_id + 1
#print "Adding: ", name, "Options: ", timeVarying, parametersConstants, filter
#print "Condition: ", not timeVarying or not parametersConstants or filter is not None
#Hide nodes if options are chosen
if not timeVarying or not parametersConstants or filter is not None:
self.HideNodes(timeVarying,parametersConstants,filter)
#Un-Freeze the window
self.Thaw()
def FindLoneChildDown(self, child):
"""
Search for the youngest child down the tree from "child".
Parameters::
child - The item from where the search should start.
Returns::
child - The youngest child from the starting point.
"""
while True:
nextItem, cookie = self.GetNextChild(child,0)
if nextItem is not None:
child = nextItem
else:
break
return child
def FindFirstSiblingUp(self,child,itemParent):
"""
Search for the first sibling of "child" going up in tree.
"""
while child != itemParent:
nextItem = self.GetNextSibling(child)
if nextItem is not None:
return nextItem
child = self.GetItemParent(child)
return child
def HideNodes(self, showTimeVarying=None, showParametersConstants=None, filter=None):
"""
Hide nodes depending on the input.
Parameters::
showTimeVarying - Hides or Shows the time varying variables.
showParametersConstants - Hides or Show the parameters.
"""
itemParent = self.GetRootItem()
child,cookie = self.GetFirstChild(itemParent)
found_child = child
top_siblings = self.FindTopSiblings()
#Hide items if any of the options are True
if not showTimeVarying or not showParametersConstants or filter is not None:
while child != itemParent and child is not None:
already_hidden = False
#Find the first youngest child
found_child = self.FindLoneChildDown(child)
#Find the first sibling up
child = self.FindFirstSiblingUp(found_child, itemParent)
data = self.GetPyData(found_child)
if found_child in top_siblings:
print("Found child in top siblings, ", self.GetItemText(found_child))
continue
#print "Found child:", self.GetItemText(found_child)
#print "Child: ", self.GetItemText(child), self.GetPyData(child), "Has Children: ", self.HasChildren(child)
if data is None:
print("Found (wrong) child:", self.GetItemText(found_child))
raise Exception
try:
data["timevarying"]
except KeyError:
print("Found (wrong (exception)) child:", self.GetItemText(found_child))
raise Exception
if data["timevarying"] is None:
data["timevarying"] = data["result_object"].is_variable(data["full_name"])
#Enable or disable depending on input to method
if not showTimeVarying and data["timevarying"]:
self.HideItem(found_child, showTimeVarying)
#Delete the parent if it has no children
self.HideNodeItem(found_child)
already_hidden = True
if not showParametersConstants and not data["timevarying"]:
self.HideItem(found_child, showParametersConstants)
#Delete the parent if it has no children
self.HideNodeItem(found_child)
already_hidden = True
if not already_hidden and filter is not None and not match(data["full_name"], filter):
self.HideItem(found_child, show=False)
#Delete the parent if it has no children
self.HideNodeItem(found_child)
#Re-add items if any of the options are True
if showTimeVarying or showParametersConstants or filter is not None:
self.AddHiddenItems(showTimeVarying, showParametersConstants, filter)
def FindTopSiblings(self):
"""
Finds all the siblings one level down from root.
"""
if self._update_top_siblings:
itemParent = self.GetRootItem()
child,cookie = self.GetFirstChild(itemParent)
siblings = []
while child is not None:
siblings.append(child)
child = self.GetNextSibling(child)
self._top_siblings = siblings
else:
siblings = self._top_siblings
self._update_top_siblings = False
return siblings
def AddHiddenItems(self, showTimeVarying=None, showParametersConstants=None, filter=None):
#print "Adding hidden items: ", showTimeVarying, showParametersConstants, filter
i = 0
while i < len(self.hidden_children):
data = self.hidden_children[i]
matching = False
#Do not add any items!
if data["timevarying"] and not showTimeVarying or not data["timevarying"] and not showParametersConstants:
i = i+1
continue
if filter is not None:
matching = match(data["full_name"], filter)
if data["timevarying"] and showTimeVarying and (filter is None or filter is not None and matching) or \
not data["timevarying"] and showParametersConstants and (filter is None or filter is not None and matching):
#or filter is not None and match(data["full_name"], filter):
if self.nodes[data["result_id"]][data["node_id"]]["node"] is None:
self.AddHiddenNodes(data)
#print "Adding: ", data
#print "At node: ", self.nodes[data["result_id"]][data["node_id"]]
item = self.AppendItem(self.nodes[data["result_id"]][data["node_id"]]["node"], data["child"],ct_type=1, data=data)
if item is None:
raise Exception("Something went wrong when adding the variable.")
if data["item_checked"] is not None: #Item was previously checked.
#print "Item was previously checked", data["item_checked"]
self.noteBook.GetPage(data["item_checked"]).UpdatePlotVariableReference(-1,item,data)
self.hidden_children.pop(i)
i = i-1
i = i+1
def AddHiddenNodes(self, data):
node = self.nodes[data["result_id"]][data["node_id"]]
nodes_to_be_added = [node]
while node["node"] is None and node["parent_node_id"] != -1:
node = self.nodes[data["result_id"]][node["parent_node_id"]]
if node["node"] is not None:
break
nodes_to_be_added.append(node)
#print "Nodes to be added: ", nodes_to_be_added
for i in range(len(nodes_to_be_added)):
node = nodes_to_be_added[-(i+1)]
#print "Adding node: ", node, " at ", self.nodes[data["result_id"]][node["parent_node_id"]], " or ", self.nodes[data["result_id"]][-1], data
local_data = {"result_id":data["result_id"], "node_id":node["node_id"]}
"""
if node["parent_node_id"] == -1:
item = self.AppendItem(self.nodes[data["result_id"]][-1], node["name"], data=local_data)
else:
item = self.AppendItem(node["parent_node_id"], node["name"], data=local_data)
"""
item = self.AppendItem(self.nodes[data["result_id"]][node["parent_node_id"]]["node"], node["name"], data=local_data)
#item = self.AppendItem(node["parent_node"], node["name"], data=local_data)
self.SetItemHasChildren(item, True)
self.nodes[data["result_id"]][node["node_id"]]["node"] = item
#print "Node info after adding: ", self.nodes[data["result_id"]][node["node_id"]]
def HideNodeItem(self, item):
"""
Deletes the parents that does not have any children
"""
parent = self.GetItemParent(item)
top_siblings = self.FindTopSiblings()
while not self.HasChildren(parent) and parent not in top_siblings:
old_parent = self.GetItemParent(parent)
#Add the deleted nodes to the hidden list so that we can recreate the list
#self.hidden_nodes.append(self.GetPyData(parent))
#self.hidden_nodes[self.GetPyData(parent)["node_id"]] = [self.GetPyData(parent), old_parent]
#self.nodes[self.GetPyData(parent)["result_id"]][self.GetPyData(parent)["node_id"]][0] = None
self.nodes[self.GetPyData(parent)["result_id"]][self.GetPyData(parent)["node_id"]]["node"] = None
self.Delete(parent)
parent = old_parent
def HideItem(self, item, show):
data = self.GetPyData(item)
if not show:
self.hidden_children.append(data)
self.Delete(item)
def DeleteParent(self, item):
"""
Delete the oldest parent of item, except root.
"""
if item == self.GetRootItem():
return False
parentItem = self.GetItemParent(item)
while parentItem != self.GetRootItem():
item = parentItem
parentItem = self.GetItemParent(item)
#Remove also the hidden items contained in the hidden children list
data = self.GetPyData(item)
i = 0
while i < len(self.hidden_children):
if self.hidden_children[i]["result_id"] == data["result_id"]:
self.hidden_children.pop(i)
i = i-1
i = i+1
#Delete hidden nodes
self.nodes.pop(data["result_id"])
self.Delete(item) #Delete the parent from the Tree
def FindIndexParent(self, item):
"""
Find the index of the oldest parent of item from one level down
from root.
"""
if item == self.GetRootItem():
return -1
parentItem = item
item = self.GetItemParent(parentItem)
while item != self.GetRootItem():
parentItem = item
item = self.GetItemParent(parentItem)
root = self.GetRootItem()
sibling,cookie = self.GetFirstChild(root)
index = 0
while parentItem != sibling:
sibling = self.GetNextSibling(sibling)
index += 1
return index
class DialogLinesLegends(wx.Dialog):
def __init__(self, parent, plotPage):
wx.Dialog.__init__(self, parent, -1, "Lines and Legends")
#Get the variables