Exemplo n.º 1
0
    def test_change_all_exposures_pass(self):
        """Test _change_all_exposures method"""
        meas = Measure()
        meas.exposures_set = EXP_DEMO_H5

        ref_exp = Exposures()
        ref_exp.read_hdf5(EXP_DEMO_H5)

        exposures = Exposures()
        exposures.gdf['latitude'] = np.ones(10)
        exposures.gdf['longitude'] = np.ones(10)
        new_exp = meas._change_all_exposures(exposures)

        self.assertEqual(new_exp.ref_year, ref_exp.ref_year)
        self.assertEqual(new_exp.value_unit, ref_exp.value_unit)
        self.assertEqual(new_exp.tag.file_name, ref_exp.tag.file_name)
        self.assertEqual(new_exp.tag.description, ref_exp.tag.description)
        self.assertTrue(
            np.array_equal(new_exp.gdf.value.values, ref_exp.gdf.value.values))
        self.assertTrue(
            np.array_equal(new_exp.gdf.latitude.values,
                           ref_exp.gdf.latitude.values))
        self.assertTrue(
            np.array_equal(new_exp.gdf.longitude.values,
                           ref_exp.gdf.longitude.values))
Exemplo n.º 2
0
    def test_error_logs_wrong_crs(self):
        """Ambiguous crs definition"""
        expo = good_exposures()
        expo.set_geometry_points()  # sets crs to 4326

        # all good
        _expo = Exposures(expo.gdf, meta={'crs': 4326}, crs=DEF_CRS)

        with self.assertRaises(ValueError) as cm:
            _expo = Exposures(expo.gdf, meta={'crs': 4230}, crs=4326)
        self.assertIn(
            "Inconsistent CRS definition, crs and meta arguments don't match",
            str(cm.exception))

        with self.assertRaises(ValueError) as cm:
            _expo = Exposures(expo.gdf, meta={'crs': 4230})
        self.assertIn(
            "Inconsistent CRS definition, data doesn't match meta or crs argument",
            str(cm.exception))

        with self.assertRaises(ValueError) as cm:
            _expo = Exposures(expo.gdf, crs='epsg:4230')
        self.assertIn(
            "Inconsistent CRS definition, data doesn't match meta or crs argument",
            str(cm.exception))

        _expo = Exposures(expo.gdf)
        _expo.meta['crs'] = 'epsg:4230'
        with self.assertRaises(ValueError) as cm:
            _expo.check()
        self.assertIn(
            "Inconsistent CRS definition, gdf (EPSG:4326) attribute doesn't match "
            "meta (epsg:4230) attribute.", str(cm.exception))
Exemplo n.º 3
0
    def test_io_hdf5_pass(self):
        """write and read hdf5"""
        exp_df = Exposures(pd.read_excel(ENT_TEMPLATE_XLS))
        exp_df.set_geometry_points()
        exp_df.check()
        # set metadata
        exp_df.ref_year = 2020
        exp_df.tag = Tag(ENT_TEMPLATE_XLS, 'ENT_TEMPLATE_XLS')
        exp_df.value_unit = 'XSD'

        file_name = DATA_DIR.joinpath('test_hdf5_exp.h5')
        exp_df.write_hdf5(file_name)

        exp_read = Exposures()
        exp_read.read_hdf5(file_name)

        self.assertEqual(exp_df.ref_year, exp_read.ref_year)
        self.assertEqual(exp_df.value_unit, exp_read.value_unit)
        self.assertEqual(exp_df.crs, exp_read.crs)
        self.assertEqual(exp_df.tag.file_name, exp_read.tag.file_name)
        self.assertEqual(exp_df.tag.description, exp_read.tag.description)
        self.assertTrue(
            np.array_equal(exp_df.gdf.latitude.values,
                           exp_read.gdf.latitude.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.longitude.values,
                           exp_read.gdf.longitude.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.value.values, exp_read.gdf.value.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.deductible.values,
                           exp_read.gdf.deductible.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.cover.values, exp_read.gdf.cover.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.region_id.values,
                           exp_read.gdf.region_id.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.category_id.values,
                           exp_read.gdf.category_id.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.if_TC.values, exp_read.gdf.if_TC.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.centr_TC.values,
                           exp_read.gdf.centr_TC.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.if_FL.values, exp_read.gdf.if_FL.values))
        self.assertTrue(
            np.array_equal(exp_df.gdf.centr_FL.values,
                           exp_read.gdf.centr_FL.values))

        for point_df, point_read in zip(exp_df.gdf.geometry.values,
                                        exp_read.gdf.geometry.values):
            self.assertEqual(point_df.x, point_read.x)
            self.assertEqual(point_df.y, point_read.y)
Exemplo n.º 4
0
    def test_no_coord_fail(self):
        """Error if no coordinates."""
        new_var_names = copy.deepcopy(DEF_VAR_MAT)
        new_var_names['var_name']['lat'] = 'no valid Latitude'
        exp = Exposures()
        with self.assertRaises(KeyError):
            exp.read_mat(ENT_TEST_MAT, var_names=new_var_names)

        new_var_names['var_name']['lat'] = 'nLatitude'
        new_var_names['var_name']['lon'] = 'no valid Longitude'
        exp = Exposures()
        with self.assertRaises(KeyError):
            exp.read_mat(ENT_TEST_MAT, var_names=new_var_names)
Exemplo n.º 5
0
    def test_calc_sector_total_impact(self):
        """Test running total impact calculations."""
        sup = SupplyChain()
        sup.read_wiod16(year='test',
                        range_rows=(5, 117),
                        range_cols=(4, 116),
                        col_iso3=2,
                        col_sectors=1)

        # Tropical cyclone over Florida and Caribbean
        hazard = Hazard('TC')
        hazard.read_mat(HAZ_TEST_MAT)

        # Read demo entity values
        # Set the entity default file to the demo one
        exp = Exposures()
        exp.read_hdf5(EXP_DEMO_H5)
        exp.check()
        exp.gdf.region_id = 840  #assign right id for USA
        exp.assign_centroids(hazard)

        impf_tc = IFTropCyclone()
        impf_tc.set_emanuel_usa()
        impf_set = ImpactFuncSet()
        impf_set.append(impf_tc)
        impf_set.check()

        sup.calc_sector_direct_impact(hazard, exp, impf_set)
        sup.calc_indirect_impact(io_approach='ghosh')
        sup.calc_total_impact()

        self.assertAlmostEqual((sup.years.shape[0], sup.mriot_data.shape[0]),
                               sup.total_impact.shape)
        self.assertAlmostEqual((sup.mriot_data.shape[0], ),
                               sup.total_aai_agg.shape)
Exemplo n.º 6
0
    def test_cutoff_hazard_pass(self):
        """Test _cutoff_hazard_damage"""
        meas = MeasureSet()
        meas.read_mat(ENT_TEST_MAT)
        act_1 = meas.get_measure(name='Seawall')[0]

        haz = Hazard('TC')
        haz.read_mat(HAZ_TEST_MAT)
        exp = Exposures()
        exp.read_mat(ENT_TEST_MAT)
        exp.gdf.rename(columns={'if_': 'if_TC'}, inplace=True)
        exp.check()

        imp_set = ImpactFuncSet()
        imp_set.read_mat(ENT_TEST_MAT)

        new_haz = act_1._cutoff_hazard_damage(exp, imp_set, haz)

        self.assertFalse(id(new_haz) == id(haz))

        pos_no_null = np.array([6249, 7697, 9134, 13500, 13199, 5944, 9052, 9050, 2429,
                                5139, 9053, 7102, 4096, 1070, 5948, 1076, 5947, 7432,
                                5949, 11694, 5484, 6246, 12147, 778, 3326, 7199, 12498,
                               11698, 6245, 5327, 4819, 8677, 5970, 7101, 779, 3894,
                                9051, 5976, 3329, 5978, 4282, 11697, 7193, 5351, 7310,
                                7478, 5489, 5526, 7194, 4283, 7191, 5328, 4812, 5528,
                                5527, 5488, 7475, 5529, 776, 5758, 4811, 6223, 7479,
                                7470, 5480, 5325, 7477, 7318, 7317, 11696, 7313, 13165,
                                6221])
        all_haz = np.arange(haz.intensity.shape[0])
        all_haz[pos_no_null] = -1
        pos_null = np.argwhere(all_haz > 0).reshape(-1)
        for i_ev in pos_null:
            self.assertEqual(new_haz.intensity[i_ev, :].max(), 0)
Exemplo n.º 7
0
    def _cutoff_hazard_damage(self, exposures, if_set, hazard):
        """Cutoff of hazard events which generate damage with a frequency higher
        than hazard_freq_cutoff.

        Parameters:
            exposures (Exposures): exposures instance
            imp_set (ImpactFuncSet): impact functions instance
            hazard (Hazard): hazard instance

        Returns:
            ImpactFuncSet
        """
        if self.hazard_freq_cutoff == 0:
            return hazard

        LOGGER.debug('Cutting events whose damage have a frequency > %s.',
                     self.hazard_freq_cutoff)
        from climada.engine.impact import Impact
        imp = Impact()
        exp_imp = exposures
        if self.exp_region_id != 0:
            # compute impact only in selected region
            exp_imp = exposures[exposures.region_id == self.exp_region_id]
            exp_imp = Exposures(exp_imp)
        imp.calc(exp_imp, if_set, hazard)

        new_haz = copy.deepcopy(hazard)
        sort_idxs = np.argsort(imp.at_event)[::-1]
        exceed_freq = np.cumsum(imp.frequency[sort_idxs])
        cutoff = exceed_freq > self.hazard_freq_cutoff
        sel_haz = sort_idxs[cutoff]
        new_haz_inten = new_haz.intensity.tolil()
        new_haz_inten[sel_haz, :] = np.zeros((sel_haz.size, new_haz.intensity.shape[1]))
        new_haz.intensity = new_haz_inten.tocsr()
        return new_haz
Exemplo n.º 8
0
    def _change_all_exposures(self, exposures):
        """Change exposures to provided exposures_set.

        Parameters:
            exposures (Exposures): exposures instance

        Returns:
            Exposures
        """
        if isinstance(self.exposures_set,
                      str) and self.exposures_set == NULL_STR:
            return exposures

        if isinstance(self.exposures_set, str):
            LOGGER.debug('Setting new exposures %s', self.exposures_set)
            new_exp = Exposures()
            new_exp.read_hdf5(self.exposures_set)
            new_exp.check()
        elif isinstance(self.exposures_set, Exposures):
            LOGGER.debug('Setting new exposures. ')
            new_exp = copy.deepcopy(self.exposures_set)
            new_exp.check()
        else:
            LOGGER.error('Wrong input exposures.')
            raise ValueError

        if not np.array_equal(np.unique(exposures.latitude.values),
                              np.unique(new_exp.latitude.values)) or \
        not np.array_equal(np.unique(exposures.longitude.values),
                           np.unique(new_exp.longitude.values)):
            LOGGER.warning('Exposures locations have changed.')

        return new_exp
Exemplo n.º 9
0
    def from_excel(cls, file_name, description=''):
        """Read csv or xls or xlsx file following climada's template.

        Parameters
        ----------
        file_name : str, optional
            file name(s) or folder name
            containing the files to read
        description : str or list(str), optional
            one description of the
            data or a description of each data file

        Returns
        -------
        ent : climada.entity.Entity
            The entity from excel file
        """

        exp = Exposures(pd.read_excel(file_name))
        exp.tag = Tag()
        exp.tag.file_name = str(file_name)
        exp.tag.description = description

        dr = DiscRates.from_excel(file_name, description)
        impf_set = ImpactFuncSet.from_excel(file_name, description)
        meas_set = MeasureSet.from_excel(file_name, description)

        return cls(exposures=exp,
                   disc_rates=dr,
                   impact_func_set=impf_set,
                   measure_set=meas_set)
Exemplo n.º 10
0
    def test_assign_pass(self):
        """Check that attribute `assigned` is correctly set."""
        np_rand = np.random.RandomState(123456789)

        haz = Hazard('FL')
        haz.set_raster([HAZ_DEMO_FL], window=Window(10, 20, 50, 60))
        haz.raster_to_vector()
        ncentroids = haz.centroids.size

        exp = Exposures()
        exp.gdf.crs = haz.centroids.crs

        # some are matching exactly, some are geographically close
        exp.gdf['longitude'] = np.concatenate([
            haz.centroids.lon,
            haz.centroids.lon + 0.001 * (-0.5 + np_rand.rand(ncentroids))
        ])
        exp.gdf['latitude'] = np.concatenate([
            haz.centroids.lat,
            haz.centroids.lat + 0.001 * (-0.5 + np_rand.rand(ncentroids))
        ])
        expected_result = np.concatenate(
            [np.arange(ncentroids),
             np.arange(ncentroids)])

        # make sure that it works for both float32 and float64
        for test_dtype in [np.float64, np.float32]:
            haz.centroids.lat = haz.centroids.lat.astype(test_dtype)
            haz.centroids.lon = haz.centroids.lon.astype(test_dtype)
            exp.assign_centroids(haz)
            self.assertEqual(exp.gdf.shape[0],
                             len(exp.gdf[INDICATOR_CENTR + 'FL']))
            np.testing.assert_array_equal(
                exp.gdf[INDICATOR_CENTR + 'FL'].values, expected_result)
Exemplo n.º 11
0
 def test_no_impact_fail(self):
     """Error if no impact ids."""
     new_var_names = copy.deepcopy(DEF_VAR_MAT)
     new_var_names['var_name']['imp'] = 'no valid value'
     exp = Exposures()
     with self.assertRaises(KeyError):
         exp.read_mat(ENT_TEST_MAT, var_names=new_var_names)
Exemplo n.º 12
0
    def test_set_gdf(self):
        """Test setting the GeoDataFrame"""
        empty_gdf = gpd.GeoDataFrame()
        gdf_without_geometry = good_exposures().gdf
        good_exp = good_exposures()
        good_exp.set_crs(crs='epsg:3395')
        good_exp.set_geometry_points()
        gdf_with_geometry = good_exp.gdf

        probe = Exposures()
        self.assertRaises(ValueError, probe.set_gdf, pd.DataFrame())

        probe.set_gdf(empty_gdf)
        self.assertTrue(probe.gdf.equals(gpd.GeoDataFrame()))
        self.assertTrue(u_coord.equal_crs(DEF_CRS, probe.crs))
        self.assertIsNone(probe.gdf.crs)

        probe.set_gdf(gdf_with_geometry)
        self.assertTrue(probe.gdf.equals(gdf_with_geometry))
        self.assertTrue(u_coord.equal_crs('epsg:3395', probe.crs))
        self.assertTrue(u_coord.equal_crs('epsg:3395', probe.gdf.crs))

        probe.set_gdf(gdf_without_geometry)
        self.assertTrue(probe.gdf.equals(good_exposures().gdf))
        self.assertTrue(u_coord.equal_crs(DEF_CRS, probe.crs))
        self.assertIsNone(probe.gdf.crs)
Exemplo n.º 13
0
    def test_change_exposures_if_pass(self):
        """Test _change_exposures_if"""
        meas = Measure()
        meas.imp_fun_map = '1to3'
        meas.haz_type = 'TC'

        imp_set = ImpactFuncSet()
        imp_tc = ImpactFunc()
        imp_tc.haz_type = 'TC'
        imp_tc.id = 1
        imp_tc.intensity = np.arange(10, 100, 10)
        imp_tc.mdd = np.arange(10, 100, 10)
        imp_tc.paa = np.arange(10, 100, 10)
        imp_set.append(imp_tc)

        imp_tc = ImpactFunc()
        imp_tc.haz_type = 'TC'
        imp_tc.id = 3
        imp_tc.intensity = np.arange(10, 100, 10)
        imp_tc.mdd = np.arange(10, 100, 10) * 2
        imp_tc.paa = np.arange(10, 100, 10) * 2

        exp = Exposures()
        exp.read_hdf5(EXP_DEMO_H5)
        new_exp = meas._change_exposures_if(exp)

        self.assertEqual(new_exp.ref_year, exp.ref_year)
        self.assertEqual(new_exp.value_unit, exp.value_unit)
        self.assertEqual(new_exp.tag.file_name, exp.tag.file_name)
        self.assertEqual(new_exp.tag.description, exp.tag.description)
        self.assertTrue(np.array_equal(new_exp.gdf.value.values, exp.gdf.value.values))
        self.assertTrue(np.array_equal(new_exp.gdf.latitude.values, exp.gdf.latitude.values))
        self.assertTrue(np.array_equal(new_exp.gdf.longitude.values, exp.gdf.longitude.values))
        self.assertTrue(np.array_equal(exp.gdf[INDICATOR_IF + 'TC'].values, np.ones(new_exp.gdf.shape[0])))
        self.assertTrue(np.array_equal(new_exp.gdf[INDICATOR_IF + 'TC'].values, np.ones(new_exp.gdf.shape[0]) * 3))
Exemplo n.º 14
0
    def read_excel(self, file_name, description=''):
        """Read csv or xls or xlsx file following climada's template.

        Parameters:
            file_name (str, optional): file name(s) or folder name
                containing the files to read
            description (str or list(str), optional): one description of the
                data or a description of each data file

        Raises:
            ValueError
        """
        self.exposures = Exposures(pd.read_excel(file_name))
        self.exposures.tag = Tag()
        self.exposures.tag.file_name = file_name
        self.exposures.tag.description = description

        self.disc_rates = DiscRates()
        self.disc_rates.read_excel(file_name, description)

        self.impact_funcs = ImpactFuncSet()
        self.impact_funcs.read_excel(file_name, description)

        self.measures = MeasureSet()
        self.measures.read_excel(file_name, description)
Exemplo n.º 15
0
 def test_constructoer_pass(self):
     """ Test initialization with input GeiDataFrame """
     in_gpd = gpd.GeoDataFrame()
     in_gpd['value'] = np.zeros(10)
     in_gpd.ref_year = 2015
     in_exp = Exposures(in_gpd)
     self.assertEqual(in_exp.ref_year, 2015)
     self.assertTrue(np.array_equal(in_exp.value, np.zeros(10)))
Exemplo n.º 16
0
 def test_read_template_pass(self):
     """Wrong exposures definition"""
     df = pd.read_excel(ENT_TEMPLATE_XLS)
     exp_df = Exposures(df)
     # set metadata
     exp_df.ref_year = 2020
     exp_df.tag = Tag(ENT_TEMPLATE_XLS, 'ENT_TEMPLATE_XLS')
     exp_df.value_unit = 'XSD'
     exp_df.check()
Exemplo n.º 17
0
    def test_no_refyear_pass(self):
        """Not error if no value unit."""
        new_var_names = copy.deepcopy(DEF_VAR_MAT)
        new_var_names['var_name']['ref'] = 'no valid ref'
        exp = Exposures()
        exp.read_mat(ENT_TEST_MAT, var_names=new_var_names)

        # Check results
        self.assertEqual(2018, exp.ref_year)
Exemplo n.º 18
0
    def test_no_unit_pass(self):
        """Not error if no value unit."""
        new_var_names = copy.deepcopy(DEF_VAR_MAT)
        new_var_names['var_name']['uni'] = 'no valid unit'
        exp = Exposures()
        exp.read_mat(ENT_TEST_MAT, var_names=new_var_names)

        # Check results
        self.assertEqual('USD', exp.value_unit)
Exemplo n.º 19
0
    def test_no_assigned_pass(self):
        """Not error if no value unit."""
        new_var_names = copy.deepcopy(DEF_VAR_MAT)
        new_var_names['var_name']['ass'] = 'no valid assign'
        exp = Exposures()
        exp.read_mat(ENT_TEST_MAT, var_names=new_var_names)

        # Check results
        self.assertTrue('centr_' not in exp.gdf)
Exemplo n.º 20
0
    def test_no_category_pass(self):
        """Not error if no category id."""
        new_var_names = copy.deepcopy(DEF_VAR_MAT)
        new_var_names['var_name']['cat'] = 'no valid category'
        exp = Exposures()
        exp.read_mat(ENT_TEST_MAT, var_names=new_var_names)

        # Check results
        self.assertTrue('category_id' not in exp.gdf)
Exemplo n.º 21
0
    def test_no_region_pass(self):
        """Not error if no region id."""
        new_var_names = copy.deepcopy(DEF_VAR_MAT)
        new_var_names['var_name']['reg'] = 'no valid region'
        exp = Exposures()
        exp.read_mat(ENT_TEST_MAT, var_names=new_var_names)

        # Check results
        self.assertTrue('region_id' not in exp.gdf)
Exemplo n.º 22
0
 def _build_exp(self):
     eai_exp = Exposures()
     eai_exp['value'] = self.eai_exp
     eai_exp['latitude'] = self.coord_exp[:, 0]
     eai_exp['longitude'] = self.coord_exp[:, 1]
     eai_exp.crs = self.crs
     eai_exp.value_unit = self.unit
     eai_exp.check()
     return eai_exp
Exemplo n.º 23
0
    def test_io_hdf5_pass(self):
        """write and read hdf5"""
        exp_df = Exposures(pd.read_excel(ENT_TEMPLATE_XLS), crs="epsg:32632")
        exp_df.set_geometry_points()
        exp_df.check()
        # set metadata
        exp_df.ref_year = 2020
        exp_df.tag = Tag(ENT_TEMPLATE_XLS, 'ENT_TEMPLATE_XLS')
        exp_df.value_unit = 'XSD'

        file_name = DATA_DIR.joinpath('test_hdf5_exp.h5')

        # pd.errors.PerformanceWarning should be suppressed. Therefore, make sure that
        # PerformanceWarning would result in test failure here
        import warnings
        with warnings.catch_warnings():
            warnings.simplefilter("error",
                                  category=pd.errors.PerformanceWarning)
            exp_df.write_hdf5(file_name)

        exp_read = Exposures.from_hdf5(file_name)

        self.assertEqual(exp_df.ref_year, exp_read.ref_year)
        self.assertEqual(exp_df.value_unit, exp_read.value_unit)
        self.assertDictEqual(exp_df.meta, exp_read.meta)
        self.assertTrue(u_coord.equal_crs(exp_df.crs, exp_read.crs))
        self.assertTrue(u_coord.equal_crs(exp_df.gdf.crs, exp_read.gdf.crs))
        self.assertEqual(exp_df.tag.file_name, exp_read.tag.file_name)
        self.assertEqual(exp_df.tag.description, exp_read.tag.description)
        np.testing.assert_array_equal(exp_df.gdf.latitude.values,
                                      exp_read.gdf.latitude.values)
        np.testing.assert_array_equal(exp_df.gdf.longitude.values,
                                      exp_read.gdf.longitude.values)
        np.testing.assert_array_equal(exp_df.gdf.value.values,
                                      exp_read.gdf.value.values)
        np.testing.assert_array_equal(exp_df.gdf.deductible.values,
                                      exp_read.gdf.deductible.values)
        np.testing.assert_array_equal(exp_df.gdf.cover.values,
                                      exp_read.gdf.cover.values)
        np.testing.assert_array_equal(exp_df.gdf.region_id.values,
                                      exp_read.gdf.region_id.values)
        np.testing.assert_array_equal(exp_df.gdf.category_id.values,
                                      exp_read.gdf.category_id.values)
        np.testing.assert_array_equal(exp_df.gdf.impf_TC.values,
                                      exp_read.gdf.impf_TC.values)
        np.testing.assert_array_equal(exp_df.gdf.centr_TC.values,
                                      exp_read.gdf.centr_TC.values)
        np.testing.assert_array_equal(exp_df.gdf.impf_FL.values,
                                      exp_read.gdf.impf_FL.values)
        np.testing.assert_array_equal(exp_df.gdf.centr_FL.values,
                                      exp_read.gdf.centr_FL.values)

        for point_df, point_read in zip(exp_df.gdf.geometry.values,
                                        exp_read.gdf.geometry.values):
            self.assertEqual(point_df.x, point_read.x)
            self.assertEqual(point_df.y, point_read.y)
Exemplo n.º 24
0
 def test_assign_raster_same_pass(self):
     """Test assign_centroids with raster hazard"""
     exp = Exposures()
     exp.set_from_raster(HAZ_DEMO_FL, window=Window(10, 20, 50, 60))
     exp.check()
     haz = Hazard('FL')
     haz.set_raster([HAZ_DEMO_FL], window=Window(10, 20, 50, 60))
     exp.assign_centroids(haz)
     np.testing.assert_array_equal(exp.gdf[INDICATOR_CENTR + 'FL'].values,
                                   np.arange(haz.centroids.size, dtype=int))
Exemplo n.º 25
0
    def test_set_crs(self):
        """Test setting the CRS"""
        empty_gdf = gpd.GeoDataFrame()
        gdf_without_geometry = good_exposures().gdf
        good_exp = good_exposures()
        good_exp.set_geometry_points()
        gdf_with_geometry = good_exp.gdf

        probe = Exposures(gdf_without_geometry)
        self.assertTrue(u_coord.equal_crs(DEF_CRS, probe.crs))
        probe.set_crs('epsg:3395')
        self.assertTrue(u_coord.equal_crs('epsg:3395', probe.crs))

        probe = Exposures(gdf_with_geometry)
        self.assertTrue(u_coord.equal_crs(DEF_CRS, probe.crs))
        probe.set_crs(DEF_CRS)
        self.assertTrue(u_coord.equal_crs(DEF_CRS, probe.crs))
        self.assertRaises(ValueError, probe.set_crs, 'epsg:3395')
        self.assertEqual('EPSG:4326', probe.meta.get('crs'))
Exemplo n.º 26
0
    def test_wrongDisc_fail(self):
        """Wrong discount rates"""
        ent = Entity.from_excel(ENT_TEMPLATE_XLS)
        ent.disc_rates.rates = np.array([1, 2])
        with self.assertRaises(ValueError) as cm:
            ent.check()
        self.assertIn('DiscRates.rates', str(cm.exception))

        with self.assertRaises(ValueError) as cm:
            ent.disc_rates = Exposures()
        self.assertIn('DiscRates', str(cm.exception))
Exemplo n.º 27
0
 def _build_exp(self):
     eai_exp = Exposures()
     eai_exp['value'] = self.eai_exp
     eai_exp['latitude'] = self.coord_exp[:, 0]
     eai_exp['longitude'] = self.coord_exp[:, 1]
     eai_exp.crs = self.crs
     eai_exp.value_unit = self.unit
     eai_exp.ref_year = 0
     eai_exp.tag = Tag()
     eai_exp.meta = None
     return eai_exp
Exemplo n.º 28
0
    def test_wrongImpFun_fail(self):
        """Wrong impact functions"""
        ent = Entity.from_excel(ENT_TEMPLATE_XLS)
        ent.impact_funcs.get_func('TC', 1).paa = np.array([1, 2])
        with self.assertRaises(ValueError) as cm:
            ent.check()
        self.assertIn('ImpactFunc.paa', str(cm.exception))

        with self.assertRaises(ValueError) as cm:
            ent.impact_funcs = Exposures()
        self.assertIn('ImpactFuncSet', str(cm.exception))
Exemplo n.º 29
0
    def test_exposures_value_pass(self):
        """Plot exposures values."""
        myexp = pd.read_excel(ENT_DEMO_TODAY)
        myexp = Exposures(myexp)
        myexp.check()
        myexp.tag.description = 'demo_today'
        myax = myexp.plot_hexbin()
        self.assertIn('demo_today', myax.get_title())

        myexp.tag.description = ''
        myax = myexp.plot_hexbin()
        self.assertIn('', myax.get_title())
Exemplo n.º 30
0
    def test_ctx_osm_pass(self):
        """ Test basemap function using osm images """
        myexp = Exposures()
        myexp['latitude'] = np.array([30, 40, 50])
        myexp['longitude'] = np.array([0, 0, 0])
        myexp['value'] = np.array([1, 1, 1])
        myexp.check()

        try:
            myexp.plot_basemap(url=ctx.sources.OSM_A)
        except urllib.error.HTTPError:
            self.assertEqual(1, 0)