-
Notifications
You must be signed in to change notification settings - Fork 0
/
script_manual_calibration.py
3535 lines (3135 loc) · 174 KB
/
script_manual_calibration.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
#!/usr/bin/env python
""" Script for manual calibration - Milsbo lakes project
Script Launches a run of the Mylake model using the MyLake_v2_Vansjo version with the parameter's value giving in input,
shows figures of the comparison of the simulated values (for temperature, oxygen, and chl_a) with the observation for
the lake specifies in input (Nedre or Ovre) and loops until the value "End" is given in input.
For all looping period, a report (as table in CSV, naming as "manual_calibration_{lake name}_{Variable}_{start time}_{end time}.csv")
is generated in the output folder, containing for each round of calibration, the lake name, the value given to all
parameters, the calibration performances using a different index, an overall score from visual comparison
(giving in input by the user, between 1 and 10) and optional note for each run, if giving in input by the user.
The main run asks for the lake wanted (Nedre or Ovre) and the
"""
__author__ = "Marianne Cote"
from pandas.plotting import register_matplotlib_converters
import warnings
warnings.filterwarnings("ignore")
register_matplotlib_converters()
# import sys
# import subprocess
# import pkg_resources
#
# required = {'matplotlib','scipy','time','statsmodels','numpy','math','sklearn','statistics','csv','shutil','seaborn'}
# installed = {pkg.key for pkg in pkg_resources.working_set}
# missing = required - installed
# if missing:
# python = sys.executable
# subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)
import matplotlib.pyplot as plt
from scipy.stats import linregress
import time
import statsmodels.api as smodels
from statsmodels.sandbox.regression.predstd import wls_prediction_std
import scipy.stats as stats
import numpy as np
from math import sqrt, floor, log10, log
from sklearn.metrics import r2_score, mean_squared_error
import statistics
import csv
import os
import pkg_resources
import shutil
from datetime import datetime, timedelta, date
import pandas as pd
import seaborn as sns
if not pkg_resources.get_distribution("seaborn").version == '0.11.0':
os.system('conda install seaborn=0.11.0')
import seaborn as sns
from numpy import arange, nan, reshape, sqrt
import scipy.io as sio
import subprocess
cwd = os.getcwd()
# variable_pos = {'T': 5, 'O2': 6, 'Chl': 13}
num2month = {1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "June", 7: "July", 8: "Aug", 9: "Sept", 10: "Oct",
11: "Nov", 12: "Dec"}
variables_dict = {'T': "Temperature", 'O2': "DO concentration", 'Chl': 'Chlorophyll a'}
matlab_folder = r"C:\Program Files\MATLAB\R2019b\bin\matlab" # Value by default. need to be ajust to where matlab is install and the matlab version
test_cases = 10
parameters = {"Swa_b0": [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5],
"Swa_b1": [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5],
"C_shelter": [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
"I_ScV": [0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8],
"I_ScT": [0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8],
"Alb_melt_ice": [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
"Alb_melt_snow": [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]}
variable_pos = {'T': 5, 'O2': 6}#, 'Chl': 13}
### Matlab files reading function ###
def load_data(f, sediment=0):
try:
mat_contents = sio.loadmat(f)
except NotImplementedError:
import hdf5storage
mat_contents = hdf5storage.loadmat(f)
MyLake_results = mat_contents['MyLake_results']
if sediment == 1:
Sediment_results = mat_contents['Sediment_results']
return MyLake_results, Sediment_results
return MyLake_results, []
### Function calculating Performance Index ###
def percent_bias_pbias(obs_list, sims_list):
"""
Finds the sums of squares for all temperatures listed in the comparison file.
:param obs_list: A list of observed temperatures.
:param sims_list: A list of simulated temperatures.
:return: The result of the sums of squares as a float.
"""
sums = 0
for x in range(len(obs_list)):
if obs_list[x] == 'None':
continue
sums += (float(obs_list[x]) - float(sims_list[x]))
if sum(obs_list) != 0:
percent = sums * 100 / sum(obs_list)
else:
percent = 0
return percent
def nash_sutcliffe_efficiency_nse(obs_list, sims_list):
"""
Finds the sums of squares for all temperatures listed in the comparison file.
:param obs_list: A list of observed temperatures.
:param sims_list: A list of simulated temperatures.
:return: The result of the sums of squares as a float.
"""
d = pd.DataFrame(list(zip(obs_list, sims_list)),
columns=['obs', 'sim'])
d["obs"] = d["obs"].astype(float)
d["sim"] = d["sim"].astype(float)
if 1 == 1: # try:
sums = 0
st = 0
mean = d["obs"].mean()
for x in range(len(obs_list)):
if obs_list[x] == 'None':
continue
sums += (float(obs_list[x]) - float(sims_list[x])) ** 2
st += (float(obs_list[x]) - mean) ** 2
NSE = 1 - (sums / st)
else: # except:
NSE = np.nan
return NSE
def root_mean_square(obs_list, sims_list):
"""
Finds the root_mean_square for the temperatures listed in the comparison file.
:param obs_list: A list of observed temperatures.
:param sims_list: A list of simulated temperatures.
:return: The result of the root mean square as a float.
"""
d = pd.DataFrame(list(zip(obs_list, sims_list)),
columns=['obs', 'sim'])
d["obs"] = d["obs"].astype(float)
d["sim"] = d["sim"].astype(float)
if 1 == 1: # try:
# results = mean_squared_error(d["obs"], d["sim"])
# results = mean_squared_error(sqare)
# results = sqrt(results)
# resultsnormalise = sqrt(mean_squared_error(d["obs"], d["sim"])) / (max(d["obs"]) - min(d["obs"]))
results = sqrt(mean_squared_error(d["obs"], d["sim"]))
resultsnormalise = results / standard_deviation(obs_list)
mino = np.min(d["obs"])
maxo = np.max(d["obs"])
difference = maxo - mino
normalisermse = results / difference
else: # except:
results = np.nan
resultsnormalise = np.nan
normalisermse = np.nan
return results, resultsnormalise, normalisermse
def r_squared(obs_list, sims_list):
"""
Find the R squared for the simulations compared to the expected observations
:param obs_list: A list of observed temperatures.
:param sims_list: A list of simulated temperatures.
:return: results of R squared, as float
"""
x = []
y = []
for i in obs_list:
try:
x.append(float(i))
y.append(float(sims_list[obs_list.index(i)]))
except ValueError:
continue
except IndexError:
break
try:
rsquare = r2_score(x, y)
except:
rsquare = np.nan
return rsquare
def sums_of_squares(obs_list, sims_list):
"""
Finds the sums of squares for all temperatures listed in the comparison file.
:param obs_list: A list of observed temperatures.
:param sims_list: A list of simulated temperatures.
:return: The result of the sums of squares as a float.
"""
sums = 0
for x in range(len(obs_list)):
if obs_list[x] == 'None':
continue
sums += (float(obs_list[x]) - float(sims_list[x])) ** 2
return sums
def standard_deviation(obs_list):
"""
Find the standard deviation of the observations
:param obs_list: Type list. The list of observed temperatures.
:return: The standard deviation of obs_list
"""
observations = []
for obs in obs_list:
try:
observations.append(float(obs))
except ValueError:
continue
return statistics.stdev(observations)
def rmse_by_sd(obs_list, rmse):
"""
Divides RMSE of the simulations by the SD of the observations
:param obs_list: A list of observed temperatures.
:param rmse: Float
:return: A float, RMSE / SD
"""
try:
results = rmse / standard_deviation(obs_list)
except ZeroDivisionError:
results = "Error_Zero_Division"
return results
### Fuction related to User input ###
def ask_for_matlab_directory():
"""
function to get the exact matlab directory needed to run the model.
function is case sensible.
:return: the matlab directory
"""
if os.path.exists(r"C:\Program Files\MATLAB\R2019b\bin"):
print(r"matlab.exe used: C:\Program Files\MATLAB\R2019b\bin\matlab")
return r"C:\Program Files\MATLAB\R2019b\bin\matlab"
elif os.path.exists(r"C:\Program Files\MATLAB\R2019a\bin"):
print(r"matlab.exe used: C:\Program Files\MATLAB\R2019a\bin\matlab")
return r"C:\Program Files\MATLAB\R2019a\bin\matlab"
elif os.path.exists(r"C:\Program Files\MATLAB\R2020b\bin"):
print(r"matlab.exe used: C:\Program Files\MATLAB\R2020b\bin\matlab")
return r"C:\Program Files\MATLAB\R2020b\bin\matlab"
elif os.path.exists(r"C:\Program Files\MATLAB\R2022b\bin"):
print(r"matlab.exe used: C:\Program Files\MATLAB\R2022b\bin\matlab")
return r"C:\Program Files\MATLAB\R2022b\bin\matlab"
else:
while True:
directory = input(r"Enter path to matlab.exe (ex: C:\Program Files\MATLAB\R2019b\bin\matlab) : ")
if os.path.exists(r"%s" % (directory)):
print("Path enter does not exist or does not include the '\matlab'. Enter valid path.\n")
continue
else:
# user enter correct lake name
break
return r"%s" % (directory)
def aks_for_which_lake_wanted_to_calibrated():
"""
function to get in input the lake that will be calibrated. For now, options are "Bromont" .
function is not case sensible.
:return: the lake name ("Bromont" )
"""
while True:
lake_name = input("Enter which lake will be calibrated 'Bromont' (not case sensitive): ")
if lake_name.upper() not in ("BROMONT"):
print("Lake name giving is not an option, choose between 'Bromont'.\n")
continue
else:
# user enter correct lake name
break
return "%s%s" % (lake_name[0].upper(), lake_name[1:].lower())
def aks_for_what_is_modeled():
"""
:return: what_is_calibrated, what_variable_is_calibrated
"""
while True:
what_is_calibrated = input(
"\nType the number of what you want to calibrated:\nThe water column (1), The sediment module (2), or Both (3): ")
if what_is_calibrated not in ("1", "2", "3"):
print("%s is not a option, please select '1', '2' or '3'.\n" % what_is_calibrated)
continue
else:
# user enter correct lake name
what_is_calibrated = int(what_is_calibrated)
correct = True
if what_is_calibrated == 1:
while True:
what_variable_is_calibrated = input(
"\nType the number of what variable you want to calibrated:\nTemperature (1), Oxygen concentration (2), Chlorophylle (3) or all (4): ")
if what_variable_is_calibrated not in ("1", "2", "3", "4"):
print("%s is not a option, please select '1', '2', '3' or '4'.\n" % what_variable_is_calibrated)
continue
else:
# user enter correct lake name
what_variable_is_calibrated = int(what_variable_is_calibrated)
if what_variable_is_calibrated in [1,2,3,4]:
break
else:
print(
"For now, the calibration of other variable than Temperature is not supported, please select option '1'")
correct_variable = False
if correct_variable:
correct = True
break
else:
continue
else:
what_variable_is_calibrated = 2
# print("For now, the calibration of the sediment is not supported, please select option '1'\n")
# correct = False
if correct:
break
else:
continue
return what_is_calibrated, what_variable_is_calibrated
def ask_what_to_save():
"""
function to get in input the lake that will be calibrated. For now, options are "Bromont" .
function is not case sensible.
:return: the lake name ("Bromont" )
"""
default = [True, True, False, False]
while True:
print(
"Saving option are:\nSaving calibration report? %s\nSaving calibration figure? %s\nSaving all output data? %s\nSaving comparison data? %s\n" % (
default[0], default[1], default[2], default[3]))
saving_option = input("Do you want to continue with the default saving option (y or n)? ")
if saving_option.upper() not in ("N", "Y"):
print("answer giving is not an option, choose between 'y' and 'n'.\n")
continue
else:
if saving_option.upper() == "N":
while True:
report = input("Do you want to save a report of the calibration (y or n)? ")
if report.upper() not in ("N", "Y"):
print("answer giving is not an option, choose between 'y' and 'n'.\n")
continue
else:
if report.upper() == "N":
default[0] = False
else:
default[0] = True
break
while True:
figure = input("Do you want to save the figures of the calibration (y or n)? ")
if figure.upper() not in ("N", "Y"):
print("answer giving is not an option, choose between 'y' and 'n'.\n")
continue
else:
if figure.upper() == "N":
default[1] = False
else:
default[1] = True
break
while True:
output = input("Do you want to save the output the calibration (y or n)? ")
if output.upper() not in ("N", "Y"):
print("answer giving is not an option, choose between 'y' and 'n'.\n")
continue
else:
if output.upper() == "N":
default[2] = False
else:
default[2] = True
break
while True:
comparison = input("Do you want to save the comparison files of the calibration (y or n)? ")
if comparison.upper() not in ("N", "Y"):
print("answer giving is not an option, choose between 'y' and 'n'.\n")
continue
else:
if comparison.upper() == "N":
default[3] = False
else:
default[3] = True
break
break
return default
### General Function needed by method of Lake CLass ###
def variables_by_depth(observation_folder, lakeName, output_folder, variable='T'):
"""
Creates a new csv file with the observed temperatures separated in columns by depths.
:param observation_folder: String
:param lakeName: String
:param output_folder: String
:return: None
"""
test = "{}/{}_bathymetry.csv".format(observation_folder, lakeName)
with open("{}/{}_bathymetry.csv".format(observation_folder, lakeName)) as bathymetric_file:
maxDepth = int(float(list(csv.reader(bathymetric_file))[-1][1]))
depthLevels = list(range(maxDepth + 1))
with open("{}/{}_observation_data.csv".format(observation_folder, lakeName)) as obs_file:
reader = list(csv.reader(obs_file))[1:]
depthlist = []
loop = 0
for depth in reader:
depth[3] = 7+ float(depth[3])
if float(depth[3]) not in depthlist:
depthlist.append(float(depth[3]))
elif float(depth[3]) == depthlist[0]:
loop += 1
if loop == 1000:
break
outputdir2 = list(output_folder.split("/"))
outputdir3 = 'Postproc_code'
if not os.path.exists(outputdir3):
os.mkdir(outputdir3)
outputdir3 = os.path.join(outputdir3, lakeName)
if not os.path.exists(outputdir3):
os.mkdir(outputdir3)
depthlist.sort()
with open("{}/Observed_{}.csv".format(observation_folder, variable), "w", newline='') as csvfile:
print("{}/Observed_{}.csv".format(observation_folder, variable))
header = "{}, {}\n".format(np.nan, depthlist)
csvfile.write(header.translate({ord(i): None for i in '[]'}))
out = csv.writer(csvfile)
rows = {}
dates = []
for i in depthlist:
rows[i] = []
for observation in reader:
obs_date = observation[2] # "%s%s%s"%(observation[2][0:3],observation[2][4:5],observation[2][5:])
if obs_date not in dates:
dates.append(obs_date)
# print(obs_date)
temp_list = []
number = 0
for date in dates:
for observation in reader:
# print(int(observation[2]), date)
if str(observation[2]) == str(date):
temp_list.append(observation)
for depth in depthlist:
missing_temp = True
for t in temp_list:
if float(t[3]) == depth:
if len(rows[depth]) <= number:
if t[variable_pos[variable]] == "":
rows[depth].append("None")
else:
rows[depth].append(float(t[variable_pos[variable]]))
missing_temp = False
if missing_temp:
rows[depth].append("None")
number += 1
temp_list.clear()
temp_list.clear()
for date in dates:
temp_list.append(date)
for x in depthlist:
temp_list.append(rows[x][dates.index(date)])
out.writerow(temp_list)
temp_list.clear()
print("observation done ... ... ... ... ")
def get_dates_of_simulation(start_year, stop_year):
"""
Finds the dates for each day of simulation. The dates are found by beginning at the first of January of the given
start year and adding a day until the 31st of December of the stop year, accounting for leap years.
:param start_year: An integer, the chosen year for the beginning of the simulation.
:param stop_year: An integer, the chosen year for the end of the simulation.
:return: A list of all the dates of simulation, in order from first to last. Dates are integers in the form YYYYMMDD.
"""
date_list = []
year = start_year
nb_year = stop_year - start_year
if nb_year == 0:
nb_year = 1
for i in range(0, nb_year):
if i % 400 == 0 or (i % 4 == 0 and i % 100 != 0):
for x in range(1, 367):
date = 0
str_x = str(x)
if x <= 31:
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "01" + str_x)
elif 31 < x <= 60:
str_x = str(int(str_x) - 31)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "02" + str_x)
elif 60 < x <= 91:
str_x = str(int(year) - 60)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "03" + str_x)
elif 91 < x <= 121:
str_x = str(int(year) - 91)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "04" + str_x)
elif 121 < x <= 152:
str_x = str(int(str_x) - 121)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "05" + str_x)
elif 152 < x <= 182:
str_x = str(int(str_x) - 152)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "06" + str_x)
elif 182 < x <= 213:
str_x = str(int(str_x) - 182)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "07" + str_x)
elif 213 < x <= 243:
str_x = str(int(str_x) - 213)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "08" + str_x)
elif 243 < x <= 274:
str_x = str(int(str_x) - 243)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "09" + str_x)
elif 274 < x <= 305:
str_x = str(int(str_x) - 274)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "10" + str_x)
elif 305 < x <= 335:
str_x = str(int(str_x) - 305)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "11" + str_x)
elif 335 < x <= 366:
str_x = str(int(str_x) - 335)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "12" + str_x)
date_list.append(date)
else:
for x in range(1, 366):
date = 0
str_x = str(x)
if x <= 31:
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "01" + str_x)
elif 31 < x <= 59:
str_x = str(int(str_x) - 31)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "02" + str_x)
elif 59 < x <= 90:
str_x = str(int(str_x) - 59)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "03" + str_x)
elif 90 < x <= 120:
str_x = str(int(str_x) - 90)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "04" + str_x)
elif 120 < x <= 151:
str_x = str(int(str_x) - 120)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "05" + str_x)
elif 151 < x <= 181:
str_x = str(int(str_x) - 151)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "06" + str_x)
elif 181 < x <= 212:
str_x = str(int(str_x) - 181)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "07" + str_x)
elif 212 < x <= 242:
str_x = str(int(str_x) - 212)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "08" + str_x)
elif 242 < x <= 273:
str_x = str(int(str_x) - 242)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "09" + str_x)
elif 273 < x <= 304:
str_x = str(int(str_x) - 273)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "10" + str_x)
elif 304 < x <= 334:
str_x = str(int(str_x) - 304)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "11" + str_x)
elif 334 < x <= 365:
str_x = str(int(str_x) - 334)
if len(str_x) == 1:
str_x = "0" + str_x
date = int(str(year) + "12" + str_x)
date_list.append(date)
year += 1
return date_list
def findYPoint(xa, xb, ya, yb, xc):
m = (float(ya) - float(yb)) / (float(xa) - float(xb))
yc = (float(xc) - (float(xb))) * m + float(ya)
return yc
def date_range(start, end):
delta = end - start # as timedelta
days = [start + timedelta(days=i) for i in range(delta.days + 1)]
days_str = [int(day.strftime("%Y%m%d")) for day in days]
return days_str
def date_range_as_date(start, end):
delta = end - start # as timedelta
days = [start + timedelta(days=i) for i in range(delta.days + 1)]
return days
### General Function related to Figures (Used by Class Graphic) ###
def timeline_plot(modeleddata: list, modeleddates: list, observeddata: list = None, observeddates: list = None, ax=None,
ylimit=[-0.5, 30],
line_kwargs: dict = {},
sct_kwargs: dict = {}, linestyle="-"):
"""
plot timeline with modeled data (line) and observed data (dot)
:param modeleddata: modeled data for each day included in years presenting observed data (at the same depth)
:param modeleddates: all days included in the period modeled
:param observeddata: Observed data to be plotted
:param observeddates: Dates Where observed data have been measured
:param ax: Axe where you want to plot. If None, look for the last ax used in the current figure
:param line_kwargs: Other arguments given to the line plot (measures' plot)
:param sct_kwargs: Other arguments given to the scatterplot (Observations' plot)
:return: None
"""
if ax is None:
ax = plt.gca()
if modeleddates is None or modeleddata is None:
raise TypeError
sns.lineplot(x=modeleddates, y=modeleddata, ax=ax, **line_kwargs)
if observeddata is not None:
sns.scatterplot(x=observeddates, y=observeddata, ax=ax, **sct_kwargs)
ax.set_xlabel("Dates")
ax.set_xlim(min(modeleddates), max(modeleddates))
ax.set_ylim(ylimit[0], ylimit[1])
def line_plot(lineStart=None, lineEnd=None, ax=None, linearg={}):
if ax is None:
ax = plt.gca()
if lineStart is None:
lineStart = 0
lineEnd = 20
ax.plot([lineStart, lineEnd], [lineStart, lineEnd], **linearg)
ax.set_xlim(lineStart, lineEnd)
ax.set_ylim(lineStart, lineEnd)
def linear_regression_plot(x2, y2, ax=None, linearregressionarg={}, confidentintervalarg={}, predictionintervalarg={}):
if ax is None:
ax = plt.gca()
x = smodels.add_constant(x2) # constant intercept term
# Model: y ~ x + c
model = smodels.OLS(y2, x)
fitted = model.fit()
x_pred = np.linspace(x.min(), x.max(), 50)
x_pred2 = smodels.add_constant(x_pred)
y_pred = fitted.predict(x_pred2)
ax.plot(x_pred, y_pred, **linearregressionarg)
# print(fitted.params) # the estimated parameters for the regression line
# print(fitted.summary()) # summary statistics for the regression
y_hat = fitted.predict(x) # x is an array from line 12 above
y_err = y2 - y_hat
mean_x = x.T[1].mean()
n = len(x)
dof = n - fitted.df_model - 1
t = stats.t.ppf(1 - 0.025, df=dof)
s_err = np.sum(np.power(y_err, 2))
conf = t * np.sqrt((s_err / (n - 2)) * (1.0 / n + (
np.power((x_pred - mean_x), 2) / ((np.sum(np.power(x_pred, 2))) - n * (np.power(mean_x, 2))))))
upper = y_pred + abs(conf)
lower = y_pred - abs(conf)
# Prediction Interval
sdev, lower, upper = wls_prediction_std(fitted, exog=x_pred2, alpha=0.025)
ax.fill_between(x_pred, lower, upper, **predictionintervalarg)
# ax.plot(x_pred, lower, **predictionintervalarg, alpha=1, linestyle='-.')
# ax.plot(x_pred, upper, **predictionintervalarg, alpha=1, linestyle='-.')
# ax.legend(bbox_to_anchor=(1,0), loc="lower right")
# Confidence Interval
# ax.fill_between(x_pred, lower, upper, **confidentintervalarg)
# ax.plot(x_pred, lower, **confidentintervalarg, alpha=1, linestyle='-')
# ax.plot(x_pred, upper, **confidentintervalarg, alpha=1, linestyle='-')
sns.regplot(x2, y2,ax=ax)# ci=95, scatter_kws={"color": "white", "alpha": 1, "zorder": -10}, line_kws=confidentintervalarg,
#ax=ax)
def error_bar_plot(x, y, xerr, yerr, ax=None, errorbararg={}, markerwidth=4):
if ax is None:
ax = plt.gca()
(_, caps, _) = plt.errorbar(x, y, xerr=xerr, yerr=yerr, **errorbararg)
for cap in caps:
cap.set_markeredgewidth(markerwidth)
def base_plot_comparison(x, y, lineStart=None, lineEnd=None, ax=None, linecolor="k", lake=""):
if ax is None:
ax = plt.gca()
linearg = {'color': linecolor, 'label': "y= x", 'linewidth': 4, 'linestyle': '--'}
slope, intercept, r_value, p_value, std_err = linregress(x, y)
rmse, rsr, nrmse = root_mean_square(x, y)
linearregressionarg = {'color': 'k', 'linewidth': 1.5,
"label": "linear regression (y = %0.3f x + %0.3f) \n R\u00b2 : %0.3f RMSE: %0.3f" % (
slope, intercept, r_value, rmse)}
confidenceintervalarg = {'color': 'k', 'linewidth': 1.5, 'label': "Confidence interval",
"zorder": 5} # 'alpha': 0.4,
predictionintervalarg = {'color': '#888888', 'alpha': 0.1, 'label': "Prediction interval",
"zorder": 0} # 'alpha': 0.1,
line_plot(lineStart=lineStart, lineEnd=lineEnd, ax=ax, linearg=linearg)
linear_regression_plot(x, y, ax, linearregressionarg, confidenceintervalarg, predictionintervalarg)
legendNames = ["Confidence interval", "Prediction interval"]
# ax.legend(legendNames,loc='bottom right')
ax.set_ylim()
ax.set_xlim()
ax.text(lineStart + 0.5, lineEnd - 1, "R\u00b2 : %0.3f RMSE: %0.3f" % (r_value, rmse),
horizontalalignment='left',
verticalalignment='top')
return r_value, rmse
class Lake:
"""
A class used to gather all information related to the selected lake
...
Attributes
----------
lake_name : str
The name of the lake (For now, should be "Bromont" , error otherwise)
Methods
-------
manual_calibration_loop(report = True, save_figures = False, save_output_data = False, save_comparison_data = False)
Prints the animal's name and what sound it makes
"""
def __init__(self, lake_name):
"""
Parameters
----------
lake_name : str
The name of the lake (For now, should be "Bromont" , error otherwise)
observation_folder : str
folder directory for where the formatted observations are.
input_folder : str
folder directory for where the formatted inputs are.
output_folder : str
folder directory for where the data generated are.
observation_folder : str
folder directory for where the figures generated by the functions are.
"""
self.name = lake_name
self.observation_folder = r"obs/%s" % lake_name
self.save_date = datetime.now().strftime('%Y%m%d')
if not os.path.exists("IO/Bromont/Bromont_para.txt"):
# Default value for parameters related to Temperature
self.kz_N0 = 0.00007
self.c_shelter = "NaN"
self.i_scv = 1
self.i_sct = 0
self.swa_b0 = 2.5
self.swa_b1 = 1
# Default value for parameters related to Oxygen
self.I_scDOC = 1
self.I_scO = 1
self.k_BOD = 0.1
# Default value for parameter related to Chl_a
self.I_scChl = 1
self.k_Chl = 0.4
# Default value for parameter related to sediment
self.k_POP = 0.04
self.k_POC = 0.02
self.k_DOP = 0.04
self.k_DOC = 0.02
self.k_pdesorb_a = 100
self.k_pdesorb_b = 100
else:
print("Since the script found the file '%s_Para', the value from the last calibration will be used")
par_file = pd.read_csv("IO/Bromont/Bromont_para.txt", sep='\t',skiprows=1)
par_file['Parameter'] = par_file['Parameter'].str.lower()
par_file = par_file.set_index('Parameter')
# Default value for parameters related to Temperature
self.kz_N0 = par_file.loc['kz_n0',"Value"]
self.c_shelter = par_file.loc['c_shelter',"Value"]
self.i_scv = par_file.loc['i_scv',"Value"]
self.i_sct = par_file.loc['i_sct',"Value"]
self.swa_b0 = par_file.loc['swa_b0',"Value"]
self.swa_b1 = par_file.loc['swa_b1',"Value"]
# Default value for parameters related to Oxygen
self.I_scDOC = par_file.loc['i_scdoc',"Value"]
self.I_scO = par_file.loc['i_sco',"Value"]
self.k_BOD = par_file.loc['k_bod', "Value"]
# Default value for parameter related to Chl_a
self.I_scChl = par_file.loc['i_scchl',"Value"]
self.k_Chl = 0.4
# Default value for parameter related to sediment
self.k_POP = 0.04
self.k_POC = 0.02
self.k_DOP = 0.04
self.k_DOC = 0.02
self.k_pdesorb_a = 100
self.k_pdesorb_b = 100
self.input_folder = r"IO/%s" % lake_name
self.output_folder = r"Postproc_code/%s" % lake_name
self.figures_folder = r"Postproc_code/%s/figures" % lake_name
# generate observed data
for variable in ["T", "O2"]:
variables_by_depth(self.observation_folder, self.name, self.output_folder, variable)
def manual_calibration_loop(self, report=True, save_figures=False, save_output_data=False,
save_comparison_data=False, matlab=matlab_folder):
""" Main function, loop through iteration of simulation of the temperature, oxygen, and chl_a for the selected lake.
This function calls the function asking for parameters' values, launches the simulation with those values and
generate a figure with those values.
The function will be by default
Parameters
----------
sound : str, optional
The sound the animal makes (default is None)
Raises
------
NotImplementedError
If no sound is set for the animal or passed in as a
parameter.
"""
start_time = datetime.now()
self.save_date = start_time.strftime('%Y%m%d_%H%M')
dict_variable = [{1: "T", 2: "O2", 3: "Chl", 4: "O2"}, {1: "T", 2: "O2", 3: "Chl", 4: "O2"},
{1: "T", 2: "O2", 3: "Chl", 4: "O2"}]
outputdir = os.path.join(self.output_folder, "save_output_all")
if not os.path.exists(outputdir):
os.mkdir(outputdir)
what_is_calibrated, what_variable_is_calibrated = aks_for_what_is_modeled()
if what_is_calibrated in [2, 3]:
enable_sediment = 1
else:
enable_sediment = 0
dict_variable = dict_variable[what_is_calibrated - 1]
if report:
report_core_title = "manual_calibration_%s_%s_%s.csv" % (
self.name, dict_variable[what_variable_is_calibrated], start_time.strftime('%Y%m%d_%H%M'))
table_report = [
["Iteration", "Lake", "Variable_calibrated", "kz_N0", "c_shelter", "i_scv", "i_sct", "swa_b0",
"swa_b1", "I_scDOC","I_scO","K_BOD","I_scChl","k_Chl","k_POP","k_POC","k_DOP","k_DOC","k_pdesorb_a",
"k_pdesorb_b", "RMSE_all", "R2_all", "RMSE", "NSE", "RSR", "Pbias", "R2",
"SOS", "nrmse", "M_score", "Note", "time"]]
iteration_number = 0
iteration_continue = True
save_initial_conditions = 0 # Default value. Will use the by default concentrations values from mylake_initial_concentrations.txt, may be change after first calibration to use last simulation as initial concentrations.
while True:
if iteration_number != 0:
while True:
stop_iteration = input("Continue to test value for manual calibration of %s(y or n)? "%dict_variable[what_variable_is_calibrated])
if stop_iteration.upper() not in ('Y', 'N'):
print("answer giving is not an option, choose between 'y' and 'n'.\n")
continue
else:
if stop_iteration.upper() == 'N':
iteration_continue = False
break
while True:
stop_iteration = input("Do you want to use the last calibration to set the initial concentrations given to the model. (y or n)? \n"
"If Yes, once Matlab scripts run, mylake_initial_concentrations_2.txt and sediment_initial_concentrations_2.txt (if sediment module enables) will be generated using the last simulation result (use the .mat file) and will be used as initial concentrations.\n"
"If No, it will use the mylake_initial_concentrations.txt and sediment_initial_concentrations.txt by default.")
if stop_iteration.upper() not in ('Y', 'N'):
print("answer giving is not an option, choose between 'y' and 'n'.\n")
continue
else:
if stop_iteration.upper() == 'Y':
save_initial_conditions = 1
break
if iteration_continue:
iteration_number += 1
start_iteration = datetime.now()
print("\n**** Start Iteration %s %s ****" % (iteration_number, start_iteration))
if self.ask_parameters_value(what_is_calibrated, what_variable_is_calibrated) == 0:
return 0
print("\nStart MyLake run with kz_N0 = %s, c_shelter = %s, i_scv = %s, i_sct = %s, swa_b0 = %s, "
"swa_b1 = %s, I_scDOC = %s, I_scO = %s, I_scChl = %s, k_Chl = %s, K_BOD = %s, k_POP = %s, k_POC = %s, "
"k_DOP = %s, k_DOC = %s, k_pdesorb_a = %s, k_pdesorb_b = %s" % (self.kz_N0, self.c_shelter,