Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
 def to_optimize(x):
     # For backwards compat
     _fd = 1.9e-24 * x[0]
     glen_a = (cfg.N + 2) * _fd / 2.0
     fs = 5.7e-20 * x[1]
     v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
     return (v - ref_v) ** 2
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
 def to_optimize(x):
     tmp_ = np.zeros(len(ref_gdirs))
     glen_a = cfg.A * x[0]
     for i, gdir in enumerate(ref_gdirs):
         v, a = invert_parabolic_bed(gdir, glen_a=glen_a, fs=0.0, write=False)
         tmp_[i] = v / a
     return utils.rmsd(tmp_, ref_thickness_m)
Ejemplo n.º 5
0
Archivo: itmix.py Proyecto: Enaith/oggm
 def to_optimize(x):
     tmp_ = np.zeros(len(ref_gdirs))
     glen_a = cfg.A * x[0]
     for i, gdir in enumerate(ref_gdirs):
         v, a = invert_parabolic_bed(gdir, glen_a=glen_a,
                                     fs=0., write=False)
         tmp_[i] = v / a
     return utils.rmsd(tmp_, ref_thickness_m)
Ejemplo n.º 6
0
 def to_optimize(x):
     # For backwards compat
     _fd = 1.9e-24 * x[0]
     glen_a = (cfg.N+2) * _fd / 2.
     fs = 5.7e-20 * x[1]
     v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                           glen_a=glen_a)
     return (v - ref_v)**2
Ejemplo n.º 7
0
Archivo: itmix.py Proyecto: Enaith/oggm
 def to_optimize(x):
     tmp_vols = np.zeros(len(ref_gdirs))
     glen_a = cfg.A * x[0]
     for i, gdir in enumerate(ref_gdirs):
         v, _ = invert_parabolic_bed(gdir, glen_a=glen_a,
                                     fs=0., write=False)
         tmp_vols[i] = v * 1e-9
     return utils.rmsd(tmp_vols, ref_volume_km3)
Ejemplo n.º 8
0
    def test_ideal_glacier(self):

        # we are making a
        glen_a = cfg.A * 1
        from oggm.core.models import flowline, massbalance

        gdir = utils.GlacierDirectory(self.rgin, base_dir=self.testdir)

        fls = self._parabolic_bed()
        mbmod = massbalance.ConstantBalanceModel(2800.)
        model = flowline.FluxBasedModel(fls, mb_model=mbmod, glen_a=glen_a)
        model.run_until_equilibrium()

        # from dummy bed
        map_dx = 100.
        towrite = []
        for fl in model.fls:
            # Distance between two points
            dx = fl.dx * map_dx
            # Widths
            widths = fl.widths * map_dx
            # Heights
            hgt = fl.surface_h
            # Flux
            mb = mbmod.get_mb(hgt) * cfg.SEC_IN_YEAR * cfg.RHO
            fl.flux = np.zeros(len(fl.surface_h))
            fl.set_apparent_mb(mb)
            flux = fl.flux * (map_dx**2) / cfg.SEC_IN_YEAR / cfg.RHO
            pok = np.nonzero(widths > 10.)
            widths = widths[pok]
            hgt = hgt[pok]
            flux = flux[pok]
            angle = np.arctan(-np.gradient(hgt, dx))  # beware the minus sign
            # Clip flux to 0
            assert not np.any(flux < -0.1)
            # add to output
            cl_dic = dict(dx=dx,
                          flux=flux,
                          width=widths,
                          hgt=hgt,
                          slope_angle=angle,
                          is_last=True)
            towrite.append(cl_dic)

        # Write out
        gdir.write_pickle(towrite, 'inversion_input', div_id=1)
        v, a = inversion.invert_parabolic_bed(gdir, glen_a=glen_a)
        v_km3 = v * 1e-9
        a_km2 = np.sum(widths * dx) * 1e-6
        v_vas = 0.034 * (a_km2**1.375)

        np.testing.assert_allclose(v, model.volume_m3, rtol=0.01)

        cl = gdir.read_pickle('inversion_output', div_id=1)[0]
        assert utils.rmsd(cl['thick'],
                          model.fls[0].thick[:len(cl['thick'])]) < 10.
Ejemplo n.º 9
0
    def test_distribute(self):

        hef_file = get_demo_file("Hintereisferner.shp")
        entity = gpd.GeoDataFrame.from_file(hef_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)
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.process_histalp_nonparallel([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file("mbdata_RGI40-11.00897.csv")
        mbdf = pd.read_csv(hef_file).set_index("YEAR")
        t_star, bias, prcp_fac = climate.t_star_from_refmb(gdir, mbdf["ANNUAL_BALANCE"])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias, prcp_fac=prcp_fac)

        # OK. Values from Fischer and Kuhn 2013
        # Area: 8.55
        # meanH = 67+-7
        # Volume = 0.573+-0.063
        # maxH = 242+-13
        inversion.prepare_for_inversion(gdir)

        ref_v = 0.573 * 1e9

        def to_optimize(x):
            glen_a = cfg.A * x[0]
            fs = cfg.FS * x[1]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
            return (v - ref_v) ** 2

        import scipy.optimize as optimization

        out = optimization.minimize(to_optimize, [1, 1], bounds=((0.01, 10), (0.01, 10)), tol=1e-1)["x"]
        glen_a = cfg.A * out[0]
        fs = cfg.FS * out[1]
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a, write=True)
        np.testing.assert_allclose(ref_v, v)

        inversion.distribute_thickness(gdir, how="per_altitude", add_nc_name=True)
        inversion.distribute_thickness(gdir, how="per_interpolation", add_slope=False, add_nc_name=True)

        grids_file = gdir.get_filepath("gridded_data")
        with netCDF4.Dataset(grids_file) as nc:
            t1 = nc.variables["thickness_per_altitude"][:]
            t2 = nc.variables["thickness_per_interpolation"][:]

        np.testing.assert_allclose(np.sum(t1), np.sum(t2))
        if not HAS_NEW_GDAL:
            np.testing.assert_allclose(np.max(t1), np.max(t2), atol=30)
Ejemplo n.º 10
0
    def test_ideal_glacier(self):

        # we are making a
        glen_a = cfg.A * 1
        from oggm.core.models import flowline, massbalance

        gdir = utils.GlacierDirectory(self.rgin, base_dir=self.testdir)

        fls = self._parabolic_bed()
        mbmod = massbalance.ConstantBalanceModel(2800.)
        model = flowline.FluxBasedModel(fls, mb_model=mbmod, glen_a=glen_a)
        model.run_until_equilibrium()

        # from dummy bed
        map_dx = 100.
        towrite = []
        for fl in model.fls:
            # Distance between two points
            dx = fl.dx * map_dx
            # Widths
            widths = fl.widths * map_dx
            # Heights
            hgt = fl.surface_h
            # Flux
            mb = mbmod.get_mb(hgt) * cfg.SEC_IN_YEAR * cfg.RHO
            fl.flux = np.zeros(len(fl.surface_h))
            fl.set_apparent_mb(mb)
            flux = fl.flux * (map_dx**2) / cfg.SEC_IN_YEAR / cfg.RHO
            pok = np.nonzero(widths > 10.)
            widths = widths[pok]
            hgt = hgt[pok]
            flux = flux[pok]
            angle = np.arctan(-np.gradient(hgt, dx))  # beware the minus sign
            # Clip flux to 0
            assert not np.any(flux < -0.1)
            # add to output
            cl_dic = dict(dx=dx, flux=flux, width=widths, hgt=hgt,
                          slope_angle=angle, is_last=True)
            towrite.append(cl_dic)

        # Write out
        gdir.write_pickle(towrite, 'inversion_input', div_id=1)
        v, a = inversion.invert_parabolic_bed(gdir, glen_a=glen_a)
        v_km3 = v * 1e-9
        a_km2 = np.sum(widths * dx) * 1e-6
        v_vas = 0.034*(a_km2**1.375)

        np.testing.assert_allclose(v, model.volume_m3, rtol=0.01)

        cl = gdir.read_pickle('inversion_output', div_id=1)[0]
        assert utils.rmsd(cl['thick'], model.fls[0].thick[:len(cl['thick'])]) < 10.
Ejemplo n.º 11
0
 def to_optimize(x):
     glen_a = cfg.A * x[0]
     fs = 0.
     v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
     return (v - ref_v)**2
Ejemplo n.º 12
0
    def test_invert_hef_nofs(self):

        hef_file = get_demo_file('Hintereisferner.shp')
        rgidf = gpd.GeoDataFrame.from_file(hef_file)

        # loop because for some reason indexing wont work
        for index, entity in rgidf.iterrows():
            gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
        gis.define_glacier_region(gdir, entity=entity)
        gis.glacier_masks(gdir)
        centerlines.compute_centerlines(gdir)
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.distribute_climate_data([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file('mbdata_RGI40-11.00897.csv')
        mbdf = pd.read_csv(hef_file).set_index('YEAR')
        t_star, bias = climate.t_star_from_refmb(gdir, mbdf['ANNUAL_BALANCE'])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias)

        # OK. Values from Fischer and Kuhn 2013
        # Area: 8.55
        # meanH = 67+-7
        # Volume = 0.573+-0.063
        # maxH = 242+-13

        inversion.prepare_for_inversion(gdir)

        ref_v = 0.573 * 1e9

        def to_optimize(x):
            glen_a = cfg.A * x[0]
            fs = 0.
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
            return (v - ref_v)**2

        import scipy.optimize as optimization
        out = optimization.minimize(to_optimize, [1],
                                    bounds=((0.00001, 100000), ),
                                    tol=1e-4)['x']

        self.assertTrue(out[0] > 0.1)
        self.assertTrue(out[0] < 10)

        glen_a = cfg.A * out[0]
        fs = 0.
        v, _ = inversion.invert_parabolic_bed(gdir,
                                              fs=fs,
                                              glen_a=glen_a,
                                              write=True)
        np.testing.assert_allclose(ref_v, v)

        lens = [
            len(gdir.read_pickle('centerlines', div_id=i)) for i in [1, 2, 3]
        ]
        pid = np.argmax(lens) + 1
        cls = gdir.read_pickle('inversion_output', div_id=pid)
        fls = gdir.read_pickle('inversion_flowlines', div_id=pid)
        maxs = 0.
        for cl, fl in zip(cls, fls):
            thick = cl['thick']
            _max = np.max(thick)
            if _max > maxs:
                maxs = _max
        atol = 30 if HAS_NEW_GDAL else 10
        np.testing.assert_allclose(242, maxs, atol=atol)

        # check that its not tooo sensitive to the dx
        cfg.PARAMS['flowline_dx'] = 1.
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.distribute_climate_data([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file('mbdata_RGI40-11.00897.csv')
        mbdf = pd.read_csv(hef_file).set_index('YEAR')
        t_star, bias = climate.t_star_from_refmb(gdir, mbdf['ANNUAL_BALANCE'])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias)
        inversion.prepare_for_inversion(gdir)
        v, _ = inversion.invert_parabolic_bed(gdir,
                                              fs=fs,
                                              glen_a=glen_a,
                                              write=True)

        np.testing.assert_allclose(ref_v, v, rtol=0.02)
        cls = gdir.read_pickle('inversion_output', div_id=pid)
        maxs = 0.
        for cl in cls:
            thick = cl['thick']
            _max = np.max(thick)
            if _max > maxs:
                maxs = _max

        np.testing.assert_allclose(242, maxs, atol=atol)
Ejemplo n.º 13
0
    def test_invert_hef(self):

        hef_file = get_demo_file('Hintereisferner.shp')
        rgidf = gpd.GeoDataFrame.from_file(hef_file)

        # loop because for some reason indexing wont work
        for index, entity in rgidf.iterrows():
            gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
        gis.define_glacier_region(gdir, entity=entity)
        gis.glacier_masks(gdir)
        centerlines.compute_centerlines(gdir)
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.distribute_climate_data([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file('mbdata_RGI40-11.00897.csv')
        mbdf = pd.read_csv(hef_file).set_index('YEAR')
        t_star, bias = climate.t_star_from_refmb(gdir, mbdf['ANNUAL_BALANCE'])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias)

        # OK. Values from Fischer and Kuhn 2013
        # Area: 8.55
        # meanH = 67+-7
        # Volume = 0.573+-0.063
        # maxH = 242+-13
        inversion.prepare_for_inversion(gdir)

        lens = [
            len(gdir.read_pickle('centerlines', div_id=i)) for i in [1, 2, 3]
        ]
        pid = np.argmax(lens) + 1

        # Check how many clips:
        cls = gdir.read_pickle('inversion_input', div_id=pid)
        nabove = 0
        maxs = 0.
        npoints = 0.
        for cl in cls:
            # Clip slope to avoid negative and small slopes
            slope = cl['slope_angle']
            nm = np.where(slope < np.deg2rad(2.))
            nabove += len(nm[0])
            npoints += len(slope)
            _max = np.max(slope)
            if _max > maxs:
                maxs = _max

        self.assertTrue(nabove == 0)
        self.assertTrue(np.rad2deg(maxs) < 40.)

        ref_v = 0.573 * 1e9

        def to_optimize(x):
            glen_a = cfg.A * x[0]
            fs = cfg.FS * x[1]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
            return (v - ref_v)**2

        import scipy.optimize as optimization
        out = optimization.minimize(to_optimize, [1, 1],
                                    bounds=((0.01, 10), (0.01, 10)),
                                    tol=1e-4)['x']
        self.assertTrue(out[0] > 0.1)
        self.assertTrue(out[1] > 0.1)
        self.assertTrue(out[0] < 1.1)
        self.assertTrue(out[1] < 1.1)
        glen_a = cfg.A * out[0]
        fs = cfg.FS * out[1]
        v, _ = inversion.invert_parabolic_bed(gdir,
                                              fs=fs,
                                              glen_a=glen_a,
                                              write=True)
        np.testing.assert_allclose(ref_v, v)

        lens = [
            len(gdir.read_pickle('centerlines', div_id=i)) for i in [1, 2, 3]
        ]
        pid = np.argmax(lens) + 1
        cls = gdir.read_pickle('inversion_output', div_id=pid)
        fls = gdir.read_pickle('inversion_flowlines', div_id=pid)
        maxs = 0.
        for cl, fl in zip(cls, fls):
            thick = cl['thick']
            _max = np.max(thick)
            if _max > maxs:
                maxs = _max

        np.testing.assert_allclose(242, maxs, atol=21)
Ejemplo n.º 14
0
 def to_optimize(x):
     glen_a = cfg.A * x[0]
     fs = cfg.FS * x[1]
     v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
     return (v - ref_v) ** 2
Ejemplo n.º 15
0
    def test_invert_hef(self):

        hef_file = get_demo_file("Hintereisferner.shp")
        entity = gpd.GeoDataFrame.from_file(hef_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)
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.process_histalp_nonparallel([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file("mbdata_RGI40-11.00897.csv")
        mbdf = pd.read_csv(hef_file).set_index("YEAR")
        t_star, bias, prcp_fac = climate.t_star_from_refmb(gdir, mbdf["ANNUAL_BALANCE"])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias, prcp_fac=prcp_fac)

        # OK. Values from Fischer and Kuhn 2013
        # Area: 8.55
        # meanH = 67+-7
        # Volume = 0.573+-0.063
        # maxH = 242+-13
        inversion.prepare_for_inversion(gdir)

        lens = [len(gdir.read_pickle("centerlines", div_id=i)) for i in [1, 2, 3]]
        pid = np.argmax(lens) + 1

        # Check how many clips:
        cls = gdir.read_pickle("inversion_input", div_id=pid)
        nabove = 0
        maxs = 0.0
        npoints = 0.0
        for cl in cls:
            # Clip slope to avoid negative and small slopes
            slope = cl["slope_angle"]
            nm = np.where(slope < np.deg2rad(2.0))
            nabove += len(nm[0])
            npoints += len(slope)
            _max = np.max(slope)
            if _max > maxs:
                maxs = _max

        self.assertTrue(nabove == 0)
        self.assertTrue(np.rad2deg(maxs) < 40.0)

        ref_v = 0.573 * 1e9

        def to_optimize(x):
            glen_a = cfg.A * x[0]
            fs = cfg.FS * x[1]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
            return (v - ref_v) ** 2

        import scipy.optimize as optimization

        out = optimization.minimize(to_optimize, [1, 1], bounds=((0.01, 10), (0.01, 10)), tol=1e-4)["x"]
        self.assertTrue(out[0] > 0.1)
        self.assertTrue(out[1] > 0.1)
        self.assertTrue(out[0] < 1.1)
        self.assertTrue(out[1] < 1.1)
        glen_a = cfg.A * out[0]
        fs = cfg.FS * out[1]
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a, write=True)
        np.testing.assert_allclose(ref_v, v)

        lens = [len(gdir.read_pickle("centerlines", div_id=i)) for i in [1, 2, 3]]
        pid = np.argmax(lens) + 1
        cls = gdir.read_pickle("inversion_output", div_id=pid)
        fls = gdir.read_pickle("inversion_flowlines", div_id=pid)
        maxs = 0.0
        for cl, fl in zip(cls, fls):
            thick = cl["thick"]
            _max = np.max(thick)
            if _max > maxs:
                maxs = _max

        np.testing.assert_allclose(242, maxs, atol=40)
Ejemplo n.º 16
0
    def test_invert_hef_nofs(self):

        hef_file = get_demo_file('Hintereisferner.shp')
        rgidf = gpd.GeoDataFrame.from_file(hef_file)

        # loop because for some reason indexing wont work
        for index, entity in rgidf.iterrows():
            gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
        gis.define_glacier_region(gdir, entity=entity)
        gis.glacier_masks(gdir)
        centerlines.compute_centerlines(gdir)
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.distribute_climate_data([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file('mbdata_RGI40-11.00897.csv')
        mbdf = pd.read_csv(hef_file).set_index('YEAR')
        t_star, bias = climate.t_star_from_refmb(gdir, mbdf['ANNUAL_BALANCE'])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias)

        # OK. Values from Fischer and Kuhn 2013
        # Area: 8.55
        # meanH = 67+-7
        # Volume = 0.573+-0.063
        # maxH = 242+-13

        inversion.prepare_for_inversion(gdir)

        ref_v = 0.573 * 1e9

        def to_optimize(x):
            glen_a = cfg.A * x[0]
            fs = 0.
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                                  glen_a=glen_a)
            return (v - ref_v)**2

        import scipy.optimize as optimization
        out = optimization.minimize(to_optimize, [1],
                                    bounds=((0.00001, 100000),),
                                    tol=1e-4)['x']

        self.assertTrue(out[0] > 0.1)
        self.assertTrue(out[0] < 10)

        glen_a = cfg.A * out[0]
        fs = 0.
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                              glen_a=glen_a,
                                              write=True)
        np.testing.assert_allclose(ref_v, v)

        lens = [len(gdir.read_pickle('centerlines', div_id=i)) for i in [1,2,3]]
        pid = np.argmax(lens) + 1
        cls = gdir.read_pickle('inversion_output', div_id=pid)
        fls = gdir.read_pickle('inversion_flowlines', div_id=pid)
        maxs = 0.
        for cl, fl in zip(cls, fls):
            thick = cl['thick']
            _max = np.max(thick)
            if _max > maxs:
                maxs = _max
        atol = 30 if HAS_NEW_GDAL else 10
        np.testing.assert_allclose(242, maxs, atol=atol)

        # check that its not tooo sensitive to the dx
        cfg.PARAMS['flowline_dx'] = 1.
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.distribute_climate_data([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file('mbdata_RGI40-11.00897.csv')
        mbdf = pd.read_csv(hef_file).set_index('YEAR')
        t_star, bias = climate.t_star_from_refmb(gdir, mbdf['ANNUAL_BALANCE'])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias)
        inversion.prepare_for_inversion(gdir)
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                              glen_a=glen_a,
                                              write=True)

        np.testing.assert_allclose(ref_v, v, rtol=0.02)
        cls = gdir.read_pickle('inversion_output', div_id=pid)
        maxs = 0.
        for cl in cls:
            thick = cl['thick']
            _max = np.max(thick)
            if _max > maxs:
                maxs = _max

        np.testing.assert_allclose(242, maxs, atol=atol)
Ejemplo n.º 17
0
def init_hef(reset=False, border=40, invert_with_sliding=True):

    from oggm.core.preprocessing import gis, centerlines, geometry
    from oggm.core.preprocessing import climate, inversion
    import oggm
    import oggm.cfg as cfg
    from oggm.utils import get_demo_file

    # test directory
    testdir = TESTDIR_BASE + '_border{}'.format(border)
    if not invert_with_sliding:
        testdir += '_withoutslide'
    if not os.path.exists(testdir):
        os.makedirs(testdir)
        reset = True
    if not os.path.exists(os.path.join(testdir, 'RGI40-11.00897')):
        reset = True
    if not os.path.exists(os.path.join(testdir, 'RGI40-11.00897',
                                       'inversion_params.pkl')):
        reset = True

    # Init
    cfg.initialize()
    cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
    cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')
    cfg.PARAMS['border'] = border

    hef_file = get_demo_file('Hintereisferner.shp')
    entity = gpd.GeoDataFrame.from_file(hef_file).iloc[0]
    gdir = oggm.GlacierDirectory(entity, base_dir=testdir, reset=reset)

    if not reset:
        return gdir

    gis.define_glacier_region(gdir, entity=entity)
    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.process_histalp_nonparallel([gdir])
    climate.mu_candidates(gdir, div_id=0)
    mbdf = gdir.get_ref_mb_data()['ANNUAL_BALANCE']
    res = climate.t_star_from_refmb(gdir, mbdf)
    climate.local_mustar_apparent_mb(gdir, tstar=res['t_star'][-1],
                                     bias=res['bias'][-1],
                                     prcp_fac=res['prcp_fac'])

    inversion.prepare_for_inversion(gdir)
    ref_v = 0.573 * 1e9

    if invert_with_sliding:
        def to_optimize(x):
            # For backwards compat
            _fd = 1.9e-24 * x[0]
            glen_a = (cfg.N+2) * _fd / 2.
            fs = 5.7e-20 * x[1]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                                  glen_a=glen_a)
            return (v - ref_v)**2

        out = optimization.minimize(to_optimize, [1, 1],
                                    bounds=((0.01, 10), (0.01, 10)),
                                    tol=1e-4)['x']
        _fd = 1.9e-24 * out[0]
        glen_a = (cfg.N+2) * _fd / 2.
        fs = 5.7e-20 * out[1]
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                              glen_a=glen_a,
                                              write=True)
    else:
        def to_optimize(x):
            glen_a = cfg.A * x[0]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=0.,
                                                  glen_a=glen_a)
            return (v - ref_v)**2

        out = optimization.minimize(to_optimize, [1],
                                    bounds=((0.01, 10),),
                                    tol=1e-4)['x']
        glen_a = cfg.A * out[0]
        fs = 0.
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                              glen_a=glen_a,
                                              write=True)
    d = dict(fs=fs, glen_a=glen_a)
    d['factor_glen_a'] = out[0]
    try:
        d['factor_fs'] = out[1]
    except IndexError:
        d['factor_fs'] = 0.
    gdir.write_pickle(d, 'inversion_params')

    inversion.distribute_thickness(gdir, how='per_altitude',
                                   add_nc_name=True)
    inversion.distribute_thickness(gdir, how='per_interpolation',
                                   add_slope=False, smooth=False,
                                   add_nc_name=True)

    return gdir
Ejemplo n.º 18
0
Archivo: itmix.py Proyecto: Enaith/oggm
 def to_optimize(x):
     glen_a = cfg.A * x[0]
     v, a = invert_parabolic_bed(gdir, glen_a=glen_a, fs=0.,
                                 write=False)
     return utils.rmsd(v / a, gtd_df['ref_thickness_m'].loc[gdir.rgi_id])
Ejemplo n.º 19
0
def init_hef(reset=False, border=40, invert_with_sliding=True):

    # test directory
    testdir = TESTDIR_BASE + '_border{}'.format(border)
    if not invert_with_sliding:
        testdir += '_withoutslide'
    if not os.path.exists(testdir):
        os.makedirs(testdir)
        reset = True
    if not os.path.exists(os.path.join(testdir, 'RGI40-11.00897')):
        reset = True
    if not os.path.exists(os.path.join(testdir, 'RGI40-11.00897',
                                       'inversion_params.pkl')):
        reset = True

    # Init
    cfg.initialize()
    cfg.set_divides_db(get_demo_file('HEF_divided.shp'))
    cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
    cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')
    cfg.PARAMS['border'] = border

    # loop because for some reason indexing wont work
    hef_file = get_demo_file('Hintereisferner.shp')
    rgidf = gpd.GeoDataFrame.from_file(hef_file)
    for index, entity in rgidf.iterrows():
        gdir = oggm.GlacierDirectory(entity, base_dir=testdir, reset=reset)

    if not reset:
        return gdir

    gis.define_glacier_region(gdir, entity=entity)
    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.distribute_climate_data([gdir])
    climate.mu_candidates(gdir, div_id=0)
    hef_file = get_demo_file('mbdata_RGI40-11.00897.csv')
    mbdf = pd.read_csv(hef_file).set_index('YEAR')
    t_star, bias = climate.t_star_from_refmb(gdir, mbdf['ANNUAL_BALANCE'])
    climate.local_mustar_apparent_mb(gdir, tstar=t_star[-1], bias=bias[-1])

    inversion.prepare_for_inversion(gdir)
    ref_v = 0.573 * 1e9

    if invert_with_sliding:
        def to_optimize(x):
            # For backwards compat
            _fd = 1.9e-24 * x[0]
            glen_a = (cfg.N+2) * _fd / 2.
            fs = 5.7e-20 * x[1]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                                  glen_a=glen_a)
            return (v - ref_v)**2

        import scipy.optimize as optimization
        out = optimization.minimize(to_optimize, [1, 1],
                                    bounds=((0.01, 10), (0.01, 10)),
                                    tol=1e-4)['x']
        _fd = 1.9e-24 * out[0]
        glen_a = (cfg.N+2) * _fd / 2.
        fs = 5.7e-20 * out[1]
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                              glen_a=glen_a,
                                              write=True)
    else:
        def to_optimize(x):
            glen_a = cfg.A * x[0]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=0.,
                                                  glen_a=glen_a)
            return (v - ref_v)**2

        import scipy.optimize as optimization
        out = optimization.minimize(to_optimize, [1],
                                    bounds=((0.01, 10),),
                                    tol=1e-4)['x']
        glen_a = cfg.A * out[0]
        fs = 0.
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                              glen_a=glen_a,
                                              write=True)
    d = dict(fs=fs, glen_a=glen_a)
    d['factor_glen_a'] = out[0]
    try:
        d['factor_fs'] = out[1]
    except IndexError:
        d['factor_fs'] = 0.
    gdir.write_pickle(d, 'inversion_params')

    return gdir
Ejemplo n.º 20
0
    def test_distribute(self):

        hef_file = get_demo_file('Hintereisferner.shp')
        entity = gpd.GeoDataFrame.from_file(hef_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)
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.distribute_climate_data([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file('mbdata_RGI40-11.00897.csv')
        mbdf = pd.read_csv(hef_file).set_index('YEAR')
        t_star, bias = climate.t_star_from_refmb(gdir, mbdf['ANNUAL_BALANCE'])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias)

        # OK. Values from Fischer and Kuhn 2013
        # Area: 8.55
        # meanH = 67+-7
        # Volume = 0.573+-0.063
        # maxH = 242+-13
        inversion.prepare_for_inversion(gdir)

        ref_v = 0.573 * 1e9

        def to_optimize(x):
            glen_a = cfg.A * x[0]
            fs = cfg.FS * x[1]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
            return (v - ref_v)**2

        import scipy.optimize as optimization
        out = optimization.minimize(to_optimize, [1, 1],
                                    bounds=((0.01, 10), (0.01, 10)),
                                    tol=1e-1)['x']
        glen_a = cfg.A * out[0]
        fs = cfg.FS * out[1]
        v, _ = inversion.invert_parabolic_bed(gdir,
                                              fs=fs,
                                              glen_a=glen_a,
                                              write=True)
        np.testing.assert_allclose(ref_v, v)

        inversion.distribute_thickness(gdir,
                                       how='per_altitude',
                                       add_nc_name=True)
        inversion.distribute_thickness(gdir,
                                       how='per_interpolation',
                                       add_slope=False,
                                       add_nc_name=True)

        grids_file = gdir.get_filepath('gridded_data')
        with netCDF4.Dataset(grids_file) as nc:
            t1 = nc.variables['thickness_per_altitude'][:]
            t2 = nc.variables['thickness_per_interpolation'][:]

        np.testing.assert_allclose(np.sum(t1), np.sum(t2))
        if not HAS_NEW_GDAL:
            np.testing.assert_allclose(np.max(t1), np.max(t2), atol=30)
Ejemplo n.º 21
0
def init_hef(reset=False, border=40, invert_with_sliding=True):

    from oggm.core.preprocessing import gis, centerlines, geometry
    from oggm.core.preprocessing import climate, inversion
    import oggm
    import oggm.cfg as cfg
    from oggm.utils import get_demo_file

    # test directory
    testdir = TESTDIR_BASE + "_border{}".format(border)
    if not invert_with_sliding:
        testdir += "_withoutslide"
    if not os.path.exists(testdir):
        os.makedirs(testdir)
        reset = True
    if not os.path.exists(os.path.join(testdir, "RGI40-11.00897")):
        reset = True
    if not os.path.exists(os.path.join(testdir, "RGI40-11.00897", "inversion_params.pkl")):
        reset = True

    # Init
    cfg.initialize()
    cfg.PATHS["dem_file"] = get_demo_file("hef_srtm.tif")
    cfg.PATHS["climate_file"] = get_demo_file("histalp_merged_hef.nc")
    cfg.PARAMS["border"] = border

    hef_file = get_demo_file("Hintereisferner.shp")
    entity = gpd.GeoDataFrame.from_file(hef_file).iloc[0]
    gdir = oggm.GlacierDirectory(entity, base_dir=testdir, reset=reset)

    if not reset:
        return gdir

    gis.define_glacier_region(gdir, entity=entity)
    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.process_histalp_nonparallel([gdir])
    climate.mu_candidates(gdir, div_id=0)
    hef_file = get_demo_file("mbdata_RGI40-11.00897.csv")
    mbdf = pd.read_csv(hef_file).set_index("YEAR")
    t_star, bias, prcp_fac = climate.t_star_from_refmb(gdir, mbdf["ANNUAL_BALANCE"])
    climate.local_mustar_apparent_mb(gdir, tstar=t_star[-1], bias=bias[-1], prcp_fac=prcp_fac)

    inversion.prepare_for_inversion(gdir)
    ref_v = 0.573 * 1e9

    if invert_with_sliding:

        def to_optimize(x):
            # For backwards compat
            _fd = 1.9e-24 * x[0]
            glen_a = (cfg.N + 2) * _fd / 2.0
            fs = 5.7e-20 * x[1]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
            return (v - ref_v) ** 2

        out = optimization.minimize(to_optimize, [1, 1], bounds=((0.01, 10), (0.01, 10)), tol=1e-4)["x"]
        _fd = 1.9e-24 * out[0]
        glen_a = (cfg.N + 2) * _fd / 2.0
        fs = 5.7e-20 * out[1]
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a, write=True)
    else:

        def to_optimize(x):
            glen_a = cfg.A * x[0]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=0.0, glen_a=glen_a)
            return (v - ref_v) ** 2

        out = optimization.minimize(to_optimize, [1], bounds=((0.01, 10),), tol=1e-4)["x"]
        glen_a = cfg.A * out[0]
        fs = 0.0
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a, write=True)
    d = dict(fs=fs, glen_a=glen_a)
    d["factor_glen_a"] = out[0]
    try:
        d["factor_fs"] = out[1]
    except IndexError:
        d["factor_fs"] = 0.0
    gdir.write_pickle(d, "inversion_params")

    inversion.distribute_thickness(gdir, how="per_altitude", add_nc_name=True)
    inversion.distribute_thickness(gdir, how="per_interpolation", add_slope=False, smooth=False, add_nc_name=True)

    return gdir
Ejemplo n.º 22
0
def init_hef(reset=False, border=40, invert_with_sliding=True):

    # test directory
    testdir = TESTDIR_BASE + '_border{}'.format(border)
    if not invert_with_sliding:
        testdir += '_withoutslide'
    if not os.path.exists(testdir):
        os.makedirs(testdir)
        reset = True
    if not os.path.exists(os.path.join(testdir, 'RGI40-11.00897')):
        reset = True
    if not os.path.exists(os.path.join(testdir, 'RGI40-11.00897',
                                       'inversion_params.pkl')):
        reset = True

    # Init
    cfg.initialize()
    cfg.set_divides_db(get_demo_file('HEF_divided.shp'))
    cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
    cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')
    cfg.PARAMS['border'] = border

    # loop because for some reason indexing wont work
    hef_file = get_demo_file('Hintereisferner.shp')
    rgidf = gpd.GeoDataFrame.from_file(hef_file)
    for index, entity in rgidf.iterrows():
        gdir = oggm.GlacierDirectory(entity, base_dir=testdir, reset=reset)

    if not reset:
        return gdir

    gis.define_glacier_region(gdir, entity=entity)
    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.distribute_climate_data([gdir])
    climate.mu_candidates(gdir, div_id=0)
    hef_file = get_demo_file('mbdata_RGI40-11.00897.csv')
    mbdf = pd.read_csv(hef_file).set_index('YEAR')
    t_star, bias = climate.t_star_from_refmb(gdir, mbdf['ANNUAL_BALANCE'])
    climate.local_mustar_apparent_mb(gdir, tstar=t_star[-1], bias=bias[-1])

    inversion.prepare_for_inversion(gdir)
    ref_v = 0.573 * 1e9

    if invert_with_sliding:
        def to_optimize(x):
            # For backwards compat
            _fd = 1.9e-24 * x[0]
            glen_a = (cfg.N+2) * _fd / 2.
            fs = 5.7e-20 * x[1]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                                  glen_a=glen_a)
            return (v - ref_v)**2

        import scipy.optimize as optimization
        out = optimization.minimize(to_optimize, [1, 1],
                                    bounds=((0.01, 10), (0.01, 10)),
                                    tol=1e-4)['x']
        _fd = 1.9e-24 * out[0]
        glen_a = (cfg.N+2) * _fd / 2.
        fs = 5.7e-20 * out[1]
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                              glen_a=glen_a,
                                              write=True)
    else:
        def to_optimize(x):
            glen_a = cfg.A * x[0]
            v, _ = inversion.invert_parabolic_bed(gdir, fs=0.,
                                                  glen_a=glen_a)
            return (v - ref_v)**2

        import scipy.optimize as optimization
        out = optimization.minimize(to_optimize, [1],
                                    bounds=((0.01, 10),),
                                    tol=1e-4)['x']
        glen_a = cfg.A * out[0]
        fs = 0.
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs,
                                              glen_a=glen_a,
                                              write=True)
    d = dict(fs=fs, glen_a=glen_a)
    d['factor_glen_a'] = out[0]
    try:
        d['factor_fs'] = out[1]
    except IndexError:
        d['factor_fs'] = 0.
    gdir.write_pickle(d, 'inversion_params')

    inversion.distribute_thickness(gdir, how='per_altitude',
                                   add_nc_name=True)
    inversion.distribute_thickness(gdir, how='per_interpolation',
                                   add_slope=False, smooth=False,
                                   add_nc_name=True)

    return gdir
Ejemplo n.º 23
0
    def test_invert_hef_nofs(self):

        hef_file = get_demo_file("Hintereisferner.shp")
        entity = gpd.GeoDataFrame.from_file(hef_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)
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.process_histalp_nonparallel([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file("mbdata_RGI40-11.00897.csv")
        mbdf = pd.read_csv(hef_file).set_index("YEAR")
        t_star, bias, prcp_fac = climate.t_star_from_refmb(gdir, mbdf["ANNUAL_BALANCE"])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias, prcp_fac=prcp_fac)

        # OK. Values from Fischer and Kuhn 2013
        # Area: 8.55
        # meanH = 67+-7
        # Volume = 0.573+-0.063
        # maxH = 242+-13

        inversion.prepare_for_inversion(gdir)

        ref_v = 0.573 * 1e9

        def to_optimize(x):
            glen_a = cfg.A * x[0]
            fs = 0.0
            v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a)
            return (v - ref_v) ** 2

        import scipy.optimize as optimization

        out = optimization.minimize(to_optimize, [1], bounds=((0.00001, 100000),), tol=1e-4)["x"]

        self.assertTrue(out[0] > 0.1)
        self.assertTrue(out[0] < 10)

        glen_a = cfg.A * out[0]
        fs = 0.0
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a, write=True)
        np.testing.assert_allclose(ref_v, v)

        lens = [len(gdir.read_pickle("centerlines", div_id=i)) for i in [1, 2, 3]]
        pid = np.argmax(lens) + 1
        cls = gdir.read_pickle("inversion_output", div_id=pid)
        fls = gdir.read_pickle("inversion_flowlines", div_id=pid)
        maxs = 0.0
        for cl, fl in zip(cls, fls):
            thick = cl["thick"]
            _max = np.max(thick)
            if _max > maxs:
                maxs = _max
        np.testing.assert_allclose(242, maxs, atol=25)

        # check that its not tooo sensitive to the dx
        cfg.PARAMS["flowline_dx"] = 1.0
        geometry.initialize_flowlines(gdir)
        geometry.catchment_area(gdir)
        geometry.catchment_width_geom(gdir)
        geometry.catchment_width_correction(gdir)
        climate.process_histalp_nonparallel([gdir])
        climate.mu_candidates(gdir, div_id=0)
        hef_file = get_demo_file("mbdata_RGI40-11.00897.csv")
        mbdf = pd.read_csv(hef_file).set_index("YEAR")
        t_star, bias, prcp_fac = climate.t_star_from_refmb(gdir, mbdf["ANNUAL_BALANCE"])
        t_star = t_star[-1]
        bias = bias[-1]
        climate.local_mustar_apparent_mb(gdir, tstar=t_star, bias=bias, prcp_fac=prcp_fac)
        inversion.prepare_for_inversion(gdir)
        v, _ = inversion.invert_parabolic_bed(gdir, fs=fs, glen_a=glen_a, write=True)

        np.testing.assert_allclose(ref_v, v, rtol=0.02)
        cls = gdir.read_pickle("inversion_output", div_id=pid)
        maxs = 0.0
        for cl in cls:
            thick = cl["thick"]
            _max = np.max(thick)
            if _max > maxs:
                maxs = _max

        np.testing.assert_allclose(242, maxs, atol=25)
Ejemplo n.º 24
0
def optimize_thick(gdirs):
    """Optimizes fd based on GlaThiDa thicknesses.

    We use the glacier averaged thicknesses provided by GlaThiDa and correct
    them for differences in area with RGI, using a glacier specific volume-area
    scaling formula.

    Parameters
    ----------
    gdirs: list of oggm.GlacierDirectory objects
    """

    gtd_df = _prepare_inv(gdirs)
    ref_gdirs = gtd_df['ref_gdirs']
    ref_volume_km3 = gtd_df['ref_volume_km3']
    ref_area_km2 = gtd_df['ref_area_km2']
    ref_thickness_m = gtd_df['ref_thickness_m']

    # Optimize without sliding
    log.info('Compute the inversion parameter.')

    def to_optimize(x):
        tmp_ = np.zeros(len(ref_gdirs))
        glen_a = cfg.A * x[0]
        for i, gdir in enumerate(ref_gdirs):
            v, a = invert_parabolic_bed(gdir,
                                        glen_a=glen_a,
                                        fs=0.,
                                        write=False)
            tmp_[i] = v / a
        return utils.rmsd(tmp_, ref_thickness_m)

    opti = optimization.minimize(to_optimize, [1.],
                                 bounds=((0.01, 10), ),
                                 tol=1.e-4)
    # Check results and save.
    glen_a = cfg.A * opti['x'][0]
    fs = 0.

    # This is for the stats
    oggm_volume_m3 = np.zeros(len(ref_gdirs))
    rgi_area_m2 = np.zeros(len(ref_gdirs))
    for i, gdir in enumerate(ref_gdirs):
        v, a = invert_parabolic_bed(gdir, glen_a=glen_a, fs=fs, write=False)
        oggm_volume_m3[i] = v
        rgi_area_m2[i] = a
    assert np.allclose(rgi_area_m2 * 1e-6, ref_area_km2)

    # This is for each glacier
    out = dict()
    out['glen_a'] = glen_a
    out['fs'] = fs
    out['factor_glen_a'] = opti['x'][0]
    try:
        out['factor_fs'] = opti['x'][1]
    except IndexError:
        out['factor_fs'] = 0.
    for gdir in gdirs:
        gdir.write_pickle(out, 'inversion_params')

    # This is for the working dir
    # Simple stats
    out['vol_rmsd'] = utils.rmsd(oggm_volume_m3 * 1e-9, ref_volume_km3)
    out['thick_rmsd'] = utils.rmsd(oggm_volume_m3 / (ref_area_km2 * 1e6),
                                   ref_thickness_m)
    log.info(
        'Optimized glen_a and fs with a factor {factor_glen_a:.2f} and '
        '{factor_fs:.2f} for a thick RMSD of {thick_rmsd:.3f}'.format(**out))

    df = pd.DataFrame(out, index=[0])
    fpath = os.path.join(cfg.PATHS['working_dir'],
                         'inversion_optim_params.csv')
    df.to_csv(fpath)

    # All results
    df = utils.glacier_characteristics(ref_gdirs)
    df['ref_area_km2'] = ref_area_km2
    df['ref_volume_km3'] = ref_volume_km3
    df['ref_thickness_m'] = ref_thickness_m
    df['oggm_volume_km3'] = oggm_volume_m3 * 1e-9
    df['oggm_thickness_m'] = oggm_volume_m3 / (ref_area_km2 * 1e6)
    df['vas_volume_km3'] = 0.034 * (df['ref_area_km2']**1.375)
    df['vas_thickness_m'] = df['vas_volume_km3'] / ref_area_km2 * 1000

    rgi_id = [gdir.rgi_id for gdir in ref_gdirs]
    df = pd.DataFrame(df, index=rgi_id)
    fpath = os.path.join(cfg.PATHS['working_dir'],
                         'inversion_optim_results.csv')
    df.to_csv(fpath)

    # return value for tests
    return out
Ejemplo n.º 25
0
Archivo: itmix.py Proyecto: OGGM/oggm
def optimize_thick(gdirs):
    """Optimizes fd based on GlaThiDa thicknesses.

    We use the glacier averaged thicknesses provided by GlaThiDa and correct
    them for differences in area with RGI, using a glacier specific volume-area
    scaling formula.

    Parameters
    ----------
    gdirs: list of oggm.GlacierDirectory objects
    """

    gtd_df = _prepare_inv(gdirs)
    ref_gdirs = gtd_df['ref_gdirs']
    ref_volume_km3 = gtd_df['ref_volume_km3']
    ref_area_km2 = gtd_df['ref_area_km2']
    ref_thickness_m = gtd_df['ref_thickness_m']

    # Optimize without sliding
    log.info('Compute the inversion parameter.')

    def to_optimize(x):
        tmp_ = np.zeros(len(ref_gdirs))
        glen_a = cfg.A * x[0]
        for i, gdir in enumerate(ref_gdirs):
            v, a = invert_parabolic_bed(gdir, glen_a=glen_a,
                                        fs=0., write=False)
            tmp_[i] = v / a
        return utils.rmsd(tmp_, ref_thickness_m)
    opti = optimization.minimize(to_optimize, [1.],
                                bounds=((0.01, 10), ),
                                tol=1.e-4)
    # Check results and save.
    glen_a = cfg.A * opti['x'][0]
    fs = 0.

    # This is for the stats
    oggm_volume_m3 = np.zeros(len(ref_gdirs))
    rgi_area_m2 = np.zeros(len(ref_gdirs))
    for i, gdir in enumerate(ref_gdirs):
        v, a = invert_parabolic_bed(gdir, glen_a=glen_a, fs=fs,
                                    write=False)
        oggm_volume_m3[i] = v
        rgi_area_m2[i] = a
    assert np.allclose(rgi_area_m2 * 1e-6, ref_area_km2)

    # This is for each glacier
    out = dict()
    out['glen_a'] = glen_a
    out['fs'] = fs
    out['factor_glen_a'] = opti['x'][0]
    try:
        out['factor_fs'] = opti['x'][1]
    except IndexError:
        out['factor_fs'] = 0.
    for gdir in gdirs:
        gdir.write_pickle(out, 'inversion_params')

    # This is for the working dir
    # Simple stats
    out['vol_rmsd'] = utils.rmsd(oggm_volume_m3 * 1e-9, ref_volume_km3)
    out['thick_rmsd'] = utils.rmsd(oggm_volume_m3 / (ref_area_km2 * 1e6),
                                   ref_thickness_m)
    log.info('Optimized glen_a and fs with a factor {factor_glen_a:.2f} and '
             '{factor_fs:.2f} for a thick RMSD of {thick_rmsd:.3f}'.format(
        **out))

    df = pd.DataFrame(out, index=[0])
    fpath = os.path.join(cfg.PATHS['working_dir'],
                         'inversion_optim_params.csv')
    df.to_csv(fpath)

    # All results
    df = utils.glacier_characteristics(ref_gdirs)
    df['ref_area_km2'] = ref_area_km2
    df['ref_volume_km3'] = ref_volume_km3
    df['ref_thickness_m'] = ref_thickness_m
    df['oggm_volume_km3'] = oggm_volume_m3 * 1e-9
    df['oggm_thickness_m'] = oggm_volume_m3 / (ref_area_km2 * 1e6)
    df['vas_volume_km3'] = 0.034*(df['ref_area_km2']**1.375)
    df['vas_thickness_m'] = df['vas_volume_km3'] / ref_area_km2 * 1000

    rgi_id = [gdir.rgi_id for gdir in ref_gdirs]
    df = pd.DataFrame(df, index=rgi_id)
    fpath = os.path.join(cfg.PATHS['working_dir'],
                         'inversion_optim_results.csv')
    df.to_csv(fpath)

    # return value for tests
    return out