def test_plot_model(): gdir = init_hef() flowline.init_present_time_glacier(gdir) model = flowline.FlowlineModel(gdir.read_pickle('model_flowlines')) graphics.plot_modeloutput_section(gdir, model=model) graphics.plot_modeloutput_map(gdir, model=model)
def test_tstar_mb(self): gdir = init_hef(border=DOM_BORDER) flowline.init_present_time_glacier(gdir) mb_mod = massbalance.TstarMassBalanceModel(gdir) ofl = gdir.read_pickle('inversion_flowlines', div_id=0) h = np.array([]) w = np.array([]) for fl in ofl: h = np.append(h, fl.surface_h) w = np.append(w, fl.widths) ombh = mb_mod.get_mb(h, None) otmb = np.sum(ombh * w) np.testing.assert_allclose(0., otmb, atol=0.26) mb_mod = massbalance.TodayMassBalanceModel(gdir) ofl = gdir.read_pickle('inversion_flowlines', div_id=0) h = np.array([]) w = np.array([]) for fl in ofl: h = np.append(h, fl.surface_h) w = np.append(w, fl.widths) mbh = mb_mod.get_mb(h, None) tmb = np.sum(mbh * w) self.assertTrue(tmb < otmb) if do_plot: # pragma: no cover plt.plot(h, ombh, 'o') plt.plot(h, mbh, 'o') plt.show()
def test_equilibrium(self): #TODO: equilibrium test only working with parabolic bed _tmp = cfg.PARAMS['bed_shape'] cfg.PARAMS['bed_shape'] = 'parabolic' flowline.init_present_time_glacier(self.gdir) cfg.PARAMS['bed_shape'] = _tmp mb_mod = massbalance.TstarMassBalanceModel(self.gdir) fls = self.gdir.read_pickle('model_flowlines') model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0., fs=self.fs, glen_a=self.glen_a) ref_vol = model.volume_km3 ref_area = model.area_km2 ref_len = model.fls[-1].length_m np.testing.assert_allclose(ref_area, self.gdir.rgi_area_km2, rtol=0.03) model.run_until(50.) self.assertFalse(model.dt_warning) after_vol = model.volume_km3 after_area = model.area_km2 after_len = model.fls[-1].length_m np.testing.assert_allclose(ref_vol, after_vol, rtol=0.03) np.testing.assert_allclose(ref_area, after_area, rtol=0.03) np.testing.assert_allclose(ref_len, after_len, atol=200.01)
def test_histalp_mb(self): gdir = init_hef(border=DOM_BORDER) flowline.init_present_time_glacier(gdir) mb_mod = massbalance.TodayMassBalanceModel(gdir) ofl = gdir.read_pickle('inversion_flowlines', div_id=0) h = np.array([]) w = np.array([]) for fl in ofl: h = np.append(h, fl.surface_h) w = np.append(w, fl.widths) ref_mbh = mb_mod.get_mb(h, None) * 365 * 24 * 3600 mb_mod = massbalance.HistalpMassBalanceModel(gdir) # Climate period yrs = np.arange(1983, 2003.1, 1) my_mb = ref_mbh * 0. for yr in yrs: my_mb += mb_mod.get_mb(h, yr) my_mb = my_mb / len(yrs) * 365 * 24 * 3600 np.testing.assert_allclose(ref_mbh, my_mb, rtol=0.01)
def test_invert_and_run(self): from oggm.core.models import flowline, massbalance glen_a = cfg.A * 2 gdir = utils.GlacierDirectory(self.rgin, base_dir=self.testdir) gis.glacier_masks(gdir) centerlines.compute_centerlines(gdir) centerlines.compute_downstream_lines(gdir) geometry.initialize_flowlines(gdir) geometry.catchment_area(gdir) geometry.catchment_width_geom(gdir) geometry.catchment_width_correction(gdir) climate.local_mustar_apparent_mb(gdir, tstar=1975, bias=0.) inversion.prepare_for_inversion(gdir) v, a = inversion.invert_parabolic_bed(gdir, glen_a=glen_a) cfg.PARAMS['bed_shape'] = 'parabolic' flowline.init_present_time_glacier(gdir) mb_mod = massbalance.TstarMassBalanceModel(gdir) fls = gdir.read_pickle('model_flowlines') model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0., fs=0, glen_a=glen_a) ref_vol = model.volume_m3 model.run_until_equilibrium() after_vol = model.volume_m3 np.testing.assert_allclose(ref_vol, after_vol, rtol=0.1)
def test_invert_and_run(self): from oggm.core.models import flowline, massbalance glen_a = cfg.A * 2 gdir = utils.GlacierDirectory(self.rgin, base_dir=self.testdir) gis.glacier_masks(gdir) centerlines.compute_centerlines(gdir) centerlines.compute_downstream_lines(gdir) geometry.initialize_flowlines(gdir) geometry.catchment_area(gdir) geometry.catchment_width_geom(gdir) geometry.catchment_width_correction(gdir) climate.local_mustar_apparent_mb(gdir, tstar=1975, bias=0.0, prcp_fac=1) inversion.prepare_for_inversion(gdir) v, a = inversion.invert_parabolic_bed(gdir, glen_a=glen_a) cfg.PARAMS["bed_shape"] = "parabolic" flowline.init_present_time_glacier(gdir) mb_mod = massbalance.TstarMassBalanceModel(gdir) fls = gdir.read_pickle("model_flowlines") model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0.0, fs=0, glen_a=glen_a) ref_vol = model.volume_m3 model.run_until_equilibrium() after_vol = model.volume_m3 np.testing.assert_allclose(ref_vol, after_vol, rtol=0.1)
def test_plot_model(): gdir = init_hef() flowline.init_present_time_glacier(gdir) fls = flowline.convert_to_mixed_flowline(gdir.read_pickle("model_flowlines")) model = flowline.FlowlineModel(fls) graphics.plot_modeloutput_section(gdir, model=model) graphics.plot_modeloutput_map(gdir, model=model)
def test_init_present_time_glacier(self): gdirs = up_to_inversion() # Inversion Results cfg.PARAMS['invert_with_sliding'] = True cfg.PARAMS['optimize_thick'] = True workflow.inversion_tasks(gdirs) fpath = os.path.join(cfg.PATHS['working_dir'], 'inversion_optim_results.csv') df = pd.read_csv(fpath, index_col=0) r1 = rmsd(df['ref_volume_km3'], df['oggm_volume_km3']) r2 = rmsd(df['ref_volume_km3'], df['vas_volume_km3']) self.assertTrue(r1 < r2) cfg.PARAMS['invert_with_sliding'] = False cfg.PARAMS['optimize_thick'] = False workflow.inversion_tasks(gdirs) fpath = os.path.join(cfg.PATHS['working_dir'], 'inversion_optim_results.csv') df = pd.read_csv(fpath, index_col=0) r1 = rmsd(df['ref_volume_km3'], df['oggm_volume_km3']) r2 = rmsd(df['ref_volume_km3'], df['vas_volume_km3']) self.assertTrue(r1 < r2) # Init glacier d = gdirs[0].read_pickle('inversion_params') fs = d['fs'] glen_a = d['glen_a'] maxs = cfg.PARAMS['max_shape_param'] for gdir in gdirs: flowline.init_present_time_glacier(gdir) mb_mod = massbalance.ConstantMassBalanceModel(gdir) fls = gdir.read_pickle('model_flowlines') model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0., fs=fs, glen_a=glen_a) _vol = model.volume_km3 _area = model.area_km2 if gdir.rgi_id in df.index: gldf = df.loc[gdir.rgi_id] # TODO: broken but should work # assert_allclose(gldf['oggm_volume_km3'], _vol, rtol=0.03) # assert_allclose(gldf['ref_area_km2'], _area, rtol=0.03) maxo = max([fl.order for fl in model.fls]) for fl in model.fls: self.assertTrue(np.all(fl.bed_shape > 0)) self.assertTrue(np.all(fl.bed_shape <= maxs)) if len(model.fls) > 1: if fl.order == (maxo-1): self.assertTrue(fl.flows_to is fls[-1]) # Test the glacier charac dfc = utils.glacier_characteristics(gdirs) self.assertTrue(np.all(dfc.terminus_type == 'Land-terminating')) cc = dfc[['dem_mean_elev', 'clim_temp_avgh']].corr().values[0, 1] self.assertTrue(cc > 0.4)
def test_modelmap(): gdir = init_hef() flowline.init_present_time_glacier(gdir) fls = gdir.read_pickle('model_flowlines') model = flowline.FlowlineModel(fls) fig, ax = plt.subplots() graphics.plot_modeloutput_map(gdir, ax=ax, model=model) fig.tight_layout() return fig
def test_modelsection(): gdir = init_hef() flowline.init_present_time_glacier(gdir) fls = gdir.read_pickle('model_flowlines') model = flowline.FlowlineModel(fls) fig = plt.figure(figsize=(12, 6)) ax = fig.add_axes([0.07, 0.08, 0.7, 0.84]) graphics.plot_modeloutput_section(gdir, ax=ax, model=model) return fig
def test_find_t0(self): gdir = init_hef(border=DOM_BORDER, invert_with_sliding=False) flowline.init_present_time_glacier(gdir) glacier = gdir.read_pickle('model_flowlines') df = pd.read_csv(utils.get_demo_file('hef_lengths.csv'), index_col=0) df.columns = ['Leclercq'] df = df.loc[1950:] vol_ref = flowline.FlowlineModel(glacier).volume_km3 init_bias = 100. # 100 so that "went too far" comes once on travis rtol = 0.005 flowline.find_inital_glacier(gdir, y0=df.index[0], init_bias=init_bias, rtol=rtol, write_steps=False) past_model = gdir.read_pickle('past_model') vol_start = past_model.volume_km3 bef_fls = copy.deepcopy(past_model.fls) mylen = [] for y in df.index: past_model.run_until(y) mylen.append(past_model.fls[-1].length_m) df['oggm'] = mylen df = df - df.iloc[-1] vol_end = past_model.volume_km3 np.testing.assert_allclose(vol_ref, vol_end, rtol=0.05) rmsd = utils.rmsd(df.Leclercq, df.oggm) self.assertTrue(rmsd < 1000.) if do_plot: # pragma: no cover df.plot() plt.ylabel('Glacier length (relative to 2003)') plt.show() fig = plt.figure() lab = 'ref (vol={:.2f}km3)'.format(vol_ref) plt.plot(glacier[-1].surface_h, 'k', label=lab) lab = 'oggm start (vol={:.2f}km3)'.format(vol_start) plt.plot(bef_fls[-1].surface_h, 'b', label=lab) lab = 'oggm end (vol={:.2f}km3)'.format(vol_end) plt.plot(past_model.fls[-1].surface_h, 'r', label=lab) plt.plot(glacier[-1].bed_h, 'gray', linewidth=2) plt.legend(loc='best') plt.show()
def test_grow(self): gdirs = up_to_inversion() for gd in gdirs[0:2]: if gd.rgi_id in ['RGI40-11.00719']: # Bad bad glacier continue flowline.init_present_time_glacier(gd) flowline.find_inital_glacier(gd)
def test_init_present_time_glacier(self): gdirs = up_to_inversion() # Inversion Results cfg.PARAMS['invert_with_sliding'] = True cfg.PARAMS['optimize_thick'] = True workflow.inversion_tasks(gdirs) fpath = os.path.join(cfg.PATHS['working_dir'], 'inversion_optim_results.csv') df = pd.read_csv(fpath, index_col=0) r1 = rmsd(df['ref_volume_km3'], df['oggm_volume_km3']) r2 = rmsd(df['ref_volume_km3'], df['vas_volume_km3']) self.assertTrue(r1 < r2) cfg.PARAMS['invert_with_sliding'] = False cfg.PARAMS['optimize_thick'] = False workflow.inversion_tasks(gdirs) fpath = os.path.join(cfg.PATHS['working_dir'], 'inversion_optim_results.csv') df = pd.read_csv(fpath, index_col=0) r1 = rmsd(df['ref_volume_km3'], df['oggm_volume_km3']) r2 = rmsd(df['ref_volume_km3'], df['vas_volume_km3']) self.assertTrue(r1 < r2) # Init glacier d = gdirs[0].read_pickle('inversion_params') fs = d['fs'] glen_a = d['glen_a'] maxs = cfg.PARAMS['max_shape_param'] for gdir in gdirs: flowline.init_present_time_glacier(gdir) mb_mod = massbalance.ConstantMassBalanceModel(gdir) fls = gdir.read_pickle('model_flowlines') model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0., fs=fs, glen_a=glen_a) _vol = model.volume_km3 _area = model.area_km2 gldf = df.loc[gdir.rgi_id] assert_allclose(gldf['oggm_volume_km3'], _vol, rtol=0.03) assert_allclose(gldf['ref_area_km2'], _area, rtol=0.03) maxo = max([fl.order for fl in model.fls]) for fl in model.fls: self.assertTrue(np.all(fl.bed_shape > 0)) self.assertTrue(np.all(fl.bed_shape <= maxs)) if len(model.fls) > 1: if fl.order == (maxo - 1): self.assertTrue(fl.flows_to is fls[-1])
def test_coxe(): testdir = os.path.join(cfg.PATHS['test_dir'], 'tmp_coxe') utils.mkdir(testdir) # Init cfg.initialize() cfg.PATHS['dem_file'] = get_demo_file('dem_RGI50-01.10299.tif') cfg.PARAMS['border'] = 40 cfg.PARAMS['use_multiple_flowlines'] = False hef_file = get_demo_file('rgi_RGI50-01.10299.shp') entity = gpd.GeoDataFrame.from_file(hef_file).iloc[0] gdir = oggm.GlacierDirectory(entity, base_dir=testdir, reset=True) gis.define_glacier_region(gdir, entity=entity) gis.glacier_masks(gdir) centerlines.compute_centerlines(gdir) centerlines.compute_downstream_lines(gdir) geometry.initialize_flowlines(gdir) # Just check if the rest runs centerlines.compute_downstream_bedshape(gdir) geometry.catchment_area(gdir) geometry.catchment_intersections(gdir) geometry.catchment_width_geom(gdir) geometry.catchment_width_correction(gdir) climate.apparent_mb_from_linear_mb(gdir) inversion.prepare_for_inversion(gdir) inversion.volume_inversion(gdir, use_cfg_params={'glen_a': cfg.A, 'fs': 0}) inversion.filter_inversion_output(gdir) flowline.init_present_time_glacier(gdir) fls = gdir.read_pickle('model_flowlines') p = gdir.read_pickle('linear_mb_params') mb_mod = massbalance.LinearMassBalanceModel(ela_h=p['ela_h'], grad=p['grad']) mb_mod.temp_bias = -0.3 model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0, is_tidewater=True) # run model.run_until(200) assert model.calving_m3_since_y0 > 0 fig, ax = plt.subplots() graphics.plot_modeloutput_map(gdir, ax=ax, model=model) fig.tight_layout() return fig
def test_backwards_mb(self): gdir = init_hef(border=DOM_BORDER) flowline.init_present_time_glacier(gdir) mb_mod_ref = massbalance.TstarMassBalanceModel(gdir) mb_mod = massbalance.BackwardsMassBalanceModel(gdir, use_tstar=True) ofl = gdir.read_pickle('inversion_flowlines', div_id=0) h = np.array([]) w = np.array([]) for fl in ofl: h = np.append(h, fl.surface_h) w = np.append(w, fl.widths) ombh = mb_mod_ref.get_mb(h, None) * SEC_IN_YEAR mbh = mb_mod.get_mb(h, None) * SEC_IN_YEAR mb_mod.set_bias(100.) mbhb = mb_mod.get_mb(h, None) * SEC_IN_YEAR np.testing.assert_allclose(ombh, mbh, rtol=0.001) self.assertTrue(np.mean(mbhb) > np.mean(mbh)) if do_plot: # pragma: no cover plt.plot(h, ombh, 'o') plt.plot(h, mbh, 'x') plt.plot(h, mbhb, 'x') plt.show() mb_mod_ref = massbalance.TodayMassBalanceModel(gdir) mb_mod = massbalance.BackwardsMassBalanceModel(gdir) ofl = gdir.read_pickle('inversion_flowlines', div_id=0) h = np.array([]) w = np.array([]) for fl in ofl: h = np.append(h, fl.surface_h) w = np.append(w, fl.widths) ombh = mb_mod_ref.get_mb(h, None) * SEC_IN_YEAR mbh = mb_mod.get_mb(h, None) * SEC_IN_YEAR mb_mod.set_bias(-100.) mbhb = mb_mod.get_mb(h, None) * SEC_IN_YEAR np.testing.assert_allclose(ombh, mbh, rtol=0.005) self.assertTrue(np.mean(mbhb) < np.mean(mbh)) if do_plot: # pragma: no cover plt.plot(h, ombh, 'o') plt.plot(h, mbh, 'x') plt.plot(h, mbhb, 'x') plt.show()
def test_init_present_time_glacier(self): gdir = init_hef(border=DOM_BORDER) flowline.init_present_time_glacier(gdir) fls = gdir.read_pickle('model_flowlines') lens = [ len(gdir.read_pickle('centerlines', div_id=i)) for i in [1, 2, 3] ] ofl = gdir.read_pickle('inversion_flowlines', div_id=np.argmax(lens) + 1)[-1] self.assertTrue(gdir.rgi_date.year == 2003) self.assertTrue(len(fls) == 5) vol = 0. area = 0. for fl in fls: refo = 1 if fl is fls[-1] else 0 self.assertTrue(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) self.assertTrue( len(fl.surface_h) == len(fl.bed_h) == len(fl.bed_shape) == len( fl.dis_on_line) == len(fl.widths)) self.assertTrue(np.all(fl.bed_shape >= 0)) self.assertTrue(np.all(fl.widths >= 0)) vol += fl.volume_km3 area += fl.area_km2 if refo == 1: rtol = 0.07 if HAS_NEW_GDAL else 0.05 np.testing.assert_allclose(ofl.widths * gdir.grid.dx, fl.widths_m[0:len(ofl.widths)], rtol=rtol) np.testing.assert_allclose(0.573, vol, rtol=0.001) np.testing.assert_allclose(7350.0, fls[-1].length_m) rtol = 0.01 if HAS_NEW_GDAL else 0.001 np.testing.assert_allclose(gdir.rgi_area_km2, area, rtol=rtol) if do_plot: # pragma: no cover plt.plot(fls[-1].bed_h) plt.plot(fls[-1].surface_h) plt.show()
def test_init_present_time_glacier(self): gdir = init_hef(border=DOM_BORDER) flowline.init_present_time_glacier(gdir) fls = gdir.read_pickle('model_flowlines') lens = [len(gdir.read_pickle('centerlines', div_id=i)) for i in [1, 2, 3]] ofl = gdir.read_pickle('inversion_flowlines', div_id=np.argmax(lens)+1)[-1] self.assertTrue(gdir.rgi_date.year == 2003) self.assertTrue(len(fls) == 5) vol = 0. area = 0. for fl in fls: refo = 1 if fl is fls[-1] else 0 self.assertTrue(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) self.assertTrue(len(fl.surface_h) == len(fl.bed_h) == len(fl.bed_shape) == len(fl.dis_on_line) == len(fl.widths)) self.assertTrue(np.all(fl.bed_shape >= 0)) self.assertTrue(np.all(fl.widths >= 0)) vol += fl.volume_km3 area += fl.area_km2 if refo == 1: rtol = 0.07 if HAS_NEW_GDAL else 0.05 np.testing.assert_allclose(ofl.widths * gdir.grid.dx, fl.widths_m[0:len(ofl.widths)], rtol=rtol) np.testing.assert_allclose(0.573, vol, rtol=0.001) np.testing.assert_allclose(7350.0, fls[-1].length_m) rtol = 0.01 if HAS_NEW_GDAL else 0.001 np.testing.assert_allclose(gdir.rgi_area_km2, area, rtol=rtol) if do_plot: # pragma: no cover plt.plot(fls[-1].bed_h) plt.plot(fls[-1].surface_h) plt.show()
def test_find_t0(self): gdir = init_hef(border=DOM_BORDER, invert_with_sliding=False) flowline.init_present_time_glacier(gdir) glacier = gdir.read_pickle('model_flowlines') df = pd.read_csv(utils.get_demo_file('hef_lengths.csv'), index_col=0) df.columns = ['Leclercq'] df = df.loc[1950:] vol_ref = flowline.FlowlineModel(glacier).volume_km3 init_bias = 100. # 100 so that "went too far" comes once on travis rtol = 0.005 flowline.find_inital_glacier(gdir, y0=df.index[0], init_bias=init_bias, rtol=rtol, write_steps=False) past_model = gdir.read_pickle('past_model') vol_start = past_model.volume_km3 bef_fls = copy.deepcopy(past_model.fls) mylen = [] for y in df.index: past_model.run_until(y) mylen.append(past_model.fls[-1].length_m) df['oggm'] = mylen df = df-df.iloc[-1] vol_end = past_model.volume_km3 np.testing.assert_allclose(vol_ref, vol_end, rtol=0.05) rmsd = utils.rmsd(df.Leclercq, df.oggm) self.assertTrue(rmsd < 1000.) if do_plot: # pragma: no cover df.plot() plt.ylabel('Glacier length (relative to 2003)') plt.show() fig = plt.figure() lab = 'ref (vol={:.2f}km3)'.format(vol_ref) plt.plot(glacier[-1].surface_h, 'k', label=lab) lab = 'oggm start (vol={:.2f}km3)'.format(vol_start) plt.plot(bef_fls[-1].surface_h, 'b', label=lab) lab = 'oggm end (vol={:.2f}km3)'.format(vol_end) plt.plot(past_model.fls[-1].surface_h, 'r', label=lab) plt.plot(glacier[-1].bed_h, 'gray', linewidth=2) plt.legend(loc='best') plt.show()
def test_init_present_time_glacier(self): gdirs = up_to_inversion() # Inversion Results cfg.PARAMS['invert_with_sliding'] = True cfg.PARAMS['optimize_thick'] = True workflow.inversion_tasks(gdirs) fpath = os.path.join(cfg.PATHS['working_dir'], 'inversion_optim_results.csv') df = pd.read_csv(fpath, index_col=0) r1 = rmsd(df['ref_volume_km3'], df['oggm_volume_km3']) r2 = rmsd(df['ref_volume_km3'], df['vas_volume_km3']) self.assertTrue(r1 < r2) cfg.PARAMS['invert_with_sliding'] = False cfg.PARAMS['optimize_thick'] = False workflow.inversion_tasks(gdirs) fpath = os.path.join(cfg.PATHS['working_dir'], 'inversion_optim_results.csv') df = pd.read_csv(fpath, index_col=0) r1 = rmsd(df['ref_volume_km3'], df['oggm_volume_km3']) r2 = rmsd(df['ref_volume_km3'], df['vas_volume_km3']) self.assertTrue(r1 < r2) # Init glacier d = gdirs[0].read_pickle('inversion_params') fs = d['fs'] glen_a = d['glen_a'] maxs = cfg.PARAMS['max_shape_param'] for gdir in gdirs: flowline.init_present_time_glacier(gdir) mb_mod = massbalance.TstarMassBalanceModel(gdir) fls = gdir.read_pickle('model_flowlines') model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0., fs=fs, glen_a=glen_a) _vol = model.volume_km3 _area = model.area_km2 gldf = df.loc[gdir.rgi_id] assert_allclose(gldf['oggm_volume_km3'], _vol, rtol=0.03) assert_allclose(gldf['ref_area_km2'], _area, rtol=0.03) maxo = max([fl.order for fl in model.fls]) for fl in model.fls: self.assertTrue(np.all(fl.bed_shape > 0)) self.assertTrue(np.all(fl.bed_shape <= maxs)) if len(model.fls) > 1: if fl.order == (maxo-1): self.assertTrue(fl.flows_to is fls[-1])
def test_chhota_shigri(): testdir = os.path.join(cfg.PATHS['test_dir'], 'tmp_chhota') utils.mkdir(testdir) # Init cfg.initialize() cfg.PATHS['dem_file'] = get_demo_file('dem_chhota_shigri.tif') cfg.PARAMS['border'] = 60 cfg.set_divides_db(get_demo_file('divides_RGI50-14.15990.shp')) hef_file = get_demo_file('RGI50-14.15990.shp') entity = gpd.GeoDataFrame.from_file(hef_file).iloc[0] gdir = oggm.GlacierDirectory(entity, base_dir=testdir) gis.define_glacier_region(gdir, entity=entity) gis.glacier_masks(gdir) centerlines.compute_centerlines(gdir) centerlines.compute_downstream_lines(gdir) geometry.initialize_flowlines(gdir) # We should have two groups lines = gdir.read_pickle('downstream_lines', div_id=0) assert len(np.unique(lines.group)) == 2 # Just check if the rest runs centerlines.compute_downstream_bedshape(gdir) geometry.catchment_area(gdir) geometry.catchment_intersections(gdir) geometry.catchment_width_geom(gdir) geometry.catchment_width_correction(gdir) climate.apparent_mb_from_linear_mb(gdir) inversion.prepare_for_inversion(gdir) inversion.volume_inversion(gdir, use_cfg_params={'glen_a': cfg.A, 'fs': 0}) inversion.filter_inversion_output(gdir) flowline.init_present_time_glacier(gdir) fls = gdir.read_pickle('model_flowlines') for fl in fls: fl.thick = np.clip(fl.thick, 100, 1000) model = flowline.FlowlineModel(fls) fig, ax = plt.subplots() graphics.plot_modeloutput_map(gdir, ax=ax, model=model) fig.tight_layout() return fig
def test_present_time_glacier_massbalance(self): gdir = init_hef(border=DOM_BORDER) flowline.init_present_time_glacier(gdir) mb_mod = massbalance.HistalpMassBalanceModel(gdir) fls = gdir.read_pickle('model_flowlines') glacier = flowline.FlowlineModel(fls) hef_file = utils.get_demo_file('mbdata_RGI40-11.00897.csv') mbdf = pd.read_csv(hef_file).set_index('YEAR') 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_mb(hgts, yr) * SEC_IN_YEAR * cfg.RHO grads += mbh tot_mb.append(np.average(mbh, weights=widths)) grads /= len(tot_mb) # Bias self.assertTrue(np.abs(utils.md(tot_mb, refmb)) < 50) # Gradient dfg = pd.read_csv(utils.get_demo_file('mbgrads_RGI40-11.00897.csv'), index_col='ALTITUDE').mean(axis=1) # Take the altitudes below 3100 and fit a line dfg = dfg[dfg.index < 3100] pok = np.where(hgts < 3100) from scipy.stats import linregress slope_obs, _, _, _, _ = linregress(dfg.index, dfg.values) slope_our, _, _, _, _ = linregress(hgts[pok], grads[pok]) np.testing.assert_allclose(slope_obs, slope_our, rtol=0.1)
def up_to_inversion(reset=False): """Run the tasks you want.""" # test directory if not os.path.exists(TEST_DIR): os.makedirs(TEST_DIR) if reset: clean_dir(TEST_DIR) # Init cfg.initialize() # Use multiprocessing cfg.PARAMS['use_multiprocessing'] = not ON_TRAVIS # Working dir cfg.PATHS['working_dir'] = TEST_DIR cfg.set_divides_db(get_demo_file('HEF_divided.shp')) cfg.PATHS['dem_file'] = get_demo_file('srtm_oeztal.tif') # Set up the paths and other stuffs cfg.set_divides_db(get_demo_file('HEF_divided.shp')) cfg.PATHS['wgms_rgi_links'] = get_demo_file('RGI_WGMS_oeztal.csv') cfg.PATHS['glathida_rgi_links'] = get_demo_file('RGI_GLATHIDA_oeztal.csv') # Read in the RGI file rgi_file = get_demo_file('rgi_oeztal.shp') rgidf = gpd.GeoDataFrame.from_file(rgi_file) # Params cfg.PARAMS['border'] = 70 cfg.PARAMS['use_inversion_params'] = True # Go gdirs = workflow.init_glacier_regions(rgidf) try: flowline.init_present_time_glacier(gdirs[0]) except Exception: reset = True if reset: # First preprocessing tasks workflow.gis_prepro_tasks(gdirs) # Climate related tasks # See if CRU is running cfg.PARAMS['temp_use_local_gradient'] = False cfg.PATHS['climate_file'] = '~' cru_dir = get_demo_file('cru_ts3.23.1901.2014.tmp.dat.nc') cfg.PATHS['cru_dir'] = os.path.dirname(cru_dir) workflow.climate_tasks(gdirs) # Use histalp for the actual test cfg.PARAMS['temp_use_local_gradient'] = True cfg.PATHS['climate_file'] = get_demo_file('HISTALP_oeztal.nc') cfg.PATHS['cru_dir'] = '~' workflow.climate_tasks(gdirs) # Inversion workflow.inversion_tasks(gdirs) return gdirs
def test_commitment(self): _tmp = cfg.PARAMS['mixed_min_shape'] cfg.PARAMS['mixed_min_shape'] = 0. flowline.init_present_time_glacier(self.gdir) cfg.PARAMS['mixed_min_shape'] = _tmp mb_mod = massbalance.BackwardsMassBalanceModel(self.gdir) fls = self.gdir.read_pickle('model_flowlines') model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0., fs=self.fs, glen_a=self.glen_a) ref_vol = model.volume_km3 ref_area = model.area_km2 ref_len = model.fls[-1].length_m np.testing.assert_allclose(ref_area, self.gdir.rgi_area_km2, rtol=0.01) model.run_until_equilibrium() self.assertTrue(model.yr > 100) after_vol_1 = model.volume_km3 after_area_1 = model.area_km2 after_len_1 = model.fls[-1].length_m _tmp = cfg.PARAMS['mixed_min_shape'] cfg.PARAMS['mixed_min_shape'] = 0.001 flowline.init_present_time_glacier(self.gdir) cfg.PARAMS['mixed_min_shape'] = _tmp glacier = self.gdir.read_pickle('model_flowlines') mb_mod = massbalance.BackwardsMassBalanceModel(self.gdir) fls = self.gdir.read_pickle('model_flowlines') model = flowline.FluxBasedModel(fls, mb_model=mb_mod, y0=0., fs=self.fs, glen_a=self.glen_a) ref_vol = model.volume_km3 ref_area = model.area_km2 ref_len = model.fls[-1].length_m np.testing.assert_allclose(ref_area, self.gdir.rgi_area_km2, rtol=0.01) model.run_until_equilibrium() self.assertTrue(model.yr > 100) after_vol_2 = model.volume_km3 after_area_2 = model.area_km2 after_len_2 = model.fls[-1].length_m self.assertTrue(after_vol_1 < (0.3 * ref_vol)) self.assertTrue(after_vol_2 < (0.3 * ref_vol)) if do_plot: # pragma: no cover fig = plt.figure() plt.plot(glacier[-1].surface_h, 'b', label='start') plt.plot(model.fls[-1].surface_h, 'r', label='end') plt.plot(glacier[-1].bed_h, 'gray', linewidth=2) plt.legend(loc='best') plt.show()
def up_to_inversion(reset=False): """Run the tasks you want.""" # test directory if not os.path.exists(TEST_DIR): os.makedirs(TEST_DIR) if reset: clean_dir(TEST_DIR) # Init cfg.initialize() # Use multiprocessing cfg.PARAMS['use_multiprocessing'] = not ON_TRAVIS # Working dir cfg.PATHS['working_dir'] = TEST_DIR cfg.PATHS['dem_file'] = get_demo_file('srtm_oetztal.tif') # Set up the paths and other stuffs cfg.set_divides_db(get_demo_file('divides_workflow.shp')) cfg.PATHS['wgms_rgi_links'] = get_demo_file('RGI_WGMS_oetztal.csv') cfg.PATHS['glathida_rgi_links'] = get_demo_file('RGI_GLATHIDA_oetztal.csv') # Read in the RGI file rgi_file = get_demo_file('rgi_oetztal.shp') rgidf = gpd.GeoDataFrame.from_file(rgi_file) # Be sure data is downloaded because lock doesn't work cl = utils.get_cru_cl_file() # Params cfg.PARAMS['border'] = 70 cfg.PARAMS['use_optimized_inversion_params'] = True # Go gdirs = workflow.init_glacier_regions(rgidf) try: flowline.init_present_time_glacier(gdirs[0]) except Exception: reset = True if reset: # First preprocessing tasks workflow.gis_prepro_tasks(gdirs) # Climate related tasks # See if CRU is running cfg.PARAMS['temp_use_local_gradient'] = False cfg.PATHS['climate_file'] = '~' cru_dir = get_demo_file('cru_ts3.23.1901.2014.tmp.dat.nc') cfg.PATHS['cru_dir'] = os.path.dirname(cru_dir) with warnings.catch_warnings(): # There is a warning from salem warnings.simplefilter("ignore") workflow.execute_entity_task(tasks.distribute_cru_style, gdirs) tasks.compute_ref_t_stars(gdirs) tasks.distribute_t_stars(gdirs) # Use histalp for the actual test cfg.PARAMS['temp_use_local_gradient'] = True cfg.PATHS['climate_file'] = get_demo_file('HISTALP_oetztal.nc') cfg.PATHS['cru_dir'] = '~' workflow.climate_tasks(gdirs) # Inversion workflow.inversion_tasks(gdirs) return gdirs