-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrun_calibration_frontalablation.py
More file actions
2648 lines (2225 loc) · 152 KB
/
run_calibration_frontalablation.py
File metadata and controls
2648 lines (2225 loc) · 152 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
"""
Calibrate frontal ablation parameters for tidewater glaciers
@author: davidrounce
"""
# Built-in libraries
#import argparse
import os
import pickle
import sys
# External libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import linregress
import xarray as xr
# Local libraries
try:
import pygem
except:
sys.path.append(os.getcwd() + '/../PyGEM/')
import pygem_input as pygem_prms
import pygem.pygem_modelsetup as modelsetup
from pygem.massbalance import PyGEMMassBalance
from pygem.glacierdynamics import MassRedistributionCurveModel
from pygem.oggm_compat import single_flowline_glacier_directory_with_calving
from pygem.shop import debris
from pygem import class_climate
import oggm
oggm_version = float(oggm.__version__[0:3])
from oggm import utils, cfg
from oggm import tasks
from oggm.core.flowline import FluxBasedModel
from oggm.core.inversion import find_inversion_calving_from_any_mb
if oggm_version > 1.301:
from oggm.core.massbalance import apparent_mb_from_any_mb # Newer Version of OGGM
else:
from oggm.core.climate import apparent_mb_from_any_mb # Older Version of OGGM
#%% ----- MANUAL INPUT DATA -----
regions = [1,3,4,5,7,9,17,19]
#regions = [19]
overwrite = False
output_fp = pygem_prms.main_directory + '/../calving_data/analysis/'
option_merge_data = False # Merge frontal ablation datasets and add mbclim data
option_ind_calving_k = False # Calibrate individual glaciers
option_reg_calving_k = False # Calibrate all glaciers regionally
if option_reg_calving_k:
drop_ind_glaciers = False # For region 9 decide if using individual glacier data or regional data
option_merge_calving_k = False # Merge all regions together
option_update_mb_data = False # Update gdirs with the new mass balance data
option_plot_calving_k = True # Plots of the calibration performance
option_scrap = False # Scrap calculations
frontal_ablation_Gta_cn = 'fa_gta_obs'
frontal_ablation_Gta_unc_cn = 'fa_gta_obs_unc'
# Frontal ablation calibration parameter (yr-1)
calving_k_init = 0.1
calving_k_bndlow = 0.001
calving_k_bndhigh = 5
calving_k_step = 0.2
nround_max = 5
cfl_number = 0.01
invert_standard=False
perc_threshold_agreement = 0.05 # Threshold (%) at which to stop optimization and consider good agreement
fa_threshold = 1e-4 # Absolute threshold at which to stop optimization (Gta)
debug=True
debug_reg_calving_fxn = True
prms_from_reg_priors=False
prms_from_glac_cal=True
##%% ----- Argument Parser -----
#def getparser():
# """
# Use argparse to add arguments from the command line
#
# Parameters
# ----------
# option_merge_data : int
# boolean switch to merge frontal ablation datasets and add mbclim data
# option_ind_calving_k : int
# boolean switch to calibrate individual glaciers
# option_reg_calving_k : int
# boolean switch to calibrate all glaciers regionally
# drop_ind_glaciers : int
# boolean switch for region 9 to decide if using individual glacier data or only regional data (used with option_reg_calving_k)
# option_merge_calving_k : int
# boolean switch to merge all regions together
# option_update_mb_data : int
# boolean switch to update gdirs with the new mass balance data
# option_plot_calving_k : int
# boolean switch to make plots of the calibration performance
# option_scrap : int
# boolean switch to run scrap (test) calculations
#
# Returns
# -------
# Object containing arguments and their respective values.
# """
# parser = argparse.ArgumentParser(description="run simulations from gcm list in parallel")
# # add arguments
# parser.add_argument('-option_merge_data', action='store', type=int, default=0,
# help='boolean switch to merge frontal ablation datasets and add mbclim data (default 0 is off)')
# parser.add_argument('-option_ind_calving_k', action='store', type=int, default=0,
# help='boolean switch to calibrate individual glaciers (default 0 is off)')
# parser.add_argument('-option_reg_calving_k', action='store', type=int, default=0,
# help='boolean switch to calibrate all glaciers regionally (default 0 is off)')
# parser.add_argument('-drop_ind_glaciers', action='store', type=int, default=0,
# help='boolean switch for region 9 to decide if using individual glacier data or only regional data (used with option_reg_calving_k) (default 0 is off)')
# parser.add_argument('-option_merge_calving_k', action='store', type=int, default=0,
# help='boolean switch to merge all regions together (default 0 is off)')
# parser.add_argument('-option_update_mb_data', action='store', type=int, default=0,
# help='boolean switch to update gdirs with the new mass balance data (default 0 is off)')
# parser.add_argument('-option_plot_calving_k', action='store', type=int, default=0,
# help='boolean switch to make plots of the calibration performance (default 0 is off)')
# parser.add_argument('-option_scrap', action='store', type=int, default=0,
# help='boolean switch to run scrap (test) calculations (default 0 is off)')
# return parser
#%% ----- CONVERSION FUNCTIONS -----
def mwea_to_gta(mwea, area_m2):
return mwea * pygem_prms.density_water * area_m2 / 1e12
def gta_to_mwea(gta, area_m2):
return gta * 1e12 / pygem_prms.density_water / area_m2
#%% ----- CALIBRATE FRONTAL ABLATION -----
def reg_calving_flux(main_glac_rgi, calving_k, fa_glac_data_reg=None,
frontal_ablation_Gta_cn=None,
prms_from_reg_priors=False, prms_from_glac_cal=False, ignore_nan=True, debug=False,
invert_standard=invert_standard,
calc_mb_geo_correction=False, reset_gdir=True):
"""
Compute the calving flux for a group of glaciers
Parameters
----------
main_glac_rgi : pd.DataFrame
rgi summary statistics of each glacier
calving_k : np.float
calving model parameter (typical values on order of 1)
prms_from_reg_priors : Boolean
use model parameters from regional priors
prms_from_glac_cal : Boolean
use model parameters from initial calibration
Returns
-------
output_df : pd.DataFrame
Dataframe containing information pertaining to each glacier's calving flux
"""
# ===== 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 pygem_prms.ref_gcm_name in ['ERA5', 'ERA-Interim'], (
'Error: Calibration not set up for ' + pygem_prms.ref_gcm_name)
gcm = class_climate.GCM(name=pygem_prms.ref_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 pygem_prms.ref_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)
# ===== CALIBRATE ALL THE GLACIERS AT ONCE =====
output_cns = ['RGIId', 'calving_k', 'calving_thick', 'calving_flux_Gta_inv', 'calving_flux_Gta', 'no_errors', 'oggm_dynamics']
output_df = pd.DataFrame(np.zeros((main_glac_rgi.shape[0],len(output_cns))), columns=output_cns)
output_df['RGIId'] = main_glac_rgi.RGIId
output_df['calving_k'] = calving_k
output_df['calving_thick'] = np.nan
output_df['calving_flux_Gta'] = np.nan
output_df['oggm_dynamics'] = 0
output_df['mb_mwea_fa_asl_lost'] = 0
for nglac in np.arange(main_glac_rgi.shape[0]):
print('\n',main_glac_rgi.loc[main_glac_rgi.index.values[nglac],'RGIId'])
# if main_glac_rgi.loc[nglac,'RGIId'] in ['RGI60-09.00855']:
# Select subsets of data
glacier_rgi_table = main_glac_rgi.loc[main_glac_rgi.index.values[nglac], :]
glacier_str = '{0:0.5f}'.format(glacier_rgi_table['RGIId_float'])
gdir = single_flowline_glacier_directory_with_calving(glacier_str,
logging_level='CRITICAL',
# logging_level='WORKFLOW'
reset=reset_gdir
)
gdir.is_tidewater = True
cfg.PARAMS['use_kcalving_for_inversion'] = True
cfg.PARAMS['use_kcalving_for_run'] = True
try:
fls = gdir.read_pickle('inversion_flowlines')
glacier_area = fls[0].widths_m * fls[0].dx_meter
debris.debris_binned(gdir, fl_str='inversion_flowlines', ignore_debris=True)
except:
fls = None
# Add climate data to glacier directory
gdir.historical_climate = {'elev': gcm_elev[nglac],
'temp': gcm_temp[nglac,:],
'tempstd': gcm_tempstd[nglac,:],
'prec': gcm_prec[nglac,:],
'lr': gcm_lr[nglac,:]}
gdir.dates_table = dates_table
# ----- Invert ice thickness and run simulation ------
if (fls is not None) and (glacier_area.sum() > 0):
# ----- Model parameters -----
kp_value = None
tbias_value = None
# Use most likely parameters from initial calibration to force the mass balance gradient for the inversion
if prms_from_reg_priors:
if pygem_prms.priors_reg_fullfn is not None:
# Load priors
priors_df = pd.read_csv(pygem_prms.priors_reg_fullfn)
priors_idx = np.where((priors_df.O1Region == glacier_rgi_table['O1Region']) &
(priors_df.O2Region == glacier_rgi_table['O2Region']))[0][0]
kp_value = priors_df.loc[priors_idx,'kp_med']
tbias_value = priors_df.loc[priors_idx,'tbias_med']
# Use the calibrated model parameters (although they were calibrated without accounting for calving)
elif prms_from_glac_cal:
modelprms_fn = glacier_str + '-modelprms_dict.pkl'
modelprms_fp = (pygem_prms.output_filepath + 'calibration/' + glacier_str.split('.')[0].zfill(2)
+ '/')
assert os.path.exists(modelprms_fp + modelprms_fn), 'modelprms_dict file does not exist'
with open(modelprms_fp + modelprms_fn, 'rb') as f:
modelprms_dict = pickle.load(f)
modelprms_em = modelprms_dict['emulator']
kp_value = modelprms_em['kp'][0]
tbias_value = modelprms_em['tbias'][0]
# Otherwise use input parameters
if kp_value is None:
kp_value = pygem_prms.kp
if tbias_value is None:
tbias_value = pygem_prms.tbias
# Set model parameters
modelprms = {'kp': kp_value,
'tbias': tbias_value,
'ddfsnow': pygem_prms.ddfsnow,
'ddfice': pygem_prms.ddfice,
'tsnow_threshold': pygem_prms.tsnow_threshold,
'precgrad': pygem_prms.precgrad}
# Calving and dynamic parameters
cfg.PARAMS['calving_k'] = calving_k
cfg.PARAMS['inversion_calving_k'] = cfg.PARAMS['calving_k']
if pygem_prms.use_reg_glena:
glena_df = pd.read_csv(pygem_prms.glena_reg_fullfn)
glena_idx = np.where(glena_df.O1Region == glacier_rgi_table.O1Region)[0][0]
glen_a_multiplier = glena_df.loc[glena_idx,'glens_a_multiplier']
fs = glena_df.loc[glena_idx,'fs']
else:
fs = pygem_prms.fs
glen_a_multiplier = pygem_prms.glen_a_multiplier
# CFL number (may use different values for calving to prevent errors)
if not glacier_rgi_table['TermType'] in [1,5] or not pygem_prms.include_calving:
cfg.PARAMS['cfl_number'] = pygem_prms.cfl_number
else:
cfg.PARAMS['cfl_number'] = pygem_prms.cfl_number_calving
# ----- Mass balance model for ice thickness inversion using OGGM -----
mbmod_inv = PyGEMMassBalance(gdir, modelprms, glacier_rgi_table,
hindcast=pygem_prms.hindcast,
debug=pygem_prms.debug_mb,
debug_refreeze=pygem_prms.debug_refreeze,
fls=fls, option_areaconstant=False,
inversion_filter=False)
h, w = gdir.get_inversion_flowline_hw()
# if debug:
# mb_t0 = (mbmod_inv.get_annual_mb(h, year=0, fl_id=0, fls=fls) * cfg.SEC_IN_YEAR *
# pygem_prms.density_ice / pygem_prms.density_water)
# plt.plot(mb_t0, h, '.')
# plt.ylabel('Elevation')
# plt.xlabel('Mass balance (mwea)')
# plt.show()
# ----- CALVING -----
# Number of years (for OGGM's run_until_and_store)
if pygem_prms.timestep == 'monthly':
nyears = int(dates_table.shape[0]/12)
else:
assert True==False, 'Adjust nyears for non-monthly timestep'
mb_years=np.arange(nyears)
# Perform inversion
# - find_inversion_calving_from_any_mb will do the inversion with calving, but if it fails
# then it will do the inversion assuming land-terminating
if invert_standard:
apparent_mb_from_any_mb(gdir, mb_model=mbmod_inv, mb_years=np.arange(nyears))
tasks.prepare_for_inversion(gdir)
tasks.mass_conservation_inversion(gdir, glen_a=cfg.PARAMS['glen_a']*glen_a_multiplier, fs=fs)
else:
out_calving = find_inversion_calving_from_any_mb(gdir, mb_model=mbmod_inv, mb_years=mb_years,
glen_a=cfg.PARAMS['glen_a']*glen_a_multiplier, fs=fs)
# ------ MODEL WITH EVOLVING AREA ------
tasks.init_present_time_glacier(gdir) # adds bins below
debris.debris_binned(gdir, fl_str='model_flowlines') # add debris enhancement factors to flowlines
nfls = gdir.read_pickle('model_flowlines')
# Mass balance model
mbmod = PyGEMMassBalance(gdir, modelprms, glacier_rgi_table,
hindcast=pygem_prms.hindcast,
debug=pygem_prms.debug_mb,
debug_refreeze=pygem_prms.debug_refreeze,
fls=nfls, option_areaconstant=True)
# Water Level
# Check that water level is within given bounds
cls = gdir.read_pickle('inversion_input')[-1]
th = cls['hgt'][-1]
vmin, vmax = cfg.PARAMS['free_board_marine_terminating']
water_level = utils.clip_scalar(0, th - vmax, th - vmin)
#%%
ev_model = FluxBasedModel(nfls, y0=0, mb_model=mbmod,
glen_a=cfg.PARAMS['glen_a']*glen_a_multiplier, fs=fs,
is_tidewater=gdir.is_tidewater,
water_level=water_level
)
try:
_, diag = ev_model.run_until_and_store(nyears)
ev_model.mb_model.glac_wide_volume_annual[-1] = diag.volume_m3[-1]
ev_model.mb_model.glac_wide_area_annual[-1] = diag.area_m2[-1]
# Record frontal ablation for tidewater glaciers and update total mass balance
if gdir.is_tidewater:
# Glacier-wide frontal ablation (m3 w.e.)
# - note: diag.calving_m3 is cumulative calving
# if debug:
# print('\n\ndiag.calving_m3:', diag.calving_m3.values)
# print('calving_m3_since_y0:', ev_model.calving_m3_since_y0)
calving_m3_annual = ((diag.calving_m3.values[1:] - diag.calving_m3.values[0:-1]) *
pygem_prms.density_ice / pygem_prms.density_water)
for n in np.arange(calving_m3_annual.shape[0]):
ev_model.mb_model.glac_wide_frontalablation[12*n+11] = calving_m3_annual[n]
# Glacier-wide total mass balance (m3 w.e.)
ev_model.mb_model.glac_wide_massbaltotal = (
ev_model.mb_model.glac_wide_massbaltotal - ev_model.mb_model.glac_wide_frontalablation)
# if debug:
# print('avg calving_m3:', calving_m3_annual.sum() / nyears)
# print('avg frontal ablation [Gta]:',
# np.round(ev_model.mb_model.glac_wide_frontalablation.sum() / 1e9 / nyears,4))
# print('avg frontal ablation [Gta]:',
# np.round(ev_model.calving_m3_since_y0 * pygem_prms.density_ice / 1e12 / nyears,4))
# Output of calving
out_calving_forward = {}
# calving flux (km3 ice/yr)
out_calving_forward['calving_flux'] = calving_m3_annual.sum() / nyears / 1e9
# calving flux (Gt/yr)
calving_flux_Gta = out_calving_forward['calving_flux'] * pygem_prms.density_ice / pygem_prms.density_water
# calving front thickness at start of simulation
thick = nfls[0].thick
last_idx = np.nonzero(thick)[0][-1]
out_calving_forward['calving_front_thick'] = thick[last_idx]
# Record in dataframe
output_df.loc[nglac,'calving_flux_Gta'] = calving_flux_Gta
output_df.loc[nglac,'calving_thick'] = out_calving_forward['calving_front_thick']
output_df.loc[nglac,'no_errors'] = 1
output_df.loc[nglac,'oggm_dynamics'] = 1
if debug:
print('OGGM dynamics, calving_k:', np.round(calving_k,4), 'glen_a:', np.round(glen_a_multiplier,2))
print(' calving front thickness [m]:', np.round(out_calving_forward['calving_front_thick'],1))
print(' calving flux model [Gt/yr]:', np.round(calving_flux_Gta,5))
except:
if gdir.is_tidewater:
if debug:
print('OGGM dynamics failed, using mass redistribution curves')
# Mass redistribution curves glacier dynamics model
ev_model = MassRedistributionCurveModel(
nfls, mb_model=mbmod, y0=0,
glen_a=cfg.PARAMS['glen_a']*glen_a_multiplier, fs=fs,
is_tidewater=gdir.is_tidewater,
water_level=water_level
)
_, diag = ev_model.run_until_and_store(nyears)
ev_model.mb_model.glac_wide_volume_annual = diag.volume_m3.values
ev_model.mb_model.glac_wide_area_annual = diag.area_m2.values
# Record frontal ablation for tidewater glaciers and update total mass balance
# Update glacier-wide frontal ablation (m3 w.e.)
ev_model.mb_model.glac_wide_frontalablation = ev_model.mb_model.glac_bin_frontalablation.sum(0)
# Update glacier-wide total mass balance (m3 w.e.)
ev_model.mb_model.glac_wide_massbaltotal = (
ev_model.mb_model.glac_wide_massbaltotal - ev_model.mb_model.glac_wide_frontalablation)
calving_flux_km3a = (ev_model.mb_model.glac_wide_frontalablation.sum() * pygem_prms.density_water /
pygem_prms.density_ice / nyears / 1e9)
# if debug:
# print('avg frontal ablation [Gta]:',
# np.round(ev_model.mb_model.glac_wide_frontalablation.sum() / 1e9 / nyears,4))
# print('avg frontal ablation [Gta]:',
# np.round(ev_model.calving_m3_since_y0 * pygem_prms.density_ice / 1e12 / nyears,4))
# Output of calving
out_calving_forward = {}
# calving flux (km3 ice/yr)
out_calving_forward['calving_flux'] = calving_flux_km3a
# calving flux (Gt/yr)
calving_flux_Gta = out_calving_forward['calving_flux'] * pygem_prms.density_ice / pygem_prms.density_water
# calving front thickness at start of simulation
thick = nfls[0].thick
last_idx = np.nonzero(thick)[0][-1]
out_calving_forward['calving_front_thick'] = thick[last_idx]
# Record in dataframe
output_df.loc[nglac,'calving_flux_Gta'] = calving_flux_Gta
output_df.loc[nglac,'calving_thick'] = out_calving_forward['calving_front_thick']
output_df.loc[nglac,'no_errors'] = 1
if debug:
print('Mass Redistribution curve, calving_k:', np.round(calving_k,1), 'glen_a:', np.round(glen_a_multiplier,2))
print(' calving front thickness [m]:', np.round(out_calving_forward['calving_front_thick'],0))
print(' calving flux model [Gt/yr]:', np.round(calving_flux_Gta,5))
if calc_mb_geo_correction:
# Mass balance correction from mass loss above sea level due to calving retreat
# (i.e., what the geodetic signal should see)
last_yr_idx = np.where(mbmod.glac_wide_area_annual > 0)[0][-1]
if last_yr_idx == mbmod.glac_bin_area_annual.shape[1]-1:
last_yr_idx = -2
bin_last_idx = np.where(mbmod.glac_bin_area_annual[:,last_yr_idx] > 0)[0][-1]
bin_area_lost = mbmod.glac_bin_area_annual[bin_last_idx:,0] - mbmod.glac_bin_area_annual[bin_last_idx:,-2]
height_asl = mbmod.heights - water_level
height_asl[mbmod.heights<0] = 0
mb_mwea_fa_asl_geo_correction = ((bin_area_lost * height_asl[bin_last_idx:]).sum() /
mbmod.glac_wide_area_annual[0] *
pygem_prms.density_ice / pygem_prms.density_water / nyears)
mb_mwea_fa_asl_geo_correction_max = 0.3*gta_to_mwea(calving_flux_Gta, glacier_rgi_table['Area']*1e6)
if mb_mwea_fa_asl_geo_correction > mb_mwea_fa_asl_geo_correction_max:
mb_mwea_fa_asl_geo_correction = mb_mwea_fa_asl_geo_correction_max
# Below sea-level correction due to calving that geodetic mass balance doesn't see
# print('test:', mbmod.glac_bin_icethickness_annual.shape, height_asl.shape, bin_area_lost.shape)
# height_bsl = mbmod.glac_bin_icethickness_annual - height_asl
# Area for retreat
if debug:
# print('\n----- area calcs -----')
# print(mbmod.glac_bin_area_annual[bin_last_idx:,0])
# print(mbmod.glac_bin_icethickness_annual[bin_last_idx:,0])
# print(mbmod.glac_bin_area_annual[bin_last_idx:,-2])
# print(mbmod.glac_bin_icethickness_annual[bin_last_idx:,-2])
# print(mbmod.heights.shape, mbmod.heights[bin_last_idx:])
print(' mb_mwea_fa_asl_geo_correction:', np.round(mb_mwea_fa_asl_geo_correction,2))
# print(' mb_mwea_fa_asl_geo_correction:', mb_mwea_fa_asl_geo_correction)
# print(glacier_rgi_table, glacier_rgi_table['Area'])
output_df.loc[nglac,'mb_mwea_fa_asl_lost'] = mb_mwea_fa_asl_geo_correction
if out_calving_forward is None:
output_df.loc[nglac,['calving_k', 'calving_thick', 'calving_flux_Gta', 'no_errors']] = (
np.nan, np.nan, np.nan, 0)
# Remove glaciers that failed to run
if fa_glac_data_reg is None:
reg_calving_gta_obs_good = None
output_df_good = output_df.dropna(axis=0, subset=['calving_flux_Gta'])
reg_calving_gta_mod_good = output_df_good.calving_flux_Gta.sum()
elif ignore_nan:
output_df_good = output_df.dropna(axis=0, subset=['calving_flux_Gta'])
reg_calving_gta_mod_good = output_df_good.calving_flux_Gta.sum()
rgiids_data = list(fa_glac_data_reg.RGIId.values)
rgiids_mod = list(output_df_good.RGIId.values)
fa_data_idx = [rgiids_data.index(x) for x in rgiids_mod]
reg_calving_gta_obs_good = fa_glac_data_reg.loc[fa_data_idx,frontal_ablation_Gta_cn].sum()
else:
reg_calving_gta_mod_good = output_df.calving_flux_Gta.sum()
reg_calving_gta_obs_good = fa_glac_data_reg[frontal_ablation_Gta_cn].sum()
return output_df, reg_calving_gta_mod_good, reg_calving_gta_obs_good
def run_opt_fa(main_glac_rgi_ind, calving_k, calving_k_bndlow, calving_k_bndhigh, fa_glac_data_ind,
calving_k_step=calving_k_step,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
ignore_nan=False, debug=debug_reg_calving_fxn, calc_mb_geo_correction=False):
"""
Run the optimization of the frontal ablation for an individual glacier
"""
output_df, reg_calving_gta_mod, reg_calving_gta_obs = (
reg_calving_flux(main_glac_rgi_ind, calving_k, fa_glac_data_reg=fa_glac_data_ind,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
ignore_nan=False, debug=debug_reg_calving_fxn,
calc_mb_geo_correction=calc_mb_geo_correction))
calving_k_bndlow_hold = np.copy(calving_k_bndlow)
if debug:
print(' fa_model_init [Gt/yr] :', np.round(reg_calving_gta_mod,4))
# ----- Rough optimizer using calving_k_step to loop through parameters within bounds ------
calving_k_last = calving_k
# output_df_last = output_df.copy()
reg_calving_gta_mod_last = reg_calving_gta_mod.copy()
if reg_calving_gta_mod < reg_calving_gta_obs:
if debug:
print('\nincrease calving_k')
# print('reg_calving_gta_mod:', reg_calving_gta_mod)
# print('reg_calving_gta_obs:', reg_calving_gta_obs)
# print('calving_k:', calving_k)
# print('calving_k_bndhigh:', calving_k_bndhigh)
# print('calving_k_bndlow:', calving_k_bndlow)
while ((reg_calving_gta_mod < reg_calving_gta_obs and np.round(calving_k,2) < calving_k_bndhigh
and calving_k > calving_k_bndlow
and (np.abs(reg_calving_gta_mod - reg_calving_gta_obs) / reg_calving_gta_obs > perc_threshold_agreement
and np.abs(reg_calving_gta_mod - reg_calving_gta_obs) > fa_threshold))):
# Record previous output
calving_k_last = np.copy(calving_k)
# output_df_last = output_df.copy()
reg_calving_gta_mod_last = reg_calving_gta_mod.copy()
if debug:
print(' increase calving_k_step:', calving_k_step)
# Increase calving k
calving_k += calving_k_step
if calving_k > calving_k_bndhigh:
calving_k = calving_k_bndhigh
# Re-run the regional frontal ablation estimates
output_df, reg_calving_gta_mod, reg_calving_gta_obs = (
reg_calving_flux(main_glac_rgi_ind, calving_k, fa_glac_data_reg=fa_glac_data_ind,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
ignore_nan=False, debug=debug_reg_calving_fxn,
calc_mb_geo_correction=calc_mb_geo_correction))
if debug:
print(' fa_data [Gt/yr]:', np.round(reg_calving_gta_obs,4))
print(' fa_model [Gt/yr] :', np.round(reg_calving_gta_mod,4))
# Set lower bound
calving_k_bndlow = calving_k_last
reg_calving_gta_mod_bndlow = reg_calving_gta_mod_last
# Set upper bound
calving_k_bndhigh = calving_k
reg_calving_gta_mod_bndhigh = reg_calving_gta_mod
else:
if debug:
print('\ndecrease calving_k')
print('-----')
print('reg_calving_gta_mod:', reg_calving_gta_mod)
print('reg_calving_gta_obs:', reg_calving_gta_obs)
print('calving_k:', calving_k)
print('calving_k_bndlow:', calving_k_bndlow)
print('fa perc:', (np.abs(reg_calving_gta_mod - reg_calving_gta_obs) / reg_calving_gta_obs))
print('fa thres:', np.abs(reg_calving_gta_mod - reg_calving_gta_obs))
print('good values:', output_df.loc[0,'calving_flux_Gta'])
while ((reg_calving_gta_mod > reg_calving_gta_obs and calving_k > calving_k_bndlow
and (np.abs(reg_calving_gta_mod - reg_calving_gta_obs) / reg_calving_gta_obs > perc_threshold_agreement
and np.abs(reg_calving_gta_mod - reg_calving_gta_obs) > fa_threshold))
and not np.isnan(output_df.loc[0,'calving_flux_Gta'])):
# Record previous output
calving_k_last = np.copy(calving_k)
# output_df_last = output_df.copy()
reg_calving_gta_mod_last = reg_calving_gta_mod.copy()
# Decrease calving k
calving_k -= calving_k_step
if calving_k < calving_k_bndlow:
calving_k = calving_k_bndlow
# Re-run the regional frontal ablation estimates
output_df, reg_calving_gta_mod, reg_calving_gta_obs = (
reg_calving_flux(main_glac_rgi_ind, calving_k, fa_glac_data_reg=fa_glac_data_ind,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
ignore_nan=False, debug=debug_reg_calving_fxn,
calc_mb_geo_correction=calc_mb_geo_correction))
if debug:
print(' fa_data [Gt/yr]:', np.round(reg_calving_gta_obs,4))
print(' fa_model [Gt/yr] :', np.round(reg_calving_gta_mod,4))
# Set lower bound
calving_k_bndlow = calving_k
reg_calving_gta_mod_bndlow = reg_calving_gta_mod
# Set upper bound
calving_k_bndhigh = calving_k_last
reg_calving_gta_mod_bndhigh = reg_calving_gta_mod_last
print('bnds:', calving_k_bndlow, calving_k_bndhigh)
print('bnds gt/yr:', reg_calving_gta_mod_bndlow, reg_calving_gta_mod_bndhigh)
# ----- Optimize further using mid-point "bisection" method -----
# Consider replacing with scipy.optimize.brent
if not np.isnan(output_df.loc[0,'calving_flux_Gta']):
# Check if upper bound causes good fit
if (np.abs(reg_calving_gta_mod_bndhigh - reg_calving_gta_obs) / reg_calving_gta_obs < perc_threshold_agreement
or np.abs(reg_calving_gta_mod_bndhigh - reg_calving_gta_obs) < fa_threshold):
# If so, calving_k equals upper bound and re-run to get proper estimates for output
calving_k = calving_k_bndhigh
# Re-run the regional frontal ablation estimates
output_df, reg_calving_gta_mod, reg_calving_gta_obs = (
reg_calving_flux(main_glac_rgi_ind, calving_k, fa_glac_data_reg=fa_glac_data_ind,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
ignore_nan=False, debug=debug_reg_calving_fxn,
calc_mb_geo_correction=calc_mb_geo_correction))
if debug:
print('upper bound:')
print(' calving_k:', np.round(calving_k,4))
print(' fa_data [Gt/yr]:', np.round(reg_calving_gta_obs,4))
print(' fa_model [Gt/yr] :', np.round(reg_calving_gta_mod,4))
# Check if lower bound causes good fit
elif (np.abs(reg_calving_gta_mod_bndlow - reg_calving_gta_obs) / reg_calving_gta_obs < perc_threshold_agreement
or np.abs(reg_calving_gta_mod_bndlow - reg_calving_gta_obs) < fa_threshold):
calving_k = calving_k_bndlow
# Re-run the regional frontal ablation estimates
output_df, reg_calving_gta_mod, reg_calving_gta_obs = (
reg_calving_flux(main_glac_rgi_ind, calving_k, fa_glac_data_reg=fa_glac_data_ind,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
ignore_nan=False, debug=debug_reg_calving_fxn,
calc_mb_geo_correction=calc_mb_geo_correction))
if debug:
print('lower bound:')
print(' calving_k:', np.round(calving_k,4))
print(' fa_data [Gt/yr]:', np.round(reg_calving_gta_obs,4))
print(' fa_model [Gt/yr] :', np.round(reg_calving_gta_mod,4))
else:
# Calibrate between limited range
nround = 0
# Set initial calving_k
calving_k = (calving_k_bndlow + calving_k_bndhigh) / 2
# print('fa_perc:', np.abs(reg_calving_gta_mod_bndlow - reg_calving_gta_obs) / reg_calving_gta_obs)
# print('fa_dif:', np.abs(reg_calving_gta_mod_bndlow - reg_calving_gta_obs))
# print('calving_k_bndlow:', calving_k_bndlow)
# print('nround:', nround, 'nround_max:', nround_max)
# print('calving_k:', calving_k, 'calving_k_bndlow_set:', calving_k_bndlow_hold)
while ((np.abs(reg_calving_gta_mod - reg_calving_gta_obs) / reg_calving_gta_obs > perc_threshold_agreement and
np.abs(reg_calving_gta_mod - reg_calving_gta_obs) > fa_threshold) and nround <= nround_max
and calving_k > calving_k_bndlow_hold):
nround += 1
if debug:
print('\nRound', nround)
# Update calving_k using midpoint
calving_k = (calving_k_bndlow + calving_k_bndhigh) / 2
output_df, reg_calving_gta_mod, reg_calving_gta_obs = (
reg_calving_flux(main_glac_rgi_ind, calving_k, fa_glac_data_reg=fa_glac_data_ind,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
ignore_nan=False, debug=debug_reg_calving_fxn,
calc_mb_geo_correction=calc_mb_geo_correction))
if debug:
print(' calving_k:', np.round(calving_k,4))
print(' fa_data [Gt/yr]:', np.round(reg_calving_gta_obs,4))
print(' fa_model [Gt/yr] :', np.round(reg_calving_gta_mod,4))
# Update bounds
if reg_calving_gta_mod < reg_calving_gta_obs:
# Update lower bound
reg_calving_gta_mod_bndlow = reg_calving_gta_mod
calving_k_bndlow = np.copy(calving_k)
else:
# Update upper bound
reg_calving_gta_mod_bndhigh = reg_calving_gta_mod
calving_k_bndhigh = np.copy(calving_k)
# if debug:
# print('fa_perc:', np.abs(reg_calving_gta_mod_bndlow - reg_calving_gta_obs) / reg_calving_gta_obs)
# print('fa_dif:', np.abs(reg_calving_gta_mod_bndlow - reg_calving_gta_obs))
# print('calving_k_bndlow:', calving_k_bndlow)
# print('nround:', nround, 'nround_max:', nround_max)
# print(' calving_k:', calving_k)
if calving_k < calving_k_bndlow:
calving_k = calving_k_bndlow
return output_df, calving_k
#%%
if option_merge_data:
calving_fp = pygem_prms.main_directory + '/../calving_data/'
calving_fn1 = 'Northern_hemisphere_calving_flux_Kochtitzky_et_al_for_David_Rounce_with_melt_v14-wromainMB.csv'
calving_fn2 = 'frontalablation_glacier_data_minowa2021.csv'
calving_fn3 = 'frontalablation_glacier_data_osmanoglu.csv'
fa_glac_data_cns_subset = ['RGIId','fa_gta_obs', 'fa_gta_obs_unc',
'Romain_gta_mbtot', 'Romain_gta_mbclim','Romain_mwea_mbtot', 'Romain_mwea_mbclim',
'thick_measured_yn', 'start_date', 'end_date', 'source']
# Load datasets
fa_glac_data1 = pd.read_csv(calving_fp + calving_fn1)
fa_glac_data2 = pd.read_csv(calving_fp + calving_fn2)
fa_glac_data3 = pd.read_csv(calving_fp + calving_fn3)
# Process datasets
mb_data_df = pd.read_csv(pygem_prms.hugonnet_fp + pygem_prms.hugonnet_fn)
mb_data_df['mb_mwea_romain'] = mb_data_df['mb_mwea'].copy()
mb_data_df['mb_mwea_err_romain'] = mb_data_df['mb_mwea_err'].copy()
# Kochtitzky data
fa_data_df1 = pd.DataFrame(np.zeros((fa_glac_data1.shape[0],len(fa_glac_data_cns_subset))), columns=fa_glac_data_cns_subset)
fa_data_df1['RGIId'] = fa_glac_data1['RGIId']
fa_data_df1['fa_gta_obs'] = fa_glac_data1['Frontal_ablation_2000_to_2020_gt_per_yr_mean']
fa_data_df1['fa_gta_obs_unc'] = fa_glac_data1['Frontal_ablation_2000_to_2020_gt_per_yr_mean_err']
fa_data_df1['Romain_gta_mbtot'] = fa_glac_data1['Romain_gta_mbtot']
fa_data_df1['Romain_gta_mbclim'] = fa_glac_data1['Romain_gta_mbclim']
fa_data_df1['Romain_mwea_mbtot'] = fa_glac_data1['Romain_mwea_mbtot']
fa_data_df1['Romain_mwea_mbclim'] = fa_glac_data1['Romain_mwea_mbclim']
fa_data_df1['thick_measured_yn'] = fa_glac_data1['thick_measured_yn']
fa_data_df1['start_date'] = '20009999'
fa_data_df1['end_date'] = '20199999'
fa_data_df1['source'] = 'Kochtitzky et al.'
# Minowa data
fa_data_df2 = pd.DataFrame(np.zeros((fa_glac_data2.shape[0],len(fa_glac_data_cns_subset))), columns=fa_glac_data_cns_subset)
fa_data_df2['RGIId'] = fa_glac_data2['RGIId']
fa_data_df2['fa_gta_obs'] = fa_glac_data2['frontal_ablation_Gta']
fa_data_df2['fa_gta_obs_unc'] = fa_glac_data2['frontal_ablation_unc_Gta']
# fa_data_df2['thick_measured_yn'] = np.nan
fa_data_df2['start_date'] = fa_glac_data2['start_date']
fa_data_df2['end_date'] = fa_glac_data2['end_date']
fa_data_df2['source'] = fa_glac_data2['Source']
fa_data_df2.sort_values('RGIId', inplace=True)
rgiids_fa_data2 = sorted(list(fa_data_df2.RGIId))
# Osmanoglu data
fa_data_df3 = pd.DataFrame(np.zeros((fa_glac_data3.shape[0],len(fa_glac_data_cns_subset))), columns=fa_glac_data_cns_subset)
fa_data_df3['RGIId'] = fa_glac_data3['RGIId']
fa_data_df3['fa_gta_obs'] = fa_glac_data3['frontal_ablation_Gta']
fa_data_df3['fa_gta_obs_unc'] = fa_glac_data3['frontal_ablation_unc_Gta']
# fa_data_df3['thick_measured_yn'] = np.nan
fa_data_df3['start_date'] = fa_glac_data3['start_date']
fa_data_df3['end_date'] = fa_glac_data3['end_date']
fa_data_df3['source'] = fa_glac_data3['Source']
fa_data_df3.sort_values('RGIId', inplace=True)
# rgiids_fa_data3 = sorted(list(fa_data_df3.RGIId))
#
# rgiids_mb_data = list(mb_data_df.RGIId.values)
#
# # Process data
# fa_data_process = pd.concat((fa_data_df2, fa_data_df3), axis=0)
# fa_data_process.reset_index(drop=True, inplace=True)
# rgiids_process = rgiids_fa_data2 + rgiids_fa_data3
# for nglac, rgiid in enumerate(rgiids_process):
# for batman in [0]:
## if rgiid in ['RGI60-19.02066']:
#
# if debug:
# print('\n' + str(nglac) + ' ' + rgiid)
#
## # Aggregate data from multiple glaciers if needed, since some include multiple glaciers
## if ',' in rgiid:
##
## rgiids_multiple_list = rgiid.split(',')
##
## # Combine mass balance from both glaciers, remove calving, and set both to be average
## fa_idx = rgiids_fa_data_process.index(rgiid)
## fa_gta = fa_data_process.loc[fa_idx,'fa_gta_obs']
### fa_gta_err = fa_data_process.loc[fa_idx,fa_gta_err_cn]
## mb_gta_list = []
## mb_gta_err_list = []
## area_m2_list = []
## for rgiid_single in rgiids_multiple_list:
## print(rgiid_single)
## mb_idx = rgiids_mb_data.index(rgiid_single)
##
## print(rgiid_single, mb_data_df.loc[mb_idx,'mb_mwea_romain'], mb_data_df.loc[mb_idx,'area'])
##
## mb_gta_single = mwea_to_gta(mb_data_df.loc[mb_idx,'mb_mwea_romain'],
## mb_data_df.loc[mb_idx,'area'] * 1e6)
### mb_gta_err_single = mwea_to_gta(mb_data_df.loc[mb_idx,'mb_mwea_err_romain'],
### mb_data_df.loc[mb_idx,'area'] * 1e6)
## mb_gta_list.append(mb_gta_single)
### mb_gta_err_list.append(mb_gta_err_single)
## area_m2_list.append(mb_data_df.loc[mb_idx,'area'] * 1e6)
##
## mb_gta = np.array(mb_gta_list).sum()
### mb_gta_err = (np.array(mb_gta_err_list)**2).sum()**0.5
## area_m2 = np.array(area_m2_list).sum()
##
## mb_mwea = gta_to_mwea(mb_gta, area_m2)
### mb_mwea_err = gta_to_mwea(mb_gta_err, area_m2)
##
## fa_mwea = gta_to_mwea(fa_gta, area_m2)
### fa_mwea_err = gta_to_mwea(fa_gta_err, area_m2)
##
## assert True==False, 'here'
##
## # Otherwise load individual glacier data
## else:
#
# mb_idx = rgiids_mb_data.index(rgiid)
#
# # Mass balance
# mb_mwea = mb_data_df.loc[mb_idx,pygem_prms.hugonnet_mb_cn]
# mb_mwea_err = mb_data_df.loc[mb_idx,pygem_prms.hugonnet_mb_err_cn]
# area_m2 = mb_data_df.loc[mb_idx,'area'] * 1e6
# mb_gta = mwea_to_gta(mb_mwea, area_m2)
# fa_data_process.loc[nglac,'Romain_mwea_mbtot'] = mb_mwea
# fa_data_process.loc[nglac,'Romain_gta_mbtot'] = mb_gta
## fa_data_process.loc[nglac,'Romain_mwea_mbtot_err'] = mb_data_df.loc[mb_idx,pygem_prms.hugonnet_mb_err_cn]
#
# # Frontal Ablation (gta)
# fa_gta = fa_data_process.loc[nglac,'fa_gta_obs']
# # convert to mwea
# fa_mwea = gta_to_mwea(fa_gta, area_m2)
#
# # Climatic mass balance correct for frontal ablation
# # - equals total mass balance minus frontal ablation
# mb_gta_mbclim = mb_gta + fa_gta
# fa_data_process.loc[nglac,'Romain_gta_mbclim'] = mb_gta_mbclim
## # sum of squares to aggregate error
## mb_gta_mbclim_err = (mb_gta_mbtot_err**2 + fa_gta_err**2)**0.5
## fa_data_df.loc[nglac,'Romain_gta_mbclim_err'] = mb_gta_mbclim_err
#
# # Convert to mwea
# fa_data_process.loc[nglac,'Romain_mwea_mbtot'] = gta_to_mwea(mb_gta, area_m2)
## fa_data_df.loc[nglac,'Romain_mwea_mbtot_err'] = gta_to_mwea(mb_gta_mbtot_err, area_m2)
# fa_data_process.loc[nglac,'Romain_mwea_mbclim'] = gta_to_mwea(mb_gta_mbclim, area_m2)
## fa_data_df.loc[nglac,'Romain_mwea_mbclim_err'] = gta_to_mwea(mb_gta_mbclim_err, area_m2)
#
# if debug:
# print(' mb_tot (mwea):', np.round(gta_to_mwea(mb_gta, area_m2),2))
# print(' mb_clim (mwea):', np.round(gta_to_mwea(mb_gta_mbclim, area_m2),2))
#
## # Record area
## mb_idx = rgiids_mb_data.index(rgiid)
## fa_data_df.loc[nglac,'area_km2'] = mb_data_df.loc[mb_idx,'area']
# Concatenate datasets
# fa_data_df = pd.concat([fa_data_df1, fa_data_process], axis=0)
fa_data_df = pd.concat([fa_data_df1, fa_data_df2, fa_data_df3], axis=0)
area_dict = dict(zip(mb_data_df.RGIId, mb_data_df.area))
fa_data_df['area_km2'] = fa_data_df['RGIId'].map(area_dict)
# Export frontal ablation data for Will
fa_data_df.to_csv(calving_fp + calving_fn1.replace('.csv','-w17_19.csv'), index=False)
#%%
if option_reg_calving_k:
# Load calving glacier data
fa_glac_data = pd.read_csv(pygem_prms.frontalablation_glacier_data_fullfn)
for reg in regions:
# Regional data
fa_glac_data_reg = fa_glac_data.loc[fa_glac_data['O1Region'] == reg, :].copy()
fa_glac_data_reg.reset_index(inplace=True, drop=True)
# Drop individual data points
if drop_ind_glaciers:
fa_idxs = []
for nglac, rgiid in enumerate(fa_glac_data_reg.RGIId):
# Avoid regional data and observations from multiple RGIIds (len==14)
if fa_glac_data_reg.loc[nglac,'RGIId'] == 'all':
fa_idxs.append(nglac)
fa_glac_data_reg = fa_glac_data_reg.loc[fa_idxs,:]
fa_glac_data_reg.reset_index(inplace=True, drop=True)
if fa_glac_data_reg.loc[0,'RGIId'] == 'all':
main_glac_rgi_all = modelsetup.selectglaciersrgitable(rgi_regionsO1=[reg], rgi_regionsO2='all',
rgi_glac_number='all',
include_landterm=False, include_laketerm=False,
include_tidewater=True)
# Set ignore_nan to False because we don't know individual glaciers
ignore_nan = False
else:
fa_glac_data_reg['glacno'] = np.nan
for nglac, rgiid in enumerate(fa_glac_data_reg.RGIId):
# Avoid regional data and observations from multiple RGIIds (len==14)
# if (not fa_glac_data_reg.loc[nglac,'RGIId'] == 'all' and len(fa_glac_data_reg.loc[nglac,'RGIId']) == 14
# and fa_glac_data_reg.loc[nglac,'RGIId'] in ['RGI60-03.00191']):
if not fa_glac_data_reg.loc[nglac,'RGIId'] == 'all' and len(fa_glac_data_reg.loc[nglac,'RGIId']) == 14:
fa_glac_data_reg.loc[nglac,'glacno'] = (str(int(rgiid.split('-')[1].split('.')[0])) + '.' +
rgiid.split('-')[1].split('.')[1])
# Drop observations that aren't of individual glaciers
fa_glac_data_reg = fa_glac_data_reg.dropna(axis=0, subset=['glacno'])
fa_glac_data_reg.reset_index(inplace=True, drop=True)
reg_calving_gta_obs = fa_glac_data_reg[frontal_ablation_Gta_cn].sum()
glacno_reg_wdata = sorted(list(fa_glac_data_reg.glacno.values))
main_glac_rgi_all = modelsetup.selectglaciersrgitable(glac_no=glacno_reg_wdata)
# Ignore nan for individual glaciers
ignore_nan = True
# Tidewater glaciers
termtype_list = [1,5]
main_glac_rgi = main_glac_rgi_all.loc[main_glac_rgi_all['TermType'].isin(termtype_list)]
main_glac_rgi.reset_index(inplace=True, drop=True)
# ----- OPTIMIZE CALVING_K BASED ON REGIONAL FRONTAL ABLATION DATA -----
calving_k = calving_k_init
output_df, reg_calving_gta_mod, reg_calving_gta_obs = (
reg_calving_flux(main_glac_rgi, calving_k, fa_glac_data_reg=fa_glac_data_reg,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn, ignore_nan=ignore_nan,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
debug=True))
if debug:
print('calving_k:', calving_k)
print(' fa_data [Gt/yr]:', np.round(reg_calving_gta_obs,5))
print(' fa_model [Gt/yr] :', np.round(reg_calving_gta_mod,5))
# ----- Rough optimizer using calving_k_step to loop through parameters within bounds ------
if reg_calving_gta_mod < reg_calving_gta_obs:
if debug:
print('increase calving_k')
while reg_calving_gta_mod < reg_calving_gta_obs and np.round(calving_k,2) < calving_k_bndhigh:
# Record previous output
calving_k_last = calving_k
# output_df_last = output_df.copy()
reg_calving_gta_mod_last = reg_calving_gta_mod.copy()
# Increase calving k
calving_k += calving_k_step
if calving_k > calving_k_bndhigh:
calving_k = calving_k_bndhigh
# Re-run the regional frontal ablation estimates
output_df, reg_calving_gta_mod, reg_calving_gta_obs = (
reg_calving_flux(main_glac_rgi, calving_k, fa_glac_data_reg=fa_glac_data_reg,
frontal_ablation_Gta_cn=frontal_ablation_Gta_cn, ignore_nan=ignore_nan,
prms_from_reg_priors=prms_from_reg_priors, prms_from_glac_cal=prms_from_glac_cal,
debug=True))
if debug:
print('calving_k:', calving_k)
print(' fa_data [Gt/yr]:', np.round(reg_calving_gta_obs,2))
print(' fa_model [Gt/yr] :', np.round(reg_calving_gta_mod,2))
# Set lower bound
calving_k_bndlow = calving_k_last
reg_calving_gta_mod_bndlow = reg_calving_gta_mod_last
# Set upper bound
calving_k_bndhigh = calving_k
reg_calving_gta_mod_bndhigh = reg_calving_gta_mod
else:
if debug:
print('decrease calving_k')
while reg_calving_gta_mod > reg_calving_gta_obs and np.round(calving_k,2) > calving_k_bndlow:
# Record previous output