/
HydroCalc2.py
2161 lines (1686 loc) · 72.9 KB
/
HydroCalc2.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
# -*- coding: utf-8 -*-
# Copyright © 2014-2018 GWHAT Project Contributors
# https://github.com/jnsebgosselin/gwhat
#
# This file is part of GWHAT (Ground-Water Hydrograph Analysis Toolbox).
# Licensed under the terms of the GNU General Public License.
# ---- Standard library imports
from time import clock
import csv
import os
import os.path as osp
import datetime
# ---- Third party imports
import numpy as np
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSlot as QSlot
from PyQt5.QtCore import pyqtSignal as QSignal
from PyQt5.QtWidgets import (
QGridLayout, QComboBox, QTextEdit, QSizePolicy, QPushButton, QLabel,
QTabWidget, QApplication, QWidget)
import matplotlib as mpl
import matplotlib.dates as mdates
from matplotlib.figure import Figure as MplFigure
from matplotlib.patches import Rectangle
from matplotlib.transforms import ScaledTranslation
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT
from xlrd import xldate_as_tuple
from xlrd.xldate import xldate_from_date_tuple
# ---- Local imports
from gwhat.gwrecharge.gwrecharge_gui import RechgEvalWidget
import gwhat.common.widgets as myqt
from gwhat.common.widgets import DialogWindow
from gwhat.common import StyleDB
from gwhat.utils import icons
from gwhat.utils.icons import QToolButtonNormal
from gwhat.widgets.buttons import ToolBarWidget
from gwhat.brf_mod import BRFManager
from gwhat.widgets.buttons import OnOffToolButton
from gwhat.widgets.layout import VSep
from gwhat.widgets.fileio import SaveFileMixin
class WLCalc(DialogWindow, SaveFileMixin):
"""
This is the interface where are plotted the water level time series. It is
possible to dynamically zoom and span the data, change the display,
i.e. display the data as a continuous line or individual dot, perform a
MRC and ultimately estimate groundwater recharge.
"""
sig_new_mrc = QSignal()
def __init__(self, datamanager, parent=None):
DialogWindow.__init__(self, parent, maximize=True)
SaveFileMixin.__init__(self)
self._navig_and_select_tools = []
self._wldset = None
self.dmngr = datamanager
self.dmngr.wldsetChanged.connect(self.set_wldset)
self.dmngr.wxdsetChanged.connect(self.set_wxdset)
self.dmngr.sig_workdir_changed.connect(self.set_dialog_dir)
# Setup recharge calculation tool.
self.rechg_eval_widget = RechgEvalWidget(parent=self)
self.rechg_eval_widget.sig_new_gluedf.connect(self.draw_glue_wl)
# Setup BRF calculation tool.
self.brf_eval_widget = BRFManager(parent=self)
self.brf_eval_widget.sig_brfperiod_changed.connect(self.plot_brfperiod)
self.brf_eval_widget.btn_seldata.sig_value_changed.connect(
lambda: self.toggle_brfperiod_selection(
self.brf_eval_widget.btn_seldata.value())
)
self.register_navig_and_select_tool(self.brf_eval_widget.btn_seldata)
self.__figbckground = None
self.__addPeakVisible = True
self.__mouse_btn_is_pressed = False
# Calcul the delta between the datum of Excel and Maplotlib numeric
# date system.
t_xls = xldate_from_date_tuple((2000, 1, 1), 0)
t_mpl = mpl.dates.date2num(datetime.datetime(2000, 1, 1))
self.dt4xls2mpl = t_mpl - t_xls
# The date format can either be 0 for Excel format or 1 for Matplotlib
# format.
self.dformat = 1
# Recession Curve Parameters :
self.peak_indx = np.array([]).astype(int)
self.peak_memory = [np.array([]).astype(int)]
# Selected water level data.
self.wl_selected_i = []
# Soil Profiles :
self.soilFilename = []
self.SOILPROFIL = SoilProfil()
# Initialize the GUI
self.precip_bwidth = 7
self._setup_mpl_canvas()
self.__initUI__()
self.btn_pan.setValue(True)
self.setup_ax_margins(None)
self.set_wldset(self.dmngr.get_current_wldset())
self.set_wxdset(self.dmngr.get_current_wxdset())
def _setup_mpl_canvas(self):
# ---- Setup the canvas
self.fig = MplFigure(facecolor='white')
self.canvas = FigureCanvasQTAgg(self.fig)
self.canvas.mpl_connect('button_press_event', self.onclick)
self.canvas.mpl_connect('button_release_event', self.onrelease)
self.canvas.mpl_connect('resize_event', self.setup_ax_margins)
self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas.mpl_connect('figure_leave_event', self.on_fig_leave)
self.canvas.mpl_connect('axes_enter_event', self.on_axes_enter)
self.canvas.mpl_connect('axes_leave_event', self.on_axes_leave)
# ---- Setup the canvas frame
# Put figure canvas in a QFrame widget.
self.fig_frame_widget = myqt.QFrameLayout()
self.fig_frame_widget.addWidget(self.canvas, 0, 0)
self.fig_frame_widget.setFrameStyle(StyleDB().frame)
self.fig_frame_widget.setLineWidth(2)
self.fig_frame_widget.setMidLineWidth(1)
# ----- Setup the axes
# Water Level (Host) :
ax0 = self.fig.add_axes([0, 0, 1, 1], zorder=100)
ax0.patch.set_visible(False)
ax0.invert_yaxis()
# Precipitation :
ax1 = ax0.twinx()
ax1.patch.set_visible(False)
ax1.set_zorder(50)
ax1.set_navigate(False)
# ---- Setup ticks
ax0.xaxis.set_ticks_position('bottom')
ax0.tick_params(axis='x', direction='out')
ax0.yaxis.set_ticks_position('left')
ax0.tick_params(axis='y', direction='out')
ax1.yaxis.set_ticks_position('right')
ax1.tick_params(axis='y', direction='out')
# ---- Setup axis labels
ax0.set_ylabel('Water level (mbgs)', fontsize=14, labelpad=25,
va='top', color='black')
ax0.set_xlabel('Time (days)', fontsize=14, labelpad=25,
va='bottom', color='black')
ax1.set_ylabel('Precipitation (mm)', fontsize=14, labelpad=25,
va='top', color='black', rotation=270)
# ---- Setup gridlines
# ax0.grid(axis='x', color=[0.35, 0.35, 0.35], ls='--')
# ax0.set_axisbelow(True)
# ---- Setup the artists
# Water level data.
self._obs_wl_plt, = ax0.plot(
[], [], color='blue', clip_on=True, ls='-', zorder=10,
marker='None')
self._select_wl_plt, = ax0.plot(
[], [], color='orange', clip_on=True, ls='None', zorder=10,
marker='.', mfc='orange', mec='orange', ms=5, mew=1.5)
# Water levels measured manually.
self._meas_wl_plt, = ax0.plot(
[], [], clip_on=True, ls='none', zorder=10, marker='+', ms=8,
mec='red', mew=2, mfc='red')
# Predicted water levels.
self.plt_wlpre, = ax0.plot([], [], color='red', clip_on=True,
ls='-', zorder=10, marker='None')
# Recession.
self._mrc_plt, = ax0.plot([], [], color='red', clip_on=True,
zorder=15, marker='None', linestyle='--')
# Rain.
self.h_rain, = ax1.plot([], [])
# Precipitation.
self.h_ptot, = ax1.plot([], [])
# Evapotranspiration.
self.h_etp, = ax1.plot([], [], color='#FF6666', lw=1.5, zorder=500,
ls='-')
# Barometric response function (BRF).
self.h_brf1 = ax0.axvline(0, color='red', lw=1)
self.h_brf2 = ax0.axvline(0, color='red', lw=1)
self._selected_brfperiod = [None, None]
self._brf_selector = ax0.axvspan(
0, 0, edgecolor='black', facecolor='red', linestyle=':',
fill=True, alpha=0.15, visible=False)
# Predicted GLUE water levels
self.glue_plt, = ax0.plot([], [])
# Rectangular selection box.
self._rect_selection = [(None, None), (None, None)]
self._rect_selector = Rectangle(
(0, 0), 0, 0, edgecolor='black', facecolor='red', linestyle=':',
fill=True, alpha=0.15, visible=False)
ax0.add_patch(self._rect_selector)
# Vertical guide line under cursor.
self.vguide = ax0.axvline(
-1, color='black', zorder=40, linestyle='--', lw=1, visible=False)
# x and y coorrdinate labels displayed at the right-bottom corner
# of the graph
offset = ScaledTranslation(-5/72, 5/72, self.fig.dpi_scale_trans)
self.xycoord = ax0.text(
1, 0, '', ha='right', transform=ax0.transAxes + offset)
self.xycoord.set_visible(False)
# Peaks :
self._peaks_plt, = ax0.plot(
[], [], color='white', clip_on=True, zorder=30, marker='o',
linestyle='None', mec='red', mew=1.5)
# Cross Remove Peaks :
self.xcross, = ax0.plot(1, 0, color='red', clip_on=True,
zorder=20, marker='x', linestyle='None',
markersize=15, markeredgewidth=3)
def _setup_toolbar(self):
"""Setup the main toolbar of the water level calc tool."""
# ---- Navigate data.
self.toolbar = NavigationToolbar2QT(self.canvas, parent=self)
self.toolbar.hide()
self.btn_home = QToolButtonNormal(icons.get_icon('home'))
self.btn_home.setToolTip('Reset original view.')
self.btn_home.clicked.connect(self.home)
self.btn_fit_waterlevels = QToolButtonNormal('expand_all')
self.btn_fit_waterlevels.setToolTip(
"<p>Best fit the water level data along the x and y axis.</p>")
self.btn_fit_waterlevels.clicked.connect(self.setup_axis_range)
self.btn_pan = OnOffToolButton('pan', size='normal')
self.btn_pan.setToolTip(
'Pan axes with the left mouse button and zoom with the right')
self.btn_pan.sig_value_changed.connect(self.pan_is_active_changed)
self.register_navig_and_select_tool(self.btn_pan)
self.btn_zoom_to_rect = OnOffToolButton('zoom_to_rect', size='normal')
self.btn_zoom_to_rect.setToolTip(
"Zoom into the rectangle with the left mouse button and zoom"
" out with the right mouse button.")
self.btn_zoom_to_rect.sig_value_changed.connect(
self.zoom_is_active_changed)
self.register_navig_and_select_tool(self.btn_zoom_to_rect)
self.btn_wl_style = OnOffToolButton('showDataDots', size='normal')
self.btn_wl_style.setToolTip(
'<p>Show water lvl data as dots instead of a continuous line</p>')
self.btn_wl_style.sig_value_changed.connect(self.setup_wl_style)
self.btn_strati = QToolButtonNormal(icons.get_icon('stratigraphy'))
self.btn_strati.setToolTip('Toggle on and off the display of the soil'
' stratigraphic layers')
self.btn_strati.clicked.connect(self.btn_strati_isClicked)
self.btn_dateFormat = QToolButtonNormal(icons.get_icon('calendar'))
self.btn_dateFormat.setToolTip(
'Show x-axis tick labels as Excel numeric format.')
self.btn_dateFormat.clicked.connect(self.switch_date_format)
self.btn_dateFormat.setAutoRaise(False)
# dformat: False -> Excel Numeric Date Format
# True -> Matplotlib Date Format
# ---- Show/Hide section
self.btn_show_glue = OnOffToolButton('show_glue_wl', size='normal')
self.btn_show_glue.setToolTip(
"Show or hide GLUE water level 05/95 envelope.")
self.btn_show_glue.sig_value_changed.connect(self.draw_glue_wl)
self.btn_show_glue.setValue(True, silent=True)
self.btn_show_weather = OnOffToolButton('show_meteo', size='normal')
self.btn_show_weather.setToolTip("""Show or hide weather data.""")
self.btn_show_weather.sig_value_changed.connect(self.draw_weather)
self.btn_show_weather.setValue(True, silent=True)
self.btn_show_mrc = OnOffToolButton('mrc_calc', size='normal')
self.btn_show_mrc.setToolTip(
"Show or hide water levels predicted with the MRC.")
self.btn_show_mrc.sig_value_changed.connect(
self.btn_show_mrc_isclicked)
self.btn_show_mrc.setValue(True, silent=True)
self.btn_show_meas_wl = OnOffToolButton(
'manual_measures', size='normal')
self.btn_show_meas_wl.setToolTip(
"Show or hide water levels measured manually in the well.")
self.btn_show_meas_wl.setValue(True, silent=True)
self.btn_show_meas_wl.sig_value_changed.connect(self.draw_meas_wl)
# ---- Select and transform data.
self.btn_rect_select = OnOffToolButton('rect_select', size='normal')
self.btn_rect_select.setToolTip(
"Select water level data by clicking with the mouse and "
"dragging the cursor over a rectangular region of the graph.")
self.btn_rect_select.sig_value_changed.connect(
self.rect_select_is_active_changed)
self.register_navig_and_select_tool(self.btn_rect_select)
self.btn_clear_select = QToolButtonNormal('rect_select_clear')
self.btn_clear_select.setToolTip("Clear selected water levels.")
self.btn_clear_select.clicked.connect(
lambda: self.clear_selected_wl(draw=True))
self.btn_del_select = QToolButtonNormal('erase_data')
self.btn_del_select.setToolTip(
"Remove the selected water level data from the dataset.")
self.btn_del_select.clicked.connect(self.delete_selected_wl)
self.btn_undo_changes = QToolButtonNormal('undo_changes')
self.btn_undo_changes.setToolTip(
"Undo the last changes made to the water level data.")
self.btn_undo_changes.setEnabled(False)
self.btn_undo_changes.clicked.connect(self.undo_wl_changes)
self.btn_clear_changes = QToolButtonNormal('clear_changes')
self.btn_clear_changes.setToolTip(
"Clear all changes made to the water level data since the last "
"commit.")
self.btn_clear_changes.clicked.connect(self.clear_all_changes)
self.btn_clear_changes.setEnabled(False)
self.btn_commit_changes = QToolButtonNormal('commit_changes')
self.btn_commit_changes.clicked.connect(self.commit_wl_changes)
self.btn_commit_changes.setEnabled(False)
# Setup the layout.
toolbar = ToolBarWidget()
for btn in [self.btn_home, self.btn_fit_waterlevels, self.btn_pan,
self.btn_zoom_to_rect, None,
self.btn_wl_style, self.btn_dateFormat, None,
self.btn_show_glue, self.btn_show_weather,
self.btn_show_mrc, self.btn_show_meas_wl, None,
self.btn_rect_select, self.btn_clear_select,
self.btn_del_select, self.btn_undo_changes,
self.btn_clear_changes, self.btn_commit_changes]:
toolbar.addWidget(btn)
return toolbar
def _setup_mrc_tool(self):
"""Setup the tool to evaluate the MRC."""
# ---- MRC parameters
self.MRC_type = QComboBox()
self.MRC_type.addItems(['Linear', 'Exponential'])
self.MRC_type.setCurrentIndex(1)
self.MRC_ObjFnType = QComboBox()
self.MRC_ObjFnType.addItems(['RMSE', 'MAE'])
self.MRC_ObjFnType.setCurrentIndex(0)
self.MRC_results = QTextEdit()
self.MRC_results.setReadOnly(True)
self.MRC_results.setMinimumHeight(25)
self.MRC_results.setMinimumWidth(100)
self.MRC_results.setSizePolicy(
QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred))
# ---- MRC toolbar
self.btn_undo = QToolButtonNormal(icons.get_icon('undo'))
self.btn_undo.setToolTip('Undo')
self.btn_undo.setEnabled(False)
self.btn_undo.clicked.connect(self.undo)
self.btn_clearPeak = QToolButtonNormal(icons.get_icon('clear_search'))
self.btn_clearPeak.setToolTip('Clear all extremum from the graph')
self.btn_clearPeak.clicked.connect(self.clear_all_peaks)
self.btn_addpeak = OnOffToolButton('add_point', size='normal')
self.btn_addpeak.sig_value_changed.connect(self.btn_addpeak_isclicked)
self.btn_addpeak.setToolTip(
"<p>Toggle edit mode to manually add extremums to the graph</p>")
self.register_navig_and_select_tool(self.btn_addpeak)
self.btn_delpeak = OnOffToolButton('erase', size='normal')
self.btn_delpeak.clicked.connect(self.btn_delpeak_isclicked)
self.btn_delpeak.setToolTip(
"<p>Toggle edit mode to manually remove extremums"
" from the graph</p>")
self.register_navig_and_select_tool(self.btn_delpeak)
self.btn_save_mrc = QToolButtonNormal(icons.get_icon('save'))
self.btn_save_mrc.setToolTip('Save calculated MRC to file.')
self.btn_save_mrc.clicked.connect(self.save_mrc_tofile)
self.btn_MRCalc = QPushButton('Compute MRC')
self.btn_MRCalc.clicked.connect(self.btn_MRCalc_isClicked)
self.btn_MRCalc.setToolTip('<p>Calculate the Master Recession Curve'
' (MRC) for the selected time periods.</p>')
mrc_tb = ToolBarWidget()
for btn in [self.btn_undo, self.btn_clearPeak, self.btn_addpeak,
self.btn_delpeak, self.btn_save_mrc]:
mrc_tb.addWidget(btn)
# ---- MRC Layout ----
self.mrc_eval_widget = QWidget()
mrc_lay = QGridLayout(self.mrc_eval_widget)
row = 0
mrc_lay.addWidget(QLabel('MRC Type :'), row, 0)
mrc_lay.addWidget(self.MRC_type, row, 1)
row += 1
mrc_lay.addWidget(self.MRC_results, row, 0, 1, 3)
row += 1
mrc_lay.addWidget(mrc_tb, row, 0, 1, 3)
row += 1
mrc_lay.setRowMinimumHeight(row, 5)
mrc_lay.setRowStretch(row, 100)
row += 1
mrc_lay.addWidget(self.btn_MRCalc, row, 0, 1, 3)
mrc_lay.setContentsMargins(10, 10, 10, 10)
mrc_lay.setSpacing(5)
mrc_lay.setColumnStretch(2, 500)
return self.mrc_eval_widget
def __initUI__(self):
self.setWindowTitle('Hydrograph Analysis')
toolbar = self._setup_toolbar()
self.mrc_eval_widget = self._setup_mrc_tool()
# ---- Tool Tab Area
tooltab = QTabWidget()
tooltab.addTab(self.mrc_eval_widget, 'MRC')
tooltab.setTabToolTip(
0, ("<p>A tool to evaluate the master recession curve"
" of the hydrograph.</p>"))
tooltab.addTab(self.rechg_eval_widget, 'Recharge')
tooltab.setTabToolTip(
1, ("<p>A tool to evaluate groundwater recharge and its"
" uncertainty from observed water levels and daily "
" weather data.</p>"))
tooltab.addTab(self.brf_eval_widget, 'BRF')
tooltab.setTabToolTip(
2, ("<p>A tool to evaluate the barometric response function of"
" the well.</p>"))
tooltab.currentChanged.connect(
lambda: self.toggle_brfperiod_selection(False))
# ---- Right Panel
self.right_panel = myqt.QFrameLayout()
row = 0
self.right_panel.addWidget(self.dmngr, row, 0)
row += 1
self.right_panel.addWidget(tooltab, row, 0)
row += 1
self.right_panel.setRowStretch(row, 100)
self.right_panel.setSpacing(15)
# ---- Setup the main layout
mainGrid = QGridLayout(self)
mainGrid.addWidget(toolbar, 0, 0)
mainGrid.addWidget(self.fig_frame_widget, 1, 0, 2, 1)
mainGrid.addWidget(VSep(), 0, 1, 3, 1)
mainGrid.addWidget(self.right_panel, 0, 2, 2, 1)
mainGrid.setContentsMargins(10, 10, 10, 10) # (L, T, R, B)
mainGrid.setHorizontalSpacing(15)
mainGrid.setRowStretch(1, 100)
# mainGrid.setRowStretch(2, 100)
mainGrid.setColumnStretch(0, 100)
mainGrid.setColumnMinimumWidth(2, 250)
@property
def water_lvl(self):
return np.array([]) if self.wldset is None else self.wldset.waterlevels
@property
def time(self):
return np.array([]) if self.wldset is None else self.wldset.xldates
@property
def wldset(self):
return self._wldset
@property
def wxdset(self):
return self.dmngr.get_current_wxdset()
def set_wldset(self, wldset):
"""Set the namespace for the water level dataset."""
self._wldset = wldset
self.rechg_eval_widget.set_wldset(wldset)
self.mrc_eval_widget.setEnabled(self.wldset is not None)
# Setup BRF widget.
self.brf_eval_widget.set_wldset(wldset)
self.plot_brfperiod()
self.setup_hydrograph()
self.toolbar.update()
self.load_mrc_from_wldset()
def set_wxdset(self, wxdset):
"""Set the weather dataset."""
self.rechg_eval_widget.set_wxdset(wxdset)
self.draw_weather()
# ---- MRC handlers
def btn_show_mrc_isclicked(self):
"""Handle when the button to draw of hide the mrc is clicked."""
if self.btn_show_mrc.value() is False:
self.btn_addpeak.setValue(False)
self.btn_delpeak.setValue(False)
self.draw_mrc()
def btn_MRCalc_isClicked(self):
if self.wldset is None:
return
QApplication.setOverrideCursor(Qt.WaitCursor)
A, B, hp, RMSE = mrc_calc(self.time, self.water_lvl, self.peak_indx,
self.MRC_type.currentIndex())
print('MRC Parameters: A=%f, B=%f' % (A, B))
if A is None:
QApplication.restoreOverrideCursor()
return
# Display result :
txt = '∂h/∂t (mm/d) = -%0.2f h + %0.2f' % (A*1000, B*1000)
self.MRC_results.setText(txt)
txt = '%s = %f m' % (self.MRC_ObjFnType.currentText(), RMSE)
self.MRC_results.append(txt)
self.MRC_results.append('\nwhere h is the depth to water '
'table in mbgs and ∂h/∂t is the recession '
'rate in mm/d.')
# Store and plot the results.
print('Saving MRC interpretation in dataset...')
self.wldset.set_mrc(A, B, self.peak_indx, self.time, hp)
self.btn_save_mrc.setEnabled(True)
self.draw_mrc()
self.sig_new_mrc.emit()
QApplication.restoreOverrideCursor()
def load_mrc_from_wldset(self):
"""Load saved MRC results from the project hdf5 file."""
if self.wldset is not None and self.wldset.mrc_exists():
self.peak_indx = self.wldset['mrc/peak_indx'].astype(int)
self.peak_memory[0] = self.wldset['mrc/peak_indx'].astype(int)
self.btn_save_mrc.setEnabled(True)
else:
self.peak_indx = np.array([]).astype(int)
self.peak_memory = []
self.btn_save_mrc.setEnabled(False)
self.draw_mrc()
def save_mrc_tofile(self, savefilename=None):
"""Save the master recession curve results to a file."""
if savefilename is None:
savefilename = osp.join(
self.dialog_dir,
"Well_%s_mrc_results.xlsx" % self.wldset['Well'])
savefilename = self.select_savefilename(
"Save MRC results", savefilename, "*.xlsx;;*.xls;;*.csv")
if savefilename:
QApplication.setOverrideCursor(Qt.WaitCursor)
QApplication.processEvents()
try:
self.wldset.save_mrc_tofile(savefilename)
except PermissionError:
self.show_permission_error()
self.save_mrc_tofile(savefilename)
QApplication.restoreOverrideCursor()
def btn_mrc2rechg_isClicked(self):
if not self.wldset.mrc_exists():
print('Need to calculate MRC equation first.')
return
A, B = self.wldset['mrc/params']
if not os.path.exists(self.soilFilename):
print('A ".sol" file is needed for the calculation of' +
' groundwater recharge from the MRC')
return
self.SOILPROFIL.load_info(self.soilFilename)
mrc2rechg(self.time, self.water_lvl, A, B,
self.SOILPROFIL.zlayer, self.SOILPROFIL.Sy)
# ---- BRF handlers
def plot_brfperiod(self):
"""
Plot on the graph the vertical lines that are used to define the period
over which the BRF is evaluated.
"""
if (self.brf_eval_widget.btn_seldata.value() is False and
self.brf_eval_widget.isVisible()):
brfperiod = self.brf_eval_widget.get_brfperiod()
else:
brfperiod = [None, None]
for x, vline in zip(brfperiod, [self.h_brf1, self.h_brf2]):
vline.set_visible(x is not None)
if x is not None:
x = x + self.dt4xls2mpl*self.dformat
vline.set_xdata(x)
self.draw()
def toggle_brfperiod_selection(self, value):
"""
Toggle on or off the option to select the BRF calculation period on
the graph.
"""
if self.wldset is None:
self.brf_eval_widget.btn_seldata.setValue(False, silent=True)
if value is True:
self.emit_warning("Please import a valid water "
"level dataset first.")
return
self.brf_eval_widget.btn_seldata.setValue(value, silent=True)
if value is True:
self.toggle_navig_and_select_tools(
self.brf_eval_widget.btn_seldata)
self.plot_brfperiod()
# ---- Peaks handlers
def find_peak(self):
n_j, n_add = local_extrema(self.water_lvl, 4 * 5)
# Removing first and last point if necessary to always start with a
# maximum and end with a minimum.
# WARNING: y axis is inverted. Consequently, the logic needs to be
# inverted also
if n_j[0] > 0:
n_j = np.delete(n_j, 0)
if n_j[-1] < 0:
n_j = np.delete(n_j, -1)
self.peak_indx = np.abs(n_j).astype(int)
self.peak_memory.append(self.peak_indx)
self.draw_mrc()
def btn_addpeak_isclicked(self):
"""Handle when the button add_peak is clicked."""
if self.btn_addpeak.value():
self.toggle_navig_and_select_tools(self.btn_addpeak)
self.btn_show_mrc.setValue(True)
self.draw()
def btn_delpeak_isclicked(self):
"""Handle when the button btn_delpeak is clicked."""
if self.btn_delpeak.value():
self.toggle_navig_and_select_tools(self.btn_delpeak)
self.btn_show_mrc.setValue(True)
self.draw()
def clear_all_peaks(self):
"""Clear all peaks from the graph."""
if len(self.peak_indx) > 0:
self.peak_indx = np.array([]).astype(int)
self.peak_memory.append(self.peak_indx)
self.draw_mrc()
# ---- Navig and selec tools
def register_navig_and_select_tool(self, tool):
"""
Add the tool to the list of tools that are available to interactively
navigate and select the data.
"""
if not isinstance(tool, OnOffToolButton):
raise TypeError
if tool not in self._navig_and_select_tools:
self._navig_and_select_tools.append(tool)
def toggle_navig_and_select_tools(self, keep_toggled=None):
"""
Toggle off all navigation and selection tool, but the ones listed
in the keep_toggled.
"""
try:
iter(keep_toggled)
except TypeError:
keep_toggled = [keep_toggled]
for tool in self._navig_and_select_tools:
if tool not in keep_toggled:
tool.setValue(False)
@property
def zoom_is_active(self):
"""Return whether the zooming to rectangle tool is active or not."""
return self.btn_zoom_to_rect.value()
@QSlot(bool)
def zoom_is_active_changed(self, zoom_is_active):
"""Handle when the state of the button to zoom to rectangle changes."""
if self.zoom_is_active:
self.toggle_navig_and_select_tools(self.btn_zoom_to_rect)
if self.toolbar._active is None:
self.toolbar.zoom()
else:
if self.toolbar._active == 'ZOOM':
self.toolbar.zoom()
@property
def pan_is_active(self):
"""Return whether the panning of the graph is active or not."""
return self.btn_pan.value()
@QSlot(bool)
def pan_is_active_changed(self, pan_is_active):
"""Handle when the state of the button to pan the graph changes."""
if self.pan_is_active:
self.toggle_navig_and_select_tools(self.btn_pan)
if self.toolbar._active is None:
self.toolbar.pan()
else:
if self.toolbar._active == 'PAN':
self.toolbar.pan()
@property
def rect_select_is_active(self):
"""
Return whether the rectangle selection of water level data is
active or not.
"""
return self.btn_rect_select.value()
@QSlot(bool)
def rect_select_is_active_changed(self, value):
"""Handle the rectangular selection tool is toggled on or off."""
if self.rect_select_is_active:
self.toggle_navig_and_select_tools(self.btn_rect_select)
def clear_selected_wl(self, draw=True):
"""Clear the selecte water level data."""
self.wl_selected_i = []
self.draw_select_wl(draw)
def home(self):
"""Reset the orgininal view of the figure."""
self.toolbar.home()
if self.dformat == 0:
ax0 = self.fig.axes[0]
xfmt = mpl.ticker.ScalarFormatter()
ax0.xaxis.set_major_formatter(xfmt)
ax0.get_xaxis().get_major_formatter().set_useOffset(False)
xlim = ax0.get_xlim()
ax0.set_xlim(xlim[0] - self.dt4xls2mpl, xlim[1] - self.dt4xls2mpl)
self.setup_ax_margins()
def undo(self):
if len(self.peak_memory) > 1:
self.peak_indx = self.peak_memory[-2]
del self.peak_memory[-1]
self.draw_mrc()
# ---- Water level edit tools
def delete_selected_wl(self):
"""Delete the selecte water level data."""
if len(self.wl_selected_i) and self.wldset is not None:
self.wldset.delete_waterlevels_at(self.wl_selected_i)
self._draw_obs_wl()
self._update_edit_toolbar_state()
def undo_wl_changes(self):
"""Undo the last changes made to the water level data."""
if self.wldset is not None:
self.wldset.undo()
self._draw_obs_wl()
self._update_edit_toolbar_state()
def clear_all_changes(self):
"""Clear all changes that were made to the wldset."""
if self.wldset is not None:
self.wldset.clear_all_changes()
self._draw_obs_wl()
self._update_edit_toolbar_state()
def commit_wl_changes(self):
"""Commit the changes made to the water level data to the project."""
if self.wldset is not None:
self.wldset.commit()
self._update_edit_toolbar_state()
def _update_edit_toolbar_state(self):
"""Update the state of the edit toolbar."""
buttons = [self.btn_commit_changes,
self.btn_clear_changes,
self.btn_undo_changes]
for btn in buttons:
btn.setEnabled(False if self.wldset is None else
self.wldset.has_uncommited_changes)
# ---- Drawing methods
def setup_hydrograph(self):
"""Setup the hydrograph after a new wldset has been set."""
self.peak_indx = np.array([]).astype(int)
self.peak_memory = [np.array([]).astype(int)]
self.btn_undo.setEnabled(False)
self.clear_selected_wl()
self._update_edit_toolbar_state()
# Plot observed and predicted water levels
self._draw_obs_wl()
self.plt_wlpre.set_data([], [])
self.draw_meas_wl()
self.draw_glue_wl()
self.draw_weather()
if not self.btn_strati.autoRaise():
# Plot stratigraphy.
self.display_soil_layer()
self.setup_axis_range()
self.setup_xticklabels_format()
self.draw()
def setup_axis_range(self, event=None):
"""Setup the range of the x- and y-axis."""
if self.wldset is not None:
y = self.water_lvl
t = self.time + self.dt4xls2mpl * self.dformat
elif self.wxdset is not None:
y = [-1, 1]
t = self.wxdset.get_xldates() + self.dt4xls2mpl * self.dformat
else:
y = [-1, 1]
t = np.array(
[xldate_from_date_tuple((1980, 1, 1), 0),
xldate_from_date_tuple((2018, 1, 1), 0)]
) + self.dt4xls2mpl * self.dformat
Xmin0 = np.min(t) - (np.max(t) - np.min(t)) * 0.05
Xmax0 = np.max(t) + (np.max(t) - np.min(t)) * 0.05
Ymin0 = np.nanmin(y) - (np.nanmax(y) - np.nanmin(y)) * 0.25
Ymax0 = np.nanmax(y) + (np.nanmax(y) - np.nanmin(y)) * 0.25
self.fig.axes[0].axis([Xmin0, Xmax0, Ymax0, Ymin0])
# Setup the yaxis range for the weather.
self.fig.axes[1].axis(ymin=500, ymax=0)
self.draw()
def setup_ax_margins(self, event=None):
"""Setup the margins width of the axes in inches."""
fheight = self.fig.get_figheight()
fwidth = self.fig.get_figwidth()
left_margin = 1 / fwidth
right_margin = 1 / fwidth
bottom_margin = 0.75 / fheight
top_margin = 0.2 / fheight
x0 = left_margin
y0 = bottom_margin
w = 1 - (left_margin + right_margin)
h = 1 - (bottom_margin + top_margin)
for axe in self.fig.axes:
axe.set_position([x0, y0, w, h])
self.draw()
def setup_xticklabels_format(self):
"""Setup the format of the xticklabels."""
ax0 = self.fig.axes[0]
if self.dformat == 1:
xloc = mpl.dates.AutoDateLocator()
ax0.xaxis.set_major_locator(xloc)
xfmt = mpl.dates.AutoDateFormatter(xloc)
ax0.xaxis.set_major_formatter(xfmt)
elif self.dformat == 0:
xfmt = mpl.ticker.ScalarFormatter()
ax0.xaxis.set_major_formatter(xfmt)
ax0.get_xaxis().get_major_formatter().set_useOffset(False)
def switch_date_format(self):
"""
Change the format of the xticklabels.
- 0 is for Excel numeric date format.
- 1 is for Matplotlib text format.
"""
ax0 = self.fig.axes[0]
if self.dformat == 0:
# Switch to matplotlib date format
self.btn_dateFormat.setAutoRaise(False)
self.btn_dateFormat.setToolTip(
'Show x-axis tick labels as Excel numeric format')
self.dformat = 1
elif self.dformat == 1:
# Switch to Excel numeric date format
self.btn_dateFormat.setAutoRaise(True)
self.btn_dateFormat.setToolTip(
'Show x-axis tick labels as date')
self.dformat = 0
self.setup_xticklabels_format()
# Adjust the range of the x-axis.
xlim = ax0.get_xlim()
if self.dformat == 1:
ax0.set_xlim(xlim[0] + self.dt4xls2mpl, xlim[1] + self.dt4xls2mpl)
elif self.dformat == 0:
ax0.set_xlim(xlim[0] - self.dt4xls2mpl, xlim[1] - self.dt4xls2mpl)
# Adjust the water levels, peak, MRC ant weather time frame.
if len(self.peak_indx) > 0: # Peaks
self._peaks_plt.set_xdata(
self.time[self.peak_indx] + self.dt4xls2mpl * self.dformat)
self._draw_obs_wl()
self.draw_meas_wl()
self.draw_mrc()
self.draw_weather()
self.draw_glue_wl()
self.draw()
def plot_synth_hydro(self, parameters):
print(parameters)
Cro = parameters['Cro']
RASmax = parameters['RASmax']
Sy = parameters['Sy']
# ----------------------------------------------- compute recharge ----
rechg, _, _, _, _ = \
self.synth_hydrograph.surf_water_budget(Cro, RASmax)
# ------------------------------------------- compute water levels ----
# We introduce the time lag here.
tweatr = self.wxdset.get_xldates() + 0
twlvl = self.time
ts = np.where(twlvl[0] == tweatr)[0][0]
te = np.where(twlvl[-1] == tweatr)[0][0]
WLpre = self.synth_hydrograph.calc_hydrograph(rechg[ts:te], Sy)
# ---------------------------------------------- plot water levels ----
self.plt_wlpre.set_data(self.synth_hydrograph.DATE, WLpre/1000.)