Пример #1
0
def plot_candidates(gdir, df, experiment, ys):
    plot_dir = '/home/juliaeis/Dokumente/OGGM/work_dir/find_initial_state/past_state_information/plots'

    fig, ax = plt.subplots()
    # plot random run
    for suffix in df['suffix'].unique():
        rp = gdir.get_filepath('model_run', filesuffix=suffix)
        fmod = FileModel(rp)
        fmod.volume_m3_ts().plot(ax=ax, color='grey', label='', zorder=1)

    # last one again for labeling
    df['temp_bias'] = df['suffix'].apply(lambda x: float(x.split('_')[-1]))
    label = r'temperature bias $\in [$' + str(
        df['temp_bias'].min()) + ',' + str(df['temp_bias'].max()) + '$]$'
    fmod.volume_m3_ts().plot(ax=ax, color='grey', label=label, zorder=1)
    t_eq = df['time'].sort_values().iloc[0]
    ax.axvline(x=t_eq, color='k', zorder=1)

    df.plot.scatter(x='time',
                    y='ts_section',
                    ax=ax,
                    c='objective',
                    colormap='RdYlGn_r',
                    norm=mpl.colors.LogNorm(vmin=0.1, vmax=1e5),
                    s=40,
                    zorder=2)

    plt.ylabel(r'Volume $(m^3)$')
    plt.title(gdir.rgi_id)
    plt.legend()
    plt.savefig(os.path.join(
        plot_dir, 'random' + str(ys) + '_' + str(gdir.rgi_id) + '.png'),
                dpi=200)
    plt.close()
Пример #2
0
def identification(gdir, list, ys, ye, n):
    """
    Determine glacier candidates and run them to the date of observation
    :param gdir:    oggm.GlacierDirectories
    :param df:      pd.DataFrame (volume_m3_ts() from random climate runs)
    :param ys:      starting year
    :param ye:      year of observation
    :param n:       number of candidates
    :return:
    """
    i = 0
    t_stag = 0
    # find t_stag
    for suffix in list['suffix'].values:
        if i < 10:
            try:
                rp = gdir.get_filepath('model_geometry', filesuffix=suffix)
                if not os.path.exists(rp):
                    rp = os.path.join(gdir.dir, str(ys),
                                      'model_geometry' + suffix + '.nc')
                fmod = FileModel(rp)
                t = _find_extrema(fmod.volume_m3_ts())
                if t > t_stag:
                    t_stag = t
                i = i + 1
            except:
                pass

    # make sure that t_stag is not close to the end
    if t_stag > 550:
        t_stag = 550

    df = pd.DataFrame()
    for suffix in list['suffix']:
        try:
            rp = gdir.get_filepath('model_geometry', filesuffix=suffix)
            if not os.path.exists(rp):
                rp = os.path.join(gdir.dir, str(ys),
                                  'model_geometry' + suffix + '.nc')
            fmod = FileModel(rp)
            v = pd.DataFrame(
                fmod.volume_m3_ts()).rename_axis('time').reset_index()
            v = v[v['time'] >= t_stag]
            v = v.assign(suffix=lambda x: suffix)
            df = df.append(v, ignore_index=True)
        except:
            pass

    indices = []
    # find nearest glacier state for each of the n volume classes (equidistant)
    for val in np.linspace(df.volume_m3.min(), df.volume_m3.max(), n):
        index = df.iloc[(df['volume_m3'] - val).abs().argsort()][:1].index[0]
        if not index in indices:
            indices = np.append(indices, index)
    candidates = df.loc[indices]
    candidates = candidates.sort_values(['suffix', 'time'])
    candidates = candidates.drop_duplicates()

    return candidates[['time', 'suffix']]
def find_temp_bias_range(gdir,y0):
    fls = gdir.read_pickle('model_flowlines')
    t_eq = 0

    # try range (2,-2) first
    bias_list= [b.round(3) for b in np.arange(-2,2,0.05)]
    list = [(i**2, b) for i,b in enumerate(bias_list)]
    random_run_list = run_random_parallel(gdir,y0,list)


    # smaller temperature bias is still possible to test
    if random_run_list['temp_bias'].min()==-2:
        n = len(random_run_list)
        list = [((i+n+1)**2, b.round(3)) for i, b in enumerate(np.arange(-3,-2.05,0.05))]
        random_run_list = random_run_list.append(run_random_parallel(gdir, y0, list),ignore_index=True)

    # check for zero glacier
    max_bias = random_run_list['temp_bias'].idxmax()
    p = gdir.get_filepath('model_run', filesuffix=random_run_list.loc[max_bias,'suffix'])
    fmod = FileModel(p)

    if not fmod.volume_m3_ts().min()==0:
        n = len(random_run_list)
        list = [((i + n + 1) ** 2, b.round(3)) for i, b in enumerate(np.arange(2.05,3, 0.05))]
        random_run_list = random_run_list.append(run_random_parallel(gdir, y0, list), ignore_index=True)

    # find t_eq
    for suffix in random_run_list['suffix'].head(10).values:
        rp = gdir.get_filepath('model_run', filesuffix=suffix)
        fmod = FileModel(rp)
        try:
            t = _find_t_eq(fmod.volume_m3_ts())
            if t > t_eq:
                t_eq = t
        except:
            pass

    all = pd.DataFrame()
    for suffix in random_run_list['suffix']:
        rp = gdir.get_filepath('model_run',filesuffix=suffix)
        fmod = FileModel(rp)
        v = pd.DataFrame(fmod.volume_m3_ts()).reset_index()
        v = v[v['time']>=t_eq]
        v = v.assign(suffix=lambda x: suffix)
        all = all.append(v, ignore_index=True)
    return all
Пример #4
0
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)
Пример #5
0
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()
Пример #6
0
def generation(gdir, y0, mb_offset):
    """
    creates a pandas.DataFrame() with ALL created states. A subset of them will
    be tested later
    :param gdir:    oggm.GlacierDirectories
    :param y0:      int year of searched glaciers
    :return:        array
    """
    t_stag = 0
    # try range (2,-3) first  --> 100 runs
    bias_list = [b.round(3) for b in np.arange(-3, 2, 0.05)]
    list = [(i**2, b) for i, b in enumerate(bias_list)]
    random_run_list = _run_random_parallel(gdir, y0, list, mb_offset)

    # if temp bias = -3 does not create a glacier that exceeds boundary, we test further up to -5
    if random_run_list['temp_bias'].min() == -3:
        n = len(random_run_list)
        bias_list = [b.round(3) for b in np.arange(-5, -3, 0.05)]
        list = [((i + n + 1)**2, b) for i, b in enumerate(bias_list)]
        random_run_list = random_run_list.append(_run_random_parallel(
            gdir, y0, list, mb_offset),
                                                 ignore_index=True)

    # check for zero glacier
    max_bias = random_run_list['temp_bias'].idxmax()
    max_suffix = random_run_list.loc[max_bias, 'suffix']

    p = gdir.get_filepath('model_geometry', filesuffix=max_suffix)
    if not os.path.exists(p):
        p = os.path.join(gdir.dir, str(y0),
                         'model_geometry' + max_suffix + '.nc')
    fmod = FileModel(p)

    if not fmod.volume_m3_ts().min() == 0:
        n = len(random_run_list)
        list = [((i + n + 1)**2, b.round(3))
                for i, b in enumerate(np.arange(2.05, 3, 0.05))]
        random_run_list = random_run_list.append(_run_random_parallel(
            gdir, y0, list, mb_offset),
                                                 ignore_index=True)
    random_run_list = random_run_list.sort_values(by='temp_bias')
    return random_run_list
Пример #7
0
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)
Пример #8
0
def identification(gdir, list, ys, ye, n):
    """
    Determine glacier candidates and run them to the date of observation
    :param gdir:    oggm.GlacierDirectories
    :param df:      pd.DataFrame (volume_m3_ts() from random climate runs)
    :param ys:      starting year
    :param ye:      year of observation
    :param n:       number of candidates
    :return:
    """
    i = 0
    t_stag = 0
    # find t_stag
    for suffix in list['suffix'].values:
        if i < 10:
            try:
                rp = gdir.get_filepath('model_run', filesuffix=suffix)
                if not os.path.exists(rp):
                    rp = os.path.join(gdir.dir, str(ys),
                                      'model_run' + suffix + '.nc')
                fmod = FileModel(rp)
                t = _find_extrema(fmod.volume_m3_ts())
                if t > t_stag:
                    t_stag = t
                i = i + 1
            except:
                pass

    # make sure that t_stag is not close to the end
    if t_stag > 550:
        t_stag = 550

    df = pd.DataFrame()
    for suffix in list['suffix']:
        try:
            rp = gdir.get_filepath('model_run', filesuffix=suffix)
            if not os.path.exists(rp):
                rp = os.path.join(gdir.dir, str(ys),
                                  'model_run' + suffix + '.nc')
            fmod = FileModel(rp)
            v = pd.DataFrame(fmod.volume_m3_ts()).reset_index()
            v = v[v['time'] >= t_stag]
            v = v.assign(suffix=lambda x: suffix)
            df = df.append(v, ignore_index=True)
        except:
            pass

    indices = []
    # find nearest glacier state for each of the n volume classes (equidistant)
    for val in np.linspace(df.ts_section.min(), df.ts_section.max(), n):
        index = df.iloc[(df['ts_section'] - val).abs().argsort()][:1].index[0]
        if not index in indices:
            indices = np.append(indices, index)
    candidates = df.ix[indices]
    candidates = candidates.sort_values(['suffix', 'time'])
    candidates['fls_t0'] = None
    for suffix in candidates['suffix'].unique():
        rp = gdir.get_filepath('model_run', filesuffix=suffix)
        if not os.path.exists(rp):
            rp = os.path.join(gdir.dir, str(ys), 'model_run' + suffix + '.nc')
        fmod = FileModel(rp)
        for i, t in candidates[candidates['suffix'] ==
                               suffix]['time'].iteritems():
            fmod.run_until(t)
            candidates.at[i, 'random_model_t0'] = copy.deepcopy(fmod)

    candidates = candidates.drop_duplicates()
    fls_list = []
    for i in candidates.index:
        s = candidates.loc[int(i), 'suffix'].split('_random')[-1]
        suffix = str(ys) + '_past' + s + '_' + str(
            int(candidates.loc[int(i), 'time']))
        fls = candidates.loc[int(i), 'random_model_t0']
        fls_list.append([suffix, fls])
    return fls_list