Esempio n. 1
0
    def test_excel_io(self):
        """Test write and read in excel"""
        ent = Entity.from_excel(ENT_DEMO_TODAY)
        ent.check()

        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        imp_write = Impact()
        ent.exposures.assign_centroids(hazard)
        imp_write.calc(ent.exposures, ent.impact_funcs, hazard)
        file_name = DATA_FOLDER.joinpath('test.xlsx')
        imp_write.write_excel(file_name)

        imp_read = Impact.from_excel(file_name)

        np.testing.assert_array_equal(imp_write.event_id, imp_read.event_id)
        np.testing.assert_array_equal(imp_write.date, imp_read.date)
        np.testing.assert_array_equal(imp_write.coord_exp, imp_read.coord_exp)
        np.testing.assert_array_almost_equal_nulp(imp_write.eai_exp,
                                                  imp_read.eai_exp,
                                                  nulp=5)
        np.testing.assert_array_almost_equal_nulp(imp_write.at_event,
                                                  imp_read.at_event,
                                                  nulp=5)
        np.testing.assert_array_equal(imp_write.frequency, imp_read.frequency)
        self.assertEqual(imp_write.tot_value, imp_read.tot_value)
        self.assertEqual(imp_write.aai_agg, imp_read.aai_agg)
        self.assertEqual(imp_write.unit, imp_read.unit)
        self.assertEqual(
            0,
            len([
                i for i, j in zip(imp_write.event_name, imp_read.event_name)
                if i != j
            ]))
        self.assertIsInstance(imp_read.crs, str)
    def test_cutoff_hazard_pass(self):
        """Test _cutoff_hazard_damage"""
        meas = MeasureSet.from_mat(ENT_TEST_MAT)
        act_1 = meas.get_measure(name='Seawall')[0]

        haz = Hazard.from_mat(HAZ_TEST_MAT)
        exp = Exposures.from_mat(ENT_TEST_MAT)
        exp.gdf.rename(columns={'impf': 'impf_TC'}, inplace=True)
        exp.check()

        imp_set = ImpactFuncSet.from_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)
    def test_cutoff_hazard_region_pass(self):
        """Test _cutoff_hazard_damage in specific region"""
        meas = MeasureSet.from_mat(ENT_TEST_MAT)
        act_1 = meas.get_measure(name='Seawall')[0]
        act_1.exp_region_id = [1]

        haz = Hazard.from_mat(HAZ_TEST_MAT)
        exp = Exposures.from_mat(ENT_TEST_MAT)
        exp.gdf['region_id'] = np.zeros(exp.gdf.shape[0])
        exp.gdf.region_id.values[10:] = 1
        exp.check()

        imp_set = ImpactFuncSet.from_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)
        centr_null = np.unique(exp.gdf.centr_[exp.gdf.region_id == 0])
        for i_ev in pos_null:
            self.assertEqual(new_haz.intensity[i_ev, centr_null].max(), 0)
    def test_remove_measure(self):
        """Test remove_measure method"""
        hazard = Hazard.from_mat(HAZ_TEST_MAT)
        entity = Entity.from_excel(ENT_DEMO_TODAY)
        entity.check()
        entity.exposures.ref_year = 2018
        cost_ben = CostBenefit()
        cost_ben.calc(hazard,
                      entity,
                      future_year=2040,
                      risk_func=risk_aai_agg,
                      imp_time_depen=None,
                      save_imp=True)

        to_remove = 'Mangroves'
        self.assertTrue(to_remove in cost_ben.benefit.keys())
        cost_ben.remove_measure(to_remove)
        self.assertTrue(to_remove not in cost_ben.color_rgb.keys())
        self.assertTrue(to_remove not in cost_ben.benefit.keys())
        self.assertTrue(to_remove not in cost_ben.cost_ben_ratio.keys())
        self.assertTrue(to_remove not in cost_ben.imp_meas_future.keys())
        self.assertTrue(to_remove not in cost_ben.imp_meas_present.keys())
        self.assertEqual(len(cost_ben.imp_meas_present), 0)
        self.assertEqual(len(cost_ben.imp_meas_future), 4)
        self.assertEqual(len(cost_ben.color_rgb), 4)
        self.assertEqual(len(cost_ben.cost_ben_ratio), 3)
        self.assertEqual(len(cost_ben.benefit), 3)
Esempio n. 5
0
    def test_calc_imp_mat_pass(self):
        """Test save imp_mat"""
        # Read default entity values
        ent = Entity.from_excel(ENT_DEMO_TODAY)
        ent.check()

        # Read default hazard file
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        # Create impact object
        impact = Impact()

        # Assign centroids to exposures
        ent.exposures.assign_centroids(hazard)

        # Compute the impact over the whole exposures
        impact.calc(ent.exposures, ent.impact_funcs, hazard, save_mat=True)
        self.assertIsInstance(impact.imp_mat, sparse.csr_matrix)
        self.assertEqual(impact.imp_mat.shape,
                         (hazard.event_id.size, ent.exposures.gdf.value.size))
        np.testing.assert_array_almost_equal_nulp(np.array(
            impact.imp_mat.sum(axis=1)).ravel(),
                                                  impact.at_event,
                                                  nulp=5)
        np.testing.assert_array_almost_equal_nulp(
            np.sum(impact.imp_mat.toarray() * impact.frequency[:, None],
                   axis=0).reshape(-1), impact.eai_exp)
 def test_impact(self):
     ent = Entity.from_excel(ENT_DEMO_TODAY)
     ent.check()
     hazard = Hazard.from_mat(HAZ_TEST_MAT)
     impact = Impact()
     ent.exposures.assign_centroids(hazard)
     impact.calc(ent.exposures, ent.impact_funcs, hazard)
     return impact
    def test_combine_current_pass(self):
        """Test combine_measures with only future"""
        hazard = Hazard.from_mat(HAZ_TEST_MAT)
        entity = Entity.from_excel(ENT_DEMO_TODAY)
        entity.check()
        entity.exposures.ref_year = 2018
        cost_ben = CostBenefit()
        cost_ben.calc(hazard,
                      entity,
                      future_year=2040,
                      risk_func=risk_aai_agg,
                      imp_time_depen=None,
                      save_imp=True)

        new_name = 'combine'
        new_color = np.array([0.1, 0.1, 0.1])
        new_cb = cost_ben.combine_measures(['Mangroves', 'Seawall'],
                                           new_name,
                                           new_color,
                                           entity.disc_rates,
                                           imp_time_depen=None,
                                           risk_func=risk_aai_agg)

        self.assertTrue(np.allclose(new_cb.color_rgb[new_name], new_color))
        self.assertEqual(len(new_cb.imp_meas_present), 0)
        new_imp = cost_ben.imp_meas_future['no measure']['impact'].at_event - \
            cost_ben.imp_meas_future['Mangroves']['impact'].at_event
        new_imp += cost_ben.imp_meas_future['no measure']['impact'].at_event - \
            cost_ben.imp_meas_future['Seawall']['impact'].at_event
        new_imp = np.maximum(
            cost_ben.imp_meas_future['no measure']['impact'].at_event -
            new_imp, 0)
        self.assertTrue(
            np.allclose(new_cb.imp_meas_future[new_name]['impact'].at_event,
                        new_imp))
        self.assertAlmostEqual(
            new_cb.imp_meas_future[new_name]['risk'],
            np.sum(new_imp *
                   cost_ben.imp_meas_future['no measure']['impact'].frequency),
            5)
        self.assertAlmostEqual(
            new_cb.imp_meas_future[new_name]['cost'][0],
            cost_ben.imp_meas_future['Mangroves']['cost'][0] +
            cost_ben.imp_meas_future['Seawall']['cost'][0])
        self.assertAlmostEqual(new_cb.imp_meas_future[new_name]['cost'][1], 1)
        self.assertTrue(
            np.allclose(
                new_cb.imp_meas_future[new_name]['efc'].impact,
                new_cb.imp_meas_future[new_name]
                ['impact'].calc_freq_curve().impact))
        self.assertAlmostEqual(new_cb.imp_meas_future[new_name]['risk_transf'],
                               0)
        self.assertAlmostEqual(new_cb.benefit[new_name],
                               51781337529.07264,
                               places=3)
        self.assertAlmostEqual(new_cb.cost_ben_ratio[new_name],
                               0.19679962474434248)
Esempio n. 8
0
    def test_calib_instance(self):
        """Test save calib instance"""
        # Read default entity values
        ent = Entity()
        ent.read_excel(ENT_DEMO_TODAY)
        ent.check()

        # Read default hazard file
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        # get impact function from set
        imp_func = ent.impact_funcs.get_func(
            hazard.tag.haz_type, ent.exposures.gdf.impf_TC.median())

        # Assign centroids to exposures
        ent.exposures.assign_centroids(hazard)

        # create input frame
        df_in = pd.DataFrame.from_dict({
            'v_threshold': [25.7],
            'other_param': [2],
            'hazard': [HAZ_TEST_MAT]
        })
        df_in_yearly = pd.DataFrame.from_dict({
            'v_threshold': [25.7],
            'other_param': [2],
            'hazard': [HAZ_TEST_MAT]
        })

        # Compute the impact over the whole exposures
        df_out = calib_instance(hazard, ent.exposures, imp_func, df_in)
        df_out_yearly = calib_instance(hazard,
                                       ent.exposures,
                                       imp_func,
                                       df_in_yearly,
                                       yearly_impact=True)
        # calc Impact as comparison
        impact = Impact()
        impact.calc(ent.exposures, ent.impact_funcs, hazard)
        IYS = impact.calc_impact_year_set(all_years=True)

        # do the tests
        self.assertTrue(isinstance(df_out, pd.DataFrame))
        self.assertTrue(isinstance(df_out_yearly, pd.DataFrame))
        self.assertEqual(df_out.shape[0], hazard.event_id.size)
        self.assertEqual(df_out_yearly.shape[0], 161)
        self.assertTrue(all(df_out['event_id'] == hazard.event_id))
        self.assertTrue(
            all(df_out[df_in.columns[0]].isin(df_in[df_in.columns[0]])))
        self.assertTrue(
            all(df_out_yearly[df_in.columns[1]].isin(df_in[df_in.columns[1]])))
        self.assertTrue(
            all(df_out_yearly[df_in.columns[2]].isin(df_in[df_in.columns[2]])))
        self.assertTrue(
            all(df_out['impact_CLIMADA'].values == impact.at_event))
        self.assertTrue(
            all(df_out_yearly['impact_CLIMADA'].values == [*IYS.values()]))
Esempio n. 9
0
    def test_ref_value_insure_pass(self):
        """Test result against reference value"""
        # Read demo entity values
        # Set the entity default file to the demo one
        ent = Entity.from_excel(ENT_DEMO_TODAY)
        ent.check()

        # Read default hazard file
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        # Create impact object
        impact = Impact()
        impact.at_event = np.zeros(hazard.intensity.shape[0])
        impact.eai_exp = np.zeros(len(ent.exposures.gdf.value))
        impact.tot_value = 0

        # Assign centroids to exposures
        ent.exposures.assign_centroids(hazard)

        # Compute impact for 6th exposure
        iexp = 5
        # Take its impact function
        imp_id = ent.exposures.gdf.impf_TC[iexp]
        imp_fun = ent.impact_funcs.get_func(hazard.tag.haz_type, imp_id)
        # Compute
        insure_flag = True
        impact._exp_impact(np.array([iexp]), ent.exposures, hazard, imp_fun,
                           insure_flag)

        self.assertEqual(impact.eai_exp.size, ent.exposures.gdf.shape[0])
        self.assertEqual(impact.at_event.size, hazard.intensity.shape[0])

        events_pos = hazard.intensity[:, ent.exposures.gdf.
                                      centr_TC[iexp]].nonzero()[0]
        res_exp = np.zeros((ent.exposures.gdf.shape[0]))
        res_exp[iexp] = np.sum(impact.at_event[events_pos] *
                               hazard.frequency[events_pos])
        np.testing.assert_array_equal(res_exp, impact.eai_exp)

        self.assertEqual(0, impact.at_event[12])
        # Check first 3 values
        self.assertEqual(0, impact.at_event[12])
        self.assertEqual(0, impact.at_event[41])
        self.assertEqual(1.0626600695059455e+06, impact.at_event[44])

        # Check intermediate values
        self.assertEqual(0, impact.at_event[6281])
        self.assertEqual(0, impact.at_event[4998])
        self.assertEqual(0, impact.at_event[9527])
        self.assertEqual(1.3318063850487845e+08, impact.at_event[7192])
        self.assertEqual(4.667108555054083e+06, impact.at_event[8624])

        # Check last 3 values
        self.assertEqual(0, impact.at_event[14349])
        self.assertEqual(0, impact.at_event[14347])
        self.assertEqual(0, impact.at_event[14309])
    def test_calc_cb_no_change_pass(self):
        """Test _calc_cost_benefit without present value against reference value"""
        hazard = Hazard.from_mat(HAZ_TEST_MAT)
        entity = Entity.from_mat(ENT_TEST_MAT)
        entity.measures._data['TC'] = entity.measures._data.pop('XX')
        for meas in entity.measures.get_measure('TC'):
            meas.haz_type = 'TC'
        entity.check()

        cost_ben = CostBenefit()
        cost_ben._calc_impact_measures(hazard,
                                       entity.exposures,
                                       entity.measures,
                                       entity.impact_funcs,
                                       when='future',
                                       risk_func=risk_aai_agg,
                                       save_imp=True)

        cost_ben.present_year = 2018
        cost_ben.future_year = 2040
        cost_ben._calc_cost_benefit(entity.disc_rates)

        self.assertEqual(cost_ben.imp_meas_present, dict())
        self.assertEqual(len(cost_ben.imp_meas_future), 5)
        self.assertEqual(cost_ben.present_year, 2018)
        self.assertEqual(cost_ben.future_year, 2040)

        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Mangroves'],
                               0.04230714690616641)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Beach nourishment'],
                               0.06998836431681373)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Seawall'],
                               0.2679741183248266)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Building code'],
                               0.30286828677985717)

        self.assertAlmostEqual(cost_ben.benefit['Mangroves'],
                               3.100583368954022e+10,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Beach nourishment'],
                               2.468981832719974e+10,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Seawall'],
                               3.3132973770502796e+10,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Building code'],
                               3.0376240767284798e+10,
                               places=3)

        self.assertAlmostEqual(cost_ben.tot_climate_risk,
                               1.2150496306913972e+11,
                               places=3)
Esempio n. 11
0
    def test_impact_pass(self):
        """Plot impact exceedence frequency curves."""
        myent = Entity.from_excel(ENT_DEMO_TODAY)
        myent.exposures.check()
        myhaz = Hazard.from_mat(HAZ_DEMO_MAT)
        myimp = Impact()
        myimp.calc(myent.exposures, myent.impact_funcs, myhaz)
        ifc = myimp.calc_freq_curve()
        myax = ifc.plot()
        self.assertIn('Exceedance frequency curve', myax.get_title())

        ifc2 = ImpactFreqCurve()
        ifc2.return_per = ifc.return_per
        ifc2.impact = 1.5e11 * np.ones(ifc2.return_per.size)
        ifc2.unit = ''
        ifc2.label = 'prove'
        ifc2.plot(axis=myax)
Esempio n. 12
0
    def test_ref_value_pass(self):
        """Test result against reference value"""
        # Read default entity values
        ent = Entity.from_excel(ENT_DEMO_TODAY)
        ent.check()

        # Read default hazard file
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        # Create impact object
        impact = Impact()

        # Assign centroids to exposures
        ent.exposures.assign_centroids(hazard)

        # Compute the impact over the whole exposures
        impact.calc(ent.exposures, ent.impact_funcs, hazard)

        # Check result
        num_events = len(hazard.event_id)
        num_exp = ent.exposures.gdf.shape[0]
        # Check relative errors as well when absolute value gt 1.0e-7
        # impact.at_event == EDS.damage in MATLAB
        self.assertEqual(num_events, len(impact.at_event))
        self.assertEqual(0, impact.at_event[0])
        self.assertEqual(0, impact.at_event[int(num_events / 2)])
        self.assertAlmostEqual(1.472482938320243e+08, impact.at_event[13809])
        self.assertEqual(7.076504723057620e+10, impact.at_event[12147])
        self.assertEqual(0, impact.at_event[num_events - 1])
        # impact.eai_exp == EDS.ED_at_centroid in MATLAB
        self.assertEqual(num_exp, len(impact.eai_exp))
        self.assertAlmostEqual(1.518553670803242e+08, impact.eai_exp[0])
        self.assertAlmostEqual(1.373490457046383e+08,
                               impact.eai_exp[int(num_exp / 2)], 6)
        self.assertAlmostEqual(1.373490457046383e+08,
                               impact.eai_exp[int(num_exp / 2)], 5)
        self.assertAlmostEqual(1.066837260150042e+08,
                               impact.eai_exp[num_exp - 1], 6)
        self.assertAlmostEqual(1.066837260150042e+08,
                               impact.eai_exp[int(num_exp - 1)], 5)
        # impact.tot_value == EDS.Value in MATLAB
        # impact.aai_agg == EDS.ED in MATLAB
        self.assertAlmostEqual(6.570532945599105e+11, impact.tot_value)
        self.assertAlmostEqual(6.512201157564421e+09, impact.aai_agg, 5)
        self.assertAlmostEqual(6.512201157564421e+09, impact.aai_agg, 5)
Esempio n. 13
0
    def test_calc_impact_transf_pass(self):
        """Test calc_impact method: apply all measures and insurance"""

        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        entity = Entity.from_mat(ENT_TEST_MAT)
        entity.exposures.gdf.rename(columns={'impf': 'impf_TC'}, inplace=True)
        entity.measures._data['TC'] = entity.measures._data.pop('XX')
        for meas in entity.measures.get_measure('TC'):
            meas.haz_type = 'TC'
        meas = entity.measures.get_measure(name='Beach nourishment',
                                           haz_type='TC')
        meas.haz_type = 'TC'
        meas.hazard_inten_imp = (1, 0)
        meas.mdd_impact = (1, 0)
        meas.paa_impact = (1, 0)
        meas.risk_transf_attach = 5.0e8
        meas.risk_transf_cover = 1.0e9
        entity.check()

        imp, risk_transf = entity.measures.get_measure(
            name='Beach nourishment',
            haz_type='TC').calc_impact(entity.exposures, entity.impact_funcs,
                                       hazard)

        self.assertAlmostEqual(imp.aai_agg, 6.280804242609713e+09)
        self.assertAlmostEqual(imp.at_event[0], 0)
        self.assertAlmostEqual(imp.at_event[12], 8.648764833437817e+07)
        self.assertAlmostEqual(imp.at_event[41], 500000000)
        self.assertAlmostEqual(imp.at_event[11890], 6.498096646836635e+07)
        self.assertTrue(np.array_equal(imp.coord_exp, np.array([])))
        self.assertTrue(np.array_equal(imp.eai_exp, np.array([])))
        self.assertAlmostEqual(imp.tot_value, 6.570532945599105e+11)
        self.assertEqual(imp.unit, 'USD')
        self.assertEqual(imp.imp_mat.shape, (0, 0))
        self.assertTrue(np.array_equal(imp.event_id, hazard.event_id))
        self.assertTrue(np.array_equal(imp.date, hazard.date))
        self.assertEqual(imp.event_name, hazard.event_name)
        self.assertEqual(imp.tag['exp'].file_name,
                         entity.exposures.tag.file_name)
        self.assertEqual(imp.tag['haz'].file_name, hazard.tag.file_name)
        self.assertEqual(imp.tag['impf_set'].file_name,
                         entity.impact_funcs.tag.file_name)
        self.assertEqual(risk_transf.aai_agg, 2.3139691495470852e+08)
Esempio n. 14
0
    def test_select_event_identity_pass(self):
        """ test select same impact with event name, id and date """

        # Read default entity values
        ent = Entity.from_excel(ENT_DEMO_TODAY)
        ent.check()

        # Read default hazard file
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        # Create impact object
        imp = Impact()

        # Assign centroids to exposures
        ent.exposures.assign_centroids(hazard)

        # Compute the impact over the whole exposures
        imp.calc(ent.exposures, ent.impact_funcs, hazard, save_mat=True)

        sel_imp = imp.select(event_ids=imp.event_id,
                             event_names=imp.event_name,
                             dates=(min(imp.date), max(imp.date)))

        self.assertTrue(u_coord.equal_crs(sel_imp.crs, imp.crs))
        self.assertEqual(sel_imp.unit, imp.unit)

        np.testing.assert_array_equal(sel_imp.event_id, imp.event_id)
        self.assertEqual(sel_imp.event_name, imp.event_name)
        np.testing.assert_array_equal(sel_imp.date, imp.date)
        np.testing.assert_array_equal(sel_imp.frequency, imp.frequency)

        np.testing.assert_array_equal(sel_imp.at_event, imp.at_event)
        np.testing.assert_array_equal(sel_imp.imp_mat.todense(),
                                      imp.imp_mat.todense())
        np.testing.assert_array_equal(sel_imp.eai_exp, imp.eai_exp)
        self.assertAlmostEqual(round(sel_imp.aai_agg, 5),
                               round(imp.aai_agg, 5))

        self.assertEqual(sel_imp.tot_value, imp.tot_value)
        np.testing.assert_array_equal(sel_imp.coord_exp, imp.coord_exp)

        self.assertIsInstance(sel_imp, Impact)
        self.assertIsInstance(sel_imp.imp_mat, sparse.csr_matrix)
Esempio n. 15
0
    def test_hazard_fraction_pass(self):
        """Generate all possible plots of the hazard fraction."""
        hazard = Hazard.from_mat(HAZ_DEMO_MAT)
        hazard.event_name = [""] * hazard.event_id.size
        hazard.event_name[35] = "NNN_1185106_gen5"
        hazard.event_name[11897] = "GORDON_gen7"
        myax = hazard.plot_fraction(event=36)
        self.assertIn('Event ID 36: NNN_1185106_gen5', myax.get_title())

        myax = hazard.plot_fraction(event=-1)
        self.assertIn('1-largest Event. ID 11898: GORDON_gen7',
                      myax.get_title())

        myax = hazard.plot_fraction(centr=59)
        self.assertIn('Centroid 59: (30.0, -79.0)', myax.get_title())

        myax = hazard.plot_fraction(centr=-1)
        self.assertIn('1-largest Centroid. 79: (30.0, -77.0)',
                      myax.get_title())
Esempio n. 16
0
    def test_calc_impact_pass(self):
        """Test calc_impact method: apply all measures but insurance"""

        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        entity = Entity.from_mat(ENT_TEST_MAT)
        entity.exposures.gdf.rename(columns={'impf': 'impf_TC'}, inplace=True)
        entity.measures._data['TC'] = entity.measures._data.pop('XX')
        entity.measures.get_measure(name='Mangroves',
                                    haz_type='TC').haz_type = 'TC'
        for meas in entity.measures.get_measure('TC'):
            meas.haz_type = 'TC'
        entity.check()

        imp, risk_transf = entity.measures.get_measure(
            'TC', 'Mangroves').calc_impact(entity.exposures,
                                           entity.impact_funcs, hazard)

        self.assertAlmostEqual(imp.aai_agg, 4.850407096284983e+09)
        self.assertAlmostEqual(imp.at_event[0], 0)
        self.assertAlmostEqual(imp.at_event[12], 1.470194187501225e+07)
        self.assertAlmostEqual(imp.at_event[41], 4.7226357936631286e+08)
        self.assertAlmostEqual(imp.at_event[11890], 1.742110428135755e+07)
        self.assertTrue(
            np.array_equal(imp.coord_exp[:, 0], entity.exposures.gdf.latitude))
        self.assertTrue(
            np.array_equal(imp.coord_exp[:, 1],
                           entity.exposures.gdf.longitude))
        self.assertAlmostEqual(imp.eai_exp[0], 1.15677655725858e+08)
        self.assertAlmostEqual(imp.eai_exp[-1], 7.528669956120645e+07)
        self.assertAlmostEqual(imp.tot_value, 6.570532945599105e+11)
        self.assertEqual(imp.unit, 'USD')
        self.assertEqual(imp.imp_mat.shape, (0, 0))
        self.assertTrue(np.array_equal(imp.event_id, hazard.event_id))
        self.assertTrue(np.array_equal(imp.date, hazard.date))
        self.assertEqual(imp.event_name, hazard.event_name)
        self.assertEqual(imp.tag['exp'].file_name,
                         entity.exposures.tag.file_name)
        self.assertEqual(imp.tag['haz'].file_name, hazard.tag.file_name)
        self.assertEqual(imp.tag['impf_set'].file_name,
                         entity.impact_funcs.tag.file_name)
        self.assertEqual(risk_transf.aai_agg, 0)
Esempio n. 17
0
    def test_calc_impf_pass(self):
        """Execute when no impf_HAZ present, but only impf_"""
        ent = Entity.from_excel(ENT_DEMO_TODAY)
        self.assertTrue('impf_TC' in ent.exposures.gdf.columns)
        ent.exposures.gdf.rename(columns={'impf_TC': 'impf_'}, inplace=True)
        self.assertFalse('impf_TC' in ent.exposures.gdf.columns)
        ent.check()

        # Read default hazard file
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        # Create impact object
        impact = Impact()
        impact.calc(ent.exposures, ent.impact_funcs, hazard)

        # Check result
        num_events = len(hazard.event_id)
        num_exp = ent.exposures.gdf.shape[0]
        # Check relative errors as well when absolute value gt 1.0e-7
        # impact.at_event == EDS.damage in MATLAB
        self.assertEqual(num_events, len(impact.at_event))
        self.assertEqual(0, impact.at_event[0])
        self.assertEqual(0, impact.at_event[int(num_events / 2)])
        self.assertAlmostEqual(1.472482938320243e+08, impact.at_event[13809])
        self.assertEqual(7.076504723057620e+10, impact.at_event[12147])
        self.assertEqual(0, impact.at_event[num_events - 1])
        # impact.eai_exp == EDS.ED_at_centroid in MATLAB
        self.assertEqual(num_exp, len(impact.eai_exp))
        self.assertAlmostEqual(1.518553670803242e+08, impact.eai_exp[0])
        self.assertAlmostEqual(1.373490457046383e+08,
                               impact.eai_exp[int(num_exp / 2)], 6)
        self.assertAlmostEqual(1.373490457046383e+08,
                               impact.eai_exp[int(num_exp / 2)], 5)
        self.assertAlmostEqual(1.066837260150042e+08,
                               impact.eai_exp[num_exp - 1], 6)
        self.assertAlmostEqual(1.066837260150042e+08,
                               impact.eai_exp[int(num_exp - 1)], 5)
        # impact.tot_value == EDS.Value in MATLAB
        # impact.aai_agg == EDS.ED in MATLAB
        self.assertAlmostEqual(6.570532945599105e+11, impact.tot_value)
        self.assertAlmostEqual(6.512201157564421e+09, impact.aai_agg, 5)
        self.assertAlmostEqual(6.512201157564421e+09, impact.aai_agg, 5)
    def test_calc_no_change_pass(self):
        """Test calc without future change"""
        hazard = Hazard.from_mat(HAZ_TEST_MAT)
        entity = Entity.from_excel(ENT_DEMO_TODAY)
        entity.check()
        entity.exposures.ref_year = 2018
        cost_ben = CostBenefit()
        cost_ben.calc(hazard, entity, future_year=2040)

        self.assertEqual(cost_ben.imp_meas_present, dict())
        self.assertEqual(len(cost_ben.imp_meas_future), 5)
        self.assertEqual(cost_ben.present_year, 2018)
        self.assertEqual(cost_ben.future_year, 2040)

        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Mangroves'],
                               0.04230714690616641)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Beach nourishment'],
                               0.06998836431681373)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Seawall'],
                               0.2679741183248266)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Building code'],
                               0.30286828677985717)

        self.assertAlmostEqual(cost_ben.benefit['Mangroves'],
                               3.100583368954022e+10,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Beach nourishment'],
                               2.468981832719974e+10,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Seawall'],
                               3.3132973770502796e+10,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Building code'],
                               3.0376240767284798e+10,
                               places=3)

        self.assertAlmostEqual(cost_ben.tot_climate_risk,
                               1.2150496306913972e+11,
                               places=3)
Esempio n. 19
0
    def test_local_exceedance_imp_pass(self):
        """Test calc local impacts per return period"""
        # Read default entity values
        ent = Entity.from_excel(ENT_DEMO_TODAY)
        ent.check()

        # Read default hazard file
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        # Create impact object
        impact = Impact()
        # Assign centroids to exposures
        ent.exposures.assign_centroids(hazard)
        # Compute the impact over the whole exposures
        impact.calc(ent.exposures, ent.impact_funcs, hazard, save_mat=True)
        # Compute the impact per return period over the whole exposures
        impact_rp = impact.local_exceedance_imp(return_periods=(10, 40))

        self.assertIsInstance(impact_rp, np.ndarray)
        self.assertEqual(impact_rp.size, 2 * ent.exposures.gdf.value.size)
        self.assertAlmostEqual(np.max(impact_rp), 2916964966.388219, places=5)
        self.assertAlmostEqual(np.min(impact_rp), 444457580.131494, places=5)
Esempio n. 20
0
    def test_hazard_intensity_pass(self):
        """Generate all possible plots of the hazard intensity."""
        hazard = Hazard.from_mat(HAZ_DEMO_MAT)
        hazard.event_name = [""] * hazard.event_id.size
        hazard.event_name[35] = "NNN_1185106_gen5"
        hazard.event_name[3898] = "NNN_1190604_gen8"
        hazard.event_name[5488] = "NNN_1192804_gen8"
        myax = hazard.plot_intensity(event=36)
        self.assertIn('Event ID 36: NNN_1185106_gen5', myax.get_title())

        myax = hazard.plot_intensity(event=-1)
        self.assertIn('1-largest Event. ID 3899: NNN_1190604_gen8',
                      myax.get_title())

        myax = hazard.plot_intensity(event=-4)
        self.assertIn('4-largest Event. ID 5489: NNN_1192804_gen8',
                      myax.get_title())

        myax = hazard.plot_intensity(event=0)
        self.assertIn('TC max intensity at each point', myax.get_title())

        myax = hazard.plot_intensity(centr=59)
        self.assertIn('Centroid 59: (30.0, -79.0)', myax.get_title())

        myax = hazard.plot_intensity(centr=-1)
        self.assertIn('1-largest Centroid. 99: (30.0, -75.0)',
                      myax.get_title())

        myax = hazard.plot_intensity(centr=-4)
        self.assertIn('4-largest Centroid. 69: (30.0, -78.0)',
                      myax.get_title())

        myax = hazard.plot_intensity(centr=0)
        self.assertIn('TC max intensity at each event', myax.get_title())

        myax = hazard.plot_intensity(event='NNN_1192804_gen8')
        self.assertIn('NNN_1192804_gen8', myax.get_title())
Esempio n. 21
0
    def test_filter_exposures_pass(self):
        """Test _filter_exposures method with two values"""
        meas = Measure()
        meas.exp_region_id = [3, 4]
        meas.haz_type = 'TC'

        exp = Exposures.from_mat(ENT_TEST_MAT)
        exp.gdf.rename(columns={
            'impf_': 'impf_TC',
            'centr_': 'centr_TC'
        },
                       inplace=True)
        exp.gdf['region_id'] = np.ones(exp.gdf.shape[0])
        exp.gdf.region_id.values[:exp.gdf.shape[0] // 2] = 3
        exp.gdf.region_id[0] = 4
        exp.check()

        imp_set = ImpactFuncSet.from_mat(ENT_TEST_MAT)

        haz = Hazard.from_mat(HAZ_TEST_MAT)
        exp.assign_centroids(haz)

        new_exp = copy.deepcopy(exp)
        new_exp.gdf['value'] *= 3
        new_exp.gdf['impf_TC'].values[:20] = 2
        new_exp.gdf['impf_TC'].values[20:40] = 3
        new_exp.gdf['impf_TC'].values[40:] = 1

        new_ifs = copy.deepcopy(imp_set)
        new_ifs.get_func('TC')[1].intensity += 1
        ref_ifs = copy.deepcopy(new_ifs)

        new_haz = copy.deepcopy(haz)
        new_haz.intensity *= 4

        res_exp, res_ifs, res_haz = meas._filter_exposures(
            exp, imp_set, haz, new_exp.copy(deep=True), new_ifs, new_haz)

        # unchanged meta data
        self.assertEqual(res_exp.ref_year, exp.ref_year)
        self.assertEqual(res_exp.value_unit, exp.value_unit)
        self.assertEqual(res_exp.tag.file_name, exp.tag.file_name)
        self.assertEqual(res_exp.tag.description, exp.tag.description)
        self.assertTrue(u_coord.equal_crs(res_exp.crs, exp.crs))
        self.assertTrue(u_coord.equal_crs(res_exp.gdf.crs, exp.gdf.crs))

        # regions (that is just input data, no need for testing, but it makes the changed and unchanged parts obious)
        self.assertTrue(np.array_equal(res_exp.gdf.region_id.values[0], 4))
        self.assertTrue(
            np.array_equal(res_exp.gdf.region_id.values[1:25],
                           np.ones(24) * 3))
        self.assertTrue(
            np.array_equal(res_exp.gdf.region_id.values[25:], np.ones(25)))

        # changed exposures
        self.assertTrue(
            np.array_equal(res_exp.gdf.value.values[:25],
                           new_exp.gdf.value.values[:25]))
        self.assertTrue(
            np.all(
                np.not_equal(res_exp.gdf.value.values[:25],
                             exp.gdf.value.values[:25])))
        self.assertTrue(
            np.all(
                np.not_equal(res_exp.gdf.impf_TC.values[:25],
                             new_exp.gdf.impf_TC.values[:25])))
        self.assertTrue(
            np.array_equal(res_exp.gdf.latitude.values[:25],
                           new_exp.gdf.latitude.values[:25]))
        self.assertTrue(
            np.array_equal(res_exp.gdf.longitude.values[:25],
                           new_exp.gdf.longitude.values[:25]))

        # unchanged exposures
        self.assertTrue(
            np.array_equal(res_exp.gdf.value.values[25:],
                           exp.gdf.value.values[25:]))
        self.assertTrue(
            np.all(
                np.not_equal(res_exp.gdf.value.values[25:],
                             new_exp.gdf.value.values[25:])))
        self.assertTrue(
            np.array_equal(res_exp.gdf.impf_TC.values[25:],
                           exp.gdf.impf_TC.values[25:]))
        self.assertTrue(
            np.array_equal(res_exp.gdf.latitude.values[25:],
                           exp.gdf.latitude.values[25:]))
        self.assertTrue(
            np.array_equal(res_exp.gdf.longitude.values[25:],
                           exp.gdf.longitude.values[25:]))

        # unchanged impact functions
        self.assertEqual(list(res_ifs.get_func().keys()), [meas.haz_type])
        self.assertEqual(res_ifs.get_func()[meas.haz_type][1].id,
                         imp_set.get_func()[meas.haz_type][1].id)
        self.assertTrue(
            np.array_equal(res_ifs.get_func()[meas.haz_type][1].intensity,
                           imp_set.get_func()[meas.haz_type][1].intensity))
        self.assertEqual(res_ifs.get_func()[meas.haz_type][3].id,
                         imp_set.get_func()[meas.haz_type][3].id)
        self.assertTrue(
            np.array_equal(res_ifs.get_func()[meas.haz_type][3].intensity,
                           imp_set.get_func()[meas.haz_type][3].intensity))

        # changed impact functions
        self.assertTrue(
            np.array_equal(
                res_ifs.get_func()[meas.haz_type][1 + IMPF_ID_FACT].intensity,
                ref_ifs.get_func()[meas.haz_type][1].intensity))
        self.assertTrue(
            np.array_equal(
                res_ifs.get_func()[meas.haz_type][1 + IMPF_ID_FACT].paa,
                ref_ifs.get_func()[meas.haz_type][1].paa))
        self.assertTrue(
            np.array_equal(
                res_ifs.get_func()[meas.haz_type][1 + IMPF_ID_FACT].mdd,
                ref_ifs.get_func()[meas.haz_type][1].mdd))
        self.assertTrue(
            np.array_equal(
                res_ifs.get_func()[meas.haz_type][3 + IMPF_ID_FACT].intensity,
                ref_ifs.get_func()[meas.haz_type][3].intensity))
        self.assertTrue(
            np.array_equal(
                res_ifs.get_func()[meas.haz_type][3 + IMPF_ID_FACT].paa,
                ref_ifs.get_func()[meas.haz_type][3].paa))
        self.assertTrue(
            np.array_equal(
                res_ifs.get_func()[meas.haz_type][3 + IMPF_ID_FACT].mdd,
                ref_ifs.get_func()[meas.haz_type][3].mdd))

        # unchanged hazard
        self.assertTrue(
            np.array_equal(res_haz.intensity[:, :36].toarray(),
                           haz.intensity[:, :36].toarray()))
        self.assertTrue(
            np.array_equal(res_haz.intensity[:, 37:46].toarray(),
                           haz.intensity[:, 37:46].toarray()))
        self.assertTrue(
            np.array_equal(res_haz.intensity[:, 47:].toarray(),
                           haz.intensity[:, 47:].toarray()))

        # changed hazard
        self.assertTrue(
            np.array_equal(res_haz.intensity[[36, 46]].toarray(),
                           new_haz.intensity[[36, 46]].toarray()))
    def test_calc_cb_change_pass(self):
        """Test _calc_cost_benefit with present value against reference value"""
        hazard = Hazard.from_mat(HAZ_TEST_MAT)
        entity = Entity.from_mat(ENT_TEST_MAT)
        entity.measures._data['TC'] = entity.measures._data.pop('XX')
        for meas in entity.measures.get_measure('TC'):
            meas.haz_type = 'TC'
        entity.check()

        cost_ben = CostBenefit()
        cost_ben._calc_impact_measures(hazard,
                                       entity.exposures,
                                       entity.measures,
                                       entity.impact_funcs,
                                       when='present',
                                       risk_func=risk_aai_agg,
                                       save_imp=False)

        ent_future = Entity.from_excel(ENT_DEMO_FUTURE)
        ent_future.check()

        haz_future = copy.deepcopy(hazard)
        haz_future.intensity.data += 25

        cost_ben._calc_impact_measures(haz_future,
                                       ent_future.exposures,
                                       ent_future.measures,
                                       ent_future.impact_funcs,
                                       when='future',
                                       risk_func=risk_aai_agg,
                                       save_imp=False)

        cost_ben.present_year = 2018
        cost_ben.future_year = 2040
        cost_ben._calc_cost_benefit(entity.disc_rates, imp_time_depen=1)

        self.assertEqual(cost_ben.present_year, 2018)
        self.assertEqual(cost_ben.future_year, 2040)
        self.assertAlmostEqual(cost_ben.tot_climate_risk,
                               5.768659152882021e+11,
                               places=3)

        self.assertAlmostEqual(cost_ben.imp_meas_present['no measure']['risk'],
                               6.51220115756442e+09,
                               places=3)
        self.assertAlmostEqual(cost_ben.imp_meas_present['Mangroves']['risk'],
                               4.850407096284983e+09,
                               places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_present['Beach nourishment']['risk'],
            5.188921355413834e+09,
            places=3)
        self.assertAlmostEqual(cost_ben.imp_meas_present['Seawall']['risk'],
                               4.736400526119911e+09,
                               places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_present['Building code']['risk'],
            4.884150868173321e+09,
            places=3)

        self.assertAlmostEqual(cost_ben.imp_meas_future['no measure']['risk'],
                               5.9506659786664024e+10,
                               places=3)
        self.assertAlmostEqual(cost_ben.imp_meas_future['Mangroves']['risk'],
                               4.826231151473135e+10,
                               places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Beach nourishment']['risk'],
            5.0647250923231674e+10,
            places=3)
        self.assertAlmostEqual(cost_ben.imp_meas_future['Seawall']['risk'],
                               21089567135.7345,
                               places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Building code']['risk'],
            4.462999483999791e+10,
            places=3)

        self.assertAlmostEqual(cost_ben.benefit['Mangroves'],
                               113345027690.81276,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Beach nourishment'],
                               89444869971.53653,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Seawall'],
                               347977469896.1333,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Building code'],
                               144216478822.05154,
                               places=3)

        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Mangroves'],
                               0.011573232523528404)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Beach nourishment'],
                               0.01931916274851638)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Seawall'],
                               0.025515385913577368)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Building code'],
                               0.06379298728650741)

        self.assertAlmostEqual(cost_ben.tot_climate_risk,
                               576865915288.2021,
                               places=3)
    def test_calc_impact_measures_pass(self):
        """Test _calc_impact_measures against reference value"""
        self.assertTrue(HAZ_TEST_MAT.is_file(),
                        "{} is not a file".format(HAZ_TEST_MAT))
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        self.assertTrue(ENT_TEST_MAT.is_file(),
                        "{} is not a file".format(ENT_TEST_MAT))
        entity = Entity.from_mat(ENT_TEST_MAT)
        entity.check()
        entity.measures._data['TC'] = entity.measures._data.pop('XX')
        for meas in entity.measures.get_measure('TC'):
            meas.haz_type = 'TC'
        entity.check()

        cost_ben = CostBenefit()
        cost_ben._calc_impact_measures(hazard,
                                       entity.exposures,
                                       entity.measures,
                                       entity.impact_funcs,
                                       when='future',
                                       risk_func=risk_aai_agg,
                                       save_imp=True)

        self.assertEqual(cost_ben.imp_meas_present, dict())
        self.assertEqual(cost_ben.cost_ben_ratio, dict())
        self.assertEqual(cost_ben.benefit, dict())
        self.assertEqual(cost_ben.tot_climate_risk, 0.0)
        self.assertEqual(cost_ben.present_year, 2016)
        self.assertEqual(cost_ben.future_year, 2030)

        self.assertEqual(cost_ben.imp_meas_future['no measure']['cost'],
                         (0, 0))
        self.assertAlmostEqual(cost_ben.imp_meas_future['no measure']['risk'],
                               6.51220115756442e+09,
                               places=3)
        new_efc = cost_ben.imp_meas_future['no measure'][
            'impact'].calc_freq_curve()
        self.assertTrue(
            np.allclose(
                new_efc.return_per,
                cost_ben.imp_meas_future['no measure']['efc'].return_per))
        self.assertTrue(
            np.allclose(new_efc.impact,
                        cost_ben.imp_meas_future['no measure']['efc'].impact))
        self.assertEqual(
            cost_ben.imp_meas_future['no measure']
            ['impact'].at_event.nonzero()[0].size, 841)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['no measure']['impact'].at_event[14082],
            8.801682862431524e+06,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['no measure']['impact'].tot_value,
            6.570532945599105e+11,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['no measure']['impact'].aai_agg,
            6.51220115756442e+09,
            places=3)

        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Mangroves']['cost'][0],
            1.3117683608515418e+09,
            places=3)
        self.assertEqual(cost_ben.imp_meas_future['Mangroves']['cost'][1], 1)
        self.assertAlmostEqual(cost_ben.imp_meas_future['Mangroves']['risk'],
                               4.850407096284983e+09,
                               places=3)
        new_efc = cost_ben.imp_meas_future['Mangroves'][
            'impact'].calc_freq_curve()
        self.assertTrue(
            np.allclose(
                new_efc.return_per,
                cost_ben.imp_meas_future['Mangroves']['efc'].return_per))
        self.assertTrue(
            np.allclose(new_efc.impact,
                        cost_ben.imp_meas_future['Mangroves']['efc'].impact))
        self.assertEqual(
            cost_ben.imp_meas_future['Mangroves']['impact'].at_event.nonzero()
            [0].size, 665)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Mangroves']['impact'].at_event[13901],
            1.29576562770977e+09,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Mangroves']['impact'].tot_value,
            6.570532945599105e+11,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Mangroves']['impact'].aai_agg,
            4.850407096284983e+09,
            places=3)

        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Beach nourishment']['cost'][0],
            1.728000000000000e+09,
            places=3)
        self.assertEqual(
            cost_ben.imp_meas_future['Beach nourishment']['cost'][1], 1)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Beach nourishment']['risk'],
            5.188921355413834e+09,
            places=3)
        new_efc = cost_ben.imp_meas_future['Beach nourishment'][
            'impact'].calc_freq_curve()
        self.assertTrue(
            np.allclose(
                new_efc.return_per,
                cost_ben.imp_meas_future['Beach nourishment']
                ['efc'].return_per))
        self.assertTrue(
            np.allclose(
                new_efc.impact,
                cost_ben.imp_meas_future['Beach nourishment']['efc'].impact))
        self.assertEqual(
            cost_ben.imp_meas_future['Beach nourishment']
            ['impact'].at_event.nonzero()[0].size, 702)
        self.assertEqual(
            cost_ben.imp_meas_future['Beach nourishment']
            ['impact'].at_event[1110], 0.0)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Beach nourishment']['impact'].eai_exp[5],
            1.1133679079730146e+08,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Beach nourishment']['impact'].tot_value,
            6.570532945599105e+11,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Beach nourishment']['impact'].aai_agg,
            5.188921355413834e+09,
            places=3)

        self.assertAlmostEqual(cost_ben.imp_meas_future['Seawall']['cost'][0],
                               8.878779433630093e+09,
                               places=3)
        self.assertEqual(cost_ben.imp_meas_future['Seawall']['cost'][1], 1)
        self.assertAlmostEqual(cost_ben.imp_meas_future['Seawall']['risk'],
                               4.736400526119911e+09,
                               places=3)
        new_efc = cost_ben.imp_meas_future['Seawall'][
            'impact'].calc_freq_curve()
        self.assertTrue(
            np.allclose(new_efc.return_per,
                        cost_ben.imp_meas_future['Seawall']['efc'].return_per))
        self.assertTrue(
            np.allclose(new_efc.impact,
                        cost_ben.imp_meas_future['Seawall']['efc'].impact))
        self.assertEqual(
            cost_ben.imp_meas_future['Seawall']['impact'].at_event.nonzero()
            [0].size, 73)
        self.assertEqual(
            cost_ben.imp_meas_future['Seawall']['impact'].at_event[1229], 0.0)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Seawall']['impact'].tot_value,
            6.570532945599105e+11,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Seawall']['impact'].aai_agg,
            4.736400526119911e+09,
            places=3)

        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Building code']['cost'][0],
            9.200000000000000e+09,
            places=3)
        self.assertEqual(cost_ben.imp_meas_future['Building code']['cost'][1],
                         1)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Building code']['risk'],
            4.884150868173321e+09,
            places=3)
        new_efc = cost_ben.imp_meas_future['Building code'][
            'impact'].calc_freq_curve()
        self.assertTrue(
            np.allclose(
                new_efc.return_per,
                cost_ben.imp_meas_future['Building code']['efc'].return_per))
        self.assertTrue(
            np.allclose(
                new_efc.impact,
                cost_ben.imp_meas_future['Building code']['efc'].impact))
        self.assertEqual(
            cost_ben.imp_meas_future['Building code']
            ['impact'].at_event.nonzero()[0].size, 841)
        self.assertEqual(
            cost_ben.imp_meas_future['Building code']['impact'].at_event[122],
            0.0)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Building code']['impact'].eai_exp[11],
            7.757060129393841e+07,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Building code']['impact'].tot_value,
            6.570532945599105e+11,
            places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Building code']['impact'].aai_agg,
            4.884150868173321e+09,
            places=3)
    def test_apply_transf_future_pass(self):
        """Test apply_risk_transfer with present and future"""
        hazard = Hazard.from_mat(HAZ_TEST_MAT)
        entity = Entity.from_excel(ENT_DEMO_TODAY)
        entity.check()
        entity.exposures.ref_year = 2018

        fut_ent = copy.deepcopy(entity)
        fut_ent.exposures.ref_year = 2040

        cost_ben = CostBenefit()
        cost_ben.calc(hazard,
                      entity,
                      ent_future=fut_ent,
                      risk_func=risk_aai_agg,
                      imp_time_depen=None,
                      save_imp=True)

        new_name = 'combine'
        new_color = np.array([0.1, 0.1, 0.1])
        risk_transf = (1.0e7, 15.0e11, 1)
        new_cb = cost_ben.combine_measures(['Mangroves', 'Seawall'],
                                           new_name,
                                           new_color,
                                           entity.disc_rates,
                                           imp_time_depen=None,
                                           risk_func=risk_aai_agg)
        new_cb.apply_risk_transfer(new_name,
                                   risk_transf[0],
                                   risk_transf[1],
                                   entity.disc_rates,
                                   cost_fix=0,
                                   cost_factor=risk_transf[2],
                                   imp_time_depen=1,
                                   risk_func=risk_aai_agg)

        tr_name = 'risk transfer (' + new_name + ')'
        new_imp = cost_ben.imp_meas_future['no measure']['impact'].at_event - \
            cost_ben.imp_meas_future['Mangroves']['impact'].at_event
        new_imp += cost_ben.imp_meas_future['no measure']['impact'].at_event - \
            cost_ben.imp_meas_future['Seawall']['impact'].at_event
        new_imp = np.maximum(
            cost_ben.imp_meas_future['no measure']['impact'].at_event -
            new_imp, 0)
        imp_layer = np.minimum(np.maximum(new_imp - risk_transf[0], 0),
                               risk_transf[1])
        risk_transfer = np.sum(
            imp_layer *
            cost_ben.imp_meas_future['no measure']['impact'].frequency)
        new_imp = np.maximum(new_imp - imp_layer, 0)

        self.assertTrue(np.allclose(new_cb.color_rgb[new_name], new_color))
        self.assertEqual(len(new_cb.imp_meas_present), 3)
        self.assertTrue(
            np.allclose(new_cb.imp_meas_future[tr_name]['impact'].at_event,
                        new_imp))
        self.assertTrue(
            np.allclose(new_cb.imp_meas_present[tr_name]['impact'].at_event,
                        new_imp))
        self.assertAlmostEqual(
            new_cb.imp_meas_future[tr_name]['risk'],
            np.sum(new_imp *
                   cost_ben.imp_meas_future['no measure']['impact'].frequency),
            5)
        self.assertAlmostEqual(
            new_cb.imp_meas_present[tr_name]['risk'],
            np.sum(new_imp *
                   cost_ben.imp_meas_future['no measure']['impact'].frequency),
            5)
        self.assertAlmostEqual(new_cb.cost_ben_ratio[tr_name] *
                               new_cb.benefit[tr_name],
                               69715165679.7042,
                               places=3)
        self.assertTrue(
            np.allclose(
                new_cb.imp_meas_future[tr_name]['efc'].impact,
                new_cb.imp_meas_future[tr_name]
                ['impact'].calc_freq_curve().impact))
        self.assertAlmostEqual(new_cb.imp_meas_future[tr_name]['risk_transf'],
                               risk_transfer)
        # benefit = impact layer
        self.assertAlmostEqual(new_cb.benefit[tr_name], 69715165679.7042, 4)
        self.assertAlmostEqual(new_cb.cost_ben_ratio[tr_name], 1)
    def test_calc_change_pass(self):
        """Test calc with future change"""
        # present
        hazard = Hazard.from_mat(HAZ_TEST_MAT)
        entity = Entity.from_excel(ENT_DEMO_TODAY)
        entity.exposures.gdf.rename(columns={'impf_': 'impf_TC'}, inplace=True)
        entity.check()
        entity.exposures.ref_year = 2018

        # future
        ent_future = Entity.from_excel(ENT_DEMO_FUTURE)
        ent_future.check()
        ent_future.exposures.ref_year = 2040

        haz_future = copy.deepcopy(hazard)
        haz_future.intensity.data += 25

        cost_ben = CostBenefit()
        cost_ben.calc(hazard, entity, haz_future, ent_future)

        self.assertEqual(cost_ben.present_year, 2018)
        self.assertEqual(cost_ben.future_year, 2040)
        self.assertAlmostEqual(cost_ben.tot_climate_risk,
                               5.768659152882021e+11,
                               places=3)

        self.assertAlmostEqual(cost_ben.imp_meas_present['no measure']['risk'],
                               6.51220115756442e+09,
                               places=3)
        self.assertAlmostEqual(cost_ben.imp_meas_present['Mangroves']['risk'],
                               4.850407096284983e+09,
                               places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_present['Beach nourishment']['risk'],
            5.188921355413834e+09,
            places=3)
        self.assertAlmostEqual(cost_ben.imp_meas_present['Seawall']['risk'],
                               4.736400526119911e+09,
                               places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_present['Building code']['risk'],
            4.884150868173321e+09,
            places=3)

        self.assertAlmostEqual(cost_ben.imp_meas_future['no measure']['risk'],
                               5.9506659786664024e+10,
                               places=3)
        self.assertAlmostEqual(cost_ben.imp_meas_future['Mangroves']['risk'],
                               4.826231151473135e+10,
                               places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Beach nourishment']['risk'],
            5.0647250923231674e+10,
            places=3)
        self.assertAlmostEqual(cost_ben.imp_meas_future['Seawall']['risk'],
                               21089567135.7345,
                               places=3)
        self.assertAlmostEqual(
            cost_ben.imp_meas_future['Building code']['risk'],
            4.462999483999791e+10,
            places=3)

        self.assertAlmostEqual(cost_ben.benefit['Mangroves'],
                               113345027690.81276,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Beach nourishment'],
                               89444869971.53653,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Seawall'],
                               347977469896.1333,
                               places=3)
        self.assertAlmostEqual(cost_ben.benefit['Building code'],
                               144216478822.05154,
                               places=3)

        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Mangroves'],
                               0.011573232523528404)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Beach nourishment'],
                               0.01931916274851638)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Seawall'],
                               0.025515385913577368)
        self.assertAlmostEqual(cost_ben.cost_ben_ratio['Building code'],
                               0.06379298728650741)

        self.assertAlmostEqual(cost_ben.tot_climate_risk,
                               576865915288.2021,
                               places=3)
Esempio n. 26
0
    def test_apply_ref_pass(self):
        """Test apply method: apply all measures but insurance"""
        hazard = Hazard.from_mat(HAZ_TEST_MAT)

        entity = Entity.from_mat(ENT_TEST_MAT)
        entity.measures._data['TC'] = entity.measures._data.pop('XX')
        for meas in entity.measures.get_measure('TC'):
            meas.haz_type = 'TC'
        entity.check()

        new_exp, new_ifs, new_haz = entity.measures.get_measure(
            'TC', 'Mangroves').apply(entity.exposures, entity.impact_funcs,
                                     hazard)

        self.assertTrue(new_exp is entity.exposures)
        self.assertTrue(new_haz is hazard)
        self.assertFalse(new_ifs is entity.impact_funcs)

        new_imp = new_ifs.get_func('TC')[0]
        self.assertTrue(
            np.array_equal(
                new_imp.intensity,
                np.array([4., 24., 34., 44., 54., 64., 74., 84., 104.])))
        self.assertTrue(
            np.allclose(
                new_imp.mdd,
                np.array([
                    0, 0, 0.021857142857143, 0.035887500000000,
                    0.053977415307403, 0.103534246575342, 0.180414000000000,
                    0.410796000000000, 0.410796000000000
                ])))
        self.assertTrue(
            np.allclose(
                new_imp.paa,
                np.array([
                    0, 0.005000000000000, 0.042000000000000, 0.160000000000000,
                    0.398500000000000, 0.657000000000000, 1.000000000000000,
                    1.000000000000000, 1.000000000000000
                ])))

        new_imp = new_ifs.get_func('TC')[1]
        self.assertTrue(
            np.array_equal(
                new_imp.intensity,
                np.array([4., 24., 34., 44., 54., 64., 74., 84., 104.])))
        self.assertTrue(
            np.allclose(
                new_imp.mdd,
                np.array([
                    0, 0, 0, 0.025000000000000, 0.054054054054054,
                    0.104615384615385, 0.211764705882353, 0.400000000000000,
                    0.400000000000000
                ])))
        self.assertTrue(
            np.allclose(
                new_imp.paa,
                np.array([
                    0, 0.004000000000000, 0, 0.160000000000000,
                    0.370000000000000, 0.650000000000000, 0.850000000000000,
                    1.000000000000000, 1.000000000000000
                ])))