-
Notifications
You must be signed in to change notification settings - Fork 11
/
help_func.py
executable file
·2538 lines (2279 loc) · 124 KB
/
help_func.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 python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 12:28:37 2020
@author: lilianschuster
some helper functions to minimize the bias, optimise std_quot and tos
compute performance statistics
"""
import scipy
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import mean_absolute_error
import pandas as pd
import logging
from oggm.core import climate
from oggm import utils, workflow, tasks, entity_task, cfg
from oggm.exceptions import MassBalanceCalibrationError
log = logging.getLogger(__name__)
# imports from local MBsandbox package modules
import MBsandbox
from MBsandbox.mbmod_daily_oneflowline import TIModel, TIModel_Sfc_Type
# from MBsandbox.help_func import compute_stat, minimize_bias, optimize_std_quot_brentq
from MBsandbox.flowline_TIModel import (run_from_climate_data_TIModel, run_constant_climate_TIModel,
run_random_climate_TIModel)
# depends on oggm version ...
try:
from oggm.core.massbalance import apparent_mb_from_any_mb
except:
from oggm.core.climate import apparent_mb_from_any_mb
# necessary for `melt_f_calib_geod_prep_inversion`
_doc = 'the calibrated melt_f according to the geodetic data with the ' \
'chosen precipitation factor'
cfg.BASENAMES['melt_f_geod'] = ('melt_f_geod.json', _doc)
def minimize_bias(x, gd_mb=None, gdir_min=None,
pf=None, absolute_bias=False, input_filesuffix=''):
""" calibrates the melt factor (melt_f) by getting the bias to zero
comparing modelled mean specific mass balance to
direct glaciological observations
attention: this is a bit deprecated. It uses the direct glaciological
observations for calibration. If you want to use the geodetic,
you should use instead `minimize_bias_geodetic`!
(and actually the minimisation occurs only when doing scipy.optimize.brentq(minimize_bias, 10, 100, ...)
but we don't wan to change the function at this stage)
Parameters
----------
x : float
what is optimised; here the melt factor (melt_f)
gd_mb: class instance
instantiated class of TIModel, this is updated by melt_f
gdir_min :
glacier directory. The default is None but this has to be set.
pf: float: optional
precipitation factor. The default is 2.5.
absolute_bias : bool
if absolute_bias == True, the absolute value of the bias is returned.
if optimisation is done with Powell need absolute bias.
If optimisation is done with Brentq, absolute_bias has to set False
The default is False.
input_filesuffix: str
default is ''. If set, it is used to choose the right filesuffix
for the ref mb data.
Returns
-------
float
bias: modeled mass balance mean - reference mean
if absolute_bias = True: np.abs(bias) is returned
"""
h, w = gdir_min.get_inversion_flowline_hw()
mbdf = gdir_min.get_ref_mb_data(input_filesuffix=input_filesuffix)
gd_mb.melt_f = x
if type(pf) == float or type(pf) == int:
gd_mb.prcp_fac = pf
# check climate and adapt if necessary
gd_mb.historical_climate_qc_mod(gdir_min)
mb_specific = gd_mb.get_specific_mb(heights=h,
widths=w,
year=mbdf.index.values)
if absolute_bias:
bias_calib = np.abs(np.mean(mb_specific -
mbdf['ANNUAL_BALANCE'].values))
else:
bias_calib = np.mean(mb_specific - mbdf['ANNUAL_BALANCE'].values)
return bias_calib
def minimize_bias_geodetic(x, gd_mb=None, mb_geodetic=None,
h=None, w=None, pf=2.5,
absolute_bias=False,
ys=np.arange(2000, 2020, 1),
oggm_default_mb=False,
spinup=True):
""" calibrates the melt factor (melt_f) by getting the bias to zero
comparing modelled mean specific mass balance between 2000 and 2020 to
observed geodetic data (from Hugonnet et al. 2021)
(and actually the minimisation occurs only when doing scipy.optimize.brentq(minimize_bias_geodetic, 10, 100, ...)
but we don't want to change the function at this stage)
Parameters
----------
x : float
what is optimised (here the melt_f)
gd_mb: class instance
instantiated class of TIModel, this is updated by melt_f
mb_geodetic: float
geodetic mass balance between 2000-2020 of the instantiated glacier
h: ndarray
heights of the instantiated glacier
w: ndarray
widths of the instantiated glacier.
Important to set that otherwise it is assumed that the glacier has the same width everywhere!
pf: float
precipitation scaling factor
default is 2.5
absolute_bias : bool
if absolute_bias == True, the absolute value of the bias is returned.
if optimisation is done with Powell need absolute bias.
If optimisation is done with Brentq, absolute_bias has to be set False
The default is False.
ys: ndarray
years for which specific mass balance is computed
default is 2000--2019 (when using W5E5)
oggm_default_mb : bool
if default oggm mass balance should be used (default is False)
spinup : bool
send to get_specific_mb (for sfc type distinction)
Returns
-------
float
bias: modeled mass balance mean - reference mean (geodetic)
if absolute_bias = True: np.abs(bias) is returned
"""
if oggm_default_mb:
gd_mb.mu_star = x
else:
gd_mb.melt_f = x
gd_mb.prcp_fac = pf
try:
mb_specific = gd_mb.get_specific_mb(heights=h,
widths=w,
year=ys,
spinup=spinup
).mean()
except:
mb_specific = gd_mb.get_specific_mb(heights=h,
widths=w,
year=ys
).mean()
if absolute_bias:
bias_calib = np.abs(np.mean(mb_specific -
mb_geodetic))
else:
bias_calib = np.mean(mb_specific - mb_geodetic)
return bias_calib
def minimize_bias_geodetic_via_pf_fixed_melt_f(x, gd_mb=None, mb_geodetic=None,
h=None, w=None, melt_f=None,
absolute_bias=False,
ys=np.arange(2000, 2020, 1),
oggm_default_mb=False,
spinup=True):
""" calibrates the precipitation factor (pf) by getting the bias to zero
comparing modelled mean specific mass balance between 2000 and 2020 to
observed geodetic data (from Hugonnet et al. 2021)
Important, here the free parameter that is tuned to match the geodetic estimates is the precipitation factor
(and not the melt_f) !!!
(and actually the minimisation occurs only when doing
scipy.optimize.brentq(minimize_bias_geodetic_via_pf_fixed_melt_f, 0.1, 10, ...)
but we don't wan to change the function at this stage)
Parameters
----------
x : float
what is optimised (here the precipitation factor pf)
gd_mb: class instance
instantiated class of TIModel, this is updated with the prescribed pf (& melt_f)
mb_geodetic: float
geodetic mass balance between 2000-2020 of the instantiated glacier
h: np.array
heights of the instantiated glacier
w: np.array
widths of the instantiated glacier
melt_f: float
melt factor
has to be set!!!
absolute_bias : bool
if absolute_bias == True, the absolute value of the bias is returned.
if optimisation is done with Powell need absolute bias.
If optimisation is done with Brentq, absolute_bias has to be set False
The default is False.
ys: np.array
years for which specific mass balance is computed
default is 2000--2019 (when using W5E5)
oggm_default_mb : bool
if default oggm mass balance should be used (default is False)
spinup : bool
send to get_specific_mb (for sfc type distinction)
Returns
-------
float
bias: modeled mass balance mean - reference mean (geodetic)
if absolute_bias = True: np.abs(bias) is returned
"""
# not sure if this works for the oggm default PastMassBalance instance, probably not:
gd_mb.prcp_fac = x
if oggm_default_mb:
gd_mb.mu_star = melt_f
else:
gd_mb.melt_f = melt_f
try:
mb_specific = gd_mb.get_specific_mb(heights=h,
widths=w,
year=ys,
spinup=spinup
).mean()
except:
mb_specific = gd_mb.get_specific_mb(heights=h,
widths=w,
year=ys
).mean()
if absolute_bias:
bias_calib = np.abs(np.mean(mb_specific -
mb_geodetic))
else:
bias_calib = np.mean(mb_specific - mb_geodetic)
return bias_calib
def minimize_bias_geodetic_via_temp_bias(x, gd_mb=None, mb_geodetic=None,
h=None, w=None, melt_f=None, pf=None,
absolute_bias=False,
ys=np.arange(2000, 2020, 1),
oggm_default_mb=False,
spinup=True):
""" calibrates the temperature bias (t_bias) by getting the bias (|observed-geodetic|) to zero
comparing modelled mean specific mass balance between 2000 and 2020 to
observed geodetic data (from Hugonnet et al. 2021)
Important, here the free parameter that is tuned to match the geodetic estimates is the temperature bias
(and not the melt_f and also not pf). Hence, both melt_f and pf have to be prescribed !!!
(and actually the minimisation occurs only when doing
scipy.optimize.brentq(minimize_bias_geodetic_via_temp_bias, -5, 5, ...)
but we don't want to change the function at this stage)
Parameters
----------
x : float
what is optimised (here the temperature bias)
gd_mb: class instance
instantiated class of TIModel, this is updated with the prescribed pf & melt_f
mb_geodetic: float
geodetic mass balance between 2000-2020 of the instantiated glacier
h: ndarray
heights of the instantiated glacier
w: ndarray
widths of the instantiated glacier
melt_f: float
melt factor
has to be set!!!
pf : float
precipitation factor
has to be set!!!
absolute_bias : bool
if absolute_bias == True, the absolute value of the bias is returned.
if optimisation is done with Powell need absolute bias.
If optimisation is done with Brentq, absolute_bias has to be set False
The default is False.
ys: ndarray
years for which specific mass balance is computed
default is 2000--2019 (when using W5E5)
oggm_default_mb : bool
if default oggm mass balance should be used (default is False)
spinup : bool
send to get_specific_mb (for sfc type distinction)
Returns
-------
float
bias: modeled mass balance mean - reference mean (geodetic)
if absolute_bias = True: np.abs(bias) is returned
"""
# not sure if this works for the oggm default PastMassBalance instance, probably not:
gd_mb.temp_bias = x
gd_mb.prcp_fac = pf
if oggm_default_mb:
gd_mb.mu_star = melt_f
else:
gd_mb.melt_f = melt_f
try:
mb_specific = gd_mb.get_specific_mb(heights=h,
widths=w,
year=ys,
spinup=spinup
).mean()
except:
mb_specific = gd_mb.get_specific_mb(heights=h,
widths=w,
year=ys
).mean()
if absolute_bias:
bias_calib = np.abs(np.mean(mb_specific -
mb_geodetic))
else:
bias_calib = np.mean(mb_specific - mb_geodetic)
return bias_calib
def optimize_std_quot_brentq_geod_via_melt_f(x, gd_mb=None, mb_geodetic=None,
mb_glaciological=None,
h=None, w=None,
ys_glac=np.arange(1979, 2020, 1),
):
""" calibrates the optimal melt factor (melt_f) by correcting the
standard deviation of the modelled mass balance by using the standard deviation
from the direct glaciological measurements as reference
for each melt_f an optimal pf is found (by using the geodetic data via
`minimize_bias_geodetic_via_pf_fixed_melt_f`), then (1 - standard deviation quotient between modelled and
reference mass balance) is computed, which is then minimised.
Important, here the free parameter that is tuned to match the geodetic estimates is the precipitation factor
(and not the melt_f) !!!
(and actually the optimisation occurs only when doing
scipy.optimize.brentq(optimize_std_quot_brentq_geod_via_melt_f, 10, 1000, ...)
but we don't want to change the function at this stage)
Parameters
----------
x : float
what is optimised (here the melt_f)
gd_mb : class instance
instantiated class of TIModel, this is updated by pf and melt_f
mb_geodetic: float
geodetic mass balance between 2000-2020 of the instantiated glacier
mb_glaciological : pandas.core.series.Series
direct glaciological timeseries
e.g. gdir.get_ref_mb_data(input_filesuffix='_{}_{}'.format(temporal_resol, climate_type))['ANNUAL_BALANCE']
h: ndarray
heights of the instantiated glacier
w: ndarray
widths of the instantiated glacier
ys_glac : ndarray
array of years where both, glaciological observations and climate data are available
(just use the years from the ref_mb_data file)
Returns
-------
float
1- quot_std
"""
melt_f = x
# compute optimal pf according to geodetic data
pf_opt = scipy.optimize.brentq(minimize_bias_geodetic_via_pf_fixed_melt_f, 0.01, 20, # pf range
xtol=0.1,
args=(gd_mb, mb_geodetic, h, w, melt_f),
disp=True)
gd_mb.prcp_fac = pf_opt
gd_mb.melt_f = melt_f
# now compute std over this time period using
# direct glaciological observations
mod_std = gd_mb.get_specific_mb(heights=h, widths=w,
year=ys_glac).std()
ref_std = mb_glaciological.loc[ys_glac].values.std()
quot_std = mod_std / ref_std
return 1 - quot_std
def optimize_std_quot_brentq_geod_via_temp_bias(x, gd_mb=None, mb_geodetic=None,
mb_glaciological=None,
h=None, w=None,
ys_glac=np.arange(1979, 2020, 1),
pf = None
):
""" calibrates the optimal temperature bias by correcting the
standard deviation of the modelled mass balance by using the standard deviation
from the direct glaciological measurements as reference. The prcp. fac is here
not used for calibration (just set to a cte "arbitrary" value)
for each temp. bias an optimal melt_f is found (by using the geodetic data via `minimize_bias_geodetic`),
then (1 - standard deviation quotient between modelled and reference mass balance) is computed,
which is then minimised
(and actually the optimisation occurs only when doing
scipy.optimize.brentq(optimize_std_quot_brentq_geod_via_temp_bias, -5, 5, ...)
but we don't want to change the function at this stage)
Parameters
----------
x : float
what is optimised (here the temperature bias)
gd_mb : class instance
instantiated class of TIModel, this is updated by temperature bias and melt_f
mb_geodetic: float
geodetic mass balance between 2000-2020 of the instantiated glacier
mb_glaciological : pandas.core.series.Series
direct glaciological timeseries
e.g. gdir.get_ref_mb_data(input_filesuffix='_{}_{}'.format(temporal_resol, climate_type))['ANNUAL_BALANCE']
h: ndarray
heights of the instantiated glacier
w: ndarray
widths of the instantiated glacier
ys_glac : ndarray
array of years where both, glaciological observations and climate data are available
(just use the years from the ref_mb_data file)
pf : float
precipitation factor (here constant and has to be set to any value)
Returns
-------
float
1- quot_std
"""
temp_bias = x
gd_mb.temp_bias = temp_bias
# compute optimal melt_f according to geodetic data for that temp_bias
melt_f_opt = scipy.optimize.brentq(minimize_bias_geodetic, 10, 1000,
xtol=0.01,
args=(gd_mb, mb_geodetic, h, w, pf),
disp=True)
gd_mb.melt_f = melt_f_opt
gd_mb.temp_bias = temp_bias
# now compute std over this time period using
# direct glaciological observations
mod_std = gd_mb.get_specific_mb(heights=h, widths=w,
year=ys_glac).std()
ref_std = mb_glaciological.loc[ys_glac].values.std()
quot_std = mod_std / ref_std
return 1 - quot_std
def optimize_std_quot_brentq_geod(x, gd_mb=None, mb_geodetic=None,
mb_glaciological=None,
h=None, w=None,
ys_glac=np.arange(1979, 2020, 1),
):
""" calibrates the optimal precipitation factor (pf) by correcting the
standard deviation of the modelled mass balance by using the standard deviation
from the direct glaciological measurements as reference
for each pf an optimal melt_f is found (by using the geodetic data via `minimize_bias_geodetic`),
then (1 - standard deviation quotient between modelled and reference mass balance) is computed,
which is then minimised
(and actually the optimisation occurs only when doing
scipy.optimize.brentq(optimize_std_quot_brentq_geod, 0.1, 10, ...)
but we don't want to change the function at this stage)
Parameters
----------
x : float
what is optimised (here the precipitation factor)
gd_mb : class instance
instantiated class of TIModel, this is updated by pf and melt_f
mb_geodetic: float
geodetic mass balance between 2000-2020 of the instantiated glacier
mb_glaciological : pandas.core.series.Series
direct glaciological timeseries
e.g. gdir.get_ref_mb_data(input_filesuffix='_{}_{}'.format(temporal_resol, climate_type))['ANNUAL_BALANCE']
h: ndarray
heights of the instantiated glacier
w: ndarray
widths of the instantiated glacier
ys_glac : ndarray
array of years where both, glaciological observations and climate data are available
(just use the years from the ref_mb_data file)
Returns
-------
float
1- quot_std
"""
pf = x
# compute optimal melt_f according to geodetic data
melt_f_opt = scipy.optimize.brentq(minimize_bias_geodetic, 10, 1000,
xtol=0.01,
args=(gd_mb, mb_geodetic, h, w, pf),
disp=True)
gd_mb.melt_f = melt_f_opt
gd_mb.prcp_fac = pf
# now compute std over this time period using
# direct glaciological observations
mod_std = gd_mb.get_specific_mb(heights=h, widths=w,
year=ys_glac).std()
ref_std = mb_glaciological.loc[ys_glac].values.std()
quot_std = mod_std / ref_std
return 1 - quot_std
def compute_stat(mb_specific=None, mbdf=None, return_dict=False,
return_plot=False, round=False):
""" function that computes RMSD, bias, rcor, quot_std between modelled
and reference mass balance
Parameters
----------
mb_specific : np.array or pd.Series
modelled mass balance
mbdf : np.array or pd.Series
reference mass balance
return_dict : bool
If a dictionary instead of a list should be returned.
The default is False
return_plot :
If modelled mass balance should be plotted with statistics as label,
write the label_part1 (mb_type and grad_type) into return_plot.
The default is False and means that no plot is returned.
Returns
-------
RMSD :
root-mean squared deviation
bias :
modeled mass balance mean - reference mean
rcor :
correlation coefficent between modelled and reference mass balance
quot_std : TYPE
standard deviation quotient of modelled against reference mass balance
"""
# with np.array normalised by N / with pandas default option is N-1 !!!
obs = mbdf['ANNUAL_BALANCE'].values # need values otherwise problem in std
RMSD = np.sqrt(np.sum(np.square(mb_specific - obs)))/len(obs)
ref_std = obs.std()
mod_std = mb_specific.std()
bias = mb_specific.mean() - obs.mean()
# this is treated a bit different than in mb_crossval of Matthias Dusch
if ref_std == 0:
# in mb_crossval: ref_std is then set equal to std of the modeled mb
quot_std = np.NaN
# in mb_crossval: rcor is set to 1 but I guess it should not be counted
# because it is not sth. we want to count
rcor = np.NaN
else:
quot_std = mod_std/ref_std
rcor = np.corrcoef(mb_specific, obs)[0, 1]
# could also be returned as dictionary instead to not confuse the results
if return_plot is not False:
stat_l = ('RMSD {}, rcor {}'
', std_quot {}, bias {}'.format(RMSD.round(1),
rcor.round(3),
quot_std.round(3),
bias.round(2)))
label = return_plot + stat_l
plt.plot(mbdf.index, mb_specific, label=label)
if round:
RMSD = RMSD.round(1)
bias = bias.round(1)
rcor = rcor.round(3)
quot_std = quot_std.round(3)
if return_dict:
return {'RMSD': RMSD, 'bias': bias,
'rcor': rcor, 'quot_std': quot_std}
else:
return [RMSD, bias, rcor, quot_std]
# %%
def optimize_std_quot_brentq(x, gd_mb=None,
gdir_min=None,
input_filesuffix=''):
""" calibrates the optimal precipitation factor (pf) by correcting the
standard deviation of the modelled mass balance
for each pf an optimal melt_f is found, then (1 - standard deviation quotient
between modelled and reference mass balance) is computed,
which is then minimised
(this is a bit deprecated as we use geodetic data to calibrate melt_f via the mean MB)
(and actually the optimisation occurs only when doing
scipy.optimize.brentq(optimize_std_quot_brentq, 0.1, 10, ...)
but we don't want to change the function at this stage)
Parameters
----------
x : float
what is optimised (here the precipitation factor)
gd_mb: class instance
instantiated class of TIModel, this is updated by pf and melt_f
gdir_min : optional
glacier directory. The default is None but this has to be set.
input_filesuffix: str
default is ''. If set, it is used to choose the right filesuffix
for the ref mb data.
Returns
-------
float
1- quot_std
"""
h, w = gdir_min.get_inversion_flowline_hw()
mbdf = gdir_min.get_ref_mb_data(input_filesuffix=input_filesuffix)
pf = x
melt_f_opt = scipy.optimize.brentq(minimize_bias, 1, 10000,
disp=True, xtol=0.1,
args=(gd_mb, gdir_min,
pf, False,
input_filesuffix))
gd_mb.melt_f = melt_f_opt
# check climate and adapt if necessary
gd_mb.historical_climate_qc_mod(gdir_min)
mod_std = gd_mb.get_specific_mb(heights=h, widths=w,
year=mbdf.index.values).std()
ref_std = mbdf['ANNUAL_BALANCE'].values.std()
quot_std = mod_std/ref_std
return 1-quot_std
def optimize_std_quot_brentq_via_temp_b_w_min_winter_geod_bias(x, gd_mb=None,
mb_geodetic=None,
winter_mb_observed = None,
yrs_seasonal_mbs = None,
mb_glaciological=None,
ys_glac=np.arange(1979, 2020, 1),
h=None, w=None,
):
""" calibrates the optimal temperature bias by correcting the
standard deviation of the modelled mass balance by using the standard deviation
from the direct glaciological measurements as reference while maintaining minimum winter bias
and geodetic bias
for each temp. b. an optimal pf and melt_f is found (that minimise winter and geodetic bias),
then (1 - standard deviation quotient
between modelled and reference mass balance) is computed,
which is then minimised
(and actually the optimisation occurs only when doing
scipy.optimize.brentq(optimize_std_quot_brentq_via_temp_b_w_min_winter_geod_bias, -5, 5, ...)
but we don't want to change the function name at this stage)
Parameters
----------
x : float
what is optimised (here the temperature bias)
gd_mb : class instance
instantiated class of TIModel, this is updated by temperature bias and melt_f
mb_geodetic: float
geodetic mass balance between 2000-2020 of the instantiated glacier
winter_mb_observed : pandas.core.series.Series
winter MB
e.g. gdir.get_ref_mb_data(input_filesuffix='_daily_W5E5').loc[yrs_seasonal_mbs]['WINTER_BALANCE']
yrs_seasonal_mbs : np.array
years for which we want to use winter MB (those with valid winter MB), e.g. :
_, path = utils.get_wgms_files()
pd_mb_overview = pd.read_csv(path[:-len('/mbdata')] + '/mb_overview_seasonal_mb_time_periods_20220301.csv',
index_col='Unnamed: 0')
or via:
path_mbsandbox = MBsandbox.__file__[:-len('/__init__.py')]
pd_mb_overview = pd.read_csv(path_mbsandbox + '/data/mb_overview_seasonal_mb_time_periods_20220301.csv',
index_col='Unnamed: 0')
yrs_seasonal_mbs = pd_mb_overview.loc[pd_mb_overview.rgi_id == gdir.rgi_id].Year.values
mb_glaciological : pandas.core.series.Series
direct glaciological timeseries
e.g. gdir.get_ref_mb_data(input_filesuffix='_{}_{}'.format(temporal_resol, climate_type))['ANNUAL_BALANCE']
h: ndarray
heights of the instantiated glacier
w: ndarray
widths of the instantiated glacier
ys_glac : ndarray
array of years where both, glaciological observations and climate data are available
(just use the years from the ref_mb_data file)
Returns
-------
float
1- quot_std
"""
temp_bias = x
gd_mb.temp_bias = temp_bias
winter_mb_observed = winter_mb_observed.loc[yrs_seasonal_mbs]
except_necessary = 0
# minimize bias of winter MB
try:
pf_opt = scipy.optimize.brentq(minimize_winter_mb_brentq_geod_via_pf, 0.1, 10, xtol=0.1,
args=(gd_mb, mb_geodetic, winter_mb_observed, h, w, yrs_seasonal_mbs,
True) # period_from_wgms
)
except:
except_necessary += 1
try:
pf_opt = scipy.optimize.brentq(minimize_winter_mb_brentq_geod_via_pf, 0.4, 5, xtol=0.1,
args=(
gd_mb, mb_geodetic, winter_mb_observed, h, w, yrs_seasonal_mbs,
True) # period_from_wgms
)
except:
melt_f_opt_dict = {}
for pf in np.concatenate([np.arange(0.1, 3, 0.5), np.arange(3, 10, 2)]):
try:
melt_f = scipy.optimize.brentq(minimize_bias_geodetic, 10, 1000,
xtol=0.01,
args=(gd_mb, mb_geodetic,
h, w, pf),
disp=True)
melt_f_opt_dict[pf] = melt_f
except:
pass
# print(melt_f_opt_dict)
pf_start = list(melt_f_opt_dict.items())[0][0]
pf_end = list(melt_f_opt_dict.items())[-1][0]
try:
pf_opt = scipy.optimize.brentq(minimize_winter_mb_brentq_geod_via_pf, pf_start, pf_end, xtol=0.1,
args=(gd_mb, mb_geodetic, winter_mb_observed,
h, w, yrs_seasonal_mbs,
True) # period_from_wgms
)
except:
except_necessary += 1
try:
pf_start = list(melt_f_opt_dict.items())[1][0]
pf_end = list(melt_f_opt_dict.items())[-2][0]
pf_opt = scipy.optimize.brentq(minimize_winter_mb_brentq_geod_via_pf, pf_start, pf_end, xtol=0.1,
args=(gd_mb, mb_geodetic, winter_mb_observed,
h, w, yrs_seasonal_mbs,
True) # period_from_wgms
)
except:
except_necessary += 1
pf_start = list(melt_f_opt_dict.items())[2][0]
pf_end = list(melt_f_opt_dict.items())[-3][0]
pf_opt = scipy.optimize.brentq(minimize_winter_mb_brentq_geod_via_pf, pf_start, pf_end, xtol=0.1,
args=(gd_mb, mb_geodetic, winter_mb_observed,
h, w, yrs_seasonal_mbs,
True) # period_from_wgms
)
# compute optimal melt_f according to geodetic data for that temp_bias and that pf_opt
melt_f_opt = scipy.optimize.brentq(minimize_bias_geodetic, 10, 1000,
xtol=0.01,
args=(gd_mb, mb_geodetic, h, w, pf_opt),
disp=True)
gd_mb.melt_f = melt_f_opt
gd_mb.temp_bias = temp_bias
# now compute std over this time period using
# direct glaciological observations
mod_std = gd_mb.get_specific_mb(heights=h, widths=w,
year=ys_glac).std()
ref_std = mb_glaciological.loc[ys_glac].values.std()
quot_std = mod_std / ref_std
return 1 - quot_std
@entity_task(log)
def calibrate_to_geodetic_bias_quot_std_different_temp_bias(gdir,
temp_b_range=np.arange(-4, 4.1, 2),
# np.arange(-6,6.1,0.5)
method='pre-check', melt_f_update='monthly',
sfc_type_distinction=True,
path='/home/lilianschuster/Schreibtisch/PhD/bayes_2022/calib_winter_mb/test_run',
pf_cte_dict=False,
optimize_std_quot=True,
pf_cte_via= '',
t_melt=0,
path_w_prcp='/home/lilianschuster/Schreibtisch/PhD/Schuster_et_al_phd_paper_1/data/'
):
''' todo: do documentation '''
j = 0
# sfc_type_distinction types
n = 2
if not sfc_type_distinction:
melt_f_update = np.NaN
n = 1
pd_geodetic_all = utils.get_geodetic_mb_dataframe()
pd_geodetic = pd_geodetic_all.loc[pd_geodetic_all.period == '2000-01-01_2020-01-01']
mb_geodetic = pd_geodetic.loc[gdir.rgi_id].dmdtda * 1000
climate_type = 'W5E5'
# actually it does not matter which climate input fs we use as long it exists (they all have the same time period)
try:
mbdf = gdir.get_ref_mb_data(input_filesuffix='_monthly_W5E5')
except:
mbdf = gdir.get_ref_mb_data(input_filesuffix='_daily_W5E5')
# get the filtered seasonal MB data, if it is not available or has less than 5 measurements
# just take as years the annual years and as values NaNs
oggm_updated = False
if oggm_updated:
_, pathi = utils.get_wgms_files()
pd_mb_overview = pd.read_csv(
pathi[:-len('/mbdata')] + '/mb_overview_seasonal_mb_time_periods_20220301.csv',
index_col='Unnamed: 0')
else:
# path_mbsandbox = MBsandbox.__file__[:-len('/__init__.py')]
# pd_mb_overview = pd.read_csv(path_mbsandbox + '/data/mb_overview_seasonal_mb_time_periods_20220301.csv',
# index_col='Unnamed: 0')
# pd_wgms_data_stats = pd.read_csv(path_mbsandbox + '/data/wgms_data_stats_20220301.csv',
# index_col='Unnamed: 0')
#fp = utils.file_downloader('https://cluster.klima.uni-bremen.de/~lschuster/ref_glaciers' +
# '/data/mb_overview_seasonal_mb_time_periods_20220301.csv')
fp = 'https://cluster.klima.uni-bremen.de/~lschuster/ref_glaciers/data/mb_overview_seasonal_mb_time_periods_20220301.csv'
fp_stats = ('https://cluster.klima.uni-bremen.de/~lschuster/ref_glaciers' +
'/data/wgms_data_stats_20220301.csv')
pd_mb_overview = pd.read_csv(fp, index_col='Unnamed: 0')
#fp_stats = utils.file_downloader('https://cluster.klima.uni-bremen.de/~lschuster/ref_glaciers' +
# '/data/wgms_data_stats_20220301.csv')
pd_wgms_data_stats = pd.read_csv(fp_stats, index_col='Unnamed: 0')
pd_mb_overview = pd_mb_overview[pd_mb_overview['at_least_5_winter_mb']]
try:
pd_mb_overview_sel_gdir = pd_mb_overview.loc[pd_mb_overview.rgi_id == gdir.rgi_id]
pd_mb_overview_sel_gdir.index = pd_mb_overview_sel_gdir.Year
yrs_seasonal_mbs = pd_mb_overview_sel_gdir.Year.values
assert np.all(yrs_seasonal_mbs >= 1980)
assert np.all(yrs_seasonal_mbs < 2020)
except:
# just take the years where annual MB exists (even if no winter MB exist)--> get np.NaN for winter_mb_observed!
yrs_seasonal_mbs = mbdf.index
# actually it does not matter which climate input fs we use as long it exists (they all have the same time period)
try:
winter_mb_observed = gdir.get_ref_mb_data(input_filesuffix='_monthly_W5E5').loc[yrs_seasonal_mbs][
'WINTER_BALANCE']
mean_mb_prof = get_mean_mb_profile_filtered(gdir, input_fs='_monthly_W5E5', obs_ratio_needed=0.6)
except:
winter_mb_observed = gdir.get_ref_mb_data(input_filesuffix='_daily_W5E5').loc[yrs_seasonal_mbs][
'WINTER_BALANCE']
mean_mb_prof = get_mean_mb_profile_filtered(gdir, input_fs='_daily_W5E5', obs_ratio_needed=0.6)
# annual_mb_observed = gdir.get_ref_mb_data(input_filesuffix='_daily_W5E5').loc[yrs_seasonal_mbs][
# 'ANNUAL_BALANCE']
hgts, widths = gdir.get_inversion_flowline_hw()
pd_calib = pd.DataFrame(np.NaN, index=np.arange(0, int(3 * 2 * n * len(temp_b_range))), # *len(gdirs))),
columns=['rgi_id', 'temp_bias', 'pf_opt', 'melt_f',
'winter_prcp_mean', 'winter_solid_prcp_mean',
'specific_melt_winter_kg_m2', 'except_necessary', 'quot_std', 'mae_mb_profile',
'bias_winter_mb',
'mb_type', 'grad_type', 'melt_f_change', 'melt_f_update','tau_e_fold_yr'])
for mb_type in ['mb_monthly', 'mb_pseudo_daily', 'mb_pseudo_daily_fake', 'mb_real_daily']:
if mb_type == 'mb_pseudo_daily_fake':
temp_std_const_from_hist = True
mb_type_r = 'mb_pseudo_daily'
else:
temp_std_const_from_hist = False
mb_type_r = mb_type
for grad_type in ['cte', 'var_an_cycle']:
for melt_f_change_r in ['linear', 'neg_exp_t0.5yr', 'neg_exp_t1.0yr']:
if 'neg_exp' in melt_f_change_r:
melt_f_change = 'neg_exp'
if melt_f_change_r == 'neg_exp_t0.5yr':
tau_e_fold_yr = 0.5
elif melt_f_change_r == 'neg_exp_t1.0yr':
tau_e_fold_yr = 1
else:
melt_f_change = melt_f_change_r
tau_e_fold_yr = np.NaN
if sfc_type_distinction:
gd_mb = TIModel_Sfc_Type(gdir, 200,
prcp_fac=1,
mb_type=mb_type_r,
grad_type=grad_type,
baseline_climate=climate_type,
melt_f_ratio_snow_to_ice=0.5, melt_f_update=melt_f_update,
melt_f_change=melt_f_change,
tau_e_fold_yr=tau_e_fold_yr,
t_melt=t_melt,
temp_std_const_from_hist=temp_std_const_from_hist
)
else:
gd_mb = TIModel(gdir, 200,
prcp_fac=1,
mb_type=mb_type_r,
grad_type=grad_type,
baseline_climate=climate_type,
t_melt=t_melt,
temp_std_const_from_hist=temp_std_const_from_hist
)
if not sfc_type_distinction and melt_f_change == 'neg_exp':
pass
else:
if pf_cte_via == '_pf_via_winter_mb_log_fit':
#pd_pf = pd.read_csv(
# f'{path_folder}winter_prcp_mean_general_log_relation_pf_winter_mb_match.csv',
# index_col='rgi_id')
pd_pf = pd.read_csv(f'{path_w_prcp}winter_daily_prcp_mean_general_log_relation_pf_winter_mb_match.csv',
index_col='rgi_id')
# old
# pf_cte = pd_pf.loc[gdir.rgi_id]['pf_via_log_regression']
hemisphere = gdir.hemisphere
# if NH ---
import xarray as xr
fpath_clim = gdir.get_filepath('climate_historical', filesuffix='_daily_W5E5')
ds_prcp = xr.open_dataset(fpath_clim).prcp
if hemisphere == 'nh':
ds_prcp_winter = ds_prcp.where(ds_prcp['time.month'].isin([10, 11, 12, 1, 2, 3, 4]),
drop=True)
else:
ds_prcp_winter = ds_prcp.where(ds_prcp['time.month'].isin([4, 5, 6, 7, 8, 9, 10]),
drop=True)
prcp_winter_daily_mean = ds_prcp_winter.mean().values # kg m-2 day-1
def log_func(x, a, b):
r = a * np.log(x) + b
# don't allow extremely low/high prcp. factors!!!
if np.shape(r) == ():
if r > 10:
r = 10
if r < 0.1:
r = 0.1
else:
r[r > 10] = 10
r[r < 0.1] = 0.1
return r
# the log_func params are all the same over the columnspd_pf['a_log_multiplier'].iloc[0]
pf_cte = log_func(prcp_winter_daily_mean, pd_pf['a_log_multiplier'].iloc[0],
pd_pf['b_intercept'].iloc[0])
elif pf_cte_via == '' or pf_cte_via == '_pf_cte_via_std':
if not sfc_type_distinction:
melt_f_change = np.NaN
if pf_cte_dict is False:
pf_cte = pf_cte_dict
else:
pf_cte = pf_cte_dict[f'sfc_type_False_{mb_type}_{grad_type}']
else:
if pf_cte_dict is False:
pf_cte = pf_cte_dict
else:
pf_cte = pf_cte_dict[f'{melt_f_update}_melt_f_update_sfc_type_{melt_f_change_r}_{mb_type}_{grad_type}']
for temp_bias in temp_b_range:
pd_calib.loc[j] = np.NaN
try:
out = calibrate_to_geodetic_bias_std_quot_fast(gd_mb, method=method,
temp_bias=temp_bias,
hgts=hgts,
widths=widths,
mb_geodetic=mb_geodetic,
mbdf=mbdf,
winter_mb_observed=winter_mb_observed,
mean_mb_prof=mean_mb_prof,
mb_type=mb_type,
sfc_type_distinction=sfc_type_distinction,
optimize_std_quot =optimize_std_quot,
pf_cte=pf_cte)
(pd_calib.loc[j, 'pf_opt'], pd_calib.loc[j, 'melt_f'],
pd_calib.loc[j, 'winter_prcp_mean'], pd_calib.loc[j, 'winter_solid_prcp_mean'],
pd_calib.loc[j, 'specific_melt_winter_kg_m2'], pd_calib.loc[j, 'except_necessary'],
pd_calib.loc[j, 'quot_std'], pd_calib.loc[j, 'mae_mb_profile'],
pd_calib.loc[j, 'bias_winter_mb']) = out
except:
pass
pd_calib.loc[j, 'rgi_id'] = gdir.rgi_id
pd_calib.loc[j, 'temp_bias'] = temp_bias