-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgui.py
More file actions
1483 lines (1168 loc) · 59.3 KB
/
gui.py
File metadata and controls
1483 lines (1168 loc) · 59.3 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
'''tkinter Tcl/Tk GUI for the Bay Assessment Model (BAM)'''
# Python distribution modules
from subprocess import Popen
from datetime import timedelta, datetime
from collections import OrderedDict as odict
from os.path import exists as path_exists
from os.path import join as path_join
from random import randint
strptime = datetime.strptime
# Note that these are separate modules:
# tkinter.filedialog
# tkinter.messagebox
# tkinter.font
import tkinter as Tk
from tkinter import messagebox
from tkinter import filedialog
from tkinter import ttk # tk themed widgets within tkinter (tkinter.ttk)
# Community modules
from numpy import linspace, isnan
from numpy import all as npall
from numpy import nan as npNaN
from matplotlib.colors import ListedColormap
from matplotlib.colors import BoundaryNorm
from matplotlib.colorbar import ColorbarBase
# These matplotlib objects are only used in MouseClick
from matplotlib.lines import Line2D
from matplotlib.patches import Polygon
# Used in PlotData
from matplotlib.dates import YearLocator, MonthLocator, DayLocator
from matplotlib.dates import DateFormatter
from matplotlib.pyplot import cm
# Modules to embed matplotlib figure in a Tkinter window, see:
# http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends._backend_tk import NavigationToolbar2Tk
# Local modules
from init import InitTimeBasins
from init import GetBasinSalinityData
from init import GetBasinStageData
from init import GetTimeIndex
import constants
#---------------------------------------------------------------
#
#---------------------------------------------------------------
class GUI:
'''GUI : tkinter & ttk with embedded matplotlib figure.'''
def __init__( self, root, model ):
self.model = model
# GUI objects
self.Tk_root = root
self.figure = None # matplotlib figure set onto canvas
self.figure_axes = None #
self.canvas = None #
self.colorbar = None # legend
self.basinListBox = None # in the mainframe
self.basinListBoxMap = dict() # { basin name : listbox index }
self.shoalListBox = None # a Toplevel pop-up
self.gaugeListBox = None # a Toplevel pop-up
self.msgText = None # Tk.Text widget for gui messages
self.buttonStyle = ttk.Style() # Note that BAM.TButton is child class
self.buttonStyle.configure( 'BAM.TButton', font = constants.buttonFont )
self.checkButtonStyle = ttk.Style()
self.checkButtonStyle.configure('BAM.TCheckbutton',
font = constants.textFont )
self.mapOptionMenu = None # map plot variable selection
self.plotOptionMenu = None # timeseries plot variable selection
self.startTimeEntry = None # simulation start time
self.endTimeEntry = None # simulation end time
self.plotVar_IntVars = odict() # { plotVariable : Tk.IntVar() }
if not self.model.args.noGUI :
# Set Tk-wide Font default for filedialog
# But it doesn't set filedialog window or button fonts
#root.tk.call( "option", "add", "*Font", constants.textFont )
root.option_add( "*Font", constants.textFont )
self.mapPlotVariable = Tk.StringVar()
self.plotVariable = Tk.StringVar()
self.current_time_label = Tk.StringVar()
self.start_text = Tk.StringVar( value = model.args.start )
self.end_text = Tk.StringVar( value = model.args.end )
self.plot_dir = model.args.basinOutputDir
self.last_plot_dir = self.plot_dir
# matplotlib colors can be names ('red', 'blue', 'green') or
# R, G, B tuple in the range [0,1] or fraction of gray in [0,1] '0.5'
# These 10 colors define the legend and map color ranges
self.colors = [ [ 0., 0., 1. ], [ 0., .2, 1. ],
[ 0., .4, 1. ], [ 0., .6, 1. ],
[ 0., .8, 1. ], [ 1., .8, 0. ],
[ 1., .6, 0. ], [ 1., .4, 0. ],
[ 1., .2, 0. ], [ 1., 0., 0. ] ]
#------------------------------------------------------------------
#
#------------------------------------------------------------------
def FloridaBayModel_Tk ( self ) :
'''User interface for the Florida Bay Model'''
icon = None
try :
icon = Tk.PhotoImage( file = path_join( self.model.args.path,
'data','init','PyFBM_icon.png' ) )
except :
icon = Tk.PhotoImage( file = path_join( self.model.args.path,
'data','init','PyFBM_icon.gif' ) )
if icon :
self.Tk_root.iconphoto( True, icon )
# Create the main widget Frame (window) and a control frame
mainframe = ttk.Frame( self.Tk_root, padding = "3 3 3 3" )
controlframe = ttk.Frame( self.Tk_root, padding = "1 1 1 1" )
# Create matplotlib figure and the canvas it is rendered onto
self.figure = Figure( figsize = (5, 4), # width x height (in)
dpi = 150,
facecolor = 'grey' )
self.figure_axes = self.figure.add_axes( ( 0, 0, 1, 1 ),
frameon = False,
label = 'FloridaBayModel' )
# Map limits are UTM Zone 17R in (m)
self.figure_axes.set_xlim( ( 490000, 569000 ) )
self.figure_axes.set_ylim( ( 2742000, 2799000 ) )
self.canvas = FigureCanvasTkAgg( self.figure, master = mainframe )
self.canvas.mpl_connect( 'pick_event', self.MouseClick )
# Setup the menu bar
menuBar = Tk.Menu( self.Tk_root )
self.Tk_root.config( menu = menuBar )
# File Menu -----------------------------------------------
menuFile = Tk.Menu( menuBar, tearoff=False, font = constants.textFont )
menuBar.add_cascade( menu = menuFile, label = ' File ',
font = constants.textFont )
menuFile.add_command( label = ' Init', command = self.OpenInitFile )
menuFile.add_command( label = ' Edit', command = self.EditFile )
# Dir Menu -----------------------------------------------
menuDir = Tk.Menu( menuBar, tearoff=False, font = constants.textFont )
menuBar.add_cascade( menu = menuDir, label = ' Dir ',
font = constants.textFont )
menuDir.add_command( label = 'Plot Disk', command = self.GetPlotDir )
menuDir.add_command( label = ' Output ', command = self.GetOutputDir )
# Help Menu -----------------------------------------------
menuHelp = Tk.Menu( menuBar, tearoff=False, font = constants.textFont )
menuBar.add_cascade( menu = menuHelp, label = 'Help',
font = constants.textFont )
menuHelp.add_command( label = 'About', command = self.ShowAboutInfo )
# Entry for start and end time, register CheckTimeEntry validatecommand
checkTimeCommand = controlframe.register( self.CheckTimeEntry )
self.startTimeEntry = ttk.Entry( mainframe, width = 15,
font = constants.textFont,
justify = Tk.LEFT,
textvariable = self.start_text,
validatecommand = ( checkTimeCommand,
'%P', '%W' ),
validate = 'focusout' )
self.endTimeEntry = ttk.Entry( mainframe, width = 15,
font = constants.textFont,
justify = Tk.LEFT,
textvariable = self.end_text,
validatecommand = ( checkTimeCommand,
'%P', '%W' ),
validate = 'focusout' )
# Current model time
currentTimeLabel = Tk.Label( mainframe, width = 18, height = 1,
bg = 'white',
font = constants.textFont,
justify = Tk.CENTER,
textvariable = self.current_time_label )
# Text box for messages
self.msgText = Tk.Text( mainframe, height = 5,
background='white', font = constants.textFont )
self.Message( self.model.Version )
self.Message( self.model.args.commandLine + '\n' )
msgScrollBar = ttk.Scrollbar( mainframe, orient = Tk.VERTICAL,
command = self.msgText.yview )
self.msgText.configure( yscrollcommand = msgScrollBar.set )
# Basin Listbox
self.basinListBox = Tk.Listbox( mainframe, height = 5, width = 20,
selectmode = Tk.EXTENDED,
font = constants.textFont )
# Insert the basin names into the Listbox
# The listvariable = [] option won't work if
# there is whitespace in a name, so insert them manually
i = 0
for Basin in self.model.Basins.values() :
self.basinListBox.insert( i, Basin.name )
self.basinListBoxMap[ Basin.name ] = i
i = i + 1
# Listbox vertical scroll bar : calls model.basinListBox.yview
scrollBar = ttk.Scrollbar( mainframe, orient = Tk.VERTICAL,
command = self.basinListBox.yview )
# Tell the Listbox that it will scroll according to the scrollBar
self.basinListBox.configure( yscrollcommand = scrollBar.set )
# Listbox calls ProcessBasinListbox() when selection changes
self.basinListBox.bind('<<ListboxSelect>>', self.ProcessBasinListbox)
# Colorize alternating lines of the listbox
for i in range( 0, len( self.model.Basins.keys() ), 2):
self.basinListBox.itemconfigure( i, background = '#f0f0ff' )
#--------------------------------------------------------------------
# These widgets are in the control frame
# OptionMenu for map plot types
self.mapPlotVariable.set( constants.BasinMapPlotVariable[0] )
self.mapOptionMenu = Tk.OptionMenu( controlframe,
self.mapPlotVariable,
*constants.BasinMapPlotVariable )
self.mapOptionMenu.config ( font = constants.buttonFont )
self.mapOptionMenu['menu'].config( font = constants.buttonFont )
self.mapOptionMenu.config( bg = 'white' )
# Button for self.Init()
initButton = ttk.Button( controlframe, text = "Init",
style = 'BAM.TButton',
command = lambda : InitTimeBasins(self.model))
# Button for model.Run()
runButton = ttk.Button( controlframe, text = "Run",
style = 'BAM.TButton',
command = self.model.Run )
# Button for model.Pause()
pauseButton = ttk.Button( controlframe, text = "Pause",
style = 'BAM.TButton',
command = self.model.Pause )
# Button for model.Stop()
stopButton = ttk.Button( controlframe, text = "Stop",
style = 'BAM.TButton',
command = self.model.Stop )
# Button for model.GetRecordVariables()
recordVarButton = ttk.Button( controlframe, text = "Record",
style = 'BAM.TButton',
command = self.GetRecordVariables )
# OptionMenu for variable timeseries plot types
self.plotVariable.set( constants.BasinPlotVariable[0] )
self.plotOptionMenu = Tk.OptionMenu( controlframe, self.plotVariable,
*constants.BasinPlotVariable )
self.plotOptionMenu.config ( font = constants.buttonFont )
self.plotOptionMenu['menu'].config( font = constants.buttonFont )
self.plotOptionMenu.config( bg = 'white' )
# Button for model.PlotRunData()
plotRunButton = ttk.Button( controlframe, text = "Plot Run",
style = 'BAM.TButton',
command = self.PlotRunData )
# Button for model.PlotArchiveData()
plotArchiveButton = ttk.Button( controlframe, text = "Plot Disk",
style = 'BAM.TButton',
command = self.PlotArchiveData )
# Button for PlotGaugeSalinityData()
# Can't set text color in ttk Button, use standard Tk
plotGaugeSalinityButton = Tk.Button( controlframe, text = "Salinity",
command = self.PlotGaugeSalinityData,
font = constants.buttonFont,
foreground = 'blue' )
# Button for PlotGaugeStageData()
# Can't set text color in ttk Button, use standard Tk
plotGaugeStageButton = Tk.Button( controlframe, text = "Stage",
command = self.PlotGaugeStageData,
font = constants.buttonFont,
foreground = 'blue' )
#-------------------------------------------------------------------
# Setup the window layout with the 'grid' geometry manager.
# The value of the "sticky" option is a string of 0 or more of the
# compass directions N S E W, specifying which edges of the cell the
# widget should be "stuck" to.
mainframe.grid( row = 0, column = 0, sticky = (Tk.N, Tk.W, Tk.E, Tk.S) )
controlframe.grid( in_ = mainframe, row = 1, column = 1,
rowspan = 3, sticky = (Tk.N, Tk.S) )
#-------------------------------------------------------------------
# Grid all the widgets - This is the layout of the window
# This application has 5 columns and 4 rows
# Column 1 row 1 has the controlframe with its own grid manager
# col 0 | col 1 | col 2 | col 3 | col 4
# row 0 Basin List | <----------- Message Text ----------->
# row 1 \/ | Controls | Model Time | Start | End
# row 2 \/ | \/ | <---------- Map --------->
# row 3 \/ | \/ | \/
#
#-------------------------------------------------------------------
self.basinListBox.grid( column = 0, row = 0, rowspan = 4,
sticky = (Tk.N,Tk.S,Tk.W,Tk.E) )
scrollBar.grid( column = 0, row = 0, rowspan = 4,
sticky = (Tk.E,Tk.N,Tk.S) )
self.msgText.grid( column = 1, row = 0, columnspan = 4,
sticky = (Tk.N,Tk.S,Tk.W,Tk.E) )
msgScrollBar.grid( column = 4, row = 0,
sticky = (Tk.E,Tk.N,Tk.S) )
currentTimeLabel.grid ( column = 2, row = 1 )
self.startTimeEntry.grid ( column = 3, row = 1 )
self.endTimeEntry.grid ( column = 4, row = 1 )
#-------------------------------------------------------------
# controlframe.grid is set above
self.mapOptionMenu.grid( in_ = controlframe, row = 0 )
initButton.grid ( in_ = controlframe, row = 1 )
runButton.grid ( in_ = controlframe, row = 2 )
pauseButton.grid ( in_ = controlframe, row = 3 )
stopButton.grid ( in_ = controlframe, row = 4 )
ttk.Separator( orient = Tk.HORIZONTAL ).grid( in_ = controlframe,
row = 5, pady = 5,
sticky = (Tk.E,Tk.W) )
recordVarButton.grid ( in_ = controlframe, row = 6 )
ttk.Separator( orient = Tk.HORIZONTAL ).grid( in_ = controlframe,
row = 7, pady = 5,
sticky = (Tk.E,Tk.W) )
self.plotOptionMenu.grid( in_ = controlframe, row = 8 )
plotRunButton.grid ( in_ = controlframe, row = 9 )
plotArchiveButton.grid ( in_ = controlframe, row = 10 )
ttk.Separator( orient = Tk.HORIZONTAL ).grid( in_ = controlframe,
row = 11, pady = 5,
sticky = (Tk.E,Tk.W) )
plotGaugeSalinityButton.grid( in_ = controlframe, row = 12,
sticky = (Tk.E,Tk.W) )
plotGaugeStageButton.grid ( in_ = controlframe, row = 13,
sticky = (Tk.E,Tk.W) )
#-------------------------------------------------------------
self.canvas.get_tk_widget().grid ( column = 2, row = 2,
columnspan = 3, rowspan = 2,
sticky = (Tk.N,Tk.S,Tk.W,Tk.E) )
# For each widget in the mainframe, set some padding around
# the widget to space things out and look better
for child in mainframe.winfo_children():
child.grid_configure( padx = 2, pady = 2 )
# Add a Sizegrip to make resizing easier.
#ttk.Sizegrip( mainframe ).grid( column = 99, row = 99,
# sticky = (Tk.N,Tk.S,Tk.E,Tk.W))
# Setup the resize control with the 'grid' geometry manager.
# Every column and row has a "weight" grid option associated with it,
# which tells it how much it should grow if there is extra room in
# the master to fill. By default, the weight of each column or row
# is 0, meaning don't expand to fill space. Here we set the weight
# to 1 telling the widget to expand and fill space as the window
# is resized.
# Make Sure to set on the root window!!!
self.Tk_root.columnconfigure( 0, weight = 1 )
self.Tk_root.rowconfigure ( 0, weight = 1 )
mainframe.columnconfigure( 0, weight = 0 )
mainframe.columnconfigure( 1, weight = 0 )
mainframe.columnconfigure( 2, weight = 1 )
#mainframe.columnconfigure( 3, weight = 1 )
#mainframe.columnconfigure( 4, weight = 1 )
mainframe.rowconfigure ( 0, weight = 1 )
mainframe.rowconfigure ( 1, weight = 0 )
mainframe.rowconfigure ( 2, weight = 1 )
mainframe.rowconfigure ( 3, weight = 1 )
# MapPlotVarUpdate() will refresh the legend on mapPlotVariable changes
self.mapPlotVariable.trace( 'w', self.MapPlotVarUpdate )
self.RenderShoals( init = True )
self.PlotLegend( "FloridaBayModel" )
self.canvas.draw()
#------------------------------------------------------------------
#
#------------------------------------------------------------------
def Message ( self, msg ) :
'''Display message in msgText box or on console, log to run_info.'''
if not self.model.args.noGUI :
self.msgText.insert( Tk.END, msg )
self.msgText.see ( Tk.END )
else :
print( msg, end = '' )
self.model.run_info.append( msg )
#------------------------------------------------------------------
#
#------------------------------------------------------------------
def MapPlotVarUpdate ( self, *args ) :
'''User has changed mapPlotVariable, update the legend.'''
if self.model.args.DEBUG_ALL :
print( '-> MapPlotVarUpdate: ', args[0], ', ', args[2] )
self.PlotLegend( "MapPlotVarUpdate" )
self.canvas.draw()
#-----------------------------------------------------------
#
#-----------------------------------------------------------
def InitPlotVars( self ):
'''Create map of plotVariables and Tk.IntVar() to associate
with the checkButtons accessed in GetRecordVariables(). These
Tk.IntVars are held in the plotVar_IntVars map, and read in
SetRecordVariables() to determine which variables will be
recorded into the basin.plot_variables maps for eventual
plotting and archiving'''
if self.model.args.DEBUG_ALL :
print( '-> InitPlotVars' )
self.plotVar_IntVars.clear()
for plotVariable in constants.BasinPlotVariable :
if not self.model.args.noGUI :
self.plotVar_IntVars[ plotVariable ] = Tk.IntVar()
else :
# Use the IntVar() class defined below
self.plotVar_IntVars[ plotVariable ] = IntVar()
# Set Salinity, Stage, Flow, Volume, Rain, ET as defaults
self.plotVar_IntVars[ 'Salinity' ].set( 1 )
self.plotVar_IntVars[ 'Stage' ].set( 1 )
self.plotVar_IntVars[ 'Flow' ].set( 1 )
self.plotVar_IntVars[ 'Volume' ].set( 1 )
self.plotVar_IntVars[ 'Rain' ].set( 1 )
self.plotVar_IntVars[ 'Evaporation' ].set( 1 )
self.plotVar_IntVars[ 'Runoff' ].set( 1 )
# Initialize the basin.plot_variables
for plotVariable, intVar in self.plotVar_IntVars.items() :
for basin in self.model.Basins.values() :
basin.plot_variables.clear()
if intVar.get() :
basin.plot_variables[ plotVariable ] = []
#-----------------------------------------------------------
#
#-----------------------------------------------------------
def GetRecordVariables( self ):
'''Pop up checkbuttons to select basin variables to record'''
if self.model.args.DEBUG_ALL :
print( '-> GetRecordVariables' )
#-------------------------------------------------------
# A top level pop up widget
top = Tk.Toplevel()
top.wm_title( 'Variables' )
top.minsize( width = 150, height = 100 )
top.grid()
setButton = ttk.Button( top, text = "Set",
style = 'BAM.TButton',
command = self.SetRecordVariables )
closeButton = ttk.Button( top, text = "Close",
style = 'BAM.TButton',
command = lambda: top.destroy() )
checkButtons = odict()
for plotVariable in constants.BasinPlotVariable :
checkButtons[ plotVariable ] = \
ttk.Checkbutton( top, text = plotVariable,
style = 'BAM.TCheckbutton',
variable = self.plotVar_IntVars[plotVariable])
for checkButton in checkButtons.values() :
checkButton.grid( sticky = Tk.W,
padx = 30, pady = 3 )
setButton.grid ( padx = 15, pady = 2 )
closeButton.grid( padx = 15, pady = 2 )
#-----------------------------------------------------------
#
#-----------------------------------------------------------
def SetRecordVariables( self ):
'''Callback method for Set button in GetRecordVariables().
Sets the basin.plot_variables entries based on the selected
plotVariable checkboxes in GetRecordVariables()'''
if self.model.args.DEBUG_ALL :
print( '-> SetRecordVariables' )
for plotVariable, intVar in self.plotVar_IntVars.items() :
print( plotVariable, ' : ', intVar, '=', intVar.get() )
# Reset time and basins
InitTimeBasins( self.model )
msg ='*** All records erased, time reset to start time, basins reset.\n'
self.Message( msg )
for plotVariable, intVar in self.plotVar_IntVars.items() :
for basin in self.model.Basins.values() :
basin.plot_variables.clear()
if intVar.get() :
basin.plot_variables[ plotVariable ] = []
#----------------------------------------------------------------
#
#----------------------------------------------------------------
def PlotRunData( self ) :
'''Plot data for selected basins from the current simulation.'''
if self.model.args.DEBUG_ALL :
print( '-> PlotRunData', flush = True )
# Get a list of Basins from the Listbox
BasinList = self.GetBasinListbox()
if len( BasinList ) == 0 :
msg = '\nPlotRunData: No basins are selected.\n'
self.Message( msg )
return
# Get the plotVariable type from the plotOptionMenu
plotVariable = self.plotVariable.get()
# Get the data
dataList = []
basinNames = []
for Basin in BasinList :
if plotVariable not in Basin.plot_variables.keys() :
msg = '\nPlotRunData: ' + plotVariable + ' data ' +\
'is not present for basin ' + Basin.name + '.\n'
self.Message( msg )
return
dataList.append( Basin.plot_variables[ plotVariable ] )
basinNames.append( Basin.name )
self.PlotData( self.model.times, dataList, basinNames, plotVariable,
period_record_days = self.model.simulation_days )
#----------------------------------------------------------------
#
#----------------------------------------------------------------
def PlotArchiveData( self ) :
'''Plot data from a previous run stored on disk.'''
if self.model.args.DEBUG :
print( '-> PlotArchiveData', flush = True )
# Get a list of Basins from the Listbox
BasinList = self.GetBasinListbox()
if len( BasinList ) == 0 :
msg = '\nPlotArchiveData: No basins are selected.\n'
self.Message( msg )
return
self.last_plot_dir = self.plot_dir
if self.model.args.DEBUG :
print( self.plot_dir )
# Get the data into
all_times = []
times = []
basinNames = []
dataList = []
# Get the plotVariable type from the plotOptionMenu
plotVariable = self.plotVariable.get()
for Basin in BasinList :
basinNames.append( Basin.name )
# Read the basin .csv data to get [times] and [data]
file_name = path_join( self.plot_dir,
Basin.name + self.model.args.runID + '.csv' )
try :
fd = open( file_name, 'r' )
except OSError as err :
msg = "\nPlotArchiveData: OS error: {0}\n".format( err )
self.Message( msg )
return
rows = fd.readlines()
fd.close()
# Time, Stage (m), Flow (m^3/t), Salinity (ppt), Volume (m^3)
# 2000-01-01 00:00:00, 0.0, 0.0, 37.0, 52475622.557
# 2000-01-01 01:00:00, -0.0, 45.772, 37.0, 52459564.487
variables = rows[ 0 ].split(',')
for i in range( len( variables ) ) :
variables[ i ] = variables[ i ].strip()
# column index for Time
time_col_i = variables.index( 'Time' )
# column index for plotVariable
try :
unit_str = constants.PlotVariableUnit[ plotVariable ]
data_col_i = variables.index( plotVariable + ' ' + unit_str )
except ValueError as err :
msg = "\nPlotArchiveData: {0}\n".format( err )
self.Message( msg )
return
# Get all times in file from first Basin in BasinList
if Basin == BasinList[ 0 ] :
for i in range( 1, len( rows ) ) :
words = rows[ i ].split(',')
time_i = datetime.strptime( words[ time_col_i ].strip(),
'%Y-%m-%d %H:%M:%S' )
all_times.append( time_i )
# Find index in dates for start_time & end_time
start_i, end_i = GetTimeIndex( plotVariable, all_times,
self.model.start_time,
self.model.end_time )
# Populate only data needed for the simulation timeframe
times = all_times[ start_i : end_i + 1 ]
data = []
for i in range( start_i, end_i + 1 ) :
row = rows[ i + 1 ]
words = row.split(',')
value_string = words[ data_col_i ]
if 'NA' in value_string :
data.append( npNaN )
else :
data.append( float( value_string ) )
# If data is all NA don't plot
if npall( isnan( data ) ) :
msg = "\nPlotArchiveData: " + plotVariable + ' for basin ' +\
Basin.name + ' does not exist.\n'
self.Message( msg )
else :
dataList.append( data )
period_record = times[ len( times ) - 1 ] - times[ 0 ] # timedelta
self.PlotData( times, dataList, basinNames, plotVariable,
period_record_days = period_record.days,
path = ' from: ' + self.plot_dir )
#----------------------------------------------------------------
#
#----------------------------------------------------------------
def PlotGaugeSalinityData( self ) :
'''Plot salinity data from gauge observations.'''
if self.model.args.DEBUG :
print( '-> PlotGaugeSalinityData', flush = True )
BasinList = self.GetBasinListbox()
if len( BasinList ) == 0 :
msg = '\nPlotGaugeSalinityData: No basins are selected.\n'
self.Message( msg )
return
basin_names = [ Basin.name for Basin in BasinList ]
# Read the salinity .csv gauge data to get [times] and [data]
if not self.model.salinity_data :
GetBasinSalinityData( self.model )
# plotVariables are salinity stations IDs : 'MD', 'GB'...
plotVariables = []
for Basin in BasinList :
if Basin.salinity_station :
plotVariables.append( Basin.salinity_station )
# Get times[] from model.salinity_data.keys()
times = [ datetime( year = key_tuple[0],
month = key_tuple[1],
day = key_tuple[2] )
for key_tuple in self.model.salinity_data.keys() ]
# Get data
dataList = []
for plotVariable in plotVariables :
data = []
for key in self.model.salinity_data.keys() :
data.append( self.model.salinity_data[key][plotVariable] )
dataList.append( data )
if not dataList :
msg = 'No salinity gauge data for these basins.\n'
self.Message( msg )
return
period_record = times[ -1 ] - times[ 0 ] # timedelta
self.PlotData( times, dataList,
basinNames = basin_names,
plotVariable = 'Salinity',
period_record_days = period_record.days,
title = 'Gauge: ',
path = ' from: ' + self.model.args.salinityFile )
#----------------------------------------------------------------
#
#----------------------------------------------------------------
def PlotGaugeStageData( self ) :
'''Plot stage data from gauge observations.'''
if self.model.args.DEBUG :
print( '-> PlotGaugeStageData', flush = True )
BasinList = self.GetBasinListbox()
if len( BasinList ) == 0 :
msg = '\nPlotGaugeStageData: No basins are selected.\n'
self.Message( msg )
return
basin_names = [ Basin.name for Basin in BasinList ]
# Read the stage .csv gauge data to get [times] and [data]
if not self.model.stage_data :
GetBasinStageData( self.model )
# plotVariables are stations IDs : 'MD', 'GB'...
# which are the same as the salinity_station
plotVariables = []
for Basin in BasinList :
if Basin.salinity_station :
plotVariables.append( Basin.salinity_station )
# Get times[] from model.salinity_data.keys()
times = [ datetime( year = key_tuple[0],
month = key_tuple[1],
day = key_tuple[2] )
for key_tuple in self.model.stage_data.keys() ]
# Get data
dataList = []
for plotVariable in plotVariables :
data = []
for key in self.model.stage_data.keys() :
try :
data.append( self.model.stage_data[ key ][ plotVariable ] )
except KeyError :
msg = 'No stage gauge data for ' + plotVariable + '.\n'
self.Message( msg )
break
if data :
dataList.append( data )
if not dataList :
msg = 'No stage gauge data for these basins.\n'
self.Message( msg )
return
period_record = times[ -1 ] - times[ 0 ] # timedelta
self.PlotData( times, dataList,
basinNames = basin_names,
plotVariable = 'Stage',
period_record_days = period_record.days,
title = 'Gauge: ',
path = ' from: ' + self.model.args.basinStage )
#----------------------------------------------------------------
#
#----------------------------------------------------------------
def PlotData( self, time, dataList, basinNames, plotVariable,
period_record_days, title = 'Basins: ', path = '' ) :
''' '''
if self.model.args.DEBUG_ALL :
print( '-> PlotData', flush = True )
for Basin in BasinList :
print( '\t', Basin.name, '\t: ', plotVariable )
if not len( dataList ) or not len( time ):
return
#-------------------------------------------------------
# A top level pop up widget
top = Tk.Toplevel()
top.wm_title( title + plotVariable + path )
colors = iter( cm.rainbow( linspace( 0, 1, len( dataList ) ) ) )
color = next( colors )
figure = Figure( figsize = ( 8, 5 ), dpi = 100 )
axes = figure.add_subplot( 111, label = "PlotData" )
axes.plot( time, dataList[ 0 ], label = basinNames[ 0 ],
linewidth = 2, color = color )
for i in range( 1, len( dataList ) ) :
color = next( colors )
axes.plot( time, dataList[ i ],
label = basinNames[ i ],
linewidth = 2, color = color )
axes.set_xlabel( 'Date' )
axes.set_ylabel( plotVariable + ' ' +\
constants.PlotVariableUnit[ plotVariable ] )
axes.fmt_xdata = DateFormatter('%Y-%m-%d')
# matplotlib does not default ticks well... arghhh
if period_record_days < 15 :
axes.xaxis.set_major_locator ( DayLocator() )
axes.xaxis.set_major_formatter( DateFormatter('%d') )
elif period_record_days < 91 :
axes.xaxis.set_major_locator ( MonthLocator() )
axes.xaxis.set_major_formatter( DateFormatter('%m-%d') )
axes.xaxis.set_minor_locator ( DayLocator(bymonthday=[7,14,21]))
axes.xaxis.set_minor_formatter( DateFormatter('%d') )
elif period_record_days < 181 :
axes.xaxis.set_major_locator ( MonthLocator() )
axes.xaxis.set_major_formatter( DateFormatter('%b-%d') )
axes.xaxis.set_minor_locator ( DayLocator(bymonthday=[15]))
axes.xaxis.set_minor_formatter( DateFormatter('%d') )
elif period_record_days < 366 :
axes.xaxis.set_major_locator ( MonthLocator() )
axes.xaxis.set_major_formatter( DateFormatter('%b') )
elif period_record_days < 731 :
axes.xaxis.set_major_locator ( YearLocator() )
axes.xaxis.set_major_formatter( DateFormatter('%Y') )
axes.xaxis.set_minor_locator ( MonthLocator(bymonth=[3,5,7,9,11]))
axes.xaxis.set_minor_formatter( DateFormatter('%b') )
elif period_record_days < 1826 :
axes.xaxis.set_major_locator ( YearLocator() )
axes.xaxis.set_major_formatter( DateFormatter('%Y') )
axes.xaxis.set_minor_locator ( MonthLocator(bymonth=[7]) )
axes.xaxis.set_minor_formatter( DateFormatter('%b') )
else :
axes.xaxis.set_major_locator ( YearLocator() )
axes.xaxis.set_major_formatter( DateFormatter('%Y') )
legend = axes.legend( loc = 'upper center', fontsize = 9,
frameon = False, labelspacing = None )
#figure.autofmt_xdate( bottom = 0.2, rotation = 90 )
figure.set_tight_layout( True ) # tight_layout()
# Tk.DrawingArea
canvas = FigureCanvasTkAgg( figure, master = top )
try :
canvas.draw()
except RuntimeError as err :
msg = "\nPlotData: {0}. \n".format( err ) +\
" Try setting the start/end time to cover the data record.\n"
self.Message( msg )
top.destroy()
return
canvas.get_tk_widget().pack( side = Tk.TOP, fill = Tk.BOTH,
expand = True )
toolbar = NavigationToolbar2Tk( canvas, top )
toolbar.update()
canvas._tkcanvas.pack( side = Tk.TOP, fill = Tk.BOTH, expand = True )
#----------------------------------------------------------------
#
#----------------------------------------------------------------
def RenderBasins( self, init = False ):
''' '''
for Basin in self.model.Basins.values() :
if Basin.boundary_basin :
continue
basin_xy = Basin.basin_xy
if basin_xy is None :
continue
basin_name = Basin.name
if init :
# Initialize Basin.color with salinity color
Basin.SetBasinMapColor( 'Salinity',
self.model.args.salinity_legend_bounds )
if not Basin.Axes_fill :
PolygonList = self.figure_axes.fill(
basin_xy[:,0], basin_xy[:,1],
fc = Basin.color,
ec = 'white',
zorder = -1,
picker = True,
label = basin_name ) # NOTE: this is a list...!
Basin.Axes_fill = PolygonList[ 0 ]
else :
# Don't call fill() again if not init, it creates a new Polygon
Basin.Axes_fill.set_color( Basin.color )
#----------------------------------------------------------------
#
#----------------------------------------------------------------
def RenderShoals( self, init = False ):
''' '''
for Shoal in self.model.Shoals.values():
line_xy = Shoal.line_xy
if line_xy is None :
continue
shoal_number = Shoal.name
if init :
Line2D_List = self.figure_axes.plot( line_xy[:,0],
line_xy[:,1],
#color,
linewidth = 3,
label = shoal_number,
picker = True )
Shoal.Axes_plot = Line2D_List[ 0 ]
else :
Shoal.Axes_plot.set_color( (1, 1, 1) )
#----------------------------------------------------------------
#
#----------------------------------------------------------------
def PlotLegend( self, label, init = True ) :
''' '''
if self.model.args.DEBUG_ALL:
print( '-> PlotLegend', flush = True )
# Add an axes at position rect [left, bottom, width, height]
# where all quantities are in fractions of figure width and height.
# Just returns the existing axis if it already exists
legendAxis = self.figure.add_axes( [ 0.05, 0.95, 0.7, 0.03 ],
label = 'PlotLegend' + label )
legend_color_map = ListedColormap( self.colors )