forked from OGGM/oggm
/
test_models.py
5756 lines (4854 loc) · 246 KB
/
test_models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from functools import partial
import shutil
import warnings
import copy
import time
import numpy as np
import pandas as pd
import shapely.geometry as shpg
from numpy.testing import assert_allclose
import pytest
# Local imports
import oggm
from oggm.core import massbalance
from oggm.core.massbalance import LinearMassBalance
import xarray as xr
from oggm import utils, workflow, tasks, cfg
from oggm.core import climate, inversion, centerlines
from oggm.shop import gcm_climate, bedtopo
from oggm.cfg import SEC_IN_YEAR, SEC_IN_MONTH
from oggm.utils import get_demo_file
from oggm.exceptions import InvalidParamsError, InvalidWorkflowError
from oggm.tests.funcs import get_test_dir
from oggm.tests.funcs import (dummy_bumpy_bed, dummy_constant_bed,
dummy_constant_bed_cliff,
dummy_mixed_bed, bu_tidewater_bed,
dummy_noisy_bed, dummy_parabolic_bed,
dummy_trapezoidal_bed, dummy_width_bed,
dummy_width_bed_tributary)
import matplotlib.pyplot as plt
from oggm.core.flowline import (FluxBasedModel, FlowlineModel, MassRedistributionCurveModel,
init_present_time_glacier, glacier_from_netcdf,
RectangularBedFlowline, TrapezoidalBedFlowline,
ParabolicBedFlowline, MixedBedFlowline,
flowline_from_dataset, FileModel,
run_constant_climate, run_random_climate,
run_from_climate_data, equilibrium_stop_criterion,
run_with_hydro, SemiImplicitModel)
from oggm.core.dynamic_spinup import (
run_dynamic_spinup, run_dynamic_melt_f_calibration,
dynamic_melt_f_run_with_dynamic_spinup,
dynamic_melt_f_run_with_dynamic_spinup_fallback,
dynamic_melt_f_run,
dynamic_melt_f_run_fallback)
FluxBasedModel = partial(FluxBasedModel, inplace=True)
FlowlineModel = partial(FlowlineModel, inplace=True)
pytest.importorskip('geopandas')
pytest.importorskip('rasterio')
pytest.importorskip('salem')
pytestmark = pytest.mark.test_env("models")
do_plot = False
DOM_BORDER = 80
ALL_DIAGS = ['volume', 'volume_bsl', 'volume_bwl', 'area', 'length',
'calving', 'calving_rate', 'off_area', 'on_area', 'melt_off_glacier',
'melt_on_glacier', 'liq_prcp_off_glacier', 'liq_prcp_on_glacier',
'snowfall_off_glacier', 'snowfall_on_glacier', 'model_mb',
'residual_mb', 'snow_bucket']
has_shapely2 = False
try:
import shapely.io
has_shapely2 = True
except ImportError:
pass
class TestInitPresentDayFlowline:
@pytest.mark.parametrize('downstream_line_shape', ['parabola', 'trapezoidal'])
def test_init_present_time_glacier(self, hef_gdir, downstream_line_shape):
gdir = hef_gdir
cfg.PARAMS['downstream_line_shape'] = downstream_line_shape
init_present_time_glacier(gdir)
fls = gdir.read_pickle('model_flowlines')
inv = gdir.read_pickle('inversion_output')
assert gdir.rgi_date == 2003
assert len(fls) == 3
vol = 0.
area = 0.
for fl in fls:
refo = 1 if fl is fls[-1] else 0
assert fl.order == refo
ref = np.arange(len(fl.surface_h)) * fl.dx
np.testing.assert_allclose(ref, fl.dis_on_line,
rtol=0.001,
atol=0.01)
assert (len(fl.surface_h) ==
len(fl.bed_h) ==
len(fl.bed_shape) ==
len(fl.dis_on_line) ==
len(fl.widths) ==
len(fl.bin_area_m2)
)
assert np.all(fl.widths >= 0)
vol += fl.volume_m3
area += fl.area_km2
# New loc stuff - checked with google maps
lons = fl.point_lons
lats = fl.point_lats
assert_allclose([lons[0], lats[0]], [10.7470, 46.8048], atol=1e-4)
assert_allclose([lons[-1], lats[-1]], [10.8551, 46.8376], atol=1e-4)
# Diags
ref_vol = 0.
ref_area = 0.
for cl in inv:
ref_vol += np.sum(cl['volume'])
ref_area += np.sum(cl['width'] * fl.dx_meter)
np.testing.assert_allclose(ref_vol, vol)
np.testing.assert_allclose(6900.0, fls[-1].length_m, atol=101)
np.testing.assert_allclose(gdir.rgi_area_km2, ref_area * 1e-6)
np.testing.assert_allclose(gdir.rgi_area_km2, area)
# test that final downstream line has the desired shape
fl = fls[-1]
ice_mask = fls[-1].thick > 0.
if downstream_line_shape == 'parabola':
assert np.all(np.isfinite(fl.bed_shape[~ice_mask]))
assert np.all(~np.isfinite(fl._w0_m[~ice_mask]))
if downstream_line_shape == 'trapezoidal':
assert np.all(np.isfinite(fl._w0_m[~ice_mask]))
assert np.all(~np.isfinite(fl.bed_shape[~ice_mask]))
# check that bottom width of downstream line is larger than minimum
assert np.all(fl._w0_m[~ice_mask] >
cfg.PARAMS['trapezoid_min_bottom_width'])
if do_plot:
plt.plot(fls[-1].bed_h, color='k')
plt.plot(fls[-1].surface_h)
plt.figure()
plt.plot(fls[-1].surface_h - fls[-1].bed_h)
plt.show()
# test if providing a filesuffix is working
init_present_time_glacier(gdir, filesuffix='_test')
assert os.path.isfile(os.path.join(gdir.dir, 'model_flowlines_test.pkl'))
cfg.PARAMS['downstream_line_shape'] = 'free_shape'
with pytest.raises(InvalidParamsError):
init_present_time_glacier(gdir)
def test_init_present_time_glacier_obs_thick(self, hef_elev_gdir,
monkeypatch):
gdir = hef_elev_gdir
# need to change rgi_id, which is needed to be different in other tests
# when comparing to centerlines
gdir.rgi_id = 'RGI60-11.00897'
# add some thickness data
ft = utils.get_demo_file('RGI60-11.00897_thickness.tif')
monkeypatch.setattr(utils, 'file_downloader', lambda x: ft)
bedtopo.add_consensus_thickness(gdir)
vn = 'consensus_ice_thickness'
centerlines.elevation_band_flowline(gdir, bin_variables=[vn])
centerlines.fixed_dx_elevation_band_flowline(gdir,
bin_variables=[vn])
tasks.init_present_time_glacier(gdir, filesuffix='_consensus',
use_binned_thickness_data=vn)
fl_consensus = gdir.read_pickle('model_flowlines',
filesuffix='_consensus')[0]
# check that resulting flowline has the same volume as observation
cdf = pd.read_hdf(utils.get_demo_file('rgi62_itmix_df.h5'))
ref_vol = cdf.loc[gdir.rgi_id].vol_itmix_m3
np.testing.assert_allclose(fl_consensus.volume_m3, ref_vol)
# should be trapezoid where ice
assert np.all(fl_consensus.is_trapezoid[fl_consensus.thick > 0])
# test that we can use fl in an dynamic model run without an error
mb = LinearMassBalance(3000.)
model_ref = FluxBasedModel(gdir.read_pickle('model_flowlines'),
mb_model=mb)
model_ref.run_until(100)
model_consensus = FluxBasedModel([fl_consensus], mb_model=mb)
model_consensus.run_until(100)
np.testing.assert_allclose(model_ref.volume_km3,
model_consensus.volume_km3,
atol=0.02)
# test that if w0<0 it is converted to rectangular
# set some thickness to very large values to force it
df_fixed_dx = pd.read_csv(gdir.get_filepath('elevation_band_flowline',
filesuffix='_fixed_dx'))
new_thick = df_fixed_dx['consensus_ice_thickness']
new_thick[-10:] = new_thick[-10:] + 1000
df_fixed_dx['consensus_ice_thickness'] = new_thick
ref_vol_rect = np.sum(df_fixed_dx['area_m2'] * new_thick)
df_fixed_dx.to_csv(gdir.get_filepath('elevation_band_flowline',
filesuffix='_fixed_dx'))
tasks.init_present_time_glacier(gdir, filesuffix='_consensus_rect',
use_binned_thickness_data=vn)
fl_consensus_rect = gdir.read_pickle('model_flowlines',
filesuffix='_consensus_rect')[0]
np.testing.assert_allclose(fl_consensus_rect.volume_m3, ref_vol_rect)
assert np.sum(fl_consensus_rect.is_rectangular) == 10
def test_present_time_glacier_massbalance(self, hef_gdir):
gdir = hef_gdir
init_present_time_glacier(gdir)
mb_mod = massbalance.MonthlyTIModel(gdir)
fls = gdir.read_pickle('model_flowlines')
glacier = FlowlineModel(fls)
mbdf = gdir.get_ref_mb_data()
hgts = np.array([])
widths = np.array([])
for fl in glacier.fls:
hgts = np.concatenate((hgts, fl.surface_h))
widths = np.concatenate((widths, fl.widths_m))
tot_mb = []
refmb = []
grads = hgts * 0
for yr, mb in mbdf.iterrows():
refmb.append(mb['ANNUAL_BALANCE'])
mbh = (mb_mod.get_annual_mb(hgts, yr) * SEC_IN_YEAR *
cfg.PARAMS['ice_density'])
grads += mbh
tot_mb.append(np.average(mbh, weights=widths))
grads /= len(tot_mb)
# Bias
assert np.abs(utils.md(tot_mb, refmb)) < 50
mb_profile_constant_dh = gdir.get_ref_mb_profile(constant_dh=True)
step_dh = mb_profile_constant_dh.columns[1:] - mb_profile_constant_dh.columns[:-1]
assert np.all(step_dh == 50)
mb_profile_raw = gdir.get_ref_mb_profile()
mb_profile_constant_dh_filtered_0_6 = gdir.get_ref_mb_profile(constant_dh=True,
obs_ratio_needed=0.6)
mb_profile_constant_dh_filtered_1 = gdir.get_ref_mb_profile(constant_dh=True,
obs_ratio_needed=1)
n = len(mb_profile_constant_dh.index)
n_obs_h_0_6 = mb_profile_constant_dh_filtered_0_6.describe().loc['count']
n_obs_h_1 = mb_profile_constant_dh_filtered_1.describe().loc['count']
assert np.all(n_obs_h_0_6 / n >= 0.6)
assert np.all(n_obs_h_1 / n >= 1)
# fake "filter" that is not really filtering should give
# the same estimate as default (filter = 0)
mb_profile_constant_dh_filtered_0 = gdir.get_ref_mb_profile(constant_dh=True,
obs_ratio_needed=0.00001)
np.testing.assert_allclose(mb_profile_constant_dh_filtered_0, mb_profile_constant_dh)
# Gradient
dfg = mb_profile_raw.mean()
dfg_constant_dh = mb_profile_constant_dh.mean()
dfg_constant_dh_0_6 = mb_profile_constant_dh_filtered_0_6.mean()
# Take the altitudes below 3100 and fit a line
pok = np.where(hgts < 3100)
dfg = dfg[dfg.index < 3100]
dfg_constant_dh = dfg_constant_dh[dfg_constant_dh.index < 3100]
dfg_constant_dh_0_6 = dfg_constant_dh_0_6[dfg_constant_dh_0_6.index < 3100]
from scipy.stats import linregress
slope_obs, _, _, _, _ = linregress(dfg.index, dfg.values)
slope_obs_constant_dh, _, _, _, _ = linregress(dfg_constant_dh.index,
dfg_constant_dh.values)
slope_obs_constant_dh_0_6, _, _, _, _ = linregress(dfg_constant_dh_0_6.index,
dfg_constant_dh_0_6.values)
slope_our, _, _, _, _ = linregress(hgts[pok], grads[pok])
np.testing.assert_allclose(slope_obs, slope_our, rtol=0.15)
# the observed MB gradient and the interpolated observed one (with
# constant dh) should be very similar!
np.testing.assert_allclose(slope_obs, slope_obs_constant_dh, rtol=0.01)
# the filtered slope with obs_ratio_0_6 should be at least a bit similar to
# the one where all elevation band measurements are taken into account
np.testing.assert_allclose(slope_obs_constant_dh, slope_obs_constant_dh_0_6, rtol=0.2)
@pytest.fixture(scope='class')
def other_glacier_cfg():
cfg.initialize()
cfg.set_intersects_db(get_demo_file('rgi_intersect_oetztal.shp'))
cfg.PATHS['dem_file'] = get_demo_file('srtm_oetztal.tif')
cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')
cfg.PARAMS['use_winter_prcp_fac'] = False
cfg.PARAMS['use_temp_bias_from_file'] = False
cfg.PARAMS['prcp_fac'] = 2.5
cfg.PARAMS['baseline_climate'] = 'CRU'
@pytest.mark.usefixtures('other_glacier_cfg')
class TestInitFlowlineOtherGlacier:
def test_define_divides(self, class_case_dir):
from oggm.core import centerlines
from oggm.core import climate
from oggm.core import inversion
from oggm.core import gis
from oggm import GlacierDirectory
import geopandas as gpd
hef_file = utils.get_demo_file('rgi_oetztal.shp')
rgidf = gpd.read_file(hef_file)
# This is another glacier with divides
entity = rgidf.loc[rgidf.RGIId == 'RGI50-11.00719_d01'].iloc[0]
gdir = GlacierDirectory(entity, base_dir=class_case_dir)
gis.define_glacier_region(gdir)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
centerlines.initialize_flowlines(gdir)
centerlines.compute_downstream_line(gdir)
centerlines.compute_downstream_bedshape(gdir)
centerlines.catchment_area(gdir)
centerlines.catchment_width_geom(gdir)
centerlines.catchment_width_correction(gdir)
cfg.PARAMS['baseline_climate'] = ''
climate.process_custom_climate_data(gdir)
ref_period = '1980-01-01_2000-01-01'
ref_mb = -500
massbalance.mb_calibration_from_scalar_mb(gdir,
ref_mb=ref_mb,
ref_period=ref_period)
massbalance.apparent_mb_from_any_mb(gdir, mb_years=(1980, 2000))
inversion.prepare_for_inversion(gdir)
v = inversion.mass_conservation_inversion(gdir)
init_present_time_glacier(gdir)
myarea = 0.
cls = gdir.read_pickle('inversion_flowlines')
for cl in cls:
myarea += np.sum(cl.widths * cl.dx * gdir.grid.dx ** 2)
np.testing.assert_allclose(myarea, gdir.rgi_area_m2, rtol=1e-2)
myarea = 0.
cls = gdir.read_pickle('inversion_flowlines')
for cl in cls:
myarea += np.sum(cl.widths * cl.dx * gdir.grid.dx ** 2)
np.testing.assert_allclose(myarea, gdir.rgi_area_m2, rtol=1e-2)
fls = gdir.read_pickle('model_flowlines')
if cfg.PARAMS['grid_dx_method'] == 'square':
assert len(fls) == 3
vol = 0.
area = 0.
for fl in fls:
ref = np.arange(len(fl.surface_h)) * fl.dx
np.testing.assert_allclose(ref, fl.dis_on_line,
rtol=0.001,
atol=0.01)
assert (len(fl.surface_h) ==
len(fl.bed_h) ==
len(fl.bed_shape) ==
len(fl.dis_on_line) ==
len(fl.widths))
assert np.all(fl.widths >= 0)
vol += fl.volume_km3
area += fl.area_km2
rtol = 0.08
np.testing.assert_allclose(gdir.rgi_area_km2, area, rtol=rtol)
np.testing.assert_allclose(v * 1e-9, vol, rtol=rtol)
class TestMassBalanceModels:
def test_past_mb_model(self, hef_gdir):
rho = cfg.PARAMS['ice_density']
F = SEC_IN_YEAR * rho
gdir = hef_gdir
init_present_time_glacier(gdir)
df = gdir.read_json('mb_calib')
# Climate period
yrp = [1851, 2000]
# Flowlines height
h, w = gdir.get_inversion_flowline_hw()
mb_mod = massbalance.MonthlyTIModel(gdir, bias=0)
for i, yr in enumerate(np.arange(yrp[0], yrp[1] + 1)):
my_mb_on_h = mb_mod.get_annual_mb(h, yr) * F
ela_z = mb_mod.get_ela(year=yr)
totest = mb_mod.get_annual_mb([ela_z], year=yr) * F
assert_allclose(totest[0], 0, atol=1)
mb_mod = massbalance.MonthlyTIModel(gdir)
for i, yr in enumerate(np.arange(yrp[0], yrp[1] + 1)):
ela_z = mb_mod.get_ela(year=yr)
totest = mb_mod.get_annual_mb([ela_z], year=yr) * F
assert_allclose(totest[0], 0, atol=1)
# real data
h, w = gdir.get_inversion_flowline_hw()
mbdf = gdir.get_ref_mb_data()
mbdf.loc[yr, 'MY_MB'] = np.NaN
mb_mod = massbalance.MonthlyTIModel(gdir)
for yr in mbdf.index.values:
my_mb_on_h = mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR * rho
mbdf.loc[yr, 'MY_MB'] = np.average(my_mb_on_h, weights=w)
np.testing.assert_allclose(mbdf['ANNUAL_BALANCE'].mean(),
mbdf['MY_MB'].mean(),
atol=1e-2)
mbdf['MY_ELA'] = mb_mod.get_ela(year=mbdf.index.values)
assert mbdf[['MY_ELA', 'MY_MB']].corr().values[0, 1] < -0.9
assert mbdf[['MY_ELA', 'ANNUAL_BALANCE']].corr().values[0, 1] < -0.6
mb_mod = massbalance.MonthlyTIModel(gdir, bias=0)
for yr in mbdf.index.values:
my_mb_on_h = mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR * rho
mbdf.loc[yr, 'MY_MB'] = np.average(my_mb_on_h, weights=w)
np.testing.assert_allclose(mbdf['ANNUAL_BALANCE'].mean(),
mbdf['MY_MB'].mean(),
atol=1e-2)
mb_mod = massbalance.MonthlyTIModel(gdir)
for yr in mbdf.index.values:
my_mb_on_h = mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR * rho
mbdf.loc[yr, 'MY_MB'] = np.average(my_mb_on_h, weights=w)
mb_mod.temp_bias = 1
my_mb_on_h = mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR * rho
mbdf.loc[yr, 'BIASED_MB'] = np.average(my_mb_on_h, weights=w)
mb_mod.temp_bias = 0
np.testing.assert_allclose(mbdf['ANNUAL_BALANCE'].mean(),
mbdf['MY_MB'].mean(),
atol=1e-2)
assert mbdf.ANNUAL_BALANCE.mean() > mbdf.BIASED_MB.mean()
# Repeat
mb_mod = massbalance.MonthlyTIModel(gdir, repeat=True,
ys=1901, ye=1950)
yrs = np.arange(100) + 1901
mb = mb_mod.get_specific_mb(h, w, year=yrs)
assert_allclose(mb[50], mb[-50])
# Go for glacier wide now
fls = gdir.read_pickle('inversion_flowlines')
mb_gw_mod = massbalance.MultipleFlowlineMassBalance(gdir, fls=fls,
repeat=True,
ys=1901, ye=1950)
mb_gw = mb_gw_mod.get_specific_mb(year=yrs)
assert_allclose(mb, mb_gw)
# Test massbalance task
s = massbalance.fixed_geometry_mass_balance(gdir)
assert s.index[0] == 1802
assert s.index[-1] == 2002
s = massbalance.fixed_geometry_mass_balance(gdir, ys=1990, ye=2000)
assert s.index[0] == 1990
assert s.index[-1] == 2000
s = massbalance.fixed_geometry_mass_balance(gdir,
years=mbdf.index.values)
assert_allclose(s, mbdf['MY_MB'])
def test_repr(self, hef_gdir):
from textwrap import dedent
expected = dedent("""\
<oggm.MassBalanceModel>
Class: MonthlyTIModel
Attributes:
- hemisphere: nh
- climate_source: histalp_merged_hef.nc
- melt_f: 6.59
- prcp_fac: 2.50
- temp_bias: 0.00
- bias: 0.00
- rho: 900.0
- t_solid: 0.0
- t_liq: 2.0
- t_melt: -1.0
- repeat: False
- ref_hgt: 3160.0
- ys: 1802
- ye: 2002
""")
mb_mod = massbalance.MonthlyTIModel(hef_gdir, bias=0)
assert mb_mod.__repr__() == expected
def test_prcp_fac_temp_bias_update(self, hef_gdir):
gdir = hef_gdir
init_present_time_glacier(gdir)
mb_mod = massbalance.MonthlyTIModel(gdir, bias=0)
# save old precipitation/temperature time series
prcp_old = mb_mod.prcp.copy()
temp_old = mb_mod.temp.copy()
prcp_fac_old = cfg.PARAMS['prcp_fac']
temp_bias_old = 0
# basic checks
assert mb_mod.prcp_fac == prcp_fac_old
assert mb_mod._prcp_fac == prcp_fac_old
assert mb_mod.temp_bias == temp_bias_old
# Now monthly stuff
mb_mod.temp_bias = [0] * 12
np.testing.assert_allclose(mb_mod.temp_bias, temp_bias_old)
mb_mod.prcp_fac = [prcp_fac_old] * 12
np.testing.assert_allclose(mb_mod.prcp_fac, prcp_fac_old)
# increase prcp by factor of 10 and add a temperature bias of 1
factor = 10
mb_mod.prcp_fac = factor
temp_bias = 1
mb_mod.temp_bias = temp_bias
assert mb_mod.prcp_fac == factor
assert mb_mod._prcp_fac == factor
assert mb_mod.temp_bias == temp_bias
assert mb_mod._temp_bias == temp_bias
prcp_new = mb_mod.prcp
temp_new = mb_mod.temp
assert_allclose(prcp_new, prcp_old * factor / prcp_fac_old)
assert_allclose(temp_new, temp_old + temp_bias - temp_bias_old)
# check if it gets back to the old prcp/temp time series
mb_mod.prcp_fac = prcp_fac_old
assert mb_mod.prcp_fac == prcp_fac_old
assert mb_mod._prcp_fac == prcp_fac_old
assert_allclose(mb_mod.prcp, prcp_old)
mb_mod.temp_bias = temp_bias_old
assert mb_mod.temp_bias == temp_bias_old
assert mb_mod._temp_bias == temp_bias_old
assert_allclose(mb_mod.temp, temp_old)
# check if error occurs for invalid prcp_fac
with pytest.raises(InvalidParamsError):
mb_mod.prcp_fac = -100
@pytest.mark.parametrize("cl", [massbalance.MonthlyTIModel,
massbalance.ConstantMassBalance,
massbalance.RandomMassBalance])
def test_glacierwide_mb_model(self, hef_gdir, cl):
gdir = hef_gdir
init_present_time_glacier(gdir)
fls = gdir.read_pickle('model_flowlines')
h = np.array([])
w = np.array([])
for fl in fls:
w = np.append(w, fl.widths)
h = np.append(h, fl.surface_h)
yrs = np.arange(100) + 1901
if cl is massbalance.RandomMassBalance:
kwargs = {'seed': 0, 'y0': 1985}
elif cl is massbalance.ConstantMassBalance:
kwargs = {'y0': 1985}
else:
kwargs = {}
mb = cl(gdir, **kwargs)
mb_gw = massbalance.MultipleFlowlineMassBalance(gdir, fls=fls,
mb_model_class=cl,
**kwargs)
assert_allclose(mb.get_specific_mb(h, w, year=yrs),
mb_gw.get_specific_mb(year=yrs))
assert_allclose(mb.get_ela(year=yrs),
mb_gw.get_ela(year=yrs))
_h, _w, mbs_gw = mb_gw.get_annual_mb_on_flowlines(year=1950)
mbs_h = mb.get_annual_mb(_h, year=1950)
assert_allclose(mbs_h, mbs_gw)
mb.bias = 100
mb_gw.bias = 100
assert_allclose(mb.get_specific_mb(h, w, year=yrs[:10]),
mb_gw.get_specific_mb(year=yrs[:10]))
assert_allclose(mb.get_ela(year=yrs[:10]),
mb_gw.get_ela(year=yrs[:10]))
mb.temp_bias = 100
mb_gw.temp_bias = 100
assert mb.temp_bias == mb_gw.temp_bias
assert_allclose(mb.get_specific_mb(h, w, year=yrs[:10]),
mb_gw.get_specific_mb(year=yrs[:10]))
assert_allclose(mb.get_ela(year=yrs[:10]),
mb_gw.get_ela(year=yrs[:10]))
mb.prcp_fac = 100
mb_gw.prcp_fac = 100
assert mb.prcp_fac == mb_gw.prcp_fac
assert_allclose(mb.get_specific_mb(h, w, year=yrs[:10]),
mb_gw.get_specific_mb(year=yrs[:10]))
assert_allclose(mb.get_ela(year=yrs[:10]),
mb_gw.get_ela(year=yrs[:10]))
if cl is massbalance.MonthlyTIModel:
mb = cl(gdir)
mb_gw = massbalance.MultipleFlowlineMassBalance(gdir,
mb_model_class=cl)
mb = massbalance.UncertainMassBalance(mb, rdn_bias_seed=1,
rdn_prcp_fac_seed=2,
rdn_temp_bias_seed=3)
mb_gw = massbalance.UncertainMassBalance(mb_gw, rdn_bias_seed=1,
rdn_prcp_fac_seed=2,
rdn_temp_bias_seed=3)
assert_allclose(mb.get_specific_mb(h, w, year=yrs[:30]),
mb_gw.get_specific_mb(fls=fls, year=yrs[:30]))
# ELA won't pass because of API incompatibility
# assert_allclose(mb.get_ela(year=yrs[:30]),
# mb_gw.get_ela(year=yrs[:30]))
def test_constant_mb_model(self, hef_gdir):
rho = cfg.PARAMS['ice_density']
gdir = hef_gdir
init_present_time_glacier(gdir)
h, w = gdir.get_inversion_flowline_hw()
# We calibrate to zero
df = massbalance.mb_calibration_from_scalar_mb(gdir,
calibrate_param1='temp_bias',
ref_mb=0,
ref_mb_years=(1970, 2001),
write_to_gdir=False)
cmb_mod = massbalance.ConstantMassBalance(gdir,
melt_f=df['melt_f'],
temp_bias=df['temp_bias'],
prcp_fac=df['prcp_fac'],
y0=1985)
ombh = cmb_mod.get_annual_mb(h) * SEC_IN_YEAR * rho
otmb = np.average(ombh, weights=w)
np.testing.assert_allclose(0., otmb, atol=0.2)
mb_mod = massbalance.ConstantMassBalance(gdir, y0=2002 - 15)
nmbh = mb_mod.get_annual_mb(h) * SEC_IN_YEAR * rho
ntmb = np.average(nmbh, weights=w)
assert ntmb < otmb
if do_plot: # pragma: no cover
plt.plot(h, ombh, 'o', label='zero')
plt.plot(h, nmbh, 'o', label='today')
plt.legend()
plt.show()
orig_bias = cmb_mod.temp_bias
cmb_mod.temp_bias = orig_bias + 1
biasombh = cmb_mod.get_annual_mb(h) * SEC_IN_YEAR * rho
biasotmb = np.average(biasombh, weights=w)
assert biasotmb < (otmb - 500)
cmb_mod.temp_bias = orig_bias
nobiasombh = cmb_mod.get_annual_mb(h) * SEC_IN_YEAR * rho
nobiasotmb = np.average(nobiasombh, weights=w)
np.testing.assert_allclose(0, nobiasotmb, atol=0.2)
months = np.arange(12)
monthly_1 = months * 0.
monthly_2 = months * 0.
monthly_3 = months * 0.
for m in months:
yr = utils.date_to_floatyear(0, m + 1)
cmb_mod.temp_bias = orig_bias
tmp = cmb_mod.get_monthly_mb(h, yr) * SEC_IN_MONTH * rho
monthly_1[m] = np.average(tmp, weights=w)
cmb_mod.temp_bias = orig_bias + 1
tmp = cmb_mod.get_monthly_mb(h, yr) * SEC_IN_MONTH * rho
monthly_2[m] = np.average(tmp, weights=w)
cmb_mod.temp_bias = [orig_bias] * 6 + [orig_bias + 1] + [orig_bias] * 5
cmb_mod.prcp_fac = [10] * 3 + [2.5] * 9 # This adds solid precip in win
tmp = cmb_mod.get_monthly_mb(h, yr) * SEC_IN_MONTH * rho
monthly_3[m] = np.average(tmp, weights=w)
cmb_mod.prcp_fac = 2.5
if do_plot: # pragma: no cover
plt.plot(monthly_1, '-', label='Normal')
plt.plot(monthly_2, '-', label='Temp bias')
plt.plot(monthly_3, '-', label='Temp bias monthly')
plt.legend()
plt.show()
# check that the winter months are close but summer months no
np.testing.assert_allclose(monthly_1[:4], monthly_2[:4], atol=1)
assert np.mean(monthly_3[:4]) > (np.mean(monthly_1[:4]) + 100)
assert monthly_3[6] == monthly_2[6]
assert monthly_3[7] != monthly_2[7]
# Climate info
h = np.sort(h)
cmb_mod = massbalance.ConstantMassBalance(gdir,
melt_f=df['melt_f'],
temp_bias=df['temp_bias'],
prcp_fac=df['prcp_fac'],
y0=1985)
t, tm, p, ps = cmb_mod.get_annual_climate(h)
# Simple sanity checks
assert np.all(np.diff(t) <= 0)
assert np.all(np.diff(tm) <= 0)
assert np.all(np.diff(p) == 0)
assert np.all(np.diff(ps) >= 0)
if do_plot: # pragma: no cover
f, axs = plt.subplots(1, 3, figsize=(9, 3))
axs = axs.flatten()
axs[0].plot(h, t, label='Temp')
axs[0].legend()
axs[1].plot(h, tm, label='TempMelt')
axs[1].legend()
axs[2].plot(h, p, label='Prcp')
axs[2].plot(h, ps, label='SolidPrcp')
axs[2].legend()
plt.tight_layout()
plt.show()
# ELA
elah = cmb_mod.get_ela()
t, tm, p, ps = cmb_mod.get_annual_climate([elah])
mb = ps - cmb_mod.mbmod.monthly_melt_f * tm
# not perfect because of time/months/zinterp issues
np.testing.assert_allclose(mb, 0, atol=0.2)
def test_random_mb(self, hef_gdir):
gdir = hef_gdir
init_present_time_glacier(gdir)
ref_mod = massbalance.ConstantMassBalance(gdir, y0=1985)
mb_mod = massbalance.RandomMassBalance(gdir, seed=10, y0=1985)
h, w = gdir.get_inversion_flowline_hw()
ref_mbh = ref_mod.get_annual_mb(h, None) * SEC_IN_YEAR
# two years shouldn't be equal
r_mbh1 = mb_mod.get_annual_mb(h, 1) * SEC_IN_YEAR
r_mbh2 = mb_mod.get_annual_mb(h, 2) * SEC_IN_YEAR
assert not np.all(np.allclose(r_mbh1, r_mbh2))
# the same year should be equal
r_mbh1 = mb_mod.get_annual_mb(h, 1) * SEC_IN_YEAR
r_mbh2 = mb_mod.get_annual_mb(h, 1) * SEC_IN_YEAR
np.testing.assert_allclose(r_mbh1, r_mbh2)
# After many trials the mb should be close to the same
ny = 2000
yrs = np.arange(ny)
r_mbh = 0.
mbts = yrs * 0.
for i, yr in enumerate(yrs):
mbts[i] = mb_mod.get_specific_mb(h, w, year=yr)
r_mbh += mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR
r_mbh /= ny
np.testing.assert_allclose(ref_mbh, r_mbh, atol=0.2)
elats = mb_mod.get_ela(yrs[:200])
assert np.corrcoef(mbts[:200], elats)[0, 1] < -0.95
mb_mod.temp_bias = -0.5
r_mbh_b = 0.
for yr in yrs:
r_mbh_b += mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR
r_mbh_b /= ny
assert np.mean(r_mbh) < np.mean(r_mbh_b)
# Compare sigma from real climate and mine
mb_ref = massbalance.MonthlyTIModel(gdir)
mb_mod = massbalance.RandomMassBalance(gdir, y0=2002 - 15,
seed=10)
mb_ts = []
mb_ts2 = []
yrs = np.arange(1972, 2003, 1)
for yr in yrs:
mb_ts.append(np.average(mb_ref.get_annual_mb(h, yr) * SEC_IN_YEAR,
weights=w))
mb_ts2.append(np.average(mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR,
weights=w))
np.testing.assert_allclose(np.std(mb_ts), np.std(mb_ts2), rtol=0.15)
# Monthly
time = pd.date_range('1/1/1972', periods=31 * 12, freq='MS')
yrs = utils.date_to_floatyear(time.year, time.month)
ref_mb = np.zeros(12)
my_mb = np.zeros(12)
for yr, m in zip(yrs, time.month):
ref_mb[m - 1] += np.average(mb_ref.get_monthly_mb(h, yr) *
SEC_IN_MONTH, weights=w)
my_mb[m - 1] += np.average(mb_mod.get_monthly_mb(h, yr) *
SEC_IN_MONTH, weights=w)
my_mb = my_mb / 31
ref_mb = ref_mb / 31
assert utils.rmsd(ref_mb, my_mb) < 0.1
# Prescribe MB
pdf = pd.Series(index=mb_mod._state_yr.keys(), data=mb_mod._state_yr.values())
p_mod = massbalance.RandomMassBalance(gdir, prescribe_years=pdf)
mb_ts = []
mb_ts2 = []
yrs = np.arange(1972, 2003, 1)
for yr in yrs:
mb_ts.append(np.average(mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR,
weights=w))
mb_ts2.append(np.average(p_mod.get_annual_mb(h, yr) * SEC_IN_YEAR,
weights=w))
np.testing.assert_allclose(mb_ts, mb_ts2)
def test_random_mb_unique(self, hef_gdir):
gdir = hef_gdir
init_present_time_glacier(gdir)
ref_mod = massbalance.ConstantMassBalance(gdir,
y0=2002 - 15,
halfsize=15)
mb_mod = massbalance.RandomMassBalance(gdir, seed=10,
y0=2002 - 15,
unique_samples=True,
halfsize=15)
mb_mod2 = massbalance.RandomMassBalance(gdir, seed=20,
y0=2002 - 15,
unique_samples=True,
halfsize=15)
mb_mod3 = massbalance.RandomMassBalance(gdir, seed=20,
y0=2002 - 15,
unique_samples=True,
halfsize=15)
h, w = gdir.get_inversion_flowline_hw()
ref_mbh = ref_mod.get_annual_mb(h, None) * SEC_IN_YEAR
# the same year should be equal
r_mbh1 = mb_mod.get_annual_mb(h, 1) * SEC_IN_YEAR
r_mbh2 = mb_mod.get_annual_mb(h, 1) * SEC_IN_YEAR
np.testing.assert_allclose(r_mbh1, r_mbh2)
# test 31 years (2*halfsize +1)
ny = 31
yrs = np.arange(ny)
mbts = yrs * 0.
r_mbh = 0.
r_mbh2 = 0.
r_mbh3 = 0.
mb_mod3.temp_bias = -0.5
annual_previous = -999.
for i, yr in enumerate(yrs):
# specific mass balance
mbts[i] = mb_mod.get_specific_mb(h, w, year=yr)
# annual mass balance
annual = mb_mod.get_annual_mb(h, yr) * SEC_IN_YEAR
# annual mass balance must be different than the previous one
assert not np.all(np.allclose(annual, annual_previous))
# sum over all years should be equal to ref_mbh
r_mbh += annual
r_mbh2 += mb_mod2.get_annual_mb(h, yr) * SEC_IN_YEAR
# mass balance with temperature bias
r_mbh3 += mb_mod3.get_annual_mb(h, yr) * SEC_IN_YEAR
annual_previous = annual
r_mbh /= ny
r_mbh2 /= ny
r_mbh3 /= ny
# test sums
np.testing.assert_allclose(ref_mbh, r_mbh, atol=0.02)
np.testing.assert_allclose(r_mbh, r_mbh2, atol=0.02)
# test uniqueness
# size
assert (len(list(mb_mod._state_yr.values())) ==
np.unique(list(mb_mod._state_yr.values())).size)
# size2
assert (len(list(mb_mod2._state_yr.values())) ==
np.unique(list(mb_mod2._state_yr.values())).size)
# state years 1 vs 2
assert (np.all(np.unique(list(mb_mod._state_yr.values())) ==
np.unique(list(mb_mod2._state_yr.values()))))
# state years 1 vs reference model
assert (np.all(np.unique(list(mb_mod._state_yr.values())) ==
ref_mod.years))
# test ela vs specific mb
elats = mb_mod.get_ela(yrs[:200])
assert np.corrcoef(mbts[:200], elats)[0, 1] < -0.95
# test mass balance with temperature bias
assert np.mean(r_mbh) < np.mean(r_mbh3)
def test_uncertain_mb(self, hef_gdir):
gdir = hef_gdir
ref_mod = massbalance.ConstantMassBalance(gdir, y0=2002-15)
# only change bias: this works as before
mb_mod = massbalance.UncertainMassBalance(ref_mod,
rdn_temp_bias_sigma=0,
rdn_prcp_fac_sigma=0,
rdn_bias_sigma=100)
yrs = np.arange(100)
h, w = gdir.get_inversion_flowline_hw()
ref_mb = ref_mod.get_specific_mb(h, w, year=yrs)
unc_mb = mb_mod.get_specific_mb(h, w, year=yrs)
check_mb = ref_mod.get_specific_mb(h, w, year=yrs)
assert_allclose(ref_mb, check_mb)
assert np.std(unc_mb) > 50
mb_mod = massbalance.UncertainMassBalance(ref_mod)
ref_mb = ref_mod.get_specific_mb(h, w, year=yrs)
temp_1 = ref_mod.mbmod.temp.copy()
unc_mb = mb_mod.get_specific_mb(h, w, year=yrs)
temp_2 = ref_mod.mbmod.temp.copy()
check_mb = ref_mod.get_specific_mb(h, w, year=yrs)
temp_3 = ref_mod.mbmod.temp.copy()
unc2_mb = mb_mod.get_specific_mb(h, w, year=yrs)
assert_allclose(temp_1, temp_2)
assert_allclose(temp_1, temp_3)
assert_allclose(ref_mb, check_mb)
assert_allclose(unc_mb, unc2_mb)
assert np.std(unc_mb) > 50
mb_mod = massbalance.UncertainMassBalance(ref_mod,
rdn_temp_bias_sigma=0.1,
rdn_prcp_fac_sigma=0,
rdn_bias_sigma=0)
ref_mb = ref_mod.get_specific_mb(h, w, year=yrs)
unc_mb = mb_mod.get_specific_mb(h, w, year=yrs)
check_mb = ref_mod.get_specific_mb(h, w, year=yrs)
assert_allclose(ref_mb, check_mb)
assert np.std(unc_mb) > 50
mb_mod = massbalance.UncertainMassBalance(ref_mod,
rdn_temp_bias_sigma=0,
rdn_prcp_fac_sigma=0.1,
rdn_bias_sigma=0)
ref_mb = ref_mod.get_specific_mb(h, w, year=yrs)
unc_mb = mb_mod.get_specific_mb(h, w, year=yrs)
check_mb = ref_mod.get_specific_mb(h, w, year=yrs)
assert_allclose(ref_mb, check_mb)
assert np.std(unc_mb) > 50
# Other MBs
ref_mod = massbalance.MonthlyTIModel(gdir)
mb_mod = massbalance.UncertainMassBalance(ref_mod)
yrs = np.arange(100) + 1901
ref_mb = ref_mod.get_specific_mb(h, w, year=yrs)
unc_mb = mb_mod.get_specific_mb(h, w, year=yrs)
check_mb = ref_mod.get_specific_mb(h, w, year=yrs)
unc2_mb = mb_mod.get_specific_mb(h, w, year=yrs)
assert_allclose(ref_mb, check_mb)
assert_allclose(unc_mb, unc2_mb)
assert np.std(unc_mb - ref_mb) > 50