-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathprocess_simulation.py
More file actions
11091 lines (9796 loc) · 622 KB
/
process_simulation.py
File metadata and controls
11091 lines (9796 loc) · 622 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
""" Analyze simulation output - mass change, runoff, etc. """
# Built-in libraries
import argparse
import collections
#import datetime
#import glob
import os
import pickle
import shutil
import time
import zipfile
# External libraries
import cartopy
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.path as mpath
#from matplotlib.pyplot import MaxNLocator
from matplotlib.lines import Line2D
import matplotlib.patches as patches
from matplotlib.ticker import AutoMinorLocator
from matplotlib.ticker import MultipleLocator
#from matplotlib.ticker import EngFormatter
#from matplotlib.ticker import StrMethodFormatter
#from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
#from mpl_toolkits.basemap import Basemap
import geopandas
import numpy as np
import pandas as pd
from scipy.stats import median_abs_deviation
#from scipy.stats import linregress
from scipy.ndimage import generic_filter
from scipy.ndimage import uniform_filter
#import scipy
import xarray as xr
# Local libraries
#import class_climate
#import class_mbdata
import pygem.pygem_input as pygem_prms
#import pygemfxns_gcmbiasadj as gcmbiasadj
import pygem.pygem_modelsetup as modelsetup
#from oggm import utils
from pygem.oggm_compat import single_flowline_glacier_directory
from pygem.shop import debris
from oggm import tasks
#%% ===== Input data =====
# Script options
option_find_missing = False # Checks file transfers and finds missing glaciers
option_move_files = False # Moves files from one directory to another
option_zip_sims = False # Zips binned and stats output for each region (gcm/scenario)
option_process_data = False # Processes data for regional statistics
option_process_data_nodebris = False # Processes data for regional statistics
option_process_data_wcalving = False # Processes data for regional statistics replacing tidewater glaciers w calving included
option_process_fa_err = False # Processes frontal ablation error for regional statistics
option_calving_mbclim_era5 = False # mbclim of two lowest elevation bins for Will
option_multigcm_plots_reg = False # Multi-GCM plots of various parameters for RGI regions
option_multigcm_plots_ws = False # Multi-GCM plots of various parameters for watersheds
option_glacier_cs_plots = False # Individual glacier cross section plots
option_glacier_cs_plots_NSFANS = False # Plots for NSF ANS proposal
option_debris_comparison = False # Mutli-GCM comparison of including debris or not
option_calving_comparison = False # Multi-GCM comparison of including frontal ablation or not
option_policy_temp_figs = False # Policy figures based on temperature deviations
option_sensitivity_figs = False # Mass balance sensitivity figures based on temp/prec deviations
option_swap_calving_sims = False # Unzip, swap in tidewater glacier runs with calving on, zip back and save
option_extract_sims = False # Extract sims to process subregions
option_export_timeseries = False # Export csv data for review of paper
option_extract_area = False # Export csv of area
def peakwater(runoff, time_values, nyears):
"""Compute peak water based on the running mean of N years
Parameters
----------
runoff : np.array
one-dimensional array of runoff for each timestep
time_values : np.array
time associated with each timestep
nyears : int
number of years to compute running mean used to smooth peakwater variations
Output
------
peakwater_yr : int
peakwater year
peakwater_chg : float
percent change of peak water compared to first timestep (running means used)
runoff_chg : float
percent change in runoff at the last timestep compared to the first timestep (running means used)
"""
runningmean = uniform_filter(runoff, size=(nyears))
peakwater_idx = np.where(runningmean == runningmean.max())[-1][0]
peakwater_yr = time_values[peakwater_idx]
peakwater_chg = (runningmean[peakwater_idx] - runningmean[0]) / runningmean[0] * 100
runoff_chg = (runningmean[-1] - runningmean[0]) / runningmean[0] * 100
return peakwater_yr, peakwater_chg, runoff_chg
def excess_meltwater_m3(glac_vol, option_lastloss=1):
""" Excess meltwater based on running minimum glacier volume
Note: when analyzing excess meltwater for a region, if there are glaciers that gain mass, the excess meltwater will
be zero. Consequently, the total excess meltwater will actually be more than the total mass loss because these
positive mass balances do not "remove" total excess meltwater.
Parameters
----------
glac_vol : np.array
glacier volume [km3]
option_lastloss : int
1 - excess meltwater based on last time glacier volume is lost for good
0 - excess meltwater based on first time glacier volume is lost (poorly accounts for gains)
option_lastloss = 1 calculates excess meltwater from the last time the glacier volume is lost for good
option_lastloss = 0 calculates excess meltwater from the first time the glacier volume is lost, but does
not recognize when the glacier volume returns
"""
glac_vol_m3 = glac_vol * pygem_prms.density_ice / pygem_prms.density_water * 1000**3
if option_lastloss == 1:
glac_vol_runningmin = np.maximum.accumulate(glac_vol_m3[:,::-1],axis=1)[:,::-1]
# initial volume sets limit of loss (gaining and then losing ice does not contribute to excess melt)
for ncol in range(0,glac_vol_m3.shape[1]):
mask = glac_vol_runningmin[:,ncol] > glac_vol_m3[:,0]
glac_vol_runningmin[mask,ncol] = glac_vol_m3[mask,0]
else:
# Running minimum volume up until that time period (so not beyond it!)
glac_vol_runningmin = np.minimum.accumulate(glac_vol_m3, axis=1)
glac_excess = glac_vol_runningmin[:,:-1] - glac_vol_runningmin[:,1:]
return glac_excess
def select_groups(grouping, main_glac_rgi_all):
"""
Select groups based on grouping
"""
if grouping == 'rgi_region':
groups = main_glac_rgi_all.O1Region.unique().tolist()
group_cn = 'O1Region'
elif grouping == 'degree':
groups = main_glac_rgi_all.deg_id.unique().tolist()
group_cn = 'deg_id'
else:
groups = ['all']
group_cn = 'all_group'
try:
groups = sorted(groups, key=str.lower)
except:
groups = sorted(groups)
return groups, group_cn
#%%
time_start = time.time()
if option_find_missing:
option_best_calving = False # Option to look at only tidewater glaciers
for reg in regions:
# All glaciers for fraction and missing
main_glac_rgi_all = modelsetup.selectglaciersrgitable(rgi_regionsO1=[reg],
rgi_regionsO2='all', rgi_glac_number='all',
glac_no=None)
if option_best_calving:
# Best
rcp = 'ssp126'
gcm_name = 'BCC-CSM2-MR'
# Filepath where glaciers are stored
netcdf_fp = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/stats/'
netcdf_fp_binned = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/binned/'
# Load the glaciers
glacno_list_gcmrcp = []
for i in os.listdir(netcdf_fp):
if i.endswith('.nc'):
glacno_list_gcmrcp.append(i.split('_')[0])
glacno_list_gcmrcp = sorted(glacno_list_gcmrcp)
main_glac_rgi_all = modelsetup.selectglaciersrgitable(glac_no=glacno_list_gcmrcp)
print(gcm_name, rcp, 'simulated', len(glacno_list_gcmrcp), 'glaciers')
# Load glaciers
glacno_list = []
glacno_list_gcmrcp_missing = {}
for rcp in rcps:
if 'rcp' in rcp:
gcm_names = gcm_names_rcps
elif 'ssp' in rcp:
if rcp in ['ssp119']:
gcm_names = gcm_names_ssp119
else:
gcm_names = gcm_names_ssps
for gcm_name in gcm_names:
# Filepath where glaciers are stored
netcdf_fp = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/stats/'
netcdf_fp_binned = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/binned/'
# Load the glaciers
glacno_list_gcmrcp = []
for i in os.listdir(netcdf_fp):
if i.endswith('.nc'):
glacno_list_gcmrcp.append(i.split('_')[0])
glacno_list_gcmrcp = sorted(glacno_list_gcmrcp)
print(gcm_name, rcp, 'simulated', len(glacno_list_gcmrcp), 'glaciers')
# Check other file too
glacno_binned_count = 0
for i in os.listdir(netcdf_fp_binned):
if i.endswith('.nc'):
glacno_binned_count += 1
print(' count of stats files:', len(glacno_list_gcmrcp))
print(' count of binned files:', glacno_binned_count)
# Only include the glaciers that were simulated by all GCM/RCP combinations
if len(glacno_list) == 0:
glacno_list = glacno_list_gcmrcp
else:
glacno_list = list(set(glacno_list).intersection(glacno_list_gcmrcp))
glacno_list = sorted(glacno_list)
# Missing glaciers by gcm/rcp
glacno_list_gcmrcp_missing[gcm_name + '-' + rcp] = (
sorted(np.setdiff1d(list(main_glac_rgi_all.glacno.values), glacno_list_gcmrcp).tolist()))
# #%%
# # Hack to find missing compared to other runs
## glacno_list_best = glacno_list_gcmrcp['CESM2-ssp245']
# fn_reg_glacno_list = 'R' + str(reg) + '_glacno_list.pkl'
# with open(pickle_fp + str(reg).zfill(2) + '/' + fn_reg_glacno_list, 'rb') as f:
# glacno_list_best = pickle.load(f)
#
# glacno_list_find = glacno_list_gcmrcp
#
# A = sorted(np.setdiff1d(glacno_list_best, glacno_list_find).tolist())
# if len(A) > 0:
# print(' missing:', A)
# #%%
# Glaciers with successful runs to process
main_glac_rgi = modelsetup.selectglaciersrgitable(glac_no=glacno_list)
# Missing glaciers
glacno_list_missing = sorted(np.setdiff1d(list(main_glac_rgi_all.glacno.values), glacno_list).tolist())
if len(glacno_list_missing) > 0:
main_glac_rgi_missing = modelsetup.selectglaciersrgitable(glac_no=glacno_list_missing)
print('\nGCM/RCPs successfully simulated:\n -', main_glac_rgi.shape[0], 'of', main_glac_rgi_all.shape[0], 'glaciers',
'(', np.round(main_glac_rgi.shape[0]/main_glac_rgi_all.shape[0]*100,1),'%)')
print(' -', np.round(main_glac_rgi.Area.sum(),0), 'km2 of', np.round(main_glac_rgi_all.Area.sum(),0), 'km2',
'(', np.round(main_glac_rgi.Area.sum()/main_glac_rgi_all.Area.sum()*100,1),'%)')
#%%
#%%
if option_zip_sims:
""" Zip simulations """
for reg in regions:
# All glaciers for fraction
main_glac_rgi_all = modelsetup.selectglaciersrgitable(rgi_regionsO1=[reg],
rgi_regionsO2='all', rgi_glac_number='all',
glac_no=None)
# Calving glaciers
termtype_list = [1,5]
main_glac_rgi_calving = main_glac_rgi_all.loc[main_glac_rgi_all['TermType'].isin(termtype_list)]
main_glac_rgi_calving.reset_index(inplace=True, drop=True)
glacno_list_calving = list(main_glac_rgi_calving.glacno.values)
for gcm_name in gcm_names:
for rcp in rcps:
print('zipping', reg, gcm_name, rcp)
# Filepath where glaciers are stored
netcdf_fp_binned = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/binned/'
netcdf_fp_stats = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/stats/'
# ----- Zip directories -----
zipped_fp_binned = netcdf_fp_cmip5 + '_zipped/' + str(reg).zfill(2) + '/binned/'
zipped_fp_stats = netcdf_fp_cmip5 + '_zipped/' + str(reg).zfill(2) + '/stats/'
zipped_fn_binned = gcm_name + '_' + rcp + '_binned'
zipped_fn_stats = gcm_name + '_' + rcp + '_stats'
if not os.path.exists(zipped_fp_binned):
os.makedirs(zipped_fp_binned, exist_ok=True)
if not os.path.exists(zipped_fp_stats):
os.makedirs(zipped_fp_stats, exist_ok=True)
shutil.make_archive(zipped_fp_binned + zipped_fn_binned, 'zip', netcdf_fp_binned)
shutil.make_archive(zipped_fp_stats + zipped_fn_stats, 'zip', netcdf_fp_stats)
if not 'nodebris' in netcdf_fp_cmip5:
# ----- Copy calving glaciers for comparison -----
if len(glacno_list_calving) > 0:
calving_fp_binned = netcdf_fp_cmip5 + '_calving/' + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/binned/'
calving_fp_stats = netcdf_fp_cmip5 + '_calving/' + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/stats/'
if not os.path.exists(calving_fp_binned):
os.makedirs(calving_fp_binned, exist_ok=True)
if not os.path.exists(calving_fp_stats):
os.makedirs(calving_fp_stats, exist_ok=True)
# Copy calving glaciers for comparison
for glacno in glacno_list_calving:
binned_fn = glacno + '_' + gcm_name + '_' + rcp + '_MCMC_ba1_50sets_2000_2100_binned.nc'
if os.path.exists(netcdf_fp_binned + binned_fn):
shutil.copyfile(netcdf_fp_binned + binned_fn, calving_fp_binned + binned_fn)
stats_fn = glacno + '_' + gcm_name + '_' + rcp + '_MCMC_ba1_50sets_2000_2100_all.nc'
if os.path.exists(netcdf_fp_stats + stats_fn):
shutil.copyfile(netcdf_fp_stats + stats_fn, calving_fp_stats + stats_fn)
# # ----- Missing glaciers -----
# # Filepath where glaciers are stored
# # Load the glaciers
# glacno_list_stats = []
# for i in os.listdir(netcdf_fp_stats):
# if i.endswith('.nc'):
# glacno_list_stats.append(i.split('_')[0])
# glacno_list_stats = sorted(glacno_list_stats)
#
# glacno_list_binned = []
# for i in os.listdir(netcdf_fp_binned):
# if i.endswith('.nc'):
# glacno_list_binned.append(i.split('_')[0])
# glacno_list_binned = sorted(glacno_list_binned)
#
# glacno_list_all = list(main_glac_rgi_all.glacno.values)
#
# A = np.setdiff1d(glacno_list_stats, glacno_list_binned).tolist()
# B = np.setdiff1d(glacno_list_all, glacno_list_stats).tolist()
#
# print(len(B), B)
#
# if rcp in ['rcp26']:
# C = glacno_list_stats.copy()
# elif rcp in ['rcp45']:
# D = glacno_list_stats.copy()
## C_dif = np.setdiff1d(D, C).tolist()
#%%
if option_process_data:
overwrite_pickle = False
grouping = 'all'
analysis_fp = netcdf_fp_cmip5.replace('simulations','analysis')
fig_fp = analysis_fp + 'figures/'
if not os.path.exists(fig_fp):
os.makedirs(fig_fp, exist_ok=True)
csv_fp = analysis_fp + 'csv/'
if not os.path.exists(csv_fp):
os.makedirs(csv_fp, exist_ok=True)
pickle_fp = analysis_fp + 'pickle/'
if not os.path.exists(pickle_fp):
os.makedirs(pickle_fp, exist_ok=True)
# def mwea_to_gta(mwea, area):
# return mwea * pygem_prms.density_water * area / 1e12
#%%
for reg in regions:
# Load glaciers
glacno_list = []
for rcp in rcps:
for gcm_name in gcm_names:
# Filepath where glaciers are stored
netcdf_fp = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/stats/'
# Load the glaciers
glacno_list_gcmrcp = []
for i in os.listdir(netcdf_fp):
if i.endswith('.nc'):
glacno_list_gcmrcp.append(i.split('_')[0])
glacno_list_gcmrcp = sorted(glacno_list_gcmrcp)
print(gcm_name, rcp, 'simulated', len(glacno_list_gcmrcp), 'glaciers')
# Only include the glaciers that were simulated by all GCM/RCP combinations
if len(glacno_list) == 0:
glacno_list = glacno_list_gcmrcp
else:
glacno_list = list(set(glacno_list).intersection(glacno_list_gcmrcp))
glacno_list = sorted(glacno_list)
# All glaciers for fraction
main_glac_rgi_all = modelsetup.selectglaciersrgitable(rgi_regionsO1=[reg],
rgi_regionsO2='all', rgi_glac_number='all',
glac_no=None)
# Glaciers with successful runs to process
main_glac_rgi = modelsetup.selectglaciersrgitable(glac_no=glacno_list)
# Missing glaciers
glacno_list_missing = sorted(np.setdiff1d(list(main_glac_rgi_all.glacno.values), glacno_list).tolist())
if len(glacno_list_missing) > 0:
main_glac_rgi_missing = modelsetup.selectglaciersrgitable(glac_no=glacno_list_missing)
print('\nGCM/RCPs successfully simulated:\n -', main_glac_rgi.shape[0], 'of', main_glac_rgi_all.shape[0], 'glaciers',
'(', np.round(main_glac_rgi.shape[0]/main_glac_rgi_all.shape[0]*100,1),'%)')
print(' -', np.round(main_glac_rgi.Area.sum(),0), 'km2 of', np.round(main_glac_rgi_all.Area.sum(),0), 'km2',
'(', np.round(main_glac_rgi.Area.sum()/main_glac_rgi_all.Area.sum()*100,1),'%)')
# ===== EXPORT RESULTS =====
success_fullfn = csv_fp + 'CMIP5_success.csv'
success_cns = ['O1Region', 'count_success', 'count', 'count_%', 'reg_area_km2_success', 'reg_area_km2', 'reg_area_%']
success_df_single = pd.DataFrame(np.zeros((1,len(success_cns))), columns=success_cns)
success_df_single.loc[0,:] = [reg, main_glac_rgi.shape[0], main_glac_rgi_all.shape[0],
np.round(main_glac_rgi.shape[0]/main_glac_rgi_all.shape[0]*100,2),
np.round(main_glac_rgi.Area.sum(),2), np.round(main_glac_rgi_all.Area.sum(),2),
np.round(main_glac_rgi.Area.sum()/main_glac_rgi_all.Area.sum()*100,2)]
if os.path.exists(success_fullfn):
success_df = pd.read_csv(success_fullfn)
# Add or overwrite existing file
success_idx = np.where((success_df.O1Region == reg))[0]
if len(success_idx) > 0:
success_df.loc[success_idx,:] = success_df_single.values
else:
success_df = pd.concat([success_df, success_df_single], axis=0)
else:
success_df = success_df_single
success_df = success_df.sort_values('O1Region', ascending=True)
success_df.reset_index(inplace=True, drop=True)
success_df.to_csv(success_fullfn, index=False)
# ----- Add Groups -----
# Degrees (based on degree_size)
main_glac_rgi['CenLon_round'] = np.floor(main_glac_rgi.CenLon.values/degree_size) * degree_size
main_glac_rgi['CenLat_round'] = np.floor(main_glac_rgi.CenLat.values/degree_size) * degree_size
deg_groups = main_glac_rgi.groupby(['CenLon_round', 'CenLat_round']).size().index.values.tolist()
deg_dict = dict(zip(deg_groups, np.arange(0,len(deg_groups))))
main_glac_rgi.reset_index(drop=True, inplace=True)
cenlon_cenlat = [(main_glac_rgi.loc[x,'CenLon_round'], main_glac_rgi.loc[x,'CenLat_round'])
for x in range(len(main_glac_rgi))]
main_glac_rgi['CenLon_CenLat'] = cenlon_cenlat
main_glac_rgi['deg_id'] = main_glac_rgi.CenLon_CenLat.map(deg_dict)
# River Basin
watershed_dict_fn = pygem_prms.main_directory + '/../qgis_datasets/rgi60_watershed_dict.csv'
watershed_csv = pd.read_csv(watershed_dict_fn)
watershed_dict = dict(zip(watershed_csv.RGIId, watershed_csv.watershed))
main_glac_rgi['watershed'] = main_glac_rgi.RGIId.map(watershed_dict)
if len(np.where(main_glac_rgi.watershed.isnull())[0]) > 0:
main_glac_rgi.loc[np.where(main_glac_rgi.watershed.isnull())[0],'watershed'] = 'nan'
#%%
# Unique Groups
# O2 Regions
unique_regO2s = np.unique(main_glac_rgi['O2Region'])
# Degrees
if main_glac_rgi['deg_id'].isnull().all():
unique_degids = None
else:
unique_degids = np.unique(main_glac_rgi['deg_id'])
# Watersheds
if main_glac_rgi['watershed'].isnull().all():
unique_watersheds = None
else:
unique_watersheds = np.unique(main_glac_rgi['watershed'])
# Elevation bins
elev_bin_size = 10
zmax = int(np.ceil(main_glac_rgi.Zmax.max() / elev_bin_size) * elev_bin_size) + 500
elev_bins = np.arange(0,zmax,elev_bin_size)
elev_bins = np.insert(elev_bins, 0, -1000)
# Pickle datasets
# Glacier list
fn_reg_glacno_list = 'R' + str(reg) + '_glacno_list.pkl'
if not os.path.exists(pickle_fp + str(reg).zfill(2) + '/'):
os.makedirs(pickle_fp + str(reg).zfill(2) + '/')
with open(pickle_fp + str(reg).zfill(2) + '/' + fn_reg_glacno_list, 'wb') as f:
pickle.dump(glacno_list, f)
# O2Region dict
fn_unique_regO2s = 'R' + str(reg) + '_unique_regO2s.pkl'
with open(pickle_fp + str(reg).zfill(2) + '/' + fn_unique_regO2s, 'wb') as f:
pickle.dump(unique_regO2s, f)
# Watershed dict
fn_unique_watersheds = 'R' + str(reg) + '_unique_watersheds.pkl'
with open(pickle_fp + str(reg).zfill(2) + '/' + fn_unique_watersheds, 'wb') as f:
pickle.dump(unique_watersheds, f)
# Degree ID dict
fn_unique_degids = 'R' + str(reg) + '_unique_degids.pkl'
with open(pickle_fp + str(reg).zfill(2) + '/' + fn_unique_degids, 'wb') as f:
pickle.dump(unique_degids, f)
fn_elev_bins = 'R' + str(reg) + '_elev_bins.pkl'
with open(pickle_fp + str(reg).zfill(2) + '/' + fn_elev_bins, 'wb') as f:
pickle.dump(elev_bins, f)
#%%
years = None
for gcm_name in gcm_names:
for rcp in rcps:
# Filepath where glaciers are stored
netcdf_fp_binned = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/binned/'
netcdf_fp_stats = netcdf_fp_cmip5 + str(reg).zfill(2) + '/' + gcm_name + '/' + rcp + '/stats/'
# ----- GCM/RCP PICKLE FILEPATHS AND FILENAMES -----
pickle_fp_reg = pickle_fp + str(reg).zfill(2) + '/O1Regions/' + gcm_name + '/' + rcp + '/'
if not os.path.exists(pickle_fp_reg):
os.makedirs(pickle_fp_reg)
pickle_fp_regO2 = pickle_fp + str(reg).zfill(2) + '/O2Regions/' + gcm_name + '/' + rcp + '/'
if not os.path.exists(pickle_fp_regO2):
os.makedirs(pickle_fp_regO2)
pickle_fp_watershed = pickle_fp + str(reg).zfill(2) + '/watersheds/' + gcm_name + '/' + rcp + '/'
if not os.path.exists(pickle_fp_watershed):
os.makedirs(pickle_fp_watershed)
pickle_fp_degid = pickle_fp + str(reg).zfill(2) + '/degids/' + gcm_name + '/' + rcp + '/'
if not os.path.exists(pickle_fp_degid):
os.makedirs(pickle_fp_degid)
# Region string prefix
reg_rcp_gcm_str = 'R' + str(reg) + '_' + rcp + '_' + gcm_name
regO2_rcp_gcm_str = 'R' + str(reg) + '_O2Regions_' + rcp + '_' + gcm_name
watershed_rcp_gcm_str = 'R' + str(reg) + '_watersheds_' + rcp + '_' + gcm_name
degid_rcp_gcm_str = 'R' + str(reg) + '_degids_' + rcp + '_' + gcm_name
# Volume
fn_reg_vol_annual = reg_rcp_gcm_str + '_vol_annual.pkl'
fn_regO2_vol_annual = regO2_rcp_gcm_str + '_vol_annual.pkl'
fn_watershed_vol_annual = watershed_rcp_gcm_str + '_vol_annual.pkl'
fn_degid_vol_annual = degid_rcp_gcm_str + '_vol_annual.pkl'
# Volume below sea level
fn_reg_vol_annual_bwl = reg_rcp_gcm_str + '_vol_annual_bwl.pkl'
fn_regO2_vol_annual_bwl = regO2_rcp_gcm_str + '_vol_annual_bwl.pkl'
fn_watershed_vol_annual_bwl = watershed_rcp_gcm_str + '_vol_annual_bwl.pkl'
fn_degid_vol_annual_bwl = degid_rcp_gcm_str + '_vol_annual_bwl.pkl'
# Volume below debris
fn_reg_vol_annual_bd = reg_rcp_gcm_str + '_vol_annual_bd.pkl'
fn_regO2_vol_annual_bd = regO2_rcp_gcm_str + '_vol_annual_bd.pkl'
fn_watershed_vol_annual_bd = watershed_rcp_gcm_str + '_vol_annual_bd.pkl'
fn_degid_vol_annual_bd = degid_rcp_gcm_str + '_vol_annual_bd.pkl'
# Area
fn_reg_area_annual = reg_rcp_gcm_str + '_area_annual.pkl'
fn_regO2_area_annual = regO2_rcp_gcm_str + '_area_annual.pkl'
fn_watershed_area_annual = watershed_rcp_gcm_str + '_area_annual.pkl'
fn_degid_area_annual = degid_rcp_gcm_str + '_area_annual.pkl'
# Area below debris
fn_reg_area_annual_bd = reg_rcp_gcm_str + '_area_annual_bd.pkl'
fn_regO2_area_annual_bd = regO2_rcp_gcm_str + '_area_annual_bd.pkl'
fn_watershed_area_annual_bd = watershed_rcp_gcm_str + '_area_annual_bd.pkl'
fn_degid_area_annual_bd = degid_rcp_gcm_str + '_area_annual_bd.pkl'
# Binned Volume
fn_reg_vol_annual_binned = reg_rcp_gcm_str + '_vol_annual_binned.pkl'
fn_regO2_vol_annual_binned = regO2_rcp_gcm_str + '_vol_annual_binned.pkl'
fn_watershed_vol_annual_binned = watershed_rcp_gcm_str + '_vol_annual_binned.pkl'
# Binned Volume below debris
fn_reg_vol_annual_binned_bd = reg_rcp_gcm_str + '_vol_annual_binned_bd.pkl'
fn_regO2_vol_annual_binned_bd = regO2_rcp_gcm_str + '_vol_annual_binned_bd.pkl'
fn_watershed_vol_annual_binned_bd = watershed_rcp_gcm_str + '_vol_annual_binned_bd.pkl'
# Binned Area
fn_reg_area_annual_binned = reg_rcp_gcm_str + '_area_annual_binned.pkl'
fn_regO2_area_annual_binned = regO2_rcp_gcm_str + '_area_annual_binned.pkl'
fn_watershed_area_annual_binned = watershed_rcp_gcm_str + '_area_annual_binned.pkl'
# Binned Area below debris
fn_reg_area_annual_binned_bd = reg_rcp_gcm_str + '_area_annual_binned_bd.pkl'
fn_regO2_area_annual_binned_bd = regO2_rcp_gcm_str + '_area_annual_binned_bd.pkl'
fn_watershed_area_annual_binned_bd = watershed_rcp_gcm_str + '_area_annual_binned_bd.pkl'
# Mass balance: accumulation
fn_reg_acc_monthly = reg_rcp_gcm_str + '_acc_monthly.pkl'
fn_regO2_acc_monthly = regO2_rcp_gcm_str + '_acc_monthly.pkl'
fn_watershed_acc_monthly = watershed_rcp_gcm_str + '_acc_monthly.pkl'
# Mass balance: refreeze
fn_reg_refreeze_monthly = reg_rcp_gcm_str + '_refreeze_monthly.pkl'
fn_regO2_refreeze_monthly = regO2_rcp_gcm_str + '_refreeze_monthly.pkl'
fn_watershed_refreeze_monthly = watershed_rcp_gcm_str + '_refreeze_monthly.pkl'
# Mass balance: melt
fn_reg_melt_monthly = reg_rcp_gcm_str + '_melt_monthly.pkl'
fn_regO2_melt_monthly = regO2_rcp_gcm_str + '_melt_monthly.pkl'
fn_watershed_melt_monthly = watershed_rcp_gcm_str + '_melt_monthly.pkl'
# Mass balance: frontal ablation
fn_reg_frontalablation_monthly = reg_rcp_gcm_str + '_frontalablation_monthly.pkl'
fn_regO2_frontalablation_monthly = regO2_rcp_gcm_str + '_frontalablation_monthly.pkl'
fn_watershed_frontalablation_monthly = watershed_rcp_gcm_str + '_frontalablation_monthly.pkl'
# Mass balance: total mass balance
fn_reg_massbaltotal_monthly = reg_rcp_gcm_str + '_massbaltotal_monthly.pkl'
fn_regO2_massbaltotal_monthly = regO2_rcp_gcm_str + '_massbaltotal_monthly.pkl'
fn_watershed_massbaltotal_monthly = watershed_rcp_gcm_str + '_massbaltotal_monthly.pkl'
fn_degid_massbaltotal_monthly = degid_rcp_gcm_str + '_massbaltotal_monthly.pkl'
# Binned Climatic Mass Balance
fn_reg_mbclim_annual_binned = reg_rcp_gcm_str + '_mbclim_annual_binned.pkl'
fn_regO2_mbclim_annual_binned = regO2_rcp_gcm_str + '_mbclim_annual_binned.pkl'
fn_watershed_mbclim_annual_binned = watershed_rcp_gcm_str + '_mbclim_annual_binned.pkl'
# Runoff: moving-gauged
fn_reg_runoff_monthly_moving = reg_rcp_gcm_str + '_runoff_monthly_moving.pkl'
fn_regO2_runoff_monthly_moving = regO2_rcp_gcm_str + '_runoff_monthly_moving.pkl'
fn_watershed_runoff_monthly_moving = watershed_rcp_gcm_str + '_runoff_monthly_moving.pkl'
fn_degid_runoff_monthly_moving = degid_rcp_gcm_str + '_runoff_monthly_moving.pkl'
# Runoff: fixed-gauged
fn_reg_runoff_monthly_fixed = reg_rcp_gcm_str + '_runoff_monthly_fixed.pkl'
fn_regO2_runoff_monthly_fixed = regO2_rcp_gcm_str + '_runoff_monthly_fixed.pkl'
fn_watershed_runoff_monthly_fixed = watershed_rcp_gcm_str + '_runoff_monthly_fixed.pkl'
fn_degid_runoff_monthly_fixed = degid_rcp_gcm_str + '_runoff_monthly_fixed.pkl'
# Runoff: precipitation
fn_reg_prec_monthly = reg_rcp_gcm_str + '_prec_monthly.pkl'
fn_regO2_prec_monthly = regO2_rcp_gcm_str + '_prec_monthly.pkl'
fn_watershed_prec_monthly = watershed_rcp_gcm_str + '_prec_monthly.pkl'
# Runoff: off-glacier precipitation
fn_reg_offglac_prec_monthly = reg_rcp_gcm_str + '_offglac_prec_monthly.pkl'
fn_regO2_offglac_prec_monthly = regO2_rcp_gcm_str + '_offglac_prec_monthly.pkl'
fn_watershed_offglac_prec_monthly = watershed_rcp_gcm_str + '_offglac_prec_monthly.pkl'
# Runoff: off-glacier melt
fn_reg_offglac_melt_monthly = reg_rcp_gcm_str + '_offglac_melt_monthly.pkl'
fn_regO2_offglac_melt_monthly = regO2_rcp_gcm_str + '_offglac_melt_monthly.pkl'
fn_watershed_offglac_melt_monthly = watershed_rcp_gcm_str + '_offglac_melt_monthly.pkl'
# Runoff: off-glacier refreeze
fn_reg_offglac_refreeze_monthly = reg_rcp_gcm_str + '_offglac_refreeze_monthly.pkl'
fn_regO2_offglac_refreeze_monthly = regO2_rcp_gcm_str + '_offglac_refreeze_monthly.pkl'
fn_watershed_offglac_refreeze_monthly = watershed_rcp_gcm_str + '_offglac_refreeze_monthly.pkl'
# ELA
fn_reg_ela_annual = reg_rcp_gcm_str + '_ela_annual.pkl'
fn_regO2_ela_annual = regO2_rcp_gcm_str + '_ela_annual.pkl'
fn_watershed_ela_annual = watershed_rcp_gcm_str + '_ela_annual.pkl'
# AAR
fn_reg_aar_annual = reg_rcp_gcm_str + '_aar_annual.pkl'
fn_regO2_aar_annual = regO2_rcp_gcm_str + '_aar_annual.pkl'
fn_watershed_aar_annual = watershed_rcp_gcm_str + '_aar_annual.pkl'
if not os.path.exists(pickle_fp_reg + fn_reg_vol_annual) or overwrite_pickle:
# Entire region
years = None
reg_vol_annual = None
reg_vol_annual_bwl = None
reg_vol_annual_bd = None
reg_area_annual = None
reg_area_annual_bd = None
reg_vol_annual_binned = None
reg_vol_annual_binned_bd = None
reg_area_annual_binned = None
reg_area_annual_binned_bd = None
reg_mbclim_annual_binned = None
reg_acc_monthly = None
reg_refreeze_monthly = None
reg_melt_monthly = None
reg_frontalablation_monthly = None
reg_massbaltotal_monthly = None
reg_runoff_monthly_fixed = None
reg_runoff_monthly_moving = None
reg_prec_monthly = None
reg_offglac_prec_monthly = None
reg_offglac_melt_monthly = None
reg_offglac_refreeze_monthly = None
reg_ela_annual = None
reg_ela_annual_area = None # used for weighted area calculations
reg_area_annual_acc = None
reg_area_annual_frombins = None
# Subregion groups
regO2_vol_annual = None
regO2_vol_annual_bwl = None
regO2_vol_annual_bd = None
regO2_area_annual = None
regO2_area_annual_bd = None
regO2_vol_annual_binned = None
regO2_vol_annual_binned_bd = None
regO2_area_annual_binned = None
regO2_area_annual_binned_bd = None
regO2_mbclim_annual_binned = None
regO2_acc_monthly = None
regO2_refreeze_monthly = None
regO2_melt_monthly = None
regO2_frontalablation_monthly = None
regO2_massbaltotal_monthly = None
regO2_runoff_monthly_fixed = None
regO2_runoff_monthly_moving = None
regO2_prec_monthly = None
regO2_offglac_prec_monthly = None
regO2_offglac_melt_monthly = None
regO2_offglac_refreeze_monthly = None
regO2_ela_annual = None
regO2_ela_annual_area = None # used for weighted area calculations
regO2_area_annual_acc = None
regO2_area_annual_frombins = None
# Watershed groups
watershed_vol_annual = None
watershed_vol_annual_bwl = None
watershed_vol_annual_bd = None
watershed_area_annual = None
watershed_area_annual_bd = None
watershed_vol_annual_binned = None
watershed_vol_annual_binned_bd = None
watershed_area_annual_binned = None
watershed_area_annual_binned_bd = None
watershed_mbclim_annual_binned = None
watershed_acc_monthly = None
watershed_refreeze_monthly = None
watershed_melt_monthly = None
watershed_frontalablation_monthly = None
watershed_massbaltotal_monthly = None
watershed_runoff_monthly_fixed = None
watershed_runoff_monthly_moving = None
watershed_prec_monthly = None
watershed_offglac_prec_monthly = None
watershed_offglac_melt_monthly = None
watershed_offglac_refreeze_monthly = None
watershed_ela_annual = None
watershed_ela_annual_area = None # used for weighted area calculations
watershed_area_annual_acc = None
watershed_area_annual_frombins = None
# Degree groups
degid_vol_annual = None
degid_vol_annual_bwl = None
degid_vol_annual_bd = None
degid_area_annual = None
degid_area_annual_bd = None
degid_massbaltotal_monthly = None
degid_runoff_monthly_fixed = None
degid_runoff_monthly_moving = None
for nglac, glacno in enumerate(glacno_list):
if nglac%10 == 0:
print(gcm_name, rcp, glacno)
# Group indices
glac_idx = np.where(main_glac_rgi['glacno'] == glacno)[0][0]
regO2 = main_glac_rgi.loc[glac_idx, 'O2Region']
regO2_idx = np.where(regO2 == unique_regO2s)[0][0]
watershed = main_glac_rgi.loc[glac_idx,'watershed']
watershed_idx = np.where(watershed == unique_watersheds)
degid = main_glac_rgi.loc[glac_idx, 'deg_id']
degid_idx = np.where(degid == unique_degids)[0][0]
# Filenames
nsim_strs = ['50', '1', '100', '150', '200', '250']
ds_binned = None
nset = -1
while ds_binned is None and nset <= len(nsim_strs):
nset += 1
nsim_str = nsim_strs[nset]
try:
netcdf_fn_binned_ending = 'MCMC_ba1_' + nsim_str + 'sets_2000_2100_binned.nc'
netcdf_fn_binned = '_'.join([glacno, gcm_name, rcp, netcdf_fn_binned_ending])
netcdf_fn_stats_ending = 'MCMC_ba1_' + nsim_str + 'sets_2000_2100_all.nc'
netcdf_fn_stats = '_'.join([glacno, gcm_name, rcp, netcdf_fn_stats_ending])
# Open files
ds_binned = xr.open_dataset(netcdf_fp_binned + '/' + netcdf_fn_binned)
ds_stats = xr.open_dataset(netcdf_fp_stats + '/' + netcdf_fn_stats)
except:
ds_binned = None
# Years
if years is None:
years = ds_stats.year.values
# ----- 1. Volume (m3) vs. Year -----
glac_vol_annual = ds_stats.glac_volume_annual.values[0,:]
# All
if reg_vol_annual is None:
reg_vol_annual = glac_vol_annual
else:
reg_vol_annual += glac_vol_annual
# O2Region
if regO2_vol_annual is None:
regO2_vol_annual = np.zeros((len(unique_regO2s),years.shape[0]))
regO2_vol_annual[regO2_idx,:] = glac_vol_annual
else:
regO2_vol_annual[regO2_idx,:] += glac_vol_annual
# Watershed
if watershed_vol_annual is None:
watershed_vol_annual = np.zeros((len(unique_watersheds),years.shape[0]))
watershed_vol_annual[watershed_idx,:] = glac_vol_annual
else:
watershed_vol_annual[watershed_idx,:] += glac_vol_annual
# DegId
if degid_vol_annual is None:
degid_vol_annual = np.zeros((len(unique_degids), years.shape[0]))
degid_vol_annual[degid_idx,:] = glac_vol_annual
else:
degid_vol_annual[degid_idx,:] += glac_vol_annual
# ----- 2. Volume below-sea-level (m3) vs. Year -----
# - initial elevation is stored
# - bed elevation is constant in time
# - assume sea level is at 0 m a.s.l.
z_sealevel = 0
bin_z_init = ds_binned.bin_surface_h_initial.values[0,:]
bin_thick_annual = ds_binned.bin_thick_annual.values[0,:,:]
bin_z_bed = bin_z_init - bin_thick_annual[:,0]
# Annual surface height
bin_z_surf_annual = bin_z_bed[:,np.newaxis] + bin_thick_annual
# Annual volume (m3)
bin_vol_annual = ds_binned.bin_volume_annual.values[0,:,:]
# Annual area (m2)
bin_area_annual = np.zeros(bin_vol_annual.shape)
bin_area_annual[bin_vol_annual > 0] = (
bin_vol_annual[bin_vol_annual > 0] / bin_thick_annual[bin_vol_annual > 0])
# Processed based on OGGM's _vol_below_level function
bwl = (bin_z_bed[:,np.newaxis] < 0) & (bin_thick_annual > 0)
if bwl.any():
# Annual surface height (max of sea level for calcs)
bin_z_surf_annual_bwl = bin_z_surf_annual.copy()
bin_z_surf_annual_bwl[bin_z_surf_annual_bwl > z_sealevel] = z_sealevel
# Annual thickness below sea level (m)
bin_thick_annual_bwl = bin_thick_annual.copy()
bin_thick_annual_bwl = bin_z_surf_annual_bwl - bin_z_bed[:,np.newaxis]
bin_thick_annual_bwl[~bwl] = 0
# Annual volume below sea level (m3)
bin_vol_annual_bwl = np.zeros(bin_vol_annual.shape)
bin_vol_annual_bwl[bwl] = bin_thick_annual_bwl[bwl] * bin_area_annual[bwl]
glac_vol_annual_bwl = bin_vol_annual_bwl.sum(0)
# All
if reg_vol_annual_bwl is None:
reg_vol_annual_bwl = glac_vol_annual_bwl
else:
reg_vol_annual_bwl += glac_vol_annual_bwl
# O2Region
if regO2_vol_annual_bwl is None:
regO2_vol_annual_bwl = np.zeros((len(unique_regO2s),years.shape[0]))
regO2_vol_annual_bwl[regO2_idx,:] = glac_vol_annual_bwl
else:
regO2_vol_annual_bwl[regO2_idx,:] += glac_vol_annual_bwl
# Watershed
if watershed_vol_annual_bwl is None:
watershed_vol_annual_bwl = np.zeros((len(unique_watersheds),years.shape[0]))
watershed_vol_annual_bwl[watershed_idx,:] = glac_vol_annual_bwl
else:
watershed_vol_annual_bwl[watershed_idx,:] += glac_vol_annual_bwl
# DegId
if degid_vol_annual_bwl is None:
degid_vol_annual_bwl = np.zeros((len(unique_degids), years.shape[0]))
degid_vol_annual_bwl[degid_idx,:] = glac_vol_annual_bwl
else:
degid_vol_annual_bwl[degid_idx,:] += glac_vol_annual_bwl
# ----- 3. Volume below-debris vs. Time -----
gdir = single_flowline_glacier_directory(glacno, logging_level='CRITICAL')
fls = gdir.read_pickle('inversion_flowlines')
bin_debris_hd = np.zeros(bin_z_init.shape)
bin_debris_ed = np.zeros(bin_z_init.shape) + 1
if 'debris_hd' in dir(fls[0]):
bin_debris_hd[0:fls[0].debris_hd.shape[0]] = fls[0].debris_hd
bin_debris_ed[0:fls[0].debris_hd.shape[0]] = fls[0].debris_ed
if bin_debris_hd.sum() > 0:
bin_vol_annual_bd = np.zeros(bin_vol_annual.shape)
bin_vol_annual_bd[bin_debris_hd > 0, :] = bin_vol_annual[bin_debris_hd > 0, :]
glac_vol_annual_bd = bin_vol_annual_bd.sum(0)
# All
if reg_vol_annual_bd is None:
reg_vol_annual_bd = glac_vol_annual_bd
else:
reg_vol_annual_bd += glac_vol_annual_bd
# O2Region
if regO2_vol_annual_bd is None:
regO2_vol_annual_bd = np.zeros((len(unique_regO2s),years.shape[0]))
regO2_vol_annual_bd[regO2_idx,:] = glac_vol_annual_bd
else:
regO2_vol_annual_bd[regO2_idx,:] += glac_vol_annual_bd
# Watershed
if watershed_vol_annual_bd is None:
watershed_vol_annual_bd = np.zeros((len(unique_watersheds),years.shape[0]))
watershed_vol_annual_bd[watershed_idx,:] = glac_vol_annual_bd
else:
watershed_vol_annual_bd[watershed_idx,:] += glac_vol_annual_bd
# DegId
if degid_vol_annual_bd is None:
degid_vol_annual_bd = np.zeros((len(unique_degids), years.shape[0]))
degid_vol_annual_bd[degid_idx,:] = glac_vol_annual_bd
else:
degid_vol_annual_bd[degid_idx,:] += glac_vol_annual_bd
# ----- 4. Area vs. Time -----
glac_area_annual = ds_stats.glac_area_annual.values[0,:]
# All
if reg_area_annual is None:
reg_area_annual = glac_area_annual
else:
reg_area_annual += glac_area_annual
# O2Region
if regO2_area_annual is None:
regO2_area_annual = np.zeros((len(unique_regO2s),years.shape[0]))
regO2_area_annual[regO2_idx,:] = glac_area_annual
else:
regO2_area_annual[regO2_idx,:] += glac_area_annual
# Watershed
if watershed_area_annual is None:
watershed_area_annual = np.zeros((len(unique_watersheds),years.shape[0]))
watershed_area_annual[watershed_idx,:] = glac_area_annual
else:
watershed_area_annual[watershed_idx,:] += glac_area_annual
# DegId
if degid_area_annual is None:
degid_area_annual = np.zeros((len(unique_degids), years.shape[0]))
degid_area_annual[degid_idx,:] = glac_area_annual
else:
degid_area_annual[degid_idx,:] += glac_area_annual
# ----- 5. Area below-debris vs. Time -----
if bin_debris_hd.sum() > 0:
bin_area_annual_bd = np.zeros(bin_area_annual.shape)
bin_area_annual_bd[bin_debris_hd > 0, :] = bin_area_annual[bin_debris_hd > 0, :]
glac_area_annual_bd = bin_area_annual_bd.sum(0)
# All
if reg_area_annual_bd is None:
reg_area_annual_bd = glac_area_annual_bd
else:
reg_area_annual_bd += glac_area_annual_bd
# O2Region
if regO2_area_annual_bd is None:
regO2_area_annual_bd = np.zeros((len(unique_regO2s),years.shape[0]))
regO2_area_annual_bd[regO2_idx,:] = glac_area_annual_bd
else:
regO2_area_annual_bd[regO2_idx,:] += glac_area_annual_bd
# Watershed
if watershed_area_annual_bd is None:
watershed_area_annual_bd = np.zeros((len(unique_watersheds),years.shape[0]))
watershed_area_annual_bd[watershed_idx,:] = glac_area_annual_bd
else:
watershed_area_annual_bd[watershed_idx,:] += glac_area_annual_bd
# DegId
if degid_area_annual_bd is None:
degid_area_annual_bd = np.zeros((len(unique_degids), years.shape[0]))
degid_area_annual_bd[degid_idx,:] = glac_area_annual_bd
else:
degid_area_annual_bd[degid_idx,:] += glac_area_annual_bd
# ----- 6. Binned glacier volume vs. Time -----
bin_vol_annual_10m = np.zeros((len(elev_bins)-1, len(years)))
for ncol, year in enumerate(years):
bin_counts, bin_edges = np.histogram(bin_z_surf_annual[:,ncol], bins=elev_bins,
weights=bin_vol_annual[:,ncol])
bin_vol_annual_10m[:,ncol] = bin_counts
# All
if reg_vol_annual_binned is None:
reg_vol_annual_binned = bin_vol_annual_10m
else:
reg_vol_annual_binned += bin_vol_annual_10m
# O2Region
if regO2_vol_annual_binned is None:
regO2_vol_annual_binned = np.zeros((len(unique_regO2s), bin_vol_annual_10m.shape[0], years.shape[0]))
regO2_vol_annual_binned[regO2_idx,:,:] = bin_vol_annual_10m
else:
regO2_vol_annual_binned[regO2_idx,:,:] += bin_vol_annual_10m
# Watershed
if watershed_vol_annual_binned is None:
watershed_vol_annual_binned = np.zeros((len(unique_watersheds), bin_vol_annual_10m.shape[0], years.shape[0]))
watershed_vol_annual_binned[watershed_idx,:,:] = bin_vol_annual_10m
else:
watershed_vol_annual_binned[watershed_idx,:,:] += bin_vol_annual_10m
# ----- 7. Binned glacier volume below debris vs. Time -----
if bin_debris_hd.sum() > 0:
# Bin debris mask for the given elevation bins
bin_debris_mask_10m = np.zeros((bin_vol_annual_10m.shape[0]))
bin_counts, bin_edges = np.histogram(bin_z_init, bins=elev_bins, weights=bin_debris_hd)
bin_debris_mask_10m[bin_counts > 0] = 1
bin_vol_annual_10m_bd = bin_vol_annual_10m * bin_debris_mask_10m[:,np.newaxis]
# All
if reg_vol_annual_binned_bd is None:
reg_vol_annual_binned_bd = bin_vol_annual_10m_bd
else:
reg_vol_annual_binned_bd += bin_vol_annual_10m_bd
# O2Region
if regO2_vol_annual_binned_bd is None:
regO2_vol_annual_binned_bd = np.zeros((len(unique_regO2s), bin_vol_annual_10m.shape[0], years.shape[0]))
regO2_vol_annual_binned_bd[regO2_idx,:,:] = bin_vol_annual_10m_bd
else:
regO2_vol_annual_binned_bd[regO2_idx,:,:] += bin_vol_annual_10m_bd
# Watershed
if watershed_vol_annual_binned_bd is None: