def _run_to_present(tupel, gdir, ys, ye, bias): """ Run glacier candidates forwards. """ suffix = tupel[0] #path = gdir.get_filepath('model_run', filesuffix=suffix) path = os.path.join(gdir.dir, str(ys), 'model_run' + suffix + '.nc') # does file already exists? if not os.path.exists(path): try: tasks.run_from_climate_data(gdir, ys=ys, ye=ye, bias=bias, output_filesuffix=suffix, init_model_fls=copy.deepcopy( tupel[1].fls)) return suffix # oggm failed --> probaly "glacier exeeds boundaries" except: return None else: # does file contain a model? try: fmod = FileModel(path) return suffix except: return None
def _run_to_present(array, gdir, ys, ye, mb_offset): """ Run glacier candidates forwards. """ init_yr = array[0] init_filesuffix = array[1] s = init_filesuffix.split('_random')[-1] output_filesuffix = str(ys) + '_past' + s + '_' + str(int(init_yr)) path = os.path.join(gdir.dir, str(ys), 'model_geometry' + output_filesuffix + '.nc') # does file already exists? if not os.path.exists(path): try: tasks.run_from_climate_data(gdir, ys=ys, ye=ye, bias=mb_offset, init_model_filesuffix=init_filesuffix, init_model_yr=init_yr, output_filesuffix=output_filesuffix) return output_filesuffix # oggm failed --> probaly "glacier exeeds boundaries" except: return None else: # does file contain a model? try: fmod = FileModel(path) return suffix except: return None
def _run_parallel_experiment(gdir, t0, te): """ Creates the synthetic experiment for one glacier. model_run_synthetic_experiment.nc will be saved in working directory. """ try: fls = gdir.read_pickle('model_flowlines') # try to run random climate with temperature bias -1 model = tasks.run_random_climate(gdir, nyears=600, y0=t0, bias=0, seed=1, temperature_bias=-1, init_model_fls=fls) # construct observed glacier, previous glacier will be run forward from # t0 - te with past climate file b = fls[-1].bed_h fls = copy.deepcopy(model.fls) tasks.run_from_climate_data(gdir, ys=t0, ye=te, init_model_fls=fls, output_filesuffix='_synthetic_experiment') except: print('experiment failed : ' + str(gdir.rgi_id))
def plot_lenght(gdir, candidates_df, experiment): plot_dir = '/home/juliaeis/Dokumente/OGGM/work_dir/find_initial_state/past_state_information/plots' fig, ax = plt.subplots(figsize=(20, 10)) list = range(len(candidates_df)) pool = Pool() present_models = pool.map( partial(run_and_store_to_present, gdir=gdir, ys=1850, ye=2000, flowlines=candidates_df.model), list) pool.close() pool.join() first1 = 0 first2 = 0 for i in list: if candidates_df.iloc[i].objective <= 100: color = 'green' first1 = first1 + 1 else: color = 'red' first2 = first2 + 1 path = gdir.get_filepath('model_run', filesuffix='_past_' + str(i)) fmod = FileModel(path) if first1 == 1: p1 = fmod.volume_m3_ts().plot(ax=ax, color=color, label='possible') first1 = 10 elif first2 == 1: p2 = fmod.volume_m3_ts().plot(ax=ax, color=color, label='not possible') first2 = 10 else: fmod.volume_m3_ts().plot(ax=ax, color=color, label='') tasks.run_from_climate_data(gdir, ys=1850, ye=2000, init_model_fls=deepcopy( experiment['y_t0'].fls), output_filesuffix='_past_experiment') path = gdir.get_filepath('model_run', filesuffix='_past_experiment') fmod = FileModel(path) fmod.volume_m3_ts().plot(ax=ax, style='k:', linewidth=3, label='') plt.tick_params(axis='both', which='major', labelsize=25) plt.xlabel('time', fontsize=30) plt.ylabel(r'volume $(m^3)$', fontsize=30) plt.title(gdir.rgi_id, fontsize=30) plt.legend(fontsize=20) plt.savefig(os.path.join(plot_dir, 'lenght_' + str(gdir.rgi_id) + '.png'), dpi=200) plt.show()
def plot_issue(gdir, plot_dir): #plt.style.use('ggplot') workflow.gis_prepro_tasks([gdir]) workflow.climate_tasks([gdir]) workflow.inversion_tasks([gdir]) tasks.init_present_time_glacier(gdir) # Observed length changes df = gdir.get_ref_length_data() df = df.loc[1855:2003]['dL'] df = df - df.iloc[-1] tasks.run_from_climate_data(gdir, ys=1855, ye=2003, output_filesuffix='hist_from_current') ds = xr.open_dataset( gdir.get_filepath('model_diagnostics', filesuffix='hist_from_current')) (ds.length_m.to_series().rolling(36, center=True).mean() - ds.length_m.to_series().iloc[0]).plot(c='C0', label='OGGM') #s = s - s.iloc[-1] #print(s) ax = df.plot(c='k', label='Observations') #s.plot(c='C0', label='OGGM'); plt.legend() ax.set_ylabel('Glacier Length Change [m]') plt.title('Hintereisferner length changes Experiment 2') plt.tight_layout() plt.show() ''' fls = gdir.read_pickle('model_flowlines') x = np.arange(fls[-1].nx) *fls[-1].dx * fls[-1].map_dx plt.figure(figsize=(13,10)) rc('axes', linewidth=3) plt.plot(x,fls[-1].surface_h,linewidth=3, label='Surface Elevation') plt.plot(x,fls[-1].bed_h,'k',linewidth=3,label='Bed Topography') plt.ylabel('Altitude (m)',size=30) plt.xlabel('Distance along the Flowline (m)',size=30) plt.legend(loc='best',fontsize=30) #plt.annotate('?', xy=(5000, 2700), fontsize=40) plt.tick_params(axis='both', which='major', labelsize=30) plt.title(gdir.rgi_id+ ': '+gdir.name,size=35) plt.savefig(os.path.join(plot_dir, 'issue_today.png'),dpi=200) ''' #plt.savefig(os.path.join(plot_dir, 'issue_1850.pdf'),dpi=200) plt.show() return
def _run_experiment(gdir, temp_bias, bias, ys, ye): """ Creates the synthetic experiment for one glacier. model_run_experiment.nc will be saved in working directory. """ # check, if this experiment already exists try: rp = gdir.get_filepath('model_run', filesuffix='_advanced_experiment_' + str(temp_bias) + '_' + str(bias)) model = FileModel(rp) # otherwise create experiment except: try: fls = gdir.read_pickle('model_flowlines') model = tasks.run_random_climate( gdir, nyears=600, y0=ys, bias=bias, seed=1, temperature_bias=temp_bias, init_model_fls=fls, output_filesuffix='_random_experiment_' + str(temp_bias) + '_' + str(bias)) # construct observed glacier, previous glacier will be run forward from # 1917 - rgi_date with past climate file fls = copy.deepcopy(model.fls) tasks.run_from_climate_data( gdir, ys=ys, ye=ye, init_model_fls=fls, bias=bias, output_filesuffix='_advanced_experiment_' + str(temp_bias) + '_' + str(bias)) # to return FileModel rp = gdir.get_filepath('model_run', filesuffix='_advanced_experiment_' + str(temp_bias) + '_' + str(bias)) model = FileModel(rp) except: with open(os.path.join(gdir.dir, 'log.txt')) as log: error = list(log)[-1].split(';')[-1] return error return model
def _single_calibration_run(gdir, mb_offset, ys, ye): """ Creates the synthetic experiment for one glacier. model_geometry_experiment.nc will be saved in working directory. """ # check, if this model_geometry already exists try: rp = gdir.get_filepath('model_geometry', filesuffix='_calibration_past_' + str(mb_offset)) model = FileModel(rp) # otherwise create calibration_run with mb_offset except: try: fls = gdir.read_pickle('model_flowlines') # run a 600 years random run with mb_offset tasks.run_random_climate(gdir, nyears=600, y0=ys, bias=mb_offset, seed=1, init_model_fls=fls, output_filesuffix='_calibration_random_' + str(mb_offset)) # construct s_OGGM --> previous glacier will be run forward from # ys - ye with past climate file tasks.run_from_climate_data( gdir, ys=ys, ye=ye, init_model_filesuffix='_calibration_random_' + str(mb_offset), bias=mb_offset, init_model_yr=600, output_filesuffix='_calibration_past_' + str(mb_offset)) # return FileModel rp = gdir.get_filepath('model_geometry', filesuffix='_calibration_past_' + str(mb_offset)) model = FileModel(rp) except: with open(os.path.join(gdir.dir, 'log.txt')) as log: error = list(log)[-1].split(';')[-1] return error return model
def plot_volume_dif_time(gdir, dict, experiment): fig, axs = plt.subplots(len(dict), 1) try: rp = gdir.get_filepath('model_run', filesuffix='experiment') ex_mod = FileModel(rp) except: # create volume plot from experiment model = experiment['y_t0'] tasks.run_from_climate_data(gdir, ys=1850, ye=2000, init_model_fls=model.fls, output_filesuffix='experiment') rp = gdir.get_filepath('model_run', filesuffix='experiment') ex_mod = FileModel(rp) if gdir.name != '': plt.suptitle(gdir.rgi_id + ':' + gdir.name, fontsize=20) else: plt.suptitle(gdir.rgi_id, fontsize=20) import matplotlib as mpl import matplotlib.cm as cm norm = mpl.colors.LogNorm(vmin=0.1, vmax=1e5) cmap = matplotlib.cm.get_cmap('RdYlGn_r') for i, ax in enumerate(fig.axes): yr = list(dict.keys())[i] df = dict.get(yr) df = df.sort_values('objective', ascending=False) for i, model in df['model_t0'].iteritems(): color = cmap(norm(df.loc[i, 'objective'])) model.volume_m3_ts().plot(ax=ax, color=color, linewidth=2) ex_mod.volume_m3_ts().plot(ax=ax, color='k', linestyle=':', linewidth=3)
def _run_parallel_experiment(gdir, t0, te): """ Creates the synthetic experiment for one glacier. model_geometry_synthetic_experiment.nc will be saved in working directory. """ try: fls = gdir.read_pickle('model_flowlines') # try to run random climate with temperature bias -1 tasks.run_random_climate( gdir, nyears=600, y0=t0, bias=0, seed=1, temperature_bias=-1, init_model_fls=fls, output_filesuffix='_random_synthetic_experiment') # construct observed glacier, previous glacier will be run forward from # t0 - te with past climate file tasks.run_from_climate_data( gdir, ys=t0, ye=te, init_model_filesuffix='_random_synthetic_experiment', init_model_yr=600, output_filesuffix='_synthetic_experiment') # remove output file from random run os.remove( gdir.get_filepath('model_geometry', filesuffix='_random_synthetic_experiment')) os.remove( gdir.get_filepath('model_diagnostics', filesuffix='_random_synthetic_experiment')) except: print('experiment failed : ' + str(gdir.rgi_id))
def _run_experiment(gdir, temp_bias, bias, ys, ye): """ Creates the synthetic experiment for one glacier. model_run_experiment.nc will be saved in working directory. """ # check, if this experiment already exists try: rp = gdir.get_filepath('model_run', filesuffix='_advanced_experiment_' + str(temp_bias) + '_' + str(bias)) model = FileModel(rp) # otherwise create experiment except: fls = gdir.read_pickle('model_flowlines') try: model = tasks.run_random_climate(gdir, nyears=400, y0=ys, bias=bias, seed=1, temperature_bias=temp_bias, init_model_fls=fls) # construct observed glacier, previous glacier will be run forward from # 1917 - 2000 with past climate file fls = deepcopy(model.fls) model = tasks.run_from_climate_data( gdir, ys=ys, ye=ye, init_model_fls=fls, bias=bias, output_filesuffix='_advanced_experiment_' + str(temp_bias) + '_' + str(bias)) except: pass return model
def run_to_present(tupel,gdir,ys,ye): suffix = tupel[0] path = gdir.get_filepath('model_run',filesuffix=suffix) # does file already exists? if not os.path.exists(path): try: model = tasks.run_from_climate_data(gdir, ys=ys, ye=ye, output_filesuffix=suffix, init_model_fls=copy.deepcopy( tupel[1].fls)) return suffix # oggm failed --> probaly "glacier exeeds boundaries" except: return None else: # does file contain a model? try: fmod = FileModel(path) return suffix except: return None
def plot_surface_col(gdir, df, experiment, ys): #df = df[df['objective']<=100] x = np.arange(experiment['y_t'].fls[-1].nx) * \ experiment['y_t'].fls[-1].dx * experiment['y_t'].fls[-1].map_dx fig = plt.figure(figsize=(20, 15)) grid = plt.GridSpec(2, 2, hspace=0.2, wspace=0.2) ax1 = plt.subplot(grid[0, 0]) ax2 = plt.subplot(grid[0, 1]) ax3 = plt.subplot(grid[1, :]) p2 = ax2.get_position() if gdir.name != '': plt.suptitle(gdir.rgi_id + ':' + gdir.name, x=p2.x1 / 2, fontsize=20) else: plt.suptitle(gdir.rgi_id, x=p2.x1 / 2, fontsize=20) import matplotlib as mpl import matplotlib.cm as cm norm = mpl.colors.LogNorm(vmin=0.1, vmax=1e5) cmap = matplotlib.cm.get_cmap('RdYlGn_r') df = df.sort_values('objective', ascending=False) for i, model in df['model_t0'].iteritems(): color = cmap(norm(df.loc[i, 'objective'])) ax1.plot(x, model.fls[-1].surface_h, color=color, linewidth=2) model.volume_m3_ts().plot(ax=ax3, color=color, linewidth=2) for i, model in df['model_t'].iteritems(): color = cmap(norm(df.loc[i, 'objective'])) ax2.plot(x, model.fls[-1].surface_h, color=color, linewidth=2) ax2.plot(x, experiment['y_t'].fls[-1].surface_h, 'k:', linewidth=3) ax2.plot(x, model.fls[-1].bed_h, 'k', linewidth=3) # create volume plot from experiment model = experiment['y_t0'] tasks.run_from_climate_data(gdir, ys=1850, ye=2000, init_model_fls=model.fls, output_filesuffix='experiment') rp = gdir.get_filepath('model_run', filesuffix='experiment') ex_mod = FileModel(rp) ex_mod.volume_m3_ts().plot(ax=ax3, color='k', linestyle=':', linewidth=3) ex_mod.run_until(ys) ax1.plot(x, ex_mod.fls[-1].surface_h, 'k:', linewidth=3) ax1.plot(x, ex_mod.fls[-1].bed_h, 'k', linewidth=3) ax1.annotate(r'$t = ' + str(ys) + '$', xy=(0.8, 0.9), xycoords='axes fraction', fontsize=15) ax2.annotate(r'$t = 2000$', xy=(0.8, 0.9), xycoords='axes fraction', fontsize=15) ax1.set_ylabel('Altitude (m)', fontsize=15) ax1.set_xlabel('Distance along the main flowline (m)', fontsize=15) ax2.set_ylabel('Altitude (m)', fontsize=15) ax2.set_xlabel('Distance along the main flowline (m)', fontsize=15) ax3.set_ylabel(r'Volume ($m^3$)', fontsize=15) ax3.set_xlabel('Time (years)', fontsize=15) sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) sm.set_array([]) cax, kw = mpl.colorbar.make_axes([ax1, ax2, ax3]) cbar = fig.colorbar(sm, cax=cax, **kw) cbar.ax.tick_params(labelsize=15) cbar.set_label('objective', fontsize=15) ax1.tick_params(axis='both', which='major', labelsize=15) ax2.tick_params(axis='both', which='major', labelsize=15) ax3.tick_params(axis='both', which='major', labelsize=15) ax3.yaxis.offsetText.set_fontsize(15) plot_dir = '/home/juliaeis/Dokumente/OGGM/work_dir/find_initial_state/past_state_information/plots' plt.savefig(os.path.join(plot_dir, 'surface_' + str(ys) + '_' + gdir.rgi_id + '.pdf'), dpi=200) plt.savefig(os.path.join(plot_dir, 'surface_' + str(ys) + '_' + gdir.rgi_id + '.png'), dpi=200)
def run_and_store_to_present(i, gdir, ys, ye, flowlines): tasks.run_from_climate_data(gdir, ys=1850, ye=2000, init_model_fls=deepcopy(flowlines.iloc[i].fls), output_filesuffix='_past_' + str(i))