Beispiel #1
0
def get_mean_temps_2k(rgi, return_prcp):
    from oggm import cfg, utils, workflow, tasks
    from oggm.core.massbalance import PastMassBalance

    # Initialize OGGM
    cfg.initialize()
    wd = utils.gettempdir(reset=True)
    cfg.PATHS['working_dir'] = wd
    utils.mkdir(wd, reset=True)
    cfg.PARAMS['baseline_climate'] = 'HISTALP'
    # and set standard histalp values
    cfg.PARAMS['temp_melt'] = -1.75
    cfg.PARAMS['prcp_scaling_factor'] = 1.75

    gdir = workflow.init_glacier_regions(rgidf=rgi.split('_')[0],
                                         from_prepro_level=3,
                                         prepro_border=10)[0]
    # run histalp climate on glacier!
    tasks.process_histalp_data(gdir)

    f = gdir.get_filepath('climate_historical')
    with utils.ncDataset(f) as nc:
        refhgt = nc.ref_hgt

    mb = PastMassBalance(gdir, check_calib_params=False)

    df = pd.DataFrame()
    df2 = pd.DataFrame()

    for y in np.arange(1870, 2015):
        for i in np.arange(9, 12):
            flyear = utils.date_to_floatyear(y, i)
            tmp = mb.get_monthly_climate([refhgt], flyear)[0]
            df.loc[y, i] = tmp.mean()

        if return_prcp:
            for i in np.arange(3, 6):
                flyear = utils.date_to_floatyear(y, i)
                pcp = mb.get_monthly_climate([refhgt], flyear)[3]
                df2.loc[y, i] = tmp.mean()

    t99 = df.loc[1984:2014, :].mean().mean()
    t85 = df.loc[1870:1900, :].mean().mean()
    t2k = df.loc[1900:2000, :].mean().mean()

    if return_prcp:
        p99 = df2.loc[1984:2014, :].mean().mean()
        p85 = df2.loc[1870:1900, :].mean().mean()
        p2k = df2.loc[1900:2000, :].mean().mean()
        return t85, t99, t2k, p85, p99, p2k

    return t85, t99, t2k
Beispiel #2
0
    def get_monthly_climate(self, heights, year=None):
        """Average climate information at given heights.

        Note that prcp is corrected with the precipitation factor and that
        all other biases (precipitation, temp) are applied

        Returns
        -------
        (temp, tempformelt, prcp, prcpsol)
        """
        _, m = floatyear_to_date(year)
        yrs = [date_to_floatyear(y, m) for y in self.years]
        heights = np.atleast_1d(heights)
        nh = len(heights)
        shape = (len(yrs), nh)
        temp = np.zeros(shape)
        tempformelt = np.zeros(shape)
        prcp = np.zeros(shape)
        prcpsol = np.zeros(shape)
        for i, yr in enumerate(yrs):
            t, tm, p, ps = self.mbmod.get_monthly_climate(heights, year=yr)
            temp[i, :] = t
            tempformelt[i, :] = tm
            prcp[i, :] = p
            prcpsol[i, :] = ps
        return (np.mean(temp, axis=0), np.mean(tempformelt, axis=0),
                np.mean(prcp, axis=0), np.mean(prcpsol, axis=0))
Beispiel #3
0
 def interp_m(self):
     # monthly MB
     months = np.arange(12) + 1
     interp_m = []
     for m in months:
         mb_on_h = self.hbins * 0.
         for yr in self.years:
             yr = date_to_floatyear(yr, m)
             mb_on_h += self.mbmod.get_monthly_mb(self.hbins, year=yr)
         interp_m.append(interp1d(self.hbins, mb_on_h / len(self.years)))
     return interp_m
Beispiel #4
0
 def interp_m(self):
     # monthly MB
     months = np.arange(12)+1
     interp_m = []
     for m in months:
         mb_on_h = self.hbins*0.
         for yr in self.years:
             yr = date_to_floatyear(yr, m)
             mb_on_h += self.mbmod.get_monthly_mb(self.hbins, year=yr)
         interp_m.append(interp1d(self.hbins, mb_on_h / len(self.years)))
     return interp_m
Beispiel #5
0
 def get_monthly_mb(self, heights, year=None, add_climate=False, **kwargs):
     _, m = floatyear_to_date(year)
     mb_on_h = heights * 0.
     for yr in self.years:
         yr = date_to_floatyear(yr, m)
         mb_on_h += self.mbmod.get_monthly_mb(heights, year=yr)
     mb_on_h /= len(self.years)
     if add_climate:
         t, tmelt, prcp, prcpsol = self.get_monthly_climate(heights,
                                                            year=year)
         return mb_on_h, t, tmelt, prcp, prcpsol
     return mb_on_h
Beispiel #6
0
    def test_date_to_floatyear(self):

        r = utils.date_to_floatyear(0, 1)
        self.assertEqual(r, 0)

        r = utils.date_to_floatyear(1, 1)
        self.assertEqual(r, 1)

        r = utils.date_to_floatyear([0, 1], [1, 1])
        np.testing.assert_array_equal(r, [0, 1])

        yr = utils.date_to_floatyear([1998, 1998], [6, 7])
        y, m = utils.floatyear_to_date(yr)
        np.testing.assert_array_equal(y, [1998, 1998])
        np.testing.assert_array_equal(m, [6, 7])

        yr = utils.date_to_floatyear([1998, 1998], [2, 3])
        y, m = utils.floatyear_to_date(yr)
        np.testing.assert_array_equal(y, [1998, 1998])
        np.testing.assert_array_equal(m, [2, 3])

        time = pd.date_range('1/1/1800', periods=300 * 12 - 11, freq='MS')
        yr = utils.date_to_floatyear(time.year, time.month)
        y, m = utils.floatyear_to_date(yr)
        np.testing.assert_array_equal(y, time.year)
        np.testing.assert_array_equal(m, time.month)

        myr = utils.monthly_timeseries(1800, 2099)
        y, m = utils.floatyear_to_date(myr)
        np.testing.assert_array_equal(y, time.year)
        np.testing.assert_array_equal(m, time.month)

        myr = utils.monthly_timeseries(1800, ny=300)
        y, m = utils.floatyear_to_date(myr)
        np.testing.assert_array_equal(y, time.year)
        np.testing.assert_array_equal(m, time.month)

        time = pd.period_range('0001-01', '6000-1', freq='M')
        myr = utils.monthly_timeseries(1, 6000)
        y, m = utils.floatyear_to_date(myr)
        np.testing.assert_array_equal(y, time.year)
        np.testing.assert_array_equal(m, time.month)

        time = pd.period_range('0001-01', '6000-12', freq='M')
        myr = utils.monthly_timeseries(1, 6000, include_last_year=True)
        y, m = utils.floatyear_to_date(myr)
        np.testing.assert_array_equal(y, time.year)
        np.testing.assert_array_equal(m, time.month)

        with self.assertRaises(ValueError):
            utils.monthly_timeseries(1)
Beispiel #7
0
 def get_monthly_mb(self, heights, year=None):
     ryr, m = floatyear_to_date(year)
     ryr = date_to_floatyear(self.get_state_yr(ryr), m)
     return self.mbmod.get_monthly_mb(heights, year=ryr)
Beispiel #8
0
 def get_monthly_mb(self, heights, year=None, fl_id=None):
     ryr, m = floatyear_to_date(year)
     ryr = date_to_floatyear(self.get_state_yr(ryr), m)
     return self.mbmod.get_monthly_mb(heights, year=ryr)
Beispiel #9
0
def get_mean_temps_eq(rgi, histalp_storage, comit_storage, ensmembers):
    from oggm import cfg, utils, GlacierDirectory
    from oggm.core.massbalance import MultipleFlowlineMassBalance
    from oggm.core.flowline import FileModel
    import shutil


    # 1. get mean surface heights
    df85 = pd.DataFrame([])
    df99 = pd.DataFrame([])
    for i in range(ensmembers):
        fnc1 = os.path.join(comit_storage, rgi,
                            'model_run_commitment1885_{:02d}.nc'.format(i))
        fnc2 = os.path.join(comit_storage, rgi,
                            'model_run_commitment1999_{:02d}.nc'.format(i))
        tmpmod1 = FileModel(fnc1)
        tmpmod2 = FileModel(fnc2)
        for j in np.arange(270, 301):
            tmpmod1.run_until(j)
            df85.loc[:, '{}{}'.format(i, j)] = tmpmod1.fls[-1].surface_h
            tmpmod2.run_until(j)
            df99.loc[:, '{}{}'.format(i, j)] = tmpmod2.fls[-1].surface_h

    meanhgt99 = df99.mean(axis=1).values
    meanhgt85 = df85.mean(axis=1).values

    # 2. get the climate
    # Initialize OGGM
    cfg.initialize()
    wd = utils.gettempdir(reset=True)
    cfg.PATHS['working_dir'] = wd
    utils.mkdir(wd, reset=True)
    cfg.PARAMS['baseline_climate'] = 'HISTALP'
    # and set standard histalp values
    cfg.PARAMS['temp_melt'] = -1.75

    i = 0
    storage_dir = os.path.join(histalp_storage, rgi, '{:02d}'.format(i),
                               rgi[:8], rgi[:11], rgi)
    new_dir = os.path.join(cfg.PATHS['working_dir'], 'per_glacier',
                           rgi[:8], rgi[:11], rgi)
    shutil.copytree(storage_dir, new_dir)
    gdir = GlacierDirectory(rgi)
    mb = MultipleFlowlineMassBalance(gdir, filename='climate_monthly',
                                     check_calib_params=False)
    # need to do the above for every ensemble member if I consider PRECIP!
    # and set cfg.PARAMS['prcp_scaling_factor'] = pdict['prcp_scaling_factor']

    df99_2 = pd.DataFrame()
    df85_2 = pd.DataFrame()
    for i in np.arange(9, 12):
        for y in np.arange(1870, 1901):
            flyear = utils.date_to_floatyear(y, i)
            tmp = mb.flowline_mb_models[-1].get_monthly_climate(meanhgt85,
                                                                flyear)[0]
            df85_2.loc[y, i] = tmp.mean()
        for y in np.arange(1984, 2015):
            tmp = mb.flowline_mb_models[-1].get_monthly_climate(meanhgt99,
                                                                flyear)[0]
            df99_2.loc[y, i] = tmp.mean()

    t99 = df99_2.mean().mean()
    t85 = df85_2.mean().mean()
    return t85, t99
Beispiel #10
0
def test_monthly_glacier_massbalance(gdir):
    # TODO: problem with that, monthly and annual MB not exactly the same!!!
    # I think there is a problem with SEC_IN_MONTH/SEC_IN_YEAR ...

    # do this for all model types
    # ONLY TEST it for ERA5dr or ERA5_daily!!!
    for climate in ['ERA5dr', 'ERA5_daily']:
        for mb_type in ['mb_monthly', 'mb_daily', 'mb_real_daily']:
            for grad_type in ['cte', 'var_an_cycle']:
                if grad_type == 'var_an_cycle':
                    fail_err_4 = ((mb_type == 'mb_monthly')
                                  and (climate == 'CRU'))
                    mu_star_opt = mu_star_opt_var
                else:
                    fail_err_4 = False
                    mu_star_opt = mu_star_opt_cte
                if climate == 'ERA5dr':
                    cfg.PARAMS['baseline_climate'] = 'ERA5dr'
                    oggm.shop.ecmwf.process_ecmwf_data(gdir, dataset="ERA5dr")
                elif climate == 'ERA5_daily':
                    process_era5_daily_data(gdir)
                    cfg.PARAMS['baseline_climate'] = 'ERA5_daily'
                else:
                    tasks.process_climate_data(gdir)
                    pass
                # mb_type ='mb_daily'
                fail_err_1 = (mb_type == 'mb_daily') and (climate != 'ERA5dr')
                fail_err_2 = ((mb_type == 'mb_monthly')
                              and (climate == 'ERA5_daily'))
                fail_err_3 = ((mb_type == 'mb_real_daily')
                              and (climate != 'ERA5_daily'))

                if fail_err_1 or fail_err_2 or fail_err_3 or fail_err_4:
                    with pytest.raises(InvalidParamsError):
                        mb_mod = mb_modules(gdir,
                                            mu_star_opt[mb_type],
                                            mb_type=mb_type,
                                            prcp_fac=pf,
                                            t_solid=0,
                                            t_liq=2,
                                            t_melt=0,
                                            default_grad=-0.0065,
                                            bias=0,
                                            grad_type=grad_type)
                else:
                    # but this is just a test for reproducibility!
                    mb_mod = mb_modules(gdir,
                                        mu_star_opt[mb_type],
                                        mb_type=mb_type,
                                        prcp_fac=pf,
                                        t_solid=0,
                                        t_liq=2,
                                        t_melt=0,
                                        default_grad=-0.0065,
                                        bias=0,
                                        grad_type=grad_type)
                    hgts, widths = gdir.get_inversion_flowline_hw()

                    rho = 900  # ice density
                    yrp = [1980, 2018]
                    for i, yr in enumerate(np.arange(yrp[0], yrp[1] + 1)):
                        my_mon_mb_on_h = 0.
                        dayofyear = 0
                        for m in np.arange(12):
                            yrm = utils.date_to_floatyear(yr, m + 1)
                            _, dayofmonth = monthrange(yr, m + 1)
                            dayofyear += dayofmonth
                            tmp = (mb_mod.get_monthly_mb(hgts, yrm) *
                                   dayofmonth * SEC_IN_DAY * rho)
                            my_mon_mb_on_h += tmp
                        my_an_mb_on_h = (mb_mod.get_annual_mb(hgts, yr) *
                                         dayofyear * SEC_IN_DAY * rho)

                        # these large errors might come from the problematic of
                        # different amount of days in a year?
                        # or maybe it just does not fit ...
                        assert_allclose(np.mean(my_an_mb_on_h -
                                                my_mon_mb_on_h),
                                        0,
                                        atol=100)