def setup_cache(self): utils.mkdir(self.testdir, reset=True) self.cfg_init() hef_file = get_demo_file('Hintereisferner_RGI5.shp') entity = gpd.read_file(hef_file).iloc[0] gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir) tasks.define_glacier_region(gdir, entity=entity) tasks.glacier_masks(gdir) tasks.compute_centerlines(gdir) tasks.initialize_flowlines(gdir) tasks.compute_downstream_line(gdir) tasks.compute_downstream_bedshape(gdir) tasks.catchment_area(gdir) tasks.catchment_intersections(gdir) tasks.catchment_width_geom(gdir) tasks.catchment_width_correction(gdir) tasks.process_custom_climate_data(gdir) tasks.mu_candidates(gdir) mbdf = gdir.get_ref_mb_data()['ANNUAL_BALANCE'] res = climate.t_star_from_refmb(gdir, mbdf) tasks.local_mustar(gdir, tstar=res['t_star'], bias=res['bias']) tasks.apparent_mb(gdir) tasks.prepare_for_inversion(gdir) tasks.mass_conservation_inversion(gdir) return gdir
def test_run(self): entity = gpd.read_file(self.rgi_file).iloc[0] gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir) gis.define_glacier_region(gdir, entity=entity) 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_intersections(gdir) centerlines.catchment_width_geom(gdir) centerlines.catchment_width_correction(gdir) # Climate tasks -- only data IO and tstar interpolation! tasks.process_dummy_cru_file(gdir, seed=0) tasks.local_t_star(gdir) tasks.mu_star_calibration(gdir) # Inversion tasks tasks.prepare_for_inversion(gdir) # We use the default parameters for this run tasks.mass_conservation_inversion(gdir) tasks.filter_inversion_output(gdir) # Final preparation for the run tasks.init_present_time_glacier(gdir) # check that calving happens in the real context as well tasks.run_constant_climate(gdir, bias=0, nyears=100) with xr.open_dataset(gdir.get_filepath('model_diagnostics')) as ds: assert ds.calving_m3.max() > 10
def to_optimize(x): tasks.mass_conservation_inversion(gdir, glen_a=glen_a * x[0], fs=fs * x[1]) tasks.distribute_thickness_per_altitude(gdir) with xr.open_dataset(gdir.get_filepath('gridded_data')) as ds: thick = ds.distributed_thickness.isel(x=('z', df['i']), y=('z', df['j'])) out = (np.abs(thick - df.thick)).mean() return out
def to_optimize(x): tasks.mass_conservation_inversion(gdir, glen_a=glen_a * x[0], fs=fs * x[1]) tasks.distribute_thickness_per_altitude(gdir) with xr.open_dataset(gdir.get_filepath('gridded_data')) as ds: thick = ds.distributed_thickness.isel(x=('z', df['i']), y=('z', df['j'])) out = (np.abs(thick - df.thick)).mean() return out
pdf = pd.DataFrame() pdf[r'$\mu (t)$'] = mu_yr_clim pdf['bias'] = diff res = t_star_from_refmb(gdir, mbdf=mbdf.ANNUAL_BALANCE) # For the mass flux cl = gdir.read_pickle('inversion_input')[-1] mbmod = ConstantMassBalance(gdir) mbx = (mbmod.get_annual_mb(cl['hgt']) * cfg.SEC_IN_YEAR * cfg.PARAMS['ice_density']) fdf = pd.DataFrame(index=np.arange(len(mbx)) * cl['dx']) fdf['Flux'] = cl['flux'] fdf['Mass balance'] = mbx # For the distributed thickness tasks.mass_conservation_inversion(gdir, glen_a=2.4e-24 * 3, fs=0) tasks.distribute_thickness_per_altitude(gdir) # plot functions def example_plot_temp_ts(): d = xr.open_dataset(gdir.get_filepath('climate_historical')) temp = d.temp.resample(time='12MS').mean('time').to_series() temp.index = temp.index.year try: temp = temp.rename_axis(None) except AttributeError: del temp.index.name temp.plot(figsize=(8, 4), label='Annual temp') tsm = temp.rolling(31, center=True, min_periods=15).mean() tsm.plot(label='31-yr avg')
tasks.glacier_masks(gdir) tasks.compute_centerlines(gdir) tasks.initialize_flowlines(gdir) tasks.compute_downstream_line(gdir) tasks.compute_downstream_bedshape(gdir) tasks.catchment_area(gdir) tasks.catchment_intersections(gdir) tasks.catchment_width_geom(gdir) tasks.catchment_width_correction(gdir) tasks.process_cru_data(gdir) tasks.local_t_star(gdir) tasks.mu_star_calibration(gdir) glen_a = cfg.PARAMS['glen_a'] tasks.prepare_for_inversion(gdir) tasks.mass_conservation_inversion(gdir, glen_a=glen_a, fs=0) tasks.filter_inversion_output(gdir) # run tasks.init_present_time_glacier(gdir) tasks.run_random_climate(gdir, bias=0., temperature_bias=-1, nyears=120, glen_a=glen_a, check_for_boundaries=False) f = 0.9 f = plt.figure(figsize=(7, 10)) from mpl_toolkits.axes_grid1 import ImageGrid
tasks.define_glacier_region(gdir, entity=entity) tasks.glacier_masks(gdir) tasks.compute_centerlines(gdir) tasks.initialize_flowlines(gdir) tasks.compute_downstream_line(gdir) tasks.compute_downstream_bedshape(gdir) tasks.catchment_area(gdir) tasks.catchment_intersections(gdir) tasks.catchment_width_geom(gdir) tasks.catchment_width_correction(gdir) tasks.process_cru_data(gdir) tasks.local_t_star(gdir) tasks.mu_star_calibration(gdir) tasks.prepare_for_inversion(gdir) tasks.mass_conservation_inversion(gdir) tasks.filter_inversion_output(gdir) tasks.init_present_time_glacier(gdir) df = utils.compile_glacier_statistics([gdir], path=False) reset = False seed = 0 tasks.run_random_climate(gdir, nyears=800, seed=0, y0=2000, output_filesuffix='_2000_def', reset=reset) tasks.run_random_climate(gdir, nyears=800, seed=0, y0=1920, output_filesuffix='_1920_def', reset=reset)
cl = gdir.read_pickle('inversion_output')[-1] assert cl['volume'][-1] == 0. volumes = [] all_mus = [] data_calving = data_calving = np.arange(0, 5, 0.2) for j, c in enumerate(data_calving): gdir.inversion_calving_rate = c # Recompute mu with calving tasks.local_t_star(gdir) execute_entity_task(tasks.mu_star_calibration, gdirs) tasks.prepare_for_inversion(gdir, add_debug_var=True) tasks.mass_conservation_inversion(gdir, fs=cfg.PARAMS['inversion_fs']) df = gdir.read_json('local_mustar') mu_star = df['mu_star_glacierwide'] vol = [] cl = gdir.read_pickle('inversion_output') for c in cl: vol.extend(c['volume']) vol = np.nansum(vol) * 1e-9 volumes.append(vol) all_mus = np.append(all_mus, mu_star) print(volumes, data_calving) print(len(volumes), len(data_calving))
def setup_cache(self): setattr(full_workflow.setup_cache, "timeout", 360) utils.mkdir(self.testdir, reset=True) self.cfg_init() entity = gpd.read_file(get_demo_file('01_rgi60_Columbia.shp')).iloc[0] gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir) tasks.define_glacier_region(gdir, entity=entity) tasks.glacier_masks(gdir) tasks.compute_centerlines(gdir) tasks.initialize_flowlines(gdir) tasks.compute_downstream_line(gdir) tasks.compute_downstream_bedshape(gdir) tasks.catchment_area(gdir) tasks.catchment_intersections(gdir) tasks.catchment_width_geom(gdir) tasks.catchment_width_correction(gdir) climate.process_dummy_cru_file(gdir, seed=0) rho = cfg.PARAMS['ice_density'] i = 0 calving_flux = [] mu_star = [] ite = [] cfg.PARAMS['clip_mu_star'] = False cfg.PARAMS['min_mu_star'] = 0 # default is now 1 while i < 12: # Calculates a calving flux from model output if i == 0: # First call we set to zero (not very necessary, # this first loop could be removed) f_calving = 0 elif i == 1: # Second call we set a very small positive calving f_calving = utils.calving_flux_from_depth(gdir, water_depth=1) elif cfg.PARAMS['clip_mu_star']: # If we have to clip mu the calving becomes the real flux fl = gdir.read_pickle('inversion_flowlines')[-1] f_calving = fl.flux[-1] * (gdir.grid.dx**2) * 1e-9 / rho else: # Otherwise it is parameterized f_calving = utils.calving_flux_from_depth(gdir) # Give it back to the inversion and recompute gdir.inversion_calving_rate = f_calving # At this step we might raise a MassBalanceCalibrationError mu_is_zero = False try: climate.local_t_star(gdir) df = gdir.read_json('local_mustar') except MassBalanceCalibrationError as e: assert 'mu* out of specified bounds' in str(e) # When this happens we clip mu* to zero and store the # bad value (just for plotting) cfg.PARAMS['clip_mu_star'] = True df = gdir.read_json('local_mustar') df['mu_star_glacierwide'] = float(str(e).split(':')[-1]) climate.local_t_star(gdir) climate.mu_star_calibration(gdir) tasks.prepare_for_inversion(gdir, add_debug_var=True) v_inv, _ = tasks.mass_conservation_inversion(gdir) # Store the data calving_flux = np.append(calving_flux, f_calving) mu_star = np.append(mu_star, df['mu_star_glacierwide']) ite = np.append(ite, i) # Do we have to do another_loop? if i > 0: avg_one = np.mean(calving_flux[-4:]) avg_two = np.mean(calving_flux[-5:-1]) difference = abs(avg_two - avg_one) conv = (difference < 0.05 * avg_two or calving_flux[-1] == 0 or calving_flux[-1] == calving_flux[-2]) if mu_is_zero or conv: break i += 1 assert i < 8 assert calving_flux[-1] < np.max(calving_flux) assert calving_flux[-1] > 2 assert mu_star[-1] == 0 mbmod = massbalance.MultipleFlowlineMassBalance mb = mbmod(gdir, use_inversion_flowlines=True, mb_model_class=massbalance.ConstantMassBalance, bias=0) flux_mb = (mb.get_specific_mb() * gdir.rgi_area_m2) * 1e-9 / rho np.testing.assert_allclose(flux_mb, calving_flux[-1], atol=0.001) return calving_flux, mu_star
pdf = pd.DataFrame() pdf[r'$\mu (t)$'] = mu_yr_clim pdf['bias'] = diff res = t_star_from_refmb(gdir, mbdf=mbdf.ANNUAL_BALANCE) # For the mass flux cl = gdir.read_pickle('inversion_input')[-1] mbmod = ConstantMassBalance(gdir) mbx = (mbmod.get_annual_mb(cl['hgt']) * cfg.SEC_IN_YEAR * cfg.PARAMS['ice_density']) fdf = pd.DataFrame(index=np.arange(len(mbx))*cl['dx']) fdf['Flux'] = cl['flux'] fdf['Mass balance'] = mbx # For the distributed thickness tasks.mass_conservation_inversion(gdir, glen_a=2.4e-24 * 3, fs=0) tasks.distribute_thickness_per_altitude(gdir) # plot functions def example_plot_temp_ts(): d = xr.open_dataset(gdir.get_filepath('climate_monthly')) temp = d.temp.resample(time='12MS').mean('time').to_series() del temp.index.name temp.plot(figsize=(8, 4), label='Annual temp') tsm = temp.rolling(31, center=True, min_periods=15).mean() tsm.plot(label='31-yr avg') plt.legend(loc='best') plt.title('HISTALP annual temperature, Hintereisferner') plt.ylabel(r'degC') plt.tight_layout()
df = pd.DataFrame(df).set_index('thick') ds = [] for thick in np.linspace(0, 500, 51): # This function simply computes the calving law out = inversion.calving_flux_from_depth(gdir, thick=thick) out['Calving law'] = out.pop('thick') # Now we feed it back to OGGM gdir.inversion_calving_rate = out['flux'] # The mass-balance has to adapt in order to create a flux tasks.local_t_star(gdir) tasks.mu_star_calibration(gdir) tasks.prepare_for_inversion(gdir) v_inv, _ = tasks.mass_conservation_inversion(gdir) # Now we get the OGGM ice thickness out['OGGM'] = inversion.calving_flux_from_depth(gdir)['thick'] # Add sliding (the fs value is outdated, but still) v_inv, _ = tasks.mass_conservation_inversion(gdir, fs=5.7e-20) out['OGGM with sliding'] = inversion.calving_flux_from_depth(gdir)['thick'] # Store ds.append(out) ds = pd.DataFrame(ds) # print(df) # print(ds)