forked from drounce/PyGEM-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_simulation.py
More file actions
executable file
·2173 lines (1974 loc) · 130 KB
/
run_simulation.py
File metadata and controls
executable file
·2173 lines (1974 loc) · 130 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
"""Run a model simulation."""
# Default climate data is ERA-Interim; specify CMIP5 by specifying a filename to the argument:
# (Command line) python run_simulation_list_multiprocess.py -gcm_list_fn=C:\...\gcm_rcpXX_filenames.txt
# - Default is running ERA-Interim in parallel with five processors.
# (Spyder) %run run_simulation_list_multiprocess.py C:\...\gcm_rcpXX_filenames.txt -option_parallels=0
# - Spyder cannot run parallels, so always set -option_parallels=0 when testing in Spyder.
# Spyder cannot run parallels, so always set -option_parallels=0 when testing in Spyder.
# Built-in libraries
import argparse
import collections
import copy
import inspect
import multiprocessing
import os
import sys
import time
import cftime
# External libraries
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import median_abs_deviation
import xarray as xr
try:
import pygem
except:
sys.path.append(os.getcwd() + '/../PyGEM/')
# Local libraries
import pygem
import pygem.gcmbiasadj as gcmbiasadj
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
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 cfg
from oggm import graphics
from oggm import tasks
from oggm import utils
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
from oggm.core.flowline import FluxBasedModel, SemiImplicitModel
from oggm.core.inversion import find_inversion_calving_from_any_mb
cfg.PARAMS['hydro_month_nh']=1
cfg.PARAMS['hydro_month_sh']=1
cfg.PARAMS['trapezoid_lambdas'] = 1
# ----- FUNCTIONS -----
def getparser():
"""
Use argparse to add arguments from the command line
Parameters
----------
gcm_list_fn (optional) : str
text file that contains the climate data to be used in the model simulation
gcm_name (optional) : str
gcm name
scenario (optional) : str
representative concentration pathway or shared socioeconomic pathway (ex. 'rcp26', 'ssp585')
realization (optional) : str
single realization from large ensemble (ex. '1011.001', '1301.020')
see CESM2 Large Ensemble Community Project by NCAR for more information
realization_list (optional) : str
text file that contains the realizations to be used in the model simulation
num_simultaneous_processes (optional) : int
number of cores to use in parallels
option_parallels (optional) : int
switch to use parallels or not
rgi_glac_number_fn (optional) : str
filename of .pkl file containing a list of glacier numbers that used to run batches on the supercomputer
batch_number (optional): int
batch number used to differentiate output on supercomputer
option_ordered : int
option to keep glaciers ordered or to grab every n value for the batch
(the latter helps make sure run times on each core are similar as it removes any timing differences caused by
regional variations)
debug (optional) : int
Switch for turning debug printing on or off (default = 0 (off))
debug_spc (optional) : int
Switch for turning debug printing of spc on or off (default = 0 (off))
Returns
-------
Object containing arguments and their respective values.
"""
parser = argparse.ArgumentParser(description="run simulations from gcm list in parallel")
# add arguments
parser.add_argument('-gcm_list_fn', action='store', type=str, default=pygem_prms.ref_gcm_name,
help='text file full of commands to run')
parser.add_argument('-gcm_name', action='store', type=str, default=None,
help='GCM name used for model run')
parser.add_argument('-scenario', action='store', type=str, default=None,
help='rcp or ssp scenario used for model run (ex. rcp26 or ssp585)')
parser.add_argument('-realization', action='store', type=str, default=None,
help='realization from large ensemble used for model run (ex. 1011.001 or 1301.020)')
parser.add_argument('-realization_list', action='store', type=str, default=None,
help='text file full of realizations to run')
parser.add_argument('-gcm_bc_startyear', action='store', type=int, default=pygem_prms.gcm_bc_startyear,
help='start year for bias correction')
parser.add_argument('-gcm_startyear', action='store', type=int, default=pygem_prms.gcm_startyear,
help='start year for the model run')
parser.add_argument('-gcm_endyear', action='store', type=int, default=pygem_prms.gcm_endyear,
help='start year for the model run')
parser.add_argument('-num_simultaneous_processes', action='store', type=int, default=4,
help='number of simultaneous processes (cores) to use')
parser.add_argument('-option_parallels', action='store', type=int, default=1,
help='Switch to use or not use parallels (1 - use parallels, 0 - do not)')
parser.add_argument('-rgi_glac_number_fn', action='store', type=str, default=None,
help='Filename containing list of rgi_glac_number, helpful for running batches on spc')
parser.add_argument('-batch_number', action='store', type=int, default=None,
help='Batch number used to differentiate output on supercomputer')
parser.add_argument('-option_ordered', action='store', type=int, default=1,
help='switch to keep lists ordered or not')
parser.add_argument('-debug', action='store', type=int, default=0,
help='Boolean for debugging to turn it on or off (default 0 is off')
parser.add_argument('-debug_spc', action='store', type=int, default=0,
help='Boolean for debugging to turn it on or off (default 0 is off')
return parser
def calc_stats_array(data, stats_cns=pygem_prms.sim_stat_cns):
"""
Calculate stats for a given variable
Parameters
----------
vn : str
variable name
ds : xarray dataset
dataset of output with all ensemble simulations
Returns
-------
stats : np.array
Statistics related to a given variable
"""
stats = None
if 'mean' in stats_cns:
if stats is None:
stats = np.nanmean(data,axis=1)[:,np.newaxis]
if 'std' in stats_cns:
stats = np.append(stats, np.nanstd(data,axis=1)[:,np.newaxis], axis=1)
if '2.5%' in stats_cns:
stats = np.append(stats, np.nanpercentile(data, 2.5, axis=1)[:,np.newaxis], axis=1)
if '25%' in stats_cns:
stats = np.append(stats, np.nanpercentile(data, 25, axis=1)[:,np.newaxis], axis=1)
if 'median' in stats_cns:
if stats is None:
stats = np.nanmedian(data, axis=1)[:,np.newaxis]
else:
stats = np.append(stats, np.nanmedian(data, axis=1)[:,np.newaxis], axis=1)
if '75%' in stats_cns:
stats = np.append(stats, np.nanpercentile(data, 75, axis=1)[:,np.newaxis], axis=1)
if '97.5%' in stats_cns:
stats = np.append(stats, np.nanpercentile(data, 97.5, axis=1)[:,np.newaxis], axis=1)
if 'mad' in stats_cns:
stats = np.append(stats, median_abs_deviation(data, axis=1, nan_policy='omit')[:,np.newaxis], axis=1)
return stats
def create_xrdataset(glacier_rgi_table, dates_table, option_wateryear=pygem_prms.gcm_wateryear,
export_extra_vars=pygem_prms.export_extra_vars):
"""
Create empty xarray dataset that will be used to record simulation runs.
Parameters
----------
main_glac_rgi : pandas dataframe
dataframe containing relevant rgi glacier information
dates_table : pandas dataframe
table of the dates, months, days in month, etc.
Returns
-------
output_ds_all : xarray Dataset
empty xarray dataset that contains variables and attributes to be filled in by simulation runs
encoding : dictionary
encoding used with exporting xarray dataset to netcdf
"""
# Create empty datasets for each variable and merge them
# Coordinate values
glac_values = np.array([glacier_rgi_table.name])
# Time attributes and values
if option_wateryear == 'hydro':
year_type = 'water year'
annual_columns = np.unique(dates_table['wateryear'].values)[0:int(dates_table.shape[0]/12)]
elif option_wateryear == 'calendar':
year_type = 'calendar year'
annual_columns = np.unique(dates_table['year'].values)[0:int(dates_table.shape[0]/12)]
elif option_wateryear == 'custom':
year_type = 'custom year'
time_values = dates_table.loc[pygem_prms.gcm_spinupyears*12:dates_table.shape[0]+1,'date'].tolist()
time_values = [cftime.DatetimeNoLeap(x.year, x.month, x.day) for x in time_values]
# append additional year to year_values to account for mass and area at end of period
year_values = annual_columns[pygem_prms.gcm_spinupyears:annual_columns.shape[0]]
year_values = np.concatenate((year_values, np.array([annual_columns[-1] + 1])))
# Variable coordinates dictionary
output_coords_dict = collections.OrderedDict()
output_coords_dict['RGIId'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['CenLon'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['CenLat'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['O1Region'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['O2Region'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['Area'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['glac_runoff_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_area_annual'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['glac_mass_annual'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['glac_mass_bsl_annual'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['glac_ELA_annual'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['offglac_runoff_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
if pygem_prms.sim_iters > 1:
output_coords_dict['glac_runoff_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_area_annual_mad'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['glac_mass_annual_mad'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['glac_mass_bsl_annual_mad'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['glac_ELA_annual_mad'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['offglac_runoff_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
if export_extra_vars:
output_coords_dict['glac_prec_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_temp_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_acc_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_refreeze_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_melt_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_frontalablation_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_massbaltotal_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_snowline_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_mass_change_ignored_annual'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['offglac_prec_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['offglac_refreeze_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['offglac_melt_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['offglac_snowpack_monthly'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
if pygem_prms.sim_iters > 1:
output_coords_dict['glac_prec_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_temp_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_acc_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_refreeze_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_melt_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_frontalablation_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_massbaltotal_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_snowline_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['glac_mass_change_ignored_annual_mad'] = collections.OrderedDict([('glac', glac_values),
('year', year_values)])
output_coords_dict['offglac_prec_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['offglac_refreeze_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['offglac_melt_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
output_coords_dict['offglac_snowpack_monthly_mad'] = collections.OrderedDict([('glac', glac_values),
('time', time_values)])
# Attributes dictionary
output_attrs_dict = {
'time': {
'long_name': 'time',
'year_type':year_type,
'comment':'start of the month'},
'glac': {
'long_name': 'glacier index',
'comment': 'glacier index referring to glaciers properties and model results'},
'year': {
'long_name': 'years',
'year_type': year_type,
'comment': 'years referring to the start of each year'},
'RGIId': {
'long_name': 'Randolph Glacier Inventory ID',
'comment': 'RGIv6.0'},
'CenLon': {
'long_name': 'center longitude',
'units': 'degrees E',
'comment': 'value from RGIv6.0'},
'CenLat': {
'long_name': 'center latitude',
'units': 'degrees N',
'comment': 'value from RGIv6.0'},
'O1Region': {
'long_name': 'RGI order 1 region',
'comment': 'value from RGIv6.0'},
'O2Region': {
'long_name': 'RGI order 2 region',
'comment': 'value from RGIv6.0'},
'Area': {
'long_name': 'glacier area',
'units': 'm2',
'comment': 'value from RGIv6.0'},
'glac_runoff_monthly': {
'long_name': 'glacier-wide runoff',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'runoff from the glacier terminus, which moves over time'},
'glac_area_annual': {
'long_name': 'glacier area',
'units': 'm2',
'temporal_resolution': 'annual',
'comment': 'area at start of the year'},
'glac_mass_annual': {
'long_name': 'glacier mass',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'mass of ice based on area and ice thickness at start of the year'},
'glac_mass_bsl_annual': {
'long_name': 'glacier mass below sea level',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'mass of ice below sea level based on area and ice thickness at start of the year'},
'glac_ELA_annual': {
'long_name': 'annual equilibrium line altitude above mean sea level',
'units': 'm',
'temporal_resolution': 'annual',
'comment': 'equilibrium line altitude is the elevation where the climatic mass balance is zero'},
'offglac_runoff_monthly': {
'long_name': 'off-glacier-wide runoff',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'off-glacier runoff from area where glacier no longer exists'},
}
if pygem_prms.sim_iters > 1:
output_attrs_dict_mad = {
'glac_runoff_monthly_mad': {
'long_name': 'glacier-wide runoff median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'runoff from the glacier terminus, which moves over time'},
'glac_area_annual_mad': {
'long_name': 'glacier area median absolute deviation',
'units': 'm2',
'temporal_resolution': 'annual',
'comment': 'area at start of the year'},
'glac_mass_annual_mad': {
'long_name': 'glacier mass median absolute deviation',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'mass of ice based on area and ice thickness at start of the year'},
'glac_mass_bsl_annual_mad': {
'long_name': 'glacier mass below sea level median absolute deviation',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'mass of ice below sea level based on area and ice thickness at start of the year'},
'glac_ELA_annual_mad': {
'long_name': 'annual equilibrium line altitude above mean sea level median absolute deviation',
'units': 'm',
'temporal_resolution': 'annual',
'comment': 'equilibrium line altitude is the elevation where the climatic mass balance is zero'},
'offglac_runoff_monthly_mad': {
'long_name': 'off-glacier-wide runoff median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'off-glacier runoff from area where glacier no longer exists'},
}
output_attrs_dict.update(output_attrs_dict_mad)
if export_extra_vars:
output_attrs_dict_extras = {
'glac_temp_monthly': {
'standard_name': 'air_temperature',
'long_name': 'glacier-wide mean air temperature',
'units': 'K',
'temporal_resolution': 'monthly',
'comment': ('each elevation bin is weighted equally to compute the mean temperature, and '
'bins where the glacier no longer exists due to retreat have been removed')},
'glac_prec_monthly': {
'long_name': 'glacier-wide precipitation (liquid)',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'only the liquid precipitation, solid precipitation excluded'},
'glac_acc_monthly': {
'long_name': 'glacier-wide accumulation, in water equivalent',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'only the solid precipitation'},
'glac_refreeze_monthly': {
'long_name': 'glacier-wide refreeze, in water equivalent',
'units': 'm3',
'temporal_resolution': 'monthly'},
'glac_melt_monthly': {
'long_name': 'glacier-wide melt, in water equivalent',
'units': 'm3',
'temporal_resolution': 'monthly'},
'glac_frontalablation_monthly': {
'long_name': 'glacier-wide frontal ablation, in water equivalent',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': (
'mass losses from calving, subaerial frontal melting, sublimation above the '
'waterline and subaqueous frontal melting below the waterline; positive values indicate mass lost like melt')},
'glac_massbaltotal_monthly': {
'long_name': 'glacier-wide total mass balance, in water equivalent',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'total mass balance is the sum of the climatic mass balance and frontal ablation'},
'glac_snowline_monthly': {
'long_name': 'transient snowline altitude above mean sea level',
'units': 'm',
'temporal_resolution': 'monthly',
'comment': 'transient snowline is altitude separating snow from ice/firn'},
'glac_mass_change_ignored_annual': {
'long_name': 'glacier mass change ignored',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'glacier mass change ignored due to flux divergence'},
'offglac_prec_monthly': {
'long_name': 'off-glacier-wide precipitation (liquid)',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'only the liquid precipitation, solid precipitation excluded'},
'offglac_refreeze_monthly': {
'long_name': 'off-glacier-wide refreeze, in water equivalent',
'units': 'm3',
'temporal_resolution': 'monthly'},
'offglac_melt_monthly': {
'long_name': 'off-glacier-wide melt, in water equivalent',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'only melt of snow and refreeze since off-glacier'},
'offglac_snowpack_monthly': {
'long_name': 'off-glacier-wide snowpack, in water equivalent',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'snow remaining accounting for new accumulation, melt, and refreeze'}
}
output_attrs_dict.update(output_attrs_dict_extras)
if pygem_prms.sim_iters > 1:
output_attrs_dict_extras_mad = {
'glac_temp_monthly_mad': {
'standard_name': 'air_temperature',
'long_name': 'glacier-wide mean air temperature median absolute deviation',
'units': 'K',
'temporal_resolution': 'monthly',
'comment': (
'each elevation bin is weighted equally to compute the mean temperature, and '
'bins where the glacier no longer exists due to retreat have been removed')},
'glac_prec_monthly_mad': {
'long_name': 'glacier-wide precipitation (liquid) median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'only the liquid precipitation, solid precipitation excluded'},
'glac_acc_monthly_mad': {
'long_name': 'glacier-wide accumulation, in water equivalent, median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'only the solid precipitation'},
'glac_refreeze_monthly_mad': {
'long_name': 'glacier-wide refreeze, in water equivalent, median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly'},
'glac_melt_monthly_mad': {
'long_name': 'glacier-wide melt, in water equivalent, median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly'},
'glac_frontalablation_monthly_mad': {
'long_name': 'glacier-wide frontal ablation, in water equivalent, median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': (
'mass losses from calving, subaerial frontal melting, sublimation above the '
'waterline and subaqueous frontal melting below the waterline')},
'glac_massbaltotal_monthly_mad': {
'long_name': 'glacier-wide total mass balance, in water equivalent, median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'total mass balance is the sum of the climatic mass balance and frontal ablation'},
'glac_snowline_monthly_mad': {
'long_name': 'transient snowline above mean sea level median absolute deviation',
'units': 'm',
'temporal_resolution': 'monthly',
'comment': 'transient snowline is altitude separating snow from ice/firn'},
'glac_mass_change_ignored_annual_mad': {
'long_name': 'glacier mass change ignored median absolute deviation',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'glacier mass change ignored due to flux divergence'},
'offglac_prec_monthly_mad': {
'long_name': 'off-glacier-wide precipitation (liquid) median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'only the liquid precipitation, solid precipitation excluded'},
'offglac_refreeze_monthly_mad': {
'long_name': 'off-glacier-wide refreeze, in water equivalent, median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly'},
'offglac_melt_monthly_mad': {
'long_name': 'off-glacier-wide melt, in water equivalent, median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'only melt of snow and refreeze since off-glacier'},
'offglac_snowpack_monthly_mad': {
'long_name': 'off-glacier-wide snowpack, in water equivalent, median absolute deviation',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'snow remaining accounting for new accumulation, melt, and refreeze'},
}
output_attrs_dict.update(output_attrs_dict_extras_mad)
# Add variables to empty dataset and merge together
count_vn = 0
encoding = {}
for vn in output_coords_dict.keys():
count_vn += 1
empty_holder = np.zeros([len(output_coords_dict[vn][i]) for i in list(output_coords_dict[vn].keys())])
output_ds = xr.Dataset({vn: (list(output_coords_dict[vn].keys()), empty_holder)},
coords=output_coords_dict[vn])
# Merge datasets of stats into one output
if count_vn == 1:
output_ds_all = output_ds
else:
output_ds_all = xr.merge((output_ds_all, output_ds))
noencoding_vn = ['RGIId']
# Add attributes
for vn in output_ds_all.variables:
try:
output_ds_all[vn].attrs = output_attrs_dict[vn]
except:
pass
# Encoding (specify _FillValue, offsets, etc.)
if vn not in noencoding_vn:
encoding[vn] = {'_FillValue': None,
'zlib':True,
'complevel':9
}
output_ds_all['RGIId'].values = np.array([glacier_rgi_table.loc['RGIId']])
output_ds_all['CenLon'].values = np.array([glacier_rgi_table.CenLon])
output_ds_all['CenLat'].values = np.array([glacier_rgi_table.CenLat])
output_ds_all['O1Region'].values = np.array([glacier_rgi_table.O1Region])
output_ds_all['O2Region'].values = np.array([glacier_rgi_table.O2Region])
output_ds_all['Area'].values = np.array([glacier_rgi_table.Area * 1e6])
output_ds_all.attrs = {'source': f'PyGEMv{pygem.__version__}',
'institution': 'University of Alaska Fairbanks, Fairbanks, AK',
'history': 'Created by David Rounce (drounce@alaska.edu) on ' + pygem_prms.model_run_date,
'references': 'doi:10.3389/feart.2019.00331 and doi:10.1017/jog.2019.91'}
return output_ds_all, encoding
def create_xrdataset_essential_sims(glacier_rgi_table, dates_table, option_wateryear=pygem_prms.gcm_wateryear,
sim_iters=pygem_prms.sim_iters):
"""
Create empty xarray dataset that will be used to record simulation runs.
Parameters
----------
main_glac_rgi : pandas dataframe
dataframe containing relevant rgi glacier information
dates_table : pandas dataframe
table of the dates, months, days in month, etc.
Returns
-------
output_ds_all : xarray Dataset
empty xarray dataset that contains variables and attributes to be filled in by simulation runs
encoding : dictionary
encoding used with exporting xarray dataset to netcdf
"""
# Create empty datasets for each variable and merge them
# Coordinate values
glac_values = np.array([glacier_rgi_table.name])
# Time attributes and values
if option_wateryear == 'hydro':
year_type = 'water year'
annual_columns = np.unique(dates_table['wateryear'].values)[0:int(dates_table.shape[0]/12)]
elif option_wateryear == 'calendar':
year_type = 'calendar year'
annual_columns = np.unique(dates_table['year'].values)[0:int(dates_table.shape[0]/12)]
elif option_wateryear == 'custom':
year_type = 'custom year'
time_values = dates_table.loc[pygem_prms.gcm_spinupyears*12:dates_table.shape[0]+1,'date'].tolist()
time_values = [cftime.DatetimeNoLeap(x.year, x.month, x.day) for x in time_values]
# append additional year to year_values to account for mass and area at end of period
year_values = annual_columns[pygem_prms.gcm_spinupyears:annual_columns.shape[0]]
year_values = np.concatenate((year_values, np.array([annual_columns[-1] + 1])))
sims = np.arange(sim_iters)
# Variable coordinates dictionary
output_coords_dict = collections.OrderedDict()
output_coords_dict['RGIId'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['CenLon'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['CenLat'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['O1Region'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['O2Region'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['Area'] = collections.OrderedDict([('glac', glac_values)])
# annual datasets
output_coords_dict['glac_area_annual'] = (
collections.OrderedDict([('glac', glac_values), ('year', year_values), ('sim', sims)]))
output_coords_dict['glac_mass_annual'] = (
collections.OrderedDict([('glac', glac_values), ('year', year_values), ('sim', sims)]))
# monthly datasets
output_coords_dict['fixed_runoff_monthly'] = (
collections.OrderedDict([('glac', glac_values), ('time', time_values), ('sim', sims)]))
# Attributes dictionary
output_attrs_dict = {
'time': {
'long_name': 'time',
'year_type':year_type,
'comment':'start of the month'},
'glac': {
'long_name': 'glacier index',
'comment': 'glacier index referring to glaciers properties and model results'},
'year': {
'long_name': 'years',
'year_type': year_type,
'comment': 'years referring to the start of each year'},
'sim': {
'long_name': 'simulation number',
'comment': 'simulation number referring to the MCMC simulation; otherwise, only 1'},
'RGIId': {
'long_name': 'Randolph Glacier Inventory ID',
'comment': 'RGIv6.0'},
'CenLon': {
'long_name': 'center longitude',
'units': 'degrees E',
'comment': 'value from RGIv6.0'},
'CenLat': {
'long_name': 'center latitude',
'units': 'degrees N',
'comment': 'value from RGIv6.0'},
'O1Region': {
'long_name': 'RGI order 1 region',
'comment': 'value from RGIv6.0'},
'O2Region': {
'long_name': 'RGI order 2 region',
'comment': 'value from RGIv6.0'},
'Area': {
'long_name': 'glacier area',
'units': 'm2',
'comment': 'value from RGIv6.0'},
'fixed_runoff_monthly': {
'long_name': 'fixed-gauge glacier runoff',
'units': 'm3',
'temporal_resolution': 'monthly',
'comment': 'runoff assuming a fixed gauge station based on initial glacier area'},
'glac_area_annual': {
'long_name': 'glacier area',
'units': 'm2',
'temporal_resolution': 'annual',
'comment': 'area at start of the year'},
'glac_mass_annual': {
'long_name': 'glacier mass',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'mass of ice based on area and ice thickness at start of the year'},
}
# Add variables to empty dataset and merge together
count_vn = 0
encoding = {}
for vn in output_coords_dict.keys():
count_vn += 1
empty_holder = np.zeros([len(output_coords_dict[vn][i]) for i in list(output_coords_dict[vn].keys())])
output_ds = xr.Dataset({vn: (list(output_coords_dict[vn].keys()), empty_holder)},
coords=output_coords_dict[vn])
# Merge datasets of stats into one output
if count_vn == 1:
output_ds_all = output_ds
else:
output_ds_all = xr.merge((output_ds_all, output_ds))
noencoding_vn = ['RGIId']
# Add attributes
for vn in output_ds_all.variables:
try:
output_ds_all[vn].attrs = output_attrs_dict[vn]
except:
pass
# Encoding (specify _FillValue, offsets, etc.)
if vn not in noencoding_vn:
encoding[vn] = {'_FillValue': None,
'zlib':True,
'complevel':9
}
output_ds_all['RGIId'].values = np.array([glacier_rgi_table.loc['RGIId']])
output_ds_all['CenLon'].values = np.array([glacier_rgi_table.CenLon])
output_ds_all['CenLat'].values = np.array([glacier_rgi_table.CenLat])
output_ds_all['O1Region'].values = np.array([glacier_rgi_table.O1Region])
output_ds_all['O2Region'].values = np.array([glacier_rgi_table.O2Region])
output_ds_all['Area'].values = np.array([glacier_rgi_table.Area * 1e6])
output_ds_all.attrs = {'source': f'PyGEMv{pygem.__version__}',
'institution': 'University of Alaska Fairbanks, Fairbanks, AK',
'history': 'Created by David Rounce (drounce@alaska.edu) on ' + pygem_prms.model_run_date,
'references': 'doi:10.3389/feart.2019.00331 and doi:10.1017/jog.2019.91'}
return output_ds_all, encoding
def create_xrdataset_binned_stats(glacier_rgi_table, dates_table, surface_h_initial,
output_glac_bin_mass_annual, output_glac_bin_icethickness_annual,
output_glac_bin_massbalclim_monthly, output_glac_bin_massbalclim_annual,
output_glac_bin_dist, option_wateryear=pygem_prms.gcm_wateryear):
"""
Create empty xarray dataset that will be used to record binned ice thickness changes
Parameters
----------
main_glac_rgi : pandas dataframe
dataframe containing relevant rgi glacier information
dates_table : pandas dataframe
table of the dates, months, days in month, etc.
Returns
-------
output_ds_all : xarray Dataset
empty xarray dataset that contains variables and attributes to be filled in by simulation runs
encoding : dictionary
encoding used with exporting xarray dataset to netcdf
"""
# Create empty datasets for each variable and merge them
# Coordinate values
glac_values = np.array([glacier_rgi_table.name])
# Time attributes and values
if option_wateryear == 'hydro':
year_type = 'water year'
annual_columns = np.unique(dates_table['wateryear'].values)[0:int(dates_table.shape[0]/12)]
elif option_wateryear == 'calendar':
year_type = 'calendar year'
annual_columns = np.unique(dates_table['year'].values)[0:int(dates_table.shape[0]/12)]
elif option_wateryear == 'custom':
year_type = 'custom year'
time_values = dates_table.loc[pygem_prms.gcm_spinupyears*12:dates_table.shape[0]+1,'date'].tolist()
time_values = [cftime.DatetimeNoLeap(x.year, x.month, x.day) for x in time_values]
# append additional year to year_values to account for mass and area at end of period
year_values = annual_columns[pygem_prms.gcm_spinupyears:annual_columns.shape[0]]
year_values = np.concatenate((year_values, np.array([annual_columns[-1] + 1])))
bin_values = np.arange(surface_h_initial.shape[0])
# Variable coordinates dictionary
output_coords_dict = collections.OrderedDict()
output_coords_dict['RGIId'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['CenLon'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['CenLat'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['O1Region'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['O2Region'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['Area'] = collections.OrderedDict([('glac', glac_values)])
output_coords_dict['bin_distance'] = collections.OrderedDict([('glac', glac_values), ('bin',bin_values)])
output_coords_dict['bin_surface_h_initial'] = collections.OrderedDict([('glac', glac_values), ('bin',bin_values)])
output_coords_dict['bin_mass_annual'] = (
collections.OrderedDict([('glac', glac_values), ('bin',bin_values), ('year', year_values)]))
output_coords_dict['bin_thick_annual'] = (
collections.OrderedDict([('glac', glac_values), ('bin',bin_values), ('year', year_values)]))
output_coords_dict['bin_massbalclim_annual'] = (
collections.OrderedDict([('glac', glac_values), ('bin',bin_values), ('year', year_values)]))
output_coords_dict['bin_massbalclim_monthly'] = (
collections.OrderedDict([('glac', glac_values), ('bin',bin_values), ('time', time_values)]))
if pygem_prms.sim_iters > 1:
output_coords_dict['bin_mass_annual_mad'] = (
collections.OrderedDict([('glac', glac_values), ('bin',bin_values), ('year', year_values)]))
output_coords_dict['bin_thick_annual_mad'] = (
collections.OrderedDict([('glac', glac_values), ('bin',bin_values), ('year', year_values)]))
output_coords_dict['bin_massbalclim_annual_mad'] = (
collections.OrderedDict([('glac', glac_values), ('bin',bin_values), ('year', year_values)]))
# Attributes dictionary
output_attrs_dict = {
'glac': {
'long_name': 'glacier index',
'comment': 'glacier index referring to glaciers properties and model results'},
'bin': {
'long_name': 'bin index',
'comment': 'bin index referring to the glacier elevation bin'},
'year': {
'long_name': 'years',
'year_type': year_type,
'comment': 'years referring to the start of each year'},
'RGIId': {
'long_name': 'Randolph Glacier Inventory ID',
'comment': 'RGIv6.0'},
'CenLon': {
'long_name': 'center longitude',
'units': 'degrees E',
'comment': 'value from RGIv6.0'},
'CenLat': {
'long_name': 'center latitude',
'units': 'degrees N',
'comment': 'value from RGIv6.0'},
'O1Region': {
'long_name': 'RGI order 1 region',
'comment': 'value from RGIv6.0'},
'O2Region': {
'long_name': 'RGI order 2 region',
'comment': 'value from RGIv6.0'},
'Area': {
'long_name': 'glacier area',
'units': 'm2',
'comment': 'value from RGIv6.0'},
'bin_distance': {
'long_name': 'distance downglacier',
'units': 'm',
'comment': 'horizontal distance calculated from top of glacier moving downglacier'},
'bin_surface_h_initial': {
'long_name': 'initial binned surface elevation',
'units': 'm above sea level'},
'bin_mass_annual': {
'long_name': 'binned ice mass',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'binned ice mass at start of the year'},
'bin_thick_annual': {
'long_name': 'binned ice thickness',
'units': 'm',
'temporal_resolution': 'annual',
'comment': 'binned ice thickness at start of the year'},
'bin_massbalclim_annual': {
'long_name': 'binned climatic mass balance, in water equivalent',
'units': 'm',
'temporal_resolution': 'annual',
'comment': 'climatic mass balance is computed before dynamics so can theoretically exceed ice thickness'},
'bin_massbalclim_monthly' : {
'long_name': 'binned monthly climatic mass balance, in water equivalent',
'units': 'm',
'temporal_resolution': 'monthly',
'comment': 'monthly climatic mass balance from the PyGEM mass balance module'},
}
if pygem_prms.sim_iters > 1:
output_attrs_dict['bin_mass_annual_mad'] = {
'long_name': 'binned ice mass median absolute deviation',
'units': 'kg',
'temporal_resolution': 'annual',
'comment': 'mass of ice based on area and ice thickness at start of the year'}
output_attrs_dict['bin_thick_annual_mad'] = {
'long_name': 'binned ice thickness median absolute deviation',
'units': 'm',
'temporal_resolution': 'annual',
'comment': 'thickness of ice at start of the year'}
output_attrs_dict['bin_massbalclim_annual_mad'] = {
'long_name': 'binned climatic mass balance, in water equivalent, median absolute deviation',
'units': 'm',
'temporal_resolution': 'annual',
'comment': 'climatic mass balance is computed before dynamics so can theoretically exceed ice thickness'}
# Add variables to empty dataset and merge together
count_vn = 0
encoding = {}
for vn in output_coords_dict.keys():
count_vn += 1
empty_holder = np.zeros([len(output_coords_dict[vn][i]) for i in list(output_coords_dict[vn].keys())])
output_ds = xr.Dataset({vn: (list(output_coords_dict[vn].keys()), empty_holder)},
coords=output_coords_dict[vn])
# Merge datasets of stats into one output
if count_vn == 1:
output_ds_all = output_ds
else:
output_ds_all = xr.merge((output_ds_all, output_ds))
noencoding_vn = ['RGIId']
# Add attributes
for vn in output_ds_all.variables:
try:
output_ds_all[vn].attrs = output_attrs_dict[vn]
except:
pass
# Encoding (specify _FillValue, offsets, etc.)
if vn not in noencoding_vn:
encoding[vn] = {'_FillValue': None,
'zlib':True,
'complevel':9
}
output_ds_all['RGIId'].values = np.array([glacier_rgi_table.loc['RGIId']])
output_ds_all['CenLon'].values = np.array([glacier_rgi_table.CenLon])
output_ds_all['CenLat'].values = np.array([glacier_rgi_table.CenLat])
output_ds_all['O1Region'].values = np.array([glacier_rgi_table.O1Region])
output_ds_all['O2Region'].values = np.array([glacier_rgi_table.O2Region])
output_ds_all['Area'].values = np.array([glacier_rgi_table.Area * 1e6])
output_ds_all['bin_distance'].values = output_glac_bin_dist[np.newaxis,:]
output_ds_all['bin_surface_h_initial'].values = surface_h_initial[np.newaxis,:]
output_ds_all['bin_mass_annual'].values = (
np.median(output_glac_bin_mass_annual, axis=2)[np.newaxis,:,:])
output_ds_all['bin_thick_annual'].values = (
np.median(output_glac_bin_icethickness_annual, axis=2)[np.newaxis,:,:])
output_ds_all['bin_massbalclim_annual'].values = (
np.median(output_glac_bin_massbalclim_annual, axis=2)[np.newaxis,:,:])
output_ds_all['bin_massbalclim_monthly'].values = (
np.median(output_glac_bin_massbalclim_monthly, axis=2)[np.newaxis,:,:])
if pygem_prms.sim_iters > 1:
output_ds_all['bin_mass_annual_mad'].values = (
median_abs_deviation(output_glac_bin_mass_annual, axis=2)[np.newaxis,:,:])
output_ds_all['bin_thick_annual_mad'].values = (
median_abs_deviation(output_glac_bin_icethickness_annual, axis=2)[np.newaxis,:,:])
output_ds_all['bin_massbalclim_annual_mad'].values = (
median_abs_deviation(output_glac_bin_massbalclim_annual, axis=2)[np.newaxis,:,:])
output_ds_all.attrs = {'source': f'PyGEMv{pygem.__version__}',
'institution': 'University of Alaska Fairbanks, Fairbanks, AK',
'history': 'Created by David Rounce (drounce@alaska.edu) on ' + pygem_prms.model_run_date,
'references': 'doi:10.3389/feart.2019.00331 and doi:10.1017/jog.2019.91'}
return output_ds_all, encoding
def main(list_packed_vars):
"""
Model simulation
Parameters
----------
list_packed_vars : list
list of packed variables that enable the use of parallels
Returns
-------
netcdf files of the simulation output (specific output is dependent on the output option)
"""
# Unpack variables
parser = getparser()
args = parser.parse_args()
count = list_packed_vars[0]
glac_no = list_packed_vars[1]
gcm_name = list_packed_vars[2]
realization = list_packed_vars[3]
if (gcm_name != pygem_prms.ref_gcm_name) and (args.scenario is None):
scenario = os.path.basename(args.gcm_list_fn).split('_')[1]
elif not args.scenario is None:
scenario = args.scenario
debug = args.debug
if debug:
if 'scenario' in locals():
print(scenario)
if args.debug_spc == 1:
debug_spc = True
else:
debug_spc = False
# ===== LOAD GLACIERS =====
main_glac_rgi = modelsetup.selectglaciersrgitable(glac_no=glac_no)
# ===== TIME PERIOD =====
# Reference Calibration Period
# adjust end year in event that reference and GCM don't align
if pygem_prms.ref_endyear <= args.gcm_endyear:
ref_endyear = pygem_prms.ref_endyear
else:
ref_endyear = args.gcm_endyear
dates_table_ref = modelsetup.datesmodelrun(startyear=pygem_prms.ref_startyear, endyear=ref_endyear,
spinupyears=pygem_prms.ref_spinupyears,
option_wateryear=pygem_prms.ref_wateryear)
# Reference Bias Adjustment Period
dates_table_ref_bc = modelsetup.datesmodelrun(startyear=args.gcm_bc_startyear, endyear=ref_endyear,
spinupyears=pygem_prms.ref_spinupyears,