-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun_calibration.py
executable file
·2648 lines (2335 loc) · 152 KB
/
run_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
"""Run model calibration."""
# Built-in libraries
import argparse
import inspect
import multiprocessing
import os
import sys
import time
# External libraries
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
from scipy import stats
import pygem
import pygem_input as pygem_prms
from pygem import class_climate
from pygem.massbalance import PyGEMMassBalance
#from pygem.glacierdynamics import MassRedistributionCurveModel
from pygem.oggm_compat import single_flowline_glacier_directory, single_flowline_glacier_directory_with_calving
import pygem.pygem_modelsetup as modelsetup
from pygem.shop import debris, mbdata, icethickness
#from oggm import cfg
#from oggm import graphics
#from oggm import tasks
#from oggm import utils
from oggm import workflow
#from oggm.core import climate
#from oggm.core.flowline import FluxBasedModel
#from oggm.core.inversion import calving_flux_from_depth
import torch
import gpytorch
import sklearn.model_selection
# Model-specific libraries
if 'MCMC' in pygem_prms.option_calibration:
import pymc
from pymc import deterministic
#%% FUNCTIONS
def getparser():
"""
Use argparse to add arguments from the command line
Parameters
----------
ref_gcm_name (optional) : str
reference gcm name
num_simultaneous_processes (optional) : int
number of cores to use in parallels
rgi_glac_number_fn : str
filename of .pkl file containing a list of glacier numbers which is used to run batches on the supercomputer
rgi_glac_number : str
rgi glacier number to run for supercomputer
progress_bar : bool
Switch for turning the progress bar on or off (default = False)
debug : bool
Switch for turning debug printing on or off (default = False)
Returns
-------
Object containing arguments and their respective values.
"""
parser = argparse.ArgumentParser(description="run calibration in parallel")
# add arguments
parser.add_argument('-ref_gcm_name', action='store', type=str, default=pygem_prms.ref_gcm_name,
help='reference gcm name')
parser.add_argument('-rgi_glac_number_fn', action='store', type=str, default=None,
help='Filename containing list of rgi_glac_number, helpful for running batches on spc')
parser.add_argument('-rgi_glac_number', action='store', type=str, default=None,
help='rgi glacier number for supercomputer')
parser.add_argument('-num_simultaneous_processes', action='store', type=int, default=1,
help='number of simultaneous processes (cores) to use (default is 1, ie. no parallelization)')
# flags
parser.add_argument('-progress_bar', action='store_true',
help='Flag to show progress bar')
parser.add_argument('-debug', action='store_true',
help='Flag for debugging')
return parser
def mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=None, t1=None, t2=None,
option_areaconstant=1, return_tbias_mustmelt=False, return_tbias_mustmelt_wmb=False):
"""
Run the mass balance and calculate the mass balance [mwea]
Parameters
----------
option_areaconstant : Boolean
Returns
-------
mb_mwea : float
mass balance [m w.e. a-1]
"""
# RUN MASS BALANCE MODEL
mbmod = PyGEMMassBalance(gdir, modelprms, glacier_rgi_table, fls=fls, option_areaconstant=True,
debug=pygem_prms.debug_mb, debug_refreeze=pygem_prms.debug_refreeze)
years = np.arange(0, int(gdir.dates_table.shape[0]/12))
for year in years:
mbmod.get_annual_mb(fls[0].surface_h, fls=fls, fl_id=0, year=year, debug=False)
# Option for must melt condition
if return_tbias_mustmelt:
# Number of years and bins with negative climatic mass balance
nbinyears_negmbclim = len(np.where(mbmod.glac_bin_massbalclim_annual < 0)[0])
return nbinyears_negmbclim
elif return_tbias_mustmelt_wmb:
nbinyears_negmbclim = len(np.where(mbmod.glac_bin_massbalclim_annual < 0)[0])
t1_idx = gdir.mbdata['t1_idx']
t2_idx = gdir.mbdata['t2_idx']
nyears = gdir.mbdata['nyears']
mb_mwea = mbmod.glac_wide_massbaltotal[t1_idx:t2_idx+1].sum() / mbmod.glac_wide_area_annual[0] / nyears
return nbinyears_negmbclim, mb_mwea
# Otherwise return specific mass balance
else:
# Specific mass balance [mwea]
t1_idx = gdir.mbdata['t1_idx']
t2_idx = gdir.mbdata['t2_idx']
nyears = gdir.mbdata['nyears']
mb_mwea = mbmod.glac_wide_massbaltotal[t1_idx:t2_idx+1].sum() / mbmod.glac_wide_area_annual[0] / nyears
return mb_mwea
# class for Gaussian Process model for mass balance emulator
class ExactGPModel(gpytorch.models.ExactGP):
""" Use the simplest form of GP model, exact inference """
def __init__(self, train_x, train_y, likelihood):
super(ExactGPModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = gpytorch.means.ConstantMean()
self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel())
def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)
# glacier wide mass balance emulator class object
class massbalEmulator:
def __init__(self, mod, likelihood, X_mean, X_std, y_mean, y_std):
self.mod = mod
self.likelihood = likelihood
self.X_mean = X_mean
self.X_std = X_std
self.y_mean = y_mean
self.y_std = y_std
# evaluate the emulator for a given set of model paramaters
def eval(self, Xtest):
# normalize each parameter
Xtest[:] = [(x - mu) / sigma for x, mu, sigma in zip(Xtest, self.X_mean, self.X_std)]
# convert to torch tensor
Xtest_normed = torch.tensor(np.array([Xtest])).to(torch.float)
# pass to mbEmulator.mod() to evaluate normed values
mb_mwea_norm = self.mod(Xtest_normed).mean.detach().numpy()[0]
# un-normalize
mb_mwea = mb_mwea_norm * self.y_std + self.y_mean
return mb_mwea
# load emulator
@classmethod
def load(cls, em_mod_path=None):
# ----- LOAD EMULATOR -----
torch.set_num_threads(1)
state_dict = torch.load(em_mod_path)
emulator_extra_fp = em_mod_path.replace('.pth', '_extra.pkl')
with open(emulator_extra_fp, 'rb') as f:
emulator_extra_dict = pickle.load(f)
X_train = emulator_extra_dict['X_train']
X_mean = emulator_extra_dict['X_mean']
X_std = emulator_extra_dict['X_std']
y_train = emulator_extra_dict['y_train']
y_mean = emulator_extra_dict['y_mean']
y_std = emulator_extra_dict['y_std']
# initialize likelihood and model
likelihood = gpytorch.likelihoods.GaussianLikelihood()
# Create a new GP model
model = ExactGPModel(X_train, y_train, likelihood)
model.load_state_dict(state_dict)
model.eval()
return cls(model, likelihood, X_mean, X_std, y_mean, y_std)
def create_emulator(glacier_str, sims_df, y_cn,
X_cns=['tbias','kp','ddfsnow'],
em_fp=pygem_prms.output_filepath + 'emulator/', debug=False):
"""
create emulator for calibrating PyGEM model parameters
Parameters
----------
glacier_str : str
glacier RGIId string
sims_dict : Dictionary
parameter distributions for each emulator simulation
y_cn : str
variable name in sims_dict which to fit parameter sets to fit
X_cns : list
PyGEM model parameters to calibrate
em_fp : str
filepath to save emulator results
Returns
-------
X_train, X_mean, X_std, y_train, y_mean, y_std, likelihood, model
"""
# This is required for the supercomputer such that resources aren't stolen from other cpus
torch.set_num_threads(1)
assert y_cn in sims_df.columns, 'emulator error: y_cn not in sims_df'
##################
### get X data ###
##################
X = sims_df.loc[:,X_cns].values
y = sims_df[y_cn].values
if debug:
print(f'Calibration x-parameters: {", ".join(X_cns)}')
print(f'Calibration y-parametes: {y_cn}')
print(f'X:\n{X}')
print(f'X-shape:\n{X.shape}\n')
print(f'y:\n{y}')
print(f'y-shape:\n{y.shape}')
##################
# Normalize data
X_mean = X.mean(axis=0)
X_std = X.std(axis=0)
X_norm = (X - X_mean) / X_std
y_mean = y.mean()
y_std = y.std()
y_norm = (y - y_mean) / y_std
# Split into training and test data and cast to torch tensors
X_train,X_test,y_train,y_test = [torch.tensor(x).to(torch.float)
for x in sklearn.model_selection.train_test_split(X_norm,y_norm)]
# Add a small amount of noise
y_train += torch.randn(*y_train.shape)*0.01
# initialize likelihood and model
likelihood = gpytorch.likelihoods.GaussianLikelihood()
model = ExactGPModel(X_train, y_train, likelihood)
# Plot test set predictions prior to training
# Get into evaluation (predictive posterior) mode
model.eval()
likelihood.eval()
with torch.no_grad():#, gpytorch.settings.fast_pred_var():
y_pred = likelihood(model(X_test))
idx = np.argsort(y_test.numpy())
with torch.no_grad():
lower, upper = y_pred.confidence_region()
if debug:
f, ax = plt.subplots(1, 1, figsize=(4, 4))
ax.plot(y_test.numpy()[idx], y_pred.mean.numpy()[idx], 'k*')
ax.fill_between(y_test.numpy()[idx], lower.numpy()[idx], upper.numpy()[idx], alpha=0.5)
plt.show()
# ----- Find optimal model hyperparameters -----
model.train()
likelihood.train()
# Use the adam optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=0.03) # Includes GaussianLikelihood parameters
# "Loss" for GPs - the marginal log likelihood
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)
for i in range(1000):
# Zero gradients from previous iteration
optimizer.zero_grad()
# Output from model
output = model(X_train)
# Calc loss and backprop gradients
loss = -mll(output, y_train)
loss.backward()
# if debug and i%100==0:
# print(i, loss.item(), model.covar_module.base_kernel.lengthscale[0],
# model.likelihood.noise.item())
optimizer.step()
# Plot posterior distributions (with test data on x-axis)
# Get into evaluation (predictive posterior) mode
model.eval()
likelihood.eval()
with torch.no_grad():#, gpytorch.settings.fast_pred_var():
y_pred = likelihood(model(X_test))
idx = np.argsort(y_test.numpy())
with torch.no_grad():
lower, upper = y_pred.confidence_region()
if debug:
f, ax = plt.subplots(1, 1, figsize=(4, 4))
ax.plot(y_test.numpy()[idx], y_pred.mean.numpy()[idx], 'k*')
ax.fill_between(y_test.numpy()[idx], lower.numpy()[idx], upper.numpy()[idx],
alpha=0.5)
plt.show()
if debug:
# Compare user-defined parameter sets within the emulator
tbias_set = (np.arange(-7,4,0.5)).reshape(-1,1)
kp_set = np.zeros(tbias_set.shape) + 1
ddf_set = np.zeros(tbias_set.shape) + 0.0041
modelprms_set = np.hstack((tbias_set, kp_set, ddf_set))
modelprms_set_norm = (modelprms_set - X_mean) / X_std
y_set_norm = model(torch.tensor(modelprms_set_norm).to(torch.float)).mean.detach().numpy()
y_set = y_set_norm * y_std + y_mean
f, ax = plt.subplots(1, 1, figsize=(4, 4))
kp_1_idx = np.where(sims_df['kp'] == 1)[0]
ax.plot(sims_df.loc[kp_1_idx,'tbias'], sims_df.loc[kp_1_idx,y_cn])
ax.plot(tbias_set,y_set,'.')
ax.set_xlabel('tbias (degC)')
if y_cn == 'mb_mwea':
ax.set_ylabel('PyGEM MB (mwea)')
elif y_cn == 'nbinyrs_negmbclim':
ax.set_ylabel('nbinyrs_negmbclim (-)')
plt.show()
# Compare the modeled and emulated mass balances
y_em_norm = model(torch.tensor(X_norm).to(torch.float)).mean.detach().numpy()
y_em = y_em_norm * y_std + y_mean
f, ax = plt.subplots(1, 1, figsize=(4, 4))
ax.plot(y,y_em,'.')
ax.plot([y.min(),y.max()], [y.min(), y.max()])
if y_cn == 'mb_mwea':
ax.set_xlabel('emulator MB (mwea)')
ax.set_ylabel('PyGEM MB (mwea)')
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
elif y_cn == 'nbinyrs_negmbclim':
ax.set_xlabel('emulator nbinyrs_negmbclim (-)')
ax.set_ylabel('PyGEM nbinyrs_negmbclim (-)')
plt.show()
# ----- EXPORT EMULATOR -----
# Save emulator (model state, x_train, y_train, etc.)
em_mod_fn = glacier_str + '-emulator-' + y_cn + '.pth'
em_mod_fp = em_fp + 'models/' + glacier_str.split('.')[0].zfill(2) + '/'
if not os.path.exists(em_mod_fp):
os.makedirs(em_mod_fp, exist_ok=True)
torch.save(model.state_dict(), em_mod_fp + em_mod_fn)
# Extra required datasets
em_extra_dict = {'X_train': X_train,
'X_mean': X_mean,
'X_std': X_std,
'y_train': y_train,
'y_mean': y_mean,
'y_std': y_std}
em_extra_fn = em_mod_fn.replace('.pth','_extra.pkl')
with open(em_mod_fp + em_extra_fn, 'wb') as f:
pickle.dump(em_extra_dict, f)
return massbalEmulator(model, likelihood, X_mean, X_std, y_mean, y_std)
#%%
def main(list_packed_vars):
"""
Model simulation
Parameters
----------
list_packed_vars : list
list of packed variables that enable the use of parallels
Returns
-------
netcdf files of the simulation output (specific output is dependent on the output option)
"""
# Unpack variables
glac_no = list_packed_vars[1]
gcm_name = list_packed_vars[2]
parser = getparser()
args = parser.parse_args()
debug = args.debug
# ===== LOAD GLACIERS =====
main_glac_rgi = modelsetup.selectglaciersrgitable(glac_no=glac_no)
# ===== TIME PERIOD =====
dates_table = modelsetup.datesmodelrun(
startyear=pygem_prms.ref_startyear, endyear=pygem_prms.ref_endyear, spinupyears=pygem_prms.ref_spinupyears,
option_wateryear=pygem_prms.ref_wateryear)
# ===== LOAD CLIMATE DATA =====
# Climate class
assert gcm_name in ['ERA5', 'ERA-Interim'], 'Error: Calibration not set up for ' + gcm_name
gcm = class_climate.GCM(name=gcm_name)
# Air temperature [degC]
gcm_temp, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.temp_fn, gcm.temp_vn, main_glac_rgi, dates_table)
if pygem_prms.option_ablation == 2 and gcm_name in ['ERA5']:
gcm_tempstd, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.tempstd_fn, gcm.tempstd_vn,
main_glac_rgi, dates_table)
else:
gcm_tempstd = np.zeros(gcm_temp.shape)
# Precipitation [m]
gcm_prec, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.prec_fn, gcm.prec_vn, main_glac_rgi, dates_table)
# Elevation [m asl]
gcm_elev = gcm.importGCMfxnearestneighbor_xarray(gcm.elev_fn, gcm.elev_vn, main_glac_rgi)
# Lapse rate [degC m-1]
gcm_lr, gcm_dates = gcm.importGCMvarnearestneighbor_xarray(gcm.lr_fn, gcm.lr_vn, main_glac_rgi, dates_table)
# ===== LOOP THROUGH GLACIERS TO RUN CALIBRATION =====
for glac in range(main_glac_rgi.shape[0]):
if debug or glac == 0 or glac == main_glac_rgi.shape[0]:
print(gcm_name,':', main_glac_rgi.loc[main_glac_rgi.index.values[glac],'RGIId'])
# Select subsets of data
glacier_rgi_table = main_glac_rgi.loc[main_glac_rgi.index.values[glac], :]
glacier_str = '{0:0.5f}'.format(glacier_rgi_table['RGIId_float'])
# ===== Load glacier data: area (km2), ice thickness (m), width (km) =====
try:
if not glacier_rgi_table['TermType'] in [1,5] or not pygem_prms.include_calving:
gdir = single_flowline_glacier_directory(glacier_str, logging_level=pygem_prms.logging_level)
gdir.is_tidewater = False
else:
# set reset=True to overwrite non-calving directory that may already exist
gdir = single_flowline_glacier_directory_with_calving(glacier_str, logging_level=pygem_prms.logging_level,
reset=False)
gdir.is_tidewater = True
fls = gdir.read_pickle('inversion_flowlines')
glacier_area = fls[0].widths_m * fls[0].dx_meter
# Add climate data to glacier directory
gdir.historical_climate = {'elev': gcm_elev[glac],
'temp': gcm_temp[glac,:],
'tempstd': gcm_tempstd[glac,:],
'prec': gcm_prec[glac,:],
'lr': gcm_lr[glac,:]}
gdir.dates_table = dates_table
# ----- Calibration data -----
try:
mbdata_fn = gdir.get_filepath('mb_obs')
if not os.path.exists(mbdata_fn):
# Compute all the stuff
list_tasks = [
# Consensus ice thickness
icethickness.consensus_gridded,
# Mass balance data
mbdata.mb_df_to_gdir
]
# Debris tasks
if pygem_prms.include_debris:
list_tasks.append(debris.debris_to_gdir)
list_tasks.append(debris.debris_binned)
for task in list_tasks:
workflow.execute_entity_task(task, gdir)
with open(mbdata_fn, 'rb') as f:
gdir.mbdata = pickle.load(f)
# Non-tidewater glaciers
if not gdir.is_tidewater:
# Load data
mb_obs_mwea = gdir.mbdata['mb_mwea']
mb_obs_mwea_err = gdir.mbdata['mb_mwea_err']
# Tidewater glaciers
# use climatic mass balance since calving_k already calibrated separately
else:
mb_obs_mwea = gdir.mbdata['mb_clim_mwea']
mb_obs_mwea_err = gdir.mbdata['mb_clim_mwea_err']
# Add time indices consistent with dates_table for mb calculations
t1_year = gdir.mbdata['t1_datetime'].year
t1_month = gdir.mbdata['t1_datetime'].month
t2_year = gdir.mbdata['t2_datetime'].year
t2_month = gdir.mbdata['t2_datetime'].month
t1_idx = dates_table[(t1_year == dates_table['year']) & (t1_month == dates_table['month'])].index.values[0]
t2_idx = dates_table[(t2_year == dates_table['year']) & (t2_month == dates_table['month'])].index.values[0]
# Record indices
gdir.mbdata['t1_idx'] = t1_idx
gdir.mbdata['t2_idx'] = t2_idx
if debug:
print(' mb_data (mwea): ' + str(np.round(mb_obs_mwea,2)) + ' +/- ' + str(np.round(mb_obs_mwea_err,2)))
except:
gdir.mbdata = None
# LOG FAILURE
fail_fp = pygem_prms.output_filepath + 'cal_fail/' + glacier_str.split('.')[0].zfill(2) + '/'
if not os.path.exists(fail_fp):
os.makedirs(fail_fp, exist_ok=True)
txt_fn_fail = glacier_str + "-cal_fail.txt"
with open(fail_fp + txt_fn_fail, "w") as text_file:
text_file.write(glacier_str + ' was missing mass balance data.')
print('\n' + glacier_str + ' mass balance data missing. Check dataset and column names.\n')
except:
fls = None
if debug:
assert os.path.exists(gdir.get_filepath('mb_obs')), 'Mass balance data missing. Check dataset and column names'
# ----- CALIBRATION OPTIONS ------
if (fls is not None) and (gdir.mbdata is not None) and (glacier_area.sum() > 0):
modelprms = {'kp': pygem_prms.kp,
'tbias': pygem_prms.tbias,
'ddfsnow': pygem_prms.ddfsnow,
'ddfice': pygem_prms.ddfice,
'tsnow_threshold': pygem_prms.tsnow_threshold,
'precgrad': pygem_prms.precgrad}
#%% ===== EMULATOR TO SETUP MCMC ANALYSIS AND/OR RUN HH2015 WITH EMULATOR =====
# - precipitation factor, temperature bias, degree-day factor of snow
if pygem_prms.option_calibration == 'emulator':
tbias_step = pygem_prms.tbias_step
tbias_init = pygem_prms.tbias_init
kp_init = pygem_prms.kp_init
ddfsnow_init = pygem_prms.ddfsnow_init
# ----- Initialize model parameters -----
modelprms['tbias'] = tbias_init
modelprms['kp'] = kp_init
modelprms['ddfsnow'] = ddfsnow_init
modelprms['ddfice'] = modelprms['ddfsnow'] / pygem_prms.ddfsnow_iceratio
# Load sims df
sims_fp = pygem_prms.emulator_fp + 'sims/' + glacier_str.split('.')[0].zfill(2) + '/'
sims_fn = glacier_str + '-' + str(pygem_prms.emulator_sims) + '_emulator_sims.csv'
if not os.path.exists(sims_fp + sims_fn) or pygem_prms.overwrite_em_sims:
# ----- Temperature bias bounds (ensure reasonable values) -----
# Tbias lower bound based on some bins having negative climatic mass balance
tbias_maxacc = (-1 * (gdir.historical_climate['temp'] + gdir.historical_climate['lr'] *
(fls[0].surface_h.min() - gdir.historical_climate['elev'])).max())
modelprms['tbias'] = tbias_maxacc
nbinyears_negmbclim, mb_mwea = mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=fls,
return_tbias_mustmelt_wmb=True)
while nbinyears_negmbclim < 10 or mb_mwea > mb_obs_mwea:
modelprms['tbias'] = modelprms['tbias'] + tbias_step
nbinyears_negmbclim, mb_mwea = mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=fls,
return_tbias_mustmelt_wmb=True)
if debug:
print('tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'ddfsnow:', np.round(modelprms['ddfsnow'],4), 'mb_mwea:', np.round(mb_mwea,3),
'nbinyears_negmbclim:', nbinyears_negmbclim)
tbias_stepsmall = 0.05
while nbinyears_negmbclim > 10:
modelprms['tbias'] = modelprms['tbias'] - tbias_stepsmall
nbinyears_negmbclim, mb_mwea = mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=fls,
return_tbias_mustmelt_wmb=True)
if debug:
print('tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'ddfsnow:', np.round(modelprms['ddfsnow'],4), 'mb_mwea:', np.round(mb_mwea,3),
'nbinyears_negmbclim:', nbinyears_negmbclim)
# Tbias lower bound
tbias_bndlow = modelprms['tbias'] + tbias_stepsmall
modelprms['tbias'] = tbias_bndlow
nbinyears_negmbclim, mb_mwea = mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=fls,
return_tbias_mustmelt_wmb=True)
output_all = np.array([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow'],
mb_mwea, nbinyears_negmbclim])
# Tbias lower bound & high precipitation factor
modelprms['kp'] = stats.gamma.ppf(0.99, pygem_prms.kp_gamma_alpha, scale=1/pygem_prms.kp_gamma_beta)
nbinyears_negmbclim, mb_mwea = mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=fls,
return_tbias_mustmelt_wmb=True)
output_single = np.array([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow'],
mb_mwea, nbinyears_negmbclim])
output_all = np.vstack((output_all, output_single))
if debug:
print('tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'ddfsnow:', np.round(modelprms['ddfsnow'],4), 'mb_mwea:', np.round(mb_mwea,3))
# Tbias 'mid-point'
modelprms['kp'] = pygem_prms.kp_init
ncount_tbias = 0
tbias_bndhigh = 10
tbias_middle = tbias_bndlow + tbias_step
while mb_mwea > mb_obs_mwea and modelprms['tbias'] < 50:
modelprms['tbias'] = modelprms['tbias'] + tbias_step
nbinyears_negmbclim, mb_mwea = mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=fls,
return_tbias_mustmelt_wmb=True)
output_single = np.array([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow'],
mb_mwea, nbinyears_negmbclim])
output_all = np.vstack((output_all, output_single))
tbias_middle = modelprms['tbias'] - tbias_step / 2
ncount_tbias += 1
if debug:
print(ncount_tbias,
'tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'ddfsnow:', np.round(modelprms['ddfsnow'],4), 'mb_mwea:', np.round(mb_mwea,3))
# Tbias upper bound (run for equal amount of steps above the midpoint)
while ncount_tbias > 0:
modelprms['tbias'] = modelprms['tbias'] + tbias_step
nbinyears_negmbclim, mb_mwea = mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=fls,
return_tbias_mustmelt_wmb=True)
output_single = np.array([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow'],
mb_mwea, nbinyears_negmbclim])
output_all = np.vstack((output_all, output_single))
tbias_bndhigh = modelprms['tbias']
ncount_tbias -= 1
if debug:
print(ncount_tbias,
'tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'ddfsnow:', np.round(modelprms['ddfsnow'],4), 'mb_mwea:', np.round(mb_mwea,3))
# ------ RANDOM RUNS -------
# Temperature bias
if pygem_prms.tbias_disttype == 'uniform':
tbias_random = np.random.uniform(low=tbias_bndlow, high=tbias_bndhigh,
size=pygem_prms.emulator_sims)
elif pygem_prms.tbias_disttype == 'truncnormal':
tbias_zlow = (tbias_bndlow - tbias_middle) / pygem_prms.tbias_sigma
tbias_zhigh = (tbias_bndhigh - tbias_middle) / pygem_prms.tbias_sigma
tbias_random = stats.truncnorm.rvs(a=tbias_zlow, b=tbias_zhigh, loc=tbias_middle,
scale=pygem_prms.tbias_sigma, size=pygem_prms.emulator_sims)
if debug:
print('\ntbias random:', tbias_random.mean(), tbias_random.std())
# Precipitation factor
kp_random = stats.gamma.rvs(pygem_prms.kp_gamma_alpha, scale=1/pygem_prms.kp_gamma_beta,
size=pygem_prms.emulator_sims)
if debug:
print('kp random:', kp_random.mean(), kp_random.std())
# Degree-day factor of snow
ddfsnow_zlow = (pygem_prms.ddfsnow_bndlow - pygem_prms.ddfsnow_mu) / pygem_prms.ddfsnow_sigma
ddfsnow_zhigh = (pygem_prms.ddfsnow_bndhigh - pygem_prms.ddfsnow_mu) / pygem_prms.ddfsnow_sigma
ddfsnow_random = stats.truncnorm.rvs(a=ddfsnow_zlow, b=ddfsnow_zhigh, loc=pygem_prms.ddfsnow_mu,
scale=pygem_prms.ddfsnow_sigma, size=pygem_prms.emulator_sims)
if debug:
print('ddfsnow random:', ddfsnow_random.mean(), ddfsnow_random.std(),'\n')
# Run through random values
for nsim in range(pygem_prms.emulator_sims):
modelprms['tbias'] = tbias_random[nsim]
modelprms['kp'] = kp_random[nsim]
modelprms['ddfsnow'] = ddfsnow_random[nsim]
modelprms['ddfice'] = modelprms['ddfsnow'] / pygem_prms.ddfsnow_iceratio
nbinyears_negmbclim, mb_mwea = mb_mwea_calc(gdir, modelprms, glacier_rgi_table, fls=fls,
return_tbias_mustmelt_wmb=True)
output_single = np.array([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow'],
mb_mwea, nbinyears_negmbclim])
output_all = np.vstack((output_all, output_single))
if debug and nsim%500 == 0:
print(nsim, 'tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'ddfsnow:', np.round(modelprms['ddfsnow'],4), 'mb_mwea:', np.round(mb_mwea,3))
# ----- Export results -----
sims_df = pd.DataFrame(output_all, columns=['tbias', 'kp', 'ddfsnow', 'mb_mwea',
'nbinyrs_negmbclim'])
if os.path.exists(sims_fp) == False:
os.makedirs(sims_fp, exist_ok=True)
sims_df.to_csv(sims_fp + sims_fn, index=False)
else:
# Load simulations
sims_df = pd.read_csv(sims_fp + sims_fn)
# ----- EMULATOR: Mass balance -----
em_mod_fn = glacier_str + '-emulator-mb_mwea.pth'
em_mod_fp = pygem_prms.emulator_fp + 'models/' + glacier_str.split('.')[0].zfill(2) + '/'
if not os.path.exists(em_mod_fp + em_mod_fn) or pygem_prms.overwrite_em_sims:
mbEmulator = create_emulator(glacier_str, sims_df, y_cn='mb_mwea', debug=debug)
else:
mbEmulator = massbalEmulator.load(em_mod_path = em_mod_fp + em_mod_fn)
# ===== HH2015 MODIFIED CALIBRATION USING EMULATOR =====
if pygem_prms.opt_hh2015_mod:
tbias_init = pygem_prms.tbias_init
tbias_step = pygem_prms.tbias_step
kp_init = pygem_prms.kp_init
kp_bndlow = pygem_prms.kp_bndlow
kp_bndhigh = pygem_prms.kp_bndhigh
ddfsnow_init = pygem_prms.ddfsnow_init
# ----- FUNCTIONS: COMPUTATIONALLY FASTER AND MORE ROBUST THAN SCIPY MINIMIZE -----
def update_bnds(prm2opt, prm_bndlow, prm_bndhigh, prm_mid, mb_mwea_low, mb_mwea_high, mb_mwea_mid,
debug=False):
""" Update bounds for various parameters for the single_param_optimizer """
# If mass balance less than observation, reduce tbias
if prm2opt == 'kp':
if mb_mwea_mid < mb_obs_mwea:
prm_bndlow_new, mb_mwea_low_new = prm_mid, mb_mwea_mid
prm_bndhigh_new, mb_mwea_high_new = prm_bndhigh, mb_mwea_high
else:
prm_bndlow_new, mb_mwea_low_new = prm_bndlow, mb_mwea_low
prm_bndhigh_new, mb_mwea_high_new = prm_mid, mb_mwea_mid
elif prm2opt == 'ddfsnow':
if mb_mwea_mid < mb_obs_mwea:
prm_bndlow_new, mb_mwea_low_new = prm_bndlow, mb_mwea_low
prm_bndhigh_new, mb_mwea_high_new = prm_mid, mb_mwea_mid
else:
prm_bndlow_new, mb_mwea_low_new = prm_mid, mb_mwea_mid
prm_bndhigh_new, mb_mwea_high_new = prm_bndhigh, mb_mwea_high
elif prm2opt == 'tbias':
if mb_mwea_mid < mb_obs_mwea:
prm_bndlow_new, mb_mwea_low_new = prm_bndlow, mb_mwea_low
prm_bndhigh_new, mb_mwea_high_new = prm_mid, mb_mwea_mid
else:
prm_bndlow_new, mb_mwea_low_new = prm_mid, mb_mwea_mid
prm_bndhigh_new, mb_mwea_high_new = prm_bndhigh, mb_mwea_high
prm_mid_new = (prm_bndlow_new + prm_bndhigh_new) / 2
modelprms[prm2opt] = prm_mid_new
modelprms['ddfice'] = modelprms['ddfsnow'] / pygem_prms.ddfsnow_iceratio
mb_mwea_mid_new = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
if debug:
print(prm2opt + '_bndlow:', np.round(prm_bndlow_new,2),
'mb_mwea_low:', np.round(mb_mwea_low_new,2))
print(prm2opt + '_bndhigh:', np.round(prm_bndhigh_new,2),
'mb_mwea_high:', np.round(mb_mwea_high_new,2))
print(prm2opt + '_mid:', np.round(prm_mid_new,2),
'mb_mwea_mid:', np.round(mb_mwea_mid_new,3))
return (prm_bndlow_new, prm_bndhigh_new, prm_mid_new,
mb_mwea_low_new, mb_mwea_high_new, mb_mwea_mid_new)
def single_param_optimizer(modelprms_subset, mb_obs_mwea, prm2opt=None,
kp_bnds=None, tbias_bnds=None, ddfsnow_bnds=None,
mb_mwea_threshold=0.005, debug=False):
""" Single parameter optimizer based on a mid-point approach
Computationally more robust and sometimes faster than scipy minimize
"""
assert prm2opt is not None, 'For single_param_optimizer you must specify parameter to optimize'
if prm2opt == 'kp':
prm_bndlow = kp_bnds[0]
prm_bndhigh = kp_bnds[1]
modelprms['tbias'] = modelprms_subset['tbias']
modelprms['ddfsnow'] = modelprms_subset['ddfsnow']
elif prm2opt == 'ddfsnow':
prm_bndlow = ddfsnow_bnds[0]
prm_bndhigh = ddfsnow_bnds[1]
modelprms['kp'] = modelprms_subset['kp']
modelprms['tbias'] = modelprms_subset['tbias']
elif prm2opt == 'tbias':
prm_bndlow = tbias_bnds[0]
prm_bndhigh = tbias_bnds[1]
modelprms['kp'] = modelprms_subset['kp']
modelprms['ddfsnow'] = modelprms_subset['ddfsnow']
# Lower bound
modelprms[prm2opt] = prm_bndlow
modelprms['ddfice'] = modelprms['ddfsnow'] / pygem_prms.ddfsnow_iceratio
mb_mwea_low = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
# Upper bound
modelprms[prm2opt] = prm_bndhigh
modelprms['ddfice'] = modelprms['ddfsnow'] / pygem_prms.ddfsnow_iceratio
mb_mwea_high = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
# Middle bound
prm_mid = (prm_bndlow + prm_bndhigh) / 2
modelprms[prm2opt] = prm_mid
modelprms['ddfice'] = modelprms['ddfsnow'] / pygem_prms.ddfsnow_iceratio
mb_mwea_mid = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
if debug:
print(prm2opt + '_bndlow:', np.round(prm_bndlow,2), 'mb_mwea_low:', np.round(mb_mwea_low,2))
print(prm2opt + '_bndhigh:', np.round(prm_bndhigh,2), 'mb_mwea_high:', np.round(mb_mwea_high,2))
print(prm2opt + '_mid:', np.round(prm_mid,2), 'mb_mwea_mid:', np.round(mb_mwea_mid,3))
# Optimize the model parameter
if np.absolute(mb_mwea_low - mb_obs_mwea) <= mb_mwea_threshold:
modelprms[prm2opt] = prm_bndlow
mb_mwea_mid = mb_mwea_low
elif np.absolute(mb_mwea_low - mb_obs_mwea) <= mb_mwea_threshold:
modelprms[prm2opt] = prm_bndhigh
mb_mwea_mid = mb_mwea_high
else:
ncount = 0
while (np.absolute(mb_mwea_mid - mb_obs_mwea) > mb_mwea_threshold and
np.absolute(mb_mwea_low - mb_mwea_high) > mb_mwea_threshold):
if debug:
print('\n ncount:', ncount)
(prm_bndlow, prm_bndhigh, prm_mid, mb_mwea_low, mb_mwea_high, mb_mwea_mid) = (
update_bnds(prm2opt, prm_bndlow, prm_bndhigh, prm_mid,
mb_mwea_low, mb_mwea_high, mb_mwea_mid, debug=debug))
ncount += 1
return modelprms, mb_mwea_mid
# ===== SET THINGS UP ======
if debug:
sims_df['mb_em'] = np.nan
for nidx in sims_df.index.values:
modelprms['tbias'] = sims_df.loc[nidx,'tbias']
modelprms['kp'] = sims_df.loc[nidx,'kp']
modelprms['ddfsnow'] = sims_df.loc[nidx,'ddfsnow']
sims_df.loc[nidx,'mb_em'] = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
sims_df['mb_em_dif'] = sims_df['mb_em'] - sims_df['mb_mwea']
# ----- TEMPERATURE BIAS BOUNDS -----
# Selects from emulator sims dataframe
sims_df_subset = sims_df.loc[sims_df['kp']==1, :]
tbias_bndhigh = sims_df_subset['tbias'].max()
tbias_bndlow = sims_df_subset['tbias'].min()
# Adjust tbias_init based on bounds
if tbias_init > tbias_bndhigh:
tbias_init = tbias_bndhigh
elif tbias_init < tbias_bndlow:
tbias_init = tbias_bndlow
# ----- Mass balance bounds -----
# Upper bound
modelprms['kp'] = kp_bndhigh
modelprms['tbias'] = tbias_bndlow
modelprms['ddfsnow'] = ddfsnow_init
mb_mwea_bndhigh = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
# Lower bound
modelprms['kp'] = kp_bndlow
modelprms['tbias'] = tbias_bndhigh
modelprms['ddfsnow'] = ddfsnow_init
mb_mwea_bndlow = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
if debug:
print('mb_mwea_max:', np.round(mb_mwea_bndhigh,2),
'mb_mwea_min:', np.round(mb_mwea_bndlow,2))
if mb_obs_mwea > mb_mwea_bndhigh:
continue_param_search = False
tbias_opt = tbias_bndlow
kp_opt= kp_bndhigh
troubleshoot_fp = (pygem_prms.output_filepath + 'errors/' +
pygem_prms.option_calibration + '/' +
glacier_str.split('.')[0].zfill(2) + '/')
if not os.path.exists(troubleshoot_fp):
os.makedirs(troubleshoot_fp, exist_ok=True)
txt_fn_extrapfail = glacier_str + "-mbs_obs_outside_bnds.txt"
with open(troubleshoot_fp + txt_fn_extrapfail, "w") as text_file:
text_file.write(glacier_str + ' observed mass balance exceeds max accumulation ' +
'with value of ' + str(np.round(mb_obs_mwea,2)) + ' mwea')
elif mb_obs_mwea < mb_mwea_bndlow:
continue_param_search = False
tbias_opt = tbias_bndhigh
kp_opt= kp_bndlow
troubleshoot_fp = (pygem_prms.output_filepath + 'errors/' +
pygem_prms.option_calibration + '/' +
glacier_str.split('.')[0].zfill(2) + '/')
if not os.path.exists(troubleshoot_fp):
os.makedirs(troubleshoot_fp, exist_ok=True)
txt_fn_extrapfail = glacier_str + "-mbs_obs_outside_bnds.txt"
with open(troubleshoot_fp + txt_fn_extrapfail, "w") as text_file:
text_file.write(glacier_str + ' observed mass balance below max loss ' +
'with value of ' + str(np.round(mb_obs_mwea,2)) + ' mwea')
else:
continue_param_search = True
# ===== ADJUST LOWER AND UPPER BOUNDS TO SET UP OPTIMIZATION ======
# Initialize model parameters
modelprms['tbias'] = tbias_init
modelprms['kp'] = kp_init
modelprms['ddfsnow'] = ddfsnow_init
test_count = 0
test_count_acc = 0
mb_mwea = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
if mb_mwea > mb_obs_mwea:
if debug:
print('increase tbias, decrease kp')
kp_bndhigh = 1
# Check if lower bound causes good agreement
modelprms['kp'] = kp_bndlow
mb_mwea = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
if debug:
print('tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'mb_mwea:', np.round(mb_mwea,2), 'obs_mwea:', np.round(mb_obs_mwea,2))
while mb_mwea > mb_obs_mwea and test_count < 100:
# Update temperature bias
modelprms['tbias'] = modelprms['tbias'] + tbias_step
# Update bounds
tbias_bndhigh_opt = modelprms['tbias']
tbias_bndlow_opt = modelprms['tbias'] - tbias_step
# Compute mass balance
mb_mwea = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
if debug:
print('tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'mb_mwea:', np.round(mb_mwea,2), 'obs_mwea:', np.round(mb_obs_mwea,2))
test_count += 1
else:
if debug:
print('decrease tbias, increase kp')
kp_bndlow = 1
# Check if upper bound causes good agreement
modelprms['kp'] = kp_bndhigh
mb_mwea = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
if debug:
print('tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'mb_mwea:', np.round(mb_mwea,2), 'obs_mwea:', np.round(mb_obs_mwea,2))
while mb_obs_mwea > mb_mwea and test_count < 100:
# Update temperature bias
modelprms['tbias'] = modelprms['tbias'] - tbias_step
# If temperature bias is at lower limit, then increase precipitation factor
if modelprms['tbias'] <= tbias_bndlow:
modelprms['tbias'] = tbias_bndlow
if test_count_acc > 0:
kp_bndhigh = kp_bndhigh + 1
modelprms['kp'] = kp_bndhigh
test_count_acc += 1
# Update bounds (must do after potential correction for lower bound)
tbias_bndlow_opt = modelprms['tbias']
tbias_bndhigh_opt = modelprms['tbias'] + tbias_step
# Compute mass balance
mb_mwea = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
if debug:
print('tbias:', np.round(modelprms['tbias'],2), 'kp:', np.round(modelprms['kp'],2),
'mb_mwea:', np.round(mb_mwea,2), 'obs_mwea:', np.round(mb_obs_mwea,2))
test_count += 1
# ===== ROUND 1: PRECIPITATION FACTOR ======
if debug:
print('Round 1:')
print(glacier_str + ' kp: ' + str(np.round(modelprms['kp'],2)) +
' ddfsnow: ' + str(np.round(modelprms['ddfsnow'],4)) +
' tbias: ' + str(np.round(modelprms['tbias'],2)))
# Reset parameters
modelprms['tbias'] = tbias_init
modelprms['kp'] = kp_init
modelprms['ddfsnow'] = ddfsnow_init
# Lower bound
modelprms['kp'] = kp_bndlow
mb_mwea_kp_low = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
# Upper bound
modelprms['kp'] = kp_bndhigh
mb_mwea_kp_high = mbEmulator.eval([modelprms['tbias'], modelprms['kp'], modelprms['ddfsnow']])
# Optimal precipitation factor
if mb_obs_mwea < mb_mwea_kp_low:
kp_opt = kp_bndlow
mb_mwea = mb_mwea_kp_low
elif mb_obs_mwea > mb_mwea_kp_high:
kp_opt = kp_bndhigh
mb_mwea = mb_mwea_kp_high
else:
# Single parameter optimizer (computationally more efficient and less prone to fail)
modelprms_subset = {'kp':kp_init, 'ddfsnow': ddfsnow_init, 'tbias': tbias_init}
kp_bnds = (kp_bndlow, kp_bndhigh)
modelprms_opt, mb_mwea = single_param_optimizer(
modelprms_subset, mb_obs_mwea, prm2opt='kp', kp_bnds=kp_bnds, debug=debug)
kp_opt = modelprms_opt['kp']
continue_param_search = False
# Update parameter values
modelprms['kp'] = kp_opt
if debug:
print(' kp:', np.round(kp_opt,2), 'mb_mwea:', np.round(mb_mwea,3),
'obs_mwea:', np.round(mb_obs_mwea,3))
# ===== ROUND 2: TEMPERATURE BIAS ======
if continue_param_search:
if debug:
print('Round 2:')
# Single parameter optimizer (computationally more efficient and less prone to fail)
modelprms_subset = {'kp':kp_opt, 'ddfsnow': ddfsnow_init,
'tbias': np.mean([tbias_bndlow_opt, tbias_bndhigh_opt])}
tbias_bnds = (tbias_bndlow_opt, tbias_bndhigh_opt)
modelprms_opt, mb_mwea = single_param_optimizer(
modelprms_subset, mb_obs_mwea, prm2opt='tbias', tbias_bnds=tbias_bnds, debug=debug)
# Update parameter values
tbias_opt = modelprms_opt['tbias']
modelprms['tbias'] = tbias_opt
if debug: