-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkals_model.py
More file actions
2220 lines (2017 loc) · 74.3 KB
/
Copy pathkals_model.py
File metadata and controls
2220 lines (2017 loc) · 74.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
import numpy as numpy
import torch
import torch.optim as optim
import torch.nn as nn
from collections import OrderedDict
from matplotlib import pyplot as plt
import math
import csv
import datetime
import os
import sys
import string
# Dynamical Neural Network Model
# by Derek Karssenberg, Utrecht University
numpy.set_printoptions(precision=2)
########################
# main configurations #
#######################
# Run in batch by providing inputs on command line
run_in_batch = True
# running in batch (typical usage) is done by for instance
# set run_in_batch to True
# python kals_model.py sub 1 1 observations one test
# 1st value is scenario (here sub)
# 2nd value is training fold (1-4) (here 1)
# 3rd value is rerun scenario (1, 2, 3,...) (here 1)
# 4th value is observations indicating fitting on observational data
# or something else (here observations)
# 5th value is one or two, representing lumped or semi-distributed (here one)
# 6th value is name of output folder (here test)
# these same related settings below are ignored when running in batch
# max number of epochs to run (will run for this number of epochs
# if validation (stopping) does not make it stop
nr_epochs = 5000
# run one area or else two
one_area = True
# multiply learning rate for quick tests (use 1.0 for real runs)
learning_rate_multiplier_value = 1.0 # 5.0 is possible for expert model fit
# fit model on observations or on artificial data
fitOnObservations = True
# add error to artificial data
addErrorToArtificialStreamFlow = False
# input directory with input data
input_data_directory = " ../data/inputData/"
# input_data_directory = "../data/inputData/"
# output directories
# folder where results folder (scen_directory) is written
out_folder = " ../data/results/"
# out_folder = "../data/results/"
# name of results folder
scen_directory = "test"
########################
# other configurations #
########################
# what weather data to use, if True GFS, else ECMWF Land
GFS = False
# training data to calculate loss over (typical sub, i.e. outflow)
training_data = "trainingSub"
# if fitting on artificial data, use linear model or non-linear one
linearArtForNotFitOnObservations = False
print_parameters = True
if run_in_batch:
batch_scenario = sys.argv[1]
training_scenario = sys.argv[2]
re_run_scenario = sys.argv[3]
fitOnObservationsOne = sys.argv[4]
oneArea = sys.argv[5]
scen_directory = sys.argv[6]
if fitOnObservationsOne == "observations":
fitOnObservations = True
else:
fitOnObservations = False
if oneArea == "one":
one_area = True
else:
one_area = False
output_directory = out_folder + scen_directory + "/"
# print status for epochs to screen
print("##### RUN INFO ######")
print("running scenario: ", batch_scenario)
print("running training fold: ", training_scenario)
print("running rerun scenario: ", re_run_scenario)
print("fitting on observations: ", fitOnObservations)
print("running one area: ", one_area)
print("results written to: ", output_directory)
print("#### END RUN INFO ######")
# Create the run directory
try:
os.mkdir(output_directory)
print(f"Directory '{output_directory}' created successfully.")
except FileExistsError:
print(f"Directory '{output_directory}' already exists.")
except PermissionError:
print(f"Permission denied: Unable to create '{output_directory}'.")
except Exception as e:
print(f"An error occurred: {e}")
####################
# some definitions #
####################
# define if an additional NN layer is used (typically True in runs thus far)
# note that for true, it may need to be in the parameter list of the optimizer
deep_layer = True
m = torch.nn.ReLU()
# set the seed for the random initialization
seedAll = 5
torch.manual_seed(seedAll)
numpy.random.seed(seedAll)
# set the number of nodes in the NN layers
if deep_layer:
nodes = 100
else:
nodes = 1000
l1_regularization = False
# conversion from m3/s to m/day, catchment area 47.5 km3 (own calculation from DEM)
# GRDC gives 47.0, Lama-H gives 47.242 km3 which are very similar
conversion_fluxes = 549.3
# line width in plots
width = 0.25
# font size in plots
myFontSize = 7
# meteo start date is 1 jan 1979, end date is 31 juli 2014
# so do not select a time stem outside this range
# streamflow available always in this period
def seed_generator(string):
"""
generator of seed to support different (and known)
seed when rerunning the model
"""
tot = 0
i = 1
for letter in string:
tot += ord(letter) * i
i = i + 10
return tot + seedAll
def timeSeriesPlot_rich(
sfd, fileName, date_time_series, variableTimeSeriesList, xlabel, ylabel
):
"""
function to plot timeseries while running
the optimization
"""
fig = plt.figure(dpi=600, figsize=(6, 3))
plt.xlabel(xlabel, fontsize=myFontSize)
plt.ylabel(ylabel, fontsize=myFontSize)
plt.xticks(fontsize=myFontSize)
plt.yticks(fontsize=myFontSize)
plt.grid(True, linewidth=width, linestyle="dotted")
plt.locator_params(axis="y", nbins=30)
for item in variableTimeSeriesList:
plt.plot(date_time_series, item, linewidth=width)
fig.savefig(sfd + "/" + fileName + ".pdf")
plt.close(fig)
def scatterplot_rich(
sfd, filename, variableOne, variableTwo, xlabel, ylabel, symbol, ylim
):
"""
function to plot scatterplots while running
the optimization
"""
fig = plt.figure(dpi=600, figsize=(4, 3))
# fig = plt.figure(dpi=600)
plt.xlabel(xlabel, fontsize=myFontSize)
plt.ylabel(ylabel, fontsize=myFontSize)
plt.xticks(fontsize=myFontSize)
plt.yticks(fontsize=myFontSize)
plt.plot(variableOne, variableTwo, symbol)
plt.ylim(ylim)
maxX = max(variableOne)
plt.xlim((min(variableOne), 1.05 * maxX))
fig.savefig(sfd + "/" + filename + ".pdf")
plt.close(fig)
def createTrainingIndices():
a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
out = []
if GFS:
spin_up_duration = 366
else:
spin_up_duration = 365
for p in range(0, spin_up_duration): # add one year spin up
out.append(1)
for i in a:
for j in range(0, 365):
out.append(i)
out = numpy.array(out)
outOne = out == 1
outTwo = out == 2
outThree = out == 3
outFour = out == 4
return outOne, outTwo, outThree, outFour
def rand_min_max(mean, proportion):
max = mean + proportion * mean
min = mean - proportion * mean
return torch.rand(1) * (max - min) + min
# class weightConstraint(object):
# def __init__(self):
# pass
#
# def __call__(self, module):
# if hasattr(module, "weight"):
# w = module.weight.data
# w = w.clamp(0.0, 2.0)
# # w=w.clamp(0.0,0.0)
# module.weight.data = w
class EarlyStopper:
def __init__(self, patience=1, min_delta_proportion=1e-10):
self.patience = patience
self.min_delta_proportion = min_delta_proportion
self.counter = 0
self.min_validation_loss = float("inf")
def early_stop(self, validation_loss):
if validation_loss < self.min_validation_loss:
self.min_validation_loss = validation_loss
self.counter = 0
elif validation_loss > (
self.min_validation_loss
+ self.min_delta_proportion * self.min_validation_loss
):
self.counter += 1
if self.counter >= self.patience:
return self.counter, True
return self.counter, False
####################
# Data preparation #
####################
def createMeteoData(input_data_directory, output_directory, startDate, endDate):
"""
Creates meteodata set from input data
"""
precipitation_file = open(output_directory + "precipitation.txt", "w")
temperatureFile = open(output_directory + "temperature.txt", "w")
if GFS:
date = datetime.date(1979, 1, 1)
else:
date = datetime.date(1981, 1, 1)
timestep = datetime.timedelta(days=1)
temperature_time_series = [] # temperature
precipitation_time_series = [] # precipitation
land_sno_time_series = [] # snow
land_eva_time_series = [] # evapotranspiration
if GFS:
weatherDataCSV = "weatherdata-470125_corrected.csv"
else:
weatherDataCSV = "ID_535.csv"
with open(input_data_directory + weatherDataCSV) as csv_file:
if GFS:
csv_reader = csv.reader(csv_file, dialect="excel")
else:
csv_reader = csv.reader(csv_file, dialect="excel", delimiter=";")
line_count = 0
line_out_count = 1
for row in csv_reader:
if line_count == 0:
line_count += 1
else:
if GFS:
temperature = (float(row[4]) + float(row[5])) / 2.0
else:
temperature = float(row[5])
if GFS:
precip = row[6]
else:
precip = row[22]
if GFS:
land_sno = -9.0
land_eva = -9.0
else:
land_sno = float(row[15]) / 1000.0
land_eva = float(row[21]) / 1000.0
if (date >= startDate) and (date <= endDate):
precipitation_file.write(str(line_out_count) + " " + precip + "\n")
precipitation_time_series.append(float(precip))
temperatureFile.write(
str(line_out_count) + " " + str(temperature) + "\n"
)
temperature_time_series.append(temperature)
land_sno_time_series.append(land_sno)
land_eva_time_series.append(land_eva)
line_out_count += 1
line_count += 1
date = date + timestep
precipitation_file.close()
temperatureFile.close()
return (
temperature_time_series,
precipitation_time_series,
land_sno_time_series,
land_eva_time_series,
)
def create_cosero_data(input_data_directory, output_directory, startDate, endDate):
"""
Creates data set from cosero runs in Lama
"""
date = datetime.date(1981, 1, 1)
timestep = datetime.timedelta(days=1)
cosero_sub_s_soil_time_series = [] # subsurface storage, soil
cosero_sub_s_gw_time_series = [] # subsurface storage, groundwater
cosero_eva_f_time_series = [] # evapotranspiration flux
coseroDataCSV = "ID_535_cosero.csv"
with open(input_data_directory + coseroDataCSV) as csv_file:
csv_reader = csv.reader(csv_file, dialect="excel", delimiter=";")
line_count = 0
line_out_count = 1
for row in csv_reader:
if line_count == 0:
line_count += 1
else:
sub_s_soil = float(row[11]) / 1000.0
sub_s_gw = float(row[13]) / 1000.0
eva_f = float(row[9]) / 1000.0
if (date >= startDate) and (date <= endDate):
cosero_sub_s_soil_time_series.append(sub_s_soil)
cosero_sub_s_gw_time_series.append(sub_s_gw)
cosero_eva_f_time_series.append(eva_f)
line_out_count += 1
line_count += 1
date = date + timestep
numpy.save(
output_directory + "cosero_sub_s_soil.npy", cosero_sub_s_soil_time_series
)
numpy.save(output_directory + "cosero_sub_s_gw.npy", cosero_sub_s_gw_time_series)
numpy.save(output_directory + "cosero_eva_f.npy", cosero_eva_f_time_series)
return (
cosero_sub_s_soil_time_series,
cosero_sub_s_gw_time_series,
cosero_eva_f_time_series,
)
def create_cosero_data_additional(
input_data_directory, output_directory, startDate, endDate
):
"""
read model outputs from cosero runs in LamaH, additional attributes
bw 0 item 8
bw 1 item 9
bw 2 item 10
bw 3 item 11
bw 4 item 12
melt item 21
smelt item 36
glacmelt item 40
"""
date = datetime.date(1981, 1, 1)
timestep = datetime.timedelta(days=1)
cosero_bw0_time_series = []
cosero_bw1_time_series = []
cosero_bw2_time_series = []
cosero_bw3_time_series = []
cosero_bw4_time_series = []
cosero_melt_time_series = []
cosero_smelt_time_series = []
cosero_glacmelt_time_series = []
coseroDataCSV = "monitor_sb0276.txt"
with open(input_data_directory + coseroDataCSV) as csv_file:
csv_reader = csv.reader(
csv_file, dialect="excel", delimiter=" ", skipinitialspace=True
)
line_count = 0
line_out_count = 1
for row in csv_reader:
if line_count == 0:
line_count += 1
else:
bw0 = float(row[8]) / 1000.0
bw1 = float(row[9]) / 1000.0
bw2 = float(row[10]) / 1000.0
bw3 = float(row[11]) / 1000.0
bw4 = float(row[12]) / 1000.0
melt = float(row[21]) / 1000.0
smelt = float(row[36]) / 1000.0
glacmelt = float(row[40]) / 1000.0
if (date >= startDate) and (date <= endDate):
cosero_bw0_time_series.append(bw0)
cosero_bw1_time_series.append(bw1)
cosero_bw2_time_series.append(bw2)
cosero_bw3_time_series.append(bw3)
cosero_bw4_time_series.append(bw4)
cosero_melt_time_series.append(melt)
cosero_smelt_time_series.append(smelt)
cosero_glacmelt_time_series.append(glacmelt)
line_out_count += 1
line_count += 1
date = date + timestep
numpy.save(output_directory + "cosero_bw0.npy", cosero_bw0_time_series)
numpy.save(output_directory + "cosero_bw1.npy", cosero_bw1_time_series)
numpy.save(output_directory + "cosero_bw2.npy", cosero_bw2_time_series)
numpy.save(output_directory + "cosero_bw3.npy", cosero_bw3_time_series)
numpy.save(output_directory + "cosero_bw4.npy", cosero_bw4_time_series)
numpy.save(output_directory + "cosero_melt.npy", cosero_melt_time_series)
numpy.save(output_directory + "cosero_smelt.npy", cosero_smelt_time_series)
numpy.save(output_directory + "cosero_glacmelt.npy", cosero_glacmelt_time_series)
def create_streamflow_data(input_data_directory, output_directory, start, end):
"""
Create data set for streamflow data
"""
streamflow_file = open(output_directory + "streamflow.txt", "w")
date = datetime.date(1951, 1, 1)
timestep = datetime.timedelta(days=1)
dischargeFile = open(input_data_directory + "6246180_Q_Day.Cmd_noHeader.txt", "r")
dischargeFileContent = dischargeFile.readlines()
streamFlowTimeSeries = []
date_time_series = []
line_out_count = 1
for i in range(0, len(dischargeFileContent)):
splitted = str.split(dischargeFileContent[i])
discharge = splitted[1]
if (date >= start) and (date <= end):
streamflow_file.write(str(line_out_count) + " " + discharge + "\n")
streamFlowTimeSeries.append(float(discharge))
date_time_series.append(date)
line_out_count += 1
date = date + timestep
dischargeFile.close()
return streamFlowTimeSeries, date_time_series
#########################################
# Dynamical System Neural Network model #
#########################################
class Net(nn.Module):
def __init__(self):
super().__init__()
# neural network layers for each of the three neural network
# model components
self.eva_f_d = nn.Linear(1, nodes) # eva, evapotranspiration
self.eva_f_c = nn.Linear(nodes, 1)
self.sno_f_d = nn.Linear(1, nodes) # sno, snow
self.sno_f_c = nn.Linear(nodes, 1)
self.sub_f_d = nn.Linear(1, nodes) # sub, subsurface
self.sub_f_c = nn.Linear(nodes, 1)
# option to include an additional layer in each component
if deep_layer:
self.eva_f_dd = nn.Linear(nodes, nodes)
self.sno_f_dd = nn.Linear(nodes, nodes)
self.sub_f_dd = nn.Linear(nodes, nodes)
# calibrated parameters of process-based model components
if GFS:
if one_area:
eva_par = 0.8715501
sub_par = 0.0297130
sno_par = 0.0021341
tem_par = -0.8557543000000001
evp_par = 3.52035805 # note input to sigmoid (evp [0,1])
else:
eva_par = 0.7017500
sub_par = 0.0625746
sno_par = 0.0007901
tem_par = -0.9351652
evp_par = 3.4553902
else:
if one_area:
eva_par = 0.014076318
sub_par = 0.03213018
sno_par = 0.0029198169
tem_par = 0.0 # assumed zero
evp_par = 3.5 # note input to sigmoid (evp [0,1]), 3.5 equals 0.97
else:
eva_par = 0.072542064
sub_par = 0.113195494
sno_par = 0.0012788665
tem_par = 0.0 # assumed zero
evp_par = 3.5
self.eva_parameter_obs_creation = eva_par
self.sub_parameter_obs_creation = sub_par
self.sno_parameter_obs_creation = sno_par
self.tem_parameter_obs_creation = tem_par
self.evp_parameter_obs_creation = evp_par
# random initialisation of parameters of process-based model components
# as starting value for calibrating the process-based model
proportion = 0.5
self.eva_parameter = nn.Parameter(rand_min_max(eva_par, proportion))
self.sub_parameter = nn.Parameter(rand_min_max(sub_par, proportion))
self.sno_parameter = nn.Parameter(rand_min_max(sno_par, proportion))
self.tem_parameter = nn.Parameter(rand_min_max(tem_par, proportion))
self.evp_parameter = nn.Parameter(rand_min_max(evp_par, proportion))
# create dictionary with model parameters for accessing these
if deep_layer:
self.params = nn.ModuleDict(
{
"eva": nn.ModuleList([self.eva_f_d, self.eva_f_dd, self.eva_f_c]),
"sno": nn.ModuleList([self.sno_f_d, self.sno_f_dd, self.sno_f_c]),
"sub": nn.ModuleList([self.sub_f_d, self.sub_f_dd, self.sub_f_c]),
"exp": nn.ParameterList(
[
self.eva_parameter,
self.sub_parameter,
self.sno_parameter,
self.tem_parameter,
self.evp_parameter,
]
),
}
)
else:
self.params = nn.ModuleDict(
{
"eva": nn.ModuleList([self.eva_f_d, self.eva_f_c]),
"sno": nn.ModuleList([self.sno_f_d, self.sno_f_c]),
"sub": nn.ModuleList([self.sub_f_d, self.sub_f_c]),
"exp": nn.ParameterList(
[
self.eva_parameter,
self.sub_parameter,
self.sno_parameter,
self.tem_parameter,
self.evp_parameter,
]
),
}
)
def eva_f_calculate(self, temp, mode_eva, deep_layer, linearArt):
"""
Evapotranspiration component model
Calculates evapotranspiration from temperature (temp argument)
mode_eva defines what type of component is used:
obsCreation: process-based component model is used (without training)
linearArt: for synthetic data set generation model (True)
or process-based (expert) model
fit: machine learning component model is trained
fitExpert: process-based component model is calibrated (for real-world data
set only)
"""
if mode_eva == "obsCreation":
if linearArt:
EPot = torch.max(
((0.35 * (0.457 * torch.tensor([temp]) + 8.128)) / 1000.0)
* self.eva_parameter_obs_creation,
torch.tensor(0.0),
)
else:
if temp > -15.0:
EPot = (
(
torch.sin(
(torch.tensor([temp + 15.0]) * 0.25 - 0.5 * torch.pi)
)
+ 1
)
/ 1000.0
) + 0.0001 * torch.tensor([temp + 15.0])
else:
EPot = torch.tensor([0.0])
if mode_eva == "fit":
out_eva_f = m(self.eva_f_d((torch.tensor([temp]))))
if deep_layer:
out_eva_f = m(self.eva_f_dd(out_eva_f))
EPot = torch.sigmoid(self.eva_f_c(out_eva_f)) / 75.0
if mode_eva == "fitExpert":
EPot = torch.max(
((0.35 * (0.457 * temp + 8.128)) / 1000.0) * self.eva_parameter,
torch.tensor(0.0),
)
return EPot
def sno_f_calculate(self, temp, mode_sno, deep_layer, linearArt):
"""
Snow component model
Calculates potential snowmelt from temperature (temp argument)
mode_sno defines what type of component is used:
obsCreation: process-based component model is used (without training)
linearArt: for synthetic data set generation model (True)
or process-based (expert) model
fit: machine learning component model is trained
fitExpert: process-based component model is calibrated (for real-world data
set only)
"""
if mode_sno == "obsCreation":
if linearArt:
melting = temp > 0.0
if melting:
potential_melt = temp * self.sno_parameter_obs_creation
else:
potential_melt = torch.tensor(0.0)
else:
melting = temp > 0.0
if melting:
potential_melt = (
(torch.sin((torch.tensor([temp]) * 0.6 - 0.5 * torch.pi)) + 1)
/ 200
) + 0.0004 * torch.tensor([temp])
else:
potential_melt = torch.tensor(0.0)
if mode_sno == "fit":
out_sno_f = m(self.sno_f_d((torch.tensor([temp]))))
if deep_layer:
out_sno_f = m(self.sno_f_dd(out_sno_f))
potential_melt = torch.sigmoid(self.sno_f_c(out_sno_f)) / 50.0
if mode_sno == "fitExpert":
melting = temp > 0.0
if melting:
potential_melt = temp * self.sno_parameter
else:
potential_melt = torch.tensor(0.0)
return potential_melt
def sub_f_calculate(self, sub_s, mode_sub, deep_layer, linearArt):
"""
Subsurface water component model
Calculates snowmelt from subsurface storage (sub_s argument)
mode_sno defines what type of component is used:
obsCreation: process-based component model is used (without training)
linearArt: for synthetic data set generation model (True)
or process-based (expert) model
fit: machine learning component model is trained
fitExpert: process-based component model is calibrated (for real-world data
set only)
"""
if mode_sub == "obsCreation":
if linearArt:
seepage_pot = self.sub_parameter_obs_creation * sub_s
else:
seepage_pot = (
(torch.sin((torch.tensor([sub_s]) * 20 - 0.5 * torch.pi)) + 1) / 500
) + 0.03 * sub_s
if mode_sub == "fit":
out_sub_f = m(self.sub_f_d((torch.tensor([sub_s]) * 2.0)))
if deep_layer:
out_sub_f = m(self.sub_f_dd(out_sub_f))
proportion = torch.sigmoid(self.sub_f_c(out_sub_f))
seepage_pot = proportion * sub_s
if mode_sub == "fitExpert":
seepage = self.sub_parameter * sub_s
seepage_pot = seepage
return seepage_pot
def com_f_response(self, mode_sub, deep_layer, component, linearArt):
"""
Creates data to plot governing equation ('response function') with
used type of model component.
It first creates a range of drivers (com_s_values) and then
passes these to the model component which returns the range of
corresponding fluxes (com_f_value).
"""
if component == "sub":
com_s_values = numpy.arange(0.0, 1.0, 0.01)
if component == "sno":
com_s_values = numpy.arange(-10.0, 15.0, 0.01)
if component == "eva":
com_s_values = numpy.arange(-10.0, 15.0, 0.01)
com_f_values = numpy.empty(0)
for com_s_value in com_s_values:
if component == "sub":
com_f_value = self.sub_f_calculate(
com_s_value.item(), mode_sub, deep_layer, linearArt
)
if component == "sno":
com_f_value = self.sno_f_calculate(
com_s_value.item(), mode_sub, deep_layer, linearArt
)
if component == "eva":
com_f_value = self.eva_f_calculate(
com_s_value.item(), mode_sub, deep_layer, linearArt
)
if isinstance(com_f_value, torch.Tensor):
if mode_sub == "fitExpert":
com_f_value_detached = com_f_value.detach().numpy()
else:
if component == "sub":
com_f_value_detached = com_f_value.detach().numpy()[0]
if component == "sno":
com_f_value_detached = com_f_value.detach().numpy()
if component == "eva":
com_f_value_detached = com_f_value.detach().numpy()
else:
com_f_value_detached = com_f_value
com_f_values = numpy.append(com_f_values, com_f_value_detached)
com_f_values = numpy.maximum(com_f_values, 0.0)
return com_s_values, com_f_values
def forward(
self,
linearArt, # linear obs creation model
first_epochs, # start of training or not
sno_s_initial, # initial snow storage
sub_s_initial, # initial subsurface storage
temperature, # temperature time series
precipitation, # precipitation time series
mode_eva, # mode evapotranspiration
mode_sno, # mode snow
mode_sub, # mode subsurface
modeTem, # temperature offset
modeEvP, # potential proportion of evap to sublimation
):
# number of time steps in model run
nr_timesteps = len(temperature)
if modeTem == "fitExpert":
temperatureOffset = self.tem_parameter
if modeTem == "obsCreation":
temperatureOffset = self.tem_parameter_obs_creation
if modeEvP == "fitExpert":
evaPropToSno = torch.sigmoid(self.evp_parameter)
if modeEvP == "obsCreation":
evaPropToSno = torch.sigmoid(torch.tensor(self.evp_parameter_obs_creation))
# difference between lower and higher half of the area is (2115 m - 2797 m)
# multiplied by lapse rate of 0.005 gives 3.41 degrees difference in temperature
# use this for semi-distributed model only
if one_area:
areaTemperatureOffsets = [0.0]
else:
areaTemperatureOffsets = [1.705, -1.705]
if one_area:
numberOfAreas = 1
else:
numberOfAreas = 2
# loop over the areas (for distributed model)
for area in range(0, numberOfAreas):
# create emtpy output timeseries for writing
# storages
sno_s_ts = torch.zeros(nr_timesteps)
sub_s_ts = torch.zeros(nr_timesteps)
# fluxes
sno_f_ts = torch.zeros(nr_timesteps)
sub_f_ts = torch.zeros(nr_timesteps)
eva_f_ts = torch.zeros(nr_timesteps)
# set initial storages
sno_s = sno_s_initial
sub_s = sub_s_initial
# loop over the time steps, i.e. the actual dynamical model
for i in range(0, nr_timesteps):
# get system drivers for timestep
temp = temperature[i] + temperatureOffset + areaTemperatureOffsets[area]
######################
# evapotranspiration #
######################
EPot = torch.max(
self.eva_f_calculate(temp, mode_eva, deep_layer, linearArt),
torch.tensor(0.0),
)
eva_f = EPot
eva_f_ts[i] = eva_f
################
# snow or rain #
################
# convert from mm to m
precip = precipitation[i] / 1000.0
snowing = temp < 0.0
if snowing:
snowfall = precip
rainfall = torch.tensor(0.0)
else:
snowfall = torch.tensor(0.0)
rainfall = precip
################
# snow storage #
################
# add snowfall to snow storage
sno_s = sno_s + snowfall
sno_s_ts[i] = sno_s
# snow melt
potential_melt = self.sno_f_calculate(
temp, mode_sno, deep_layer, linearArt
)
# limit snow melt to prevent zero snow cover
# over first epochs, for more efficient training
if first_epochs:
if temp < -5.0:
potential_melt = torch.tensor(0.0)
sno_f = potential_melt
sno_f_ts[i] = sno_f
potential_melt = torch.max(potential_melt, torch.tensor(0))
actualMelt = torch.min(sno_s, potential_melt)
sno_s = sno_s - actualMelt
# sublimation
potentialSublimation = evaPropToSno * EPot
actualSublimation = torch.min(sno_s, potentialSublimation)
sno_s = sno_s - actualSublimation
potentialEvapForSub = EPot - actualSublimation
#######################
# sub surface storage #
#######################
# total input to subsurface storage
totalInput = rainfall + actualMelt
hortonRunoffProportion = 0.0
hortonRunoff = hortonRunoffProportion * totalInput
sub_s = sub_s + (1.0 - hortonRunoffProportion) * totalInput
EAct = torch.min(sub_s, potentialEvapForSub)
sub_s = sub_s - EAct
sub_s_ts[i] = sub_s
seepage_pot = self.sub_f_calculate(
sub_s, mode_sub, deep_layer, linearArt
)
seepageNotNegative = torch.max(seepage_pot, torch.tensor(0.0))
seepageAct = torch.min(seepageNotNegative, sub_s)
sub_f = seepageAct + hortonRunoff
sub_f_ts[i] = sub_f
sub_s = sub_s - seepageAct
# data reorganisation in case of two areas (vstack)
if area == 0:
# storages
sno_s_ts_areas = sno_s_ts
sub_s_ts_areas = sub_s_ts
# fluxes
sno_f_ts_areas = sno_f_ts
sub_f_ts_areas = sub_f_ts
# evapotranspiration
eva_f_ts_areas = eva_f_ts
else:
# storages
sno_s_ts_areas = torch.vstack([sno_s_ts_areas, sno_s_ts])
sub_s_ts_areas = torch.vstack([sub_s_ts_areas, sub_s_ts])
# fluxes
sno_f_ts_areas = torch.vstack([sno_f_ts_areas, sno_f_ts])
sub_f_ts_areas = torch.vstack([sub_f_ts_areas, sub_f_ts])
# evapotranspiration
eva_f_ts_areas = torch.vstack([eva_f_ts_areas, eva_f_ts])
# if one area add the same ones again (mimic two areas, each the same
# such that processing is the same for one or two areas
if one_area:
# storages
sno_s_ts_areas = torch.vstack([sno_s_ts_areas, sno_s_ts])
sub_s_ts_areas = torch.vstack([sub_s_ts_areas, sub_s_ts])
# fluxes
sno_f_ts_areas = torch.vstack([sno_f_ts_areas, sno_f_ts])
sub_f_ts_areas = torch.vstack([sub_f_ts_areas, sub_f_ts])
# evapotranspiration
eva_f_ts_areas = torch.vstack([eva_f_ts_areas, eva_f_ts])
return (
sno_s_ts_areas,
sub_s_ts_areas,
sno_f_ts_areas,
sub_f_ts_areas,
eva_f_ts_areas,
)
def compute_l1_loss(self, w):
return torch.abs(w).sum()
##################################
# Create artificial observations #
##################################
def create_artificial_observations(
temperature_time_series,
precipitation_time_series,
addErrorToArtificialStreamFlow,
linearArt,
):
"""
Create synthetic data set
"""
hydromodel = Net()
sno_s_initial = 0.0
sub_s_initial = 0.0
(
sno_s_ts_areas,
sub_s_ts_areas,
sno_f_ts_areas,
sub_f_ts_areas,
eva_f_ts_areas,
) = hydromodel(
linearArt,
False,
torch.tensor(sno_s_initial),
torch.tensor(sub_s_initial),
torch.tensor(temperature_time_series),
torch.tensor(precipitation_time_series),
mode_eva="obsCreation",
mode_sno="obsCreation",
mode_sub="obsCreation",
modeTem="obsCreation",
modeEvP="obsCreation",
)
sno_s_ts = sno_s_ts_areas.mean(dim=0)
sub_s_ts = sub_s_ts_areas.mean(dim=0)
sno_f_ts = sno_f_ts_areas.mean(dim=0)
sub_f_ts = sub_f_ts_areas.mean(dim=0)
eva_f_ts = eva_f_ts_areas.mean(dim=0)
if addErrorToArtificialStreamFlow:
sd = 0.2
errorMultiplier = numpy.minimum(
numpy.maximum(0.0, numpy.random.normal(1, sd, len(streamFlowTimeSeries))), 2
)
sub_f_ts = torch.max(sub_f_ts * errorMultiplier, torch.tensor(0.0))
return (
sno_s_ts,
sub_s_ts,
sno_f_ts,