def test_run(self):
        """TestVolcanoPolygonBuildingFunction: Test running the IF."""
        volcano_path = standard_data_path('hazard', 'volcano_krb.shp')
        building_path = standard_data_path('exposure', 'buildings.shp')

        hazard_layer = read_layer(volcano_path)
        exposure_layer = read_layer(building_path)

        impact_function = VolcanoPolygonBuildingFunction.instance()
        impact_function.hazard = SafeLayer(hazard_layer)
        impact_function.exposure = SafeLayer(exposure_layer)
        impact_function.run()
        impact_layer = impact_function.impact

        # Check the question
        expected_question = (
            'In the event of volcano krb how many buildings might be '
            'affected?')
        self.assertEqual(expected_question, impact_function.question)

        # The buildings should all be categorised into 5000 zone
        zone_sum = impact_layer.get_data(
            attribute=impact_function.target_field)
        krb3_zone_count = zone_sum.count('High Hazard Zone')
        krb2_zone_count = zone_sum.count('Medium Hazard Zone')
        # The result (counted by hand)
        expected_krb3_count = 11
        expected_krb2_count = 161
        message = 'Expecting %s for KRB III zone, but it returns %s' % (
            krb3_zone_count, expected_krb3_count)
        self.assertEqual(krb3_zone_count, expected_krb3_count, message)
        message = 'Expecting %s for KRB II zone, but it returns %s' % (
            krb2_zone_count, expected_krb2_count)
        self.assertEqual(krb2_zone_count, expected_krb2_count, message)
Example #2
0
    def calculate_impact(self):
        if_manager = ImpactFunctionManager()
        function_id = self.function_id
        impact_function = if_manager.get_instance(function_id)

        impact_function.hazard = SafeLayer(self.hazard_layer)
        impact_function.exposure = SafeLayer(self.exposure_layer)

        try:
            self.impact_layer = safe_calculate_impact(impact_function)
            self.set_style()
        except ZeroImpactException as e:
            # in case zero impact, just return
            LOGGER.info('No impact detected')
            LOGGER.info(e.message)
            return

        # copy results of impact to report_path directory
        base_name, _ = os.path.splitext(self.impact_layer.filename)
        dir_name = os.path.dirname(self.impact_layer.filename)
        for (root, dirs, files) in os.walk(dir_name):
            for f in files:
                source_filename = os.path.join(root, f)
                if source_filename.find(base_name) >= 0:
                    extensions = source_filename.replace(base_name, '')
                    new_path = os.path.join(self.report_path,
                                            'impact' + extensions)
                    shutil.copy(source_filename, new_path)

        self.impact_layer = read_layer(self.impact_path)
    def test_run(self):
        impact_function = FloodRasterBuildingFunction.instance()

        hazard_path = standard_data_path('hazard',
                                         'continuous_flood_20_20.asc')
        exposure_path = standard_data_path('exposure', 'buildings.shp')
        hazard_layer = read_layer(hazard_path)
        exposure_layer = read_layer(exposure_path)

        impact_function.hazard = SafeLayer(hazard_layer)
        impact_function.exposure = SafeLayer(exposure_layer)
        impact_function.run()
        impact_layer = impact_function.impact

        # Extract calculated result
        impact_data = impact_layer.get_data()
        self.assertEqual(len(impact_data), 181)

        # 1 = inundated, 2 = wet, 3 = dry
        expected_result = {1: 64, 2: 117, 3: 0}

        result = {1: 0, 2: 0, 3: 0}
        for feature in impact_data:
            inundated_status = feature[impact_function.target_field]
            result[inundated_status] += 1

        message = 'Expecting %s, but it returns %s' % (expected_result, result)
        self.assertEqual(expected_result, result, message)
    def test_run(self):
        function = AshRasterPopulationFunction.instance()

        hazard_path = standard_data_path('hazard', 'ash_raster_wgs84.tif')
        exposure_path = standard_data_path(
            'exposure', 'pop_binary_raster_20_20.asc')
        # We need clipping for both layers to be in the same dimension
        clipped_hazard, clipped_exposure = clip_layers(
            hazard_path, exposure_path)

        hazard_layer = read_layer(clipped_hazard.source())
        exposure_layer = read_layer(clipped_exposure.source())

        # Let's set the extent to the hazard extent
        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.run()
        impact = function.impact
        expected = [
            [u'Population in very low hazard zone', 0],
            [u'Population in medium hazard zone', 1374],
            [u'Population in high hazard zone', 20],
            [u'Population in very high hazard zone', 0],
            [u'Population in low hazard zone', 8443],
            [u'Total affected population', 9837],
            [u'Unaffected population', 0],
            [u'Total population', 9837],
            [u'Population needing evacuation <sup>1</sup>', 9837]
        ]
        self.assertListEqual(
            expected, impact.impact_data['impact summary']['fields'])
    def test_run(self):
        function = FloodEvacuationRasterHazardFunction.instance()

        hazard_path = test_data_path('hazard', 'continuous_flood_20_20.asc')
        exposure_path = test_data_path('exposure',
                                       'pop_binary_raster_20_20.asc')
        hazard_layer = read_layer(hazard_path)
        exposure_layer = read_layer(exposure_path)

        function.parameters['thresholds'].value = [0.5, 0.7, 1.0]
        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.run()
        impact = function.impact

        # Count of flooded objects is calculated "by the hands"
        # print "keywords", keywords
        keywords = impact.get_keywords()
        evacuated = float(keywords['evacuated'])
        total_needs_full = keywords['total_needs']
        total_needs_weekly = OrderedDict([[x['table name'], x['amount']]
                                          for x in total_needs_full['weekly']])
        total_needs_single = OrderedDict([[x['table name'], x['amount']]
                                          for x in total_needs_full['single']])

        expected_evacuated = 100
        self.assertEqual(evacuated, expected_evacuated)
        self.assertEqual(total_needs_weekly['Rice [kg]'], 280)
        self.assertEqual(total_needs_weekly['Family Kits'], 20)
        self.assertEqual(total_needs_weekly['Drinking Water [l]'], 1750)
        self.assertEqual(total_needs_weekly['Clean Water [l]'], 6700)
        self.assertEqual(total_needs_single['Toilets'], 5)
Example #6
0
    def test_run(self):
        function = ContinuousHazardPopulationFunction.instance()

        hazard_path = test_data_path('hazard', 'continuous_flood_20_20.asc')
        exposure_path = test_data_path('exposure',
                                       'pop_binary_raster_20_20.asc')
        hazard_layer = read_layer(hazard_path)
        exposure_layer = read_layer(exposure_path)

        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.run()
        impact = function.impact

        # print "keywords", keywords
        keywords = impact.get_keywords()
        total_needs_full = keywords['total_needs']
        total_needs_weekly = OrderedDict([[x['table name'], x['amount']]
                                          for x in total_needs_full['weekly']])
        total_needs_single = OrderedDict([[x['table name'], x['amount']]
                                          for x in total_needs_full['single']])

        self.assertEqual(total_needs_weekly['Rice [kg]'], 336)
        self.assertEqual(total_needs_weekly['Drinking Water [l]'], 2100)
        self.assertEqual(total_needs_weekly['Clean Water [l]'], 8040)
        self.assertEqual(total_needs_weekly['Family Kits'], 24)
        self.assertEqual(total_needs_single['Toilets'], 6)
    def test_run(self):
        function = ClassifiedRasterHazardBuildingFunction.instance()

        hazard_path = test_data_path('hazard', 'classified_flood_20_20.asc')
        exposure_path = test_data_path('exposure', 'buildings.shp')
        hazard_layer = read_layer(hazard_path)
        exposure_layer = read_layer(exposure_path)

        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.run()
        impact_layer = function.impact
        impact_data = impact_layer.get_data()

        # Count
        expected_impact = {1.0: 67, 2.0: 49, 3.0: 64}

        result_impact = {1.0: 0, 2.0: 0, 3.0: 0}
        for impact_feature in impact_data:
            level = impact_feature['level']
            if not math.isnan(level):
                result_impact[level] += 1
        message = 'Expecting %s, but it returns %s' % (expected_impact,
                                                       result_impact)
        self.assertEqual(expected_impact, result_impact, message)
Example #8
0
    def test_run(self):
        function = ClassifiedRasterHazardBuildingFunction.instance()

        hazard_path = standard_data_path(
            'hazard', 'classified_hazard.tif')
        exposure_path = standard_data_path('exposure', 'small_building.shp')
        hazard_layer = read_layer(hazard_path)
        exposure_layer = read_layer(exposure_path)

        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.run_analysis()
        impact_layer = function.impact
        impact_data = impact_layer.get_data()

        # Count
        expected_impact = {
            'Not affected': 5,
            'Low hazard zone': 2,
            'Medium hazard zone': 9,
            'High hazard zone': 5
        }

        result_impact = {}
        for impact_feature in impact_data:
            hazard_class = impact_feature[function.target_field]
            if hazard_class in result_impact:
                result_impact[hazard_class] += 1
            else:
                result_impact[hazard_class] = 1
        self.assertDictEqual(expected_impact, result_impact)
    def test_run(self):
        function = FloodRasterRoadsFunction.instance()

        hazard_path = standard_data_path('hazard',
                                         'continuous_flood_20_20.asc')
        exposure_path = standard_data_path('exposure', 'roads.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsRasterLayer(hazard_path, 'Flood')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Roads', 'ogr')

        # Let's set the extent to the hazard extent
        extent = hazard_layer.extent()
        rect_extent = [
            extent.xMinimum(),
            extent.yMaximum(),
            extent.xMaximum(),
            extent.yMinimum()
        ]
        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact

        keywords = impact.get_keywords()
        self.assertEquals(function.target_field, keywords['target_field'])
        expected_inundated_feature = 182
        count = sum(impact.get_data(attribute=function.target_field))
        self.assertEquals(count, expected_inundated_feature)
Example #10
0
    def test_run(self):
        """TestVolcanoPointBuildingFunction: Test running the IF."""
        volcano_path = standard_data_path('hazard', 'volcano_point.shp')
        building_path = standard_data_path('exposure', 'buildings.shp')

        hazard_layer = read_layer(volcano_path)
        exposure_layer = read_layer(building_path)

        impact_function = VolcanoPointBuildingFunction.instance()
        impact_function.hazard = SafeLayer(hazard_layer)
        impact_function.exposure = SafeLayer(exposure_layer)
        impact_function._prepare()
        impact_function.run()
        impact_layer = impact_function.impact

        # Check the question
        expected_question = (
            'In the event of volcano point how many buildings might be '
            'affected?')
        self.assertEqual(expected_question, impact_function.question)

        # The buildings should all be categorised into 3000 zone
        zone_sum = sum(
            impact_layer.get_data(attribute=impact_function.target_field))
        expected_sum = 3 * 181
        message = 'Expecting %s, but it returns %s' % (expected_sum, zone_sum)
        self.assertEqual(zone_sum, expected_sum, message)
    def test_run(self):
        """TestClassifiedPolygonPopulationFunction: Test running the IF."""
        generic_polygon_path = test_data_path(
            'hazard', 'classified_generic_polygon.shp')
        population_path = test_data_path('exposure',
                                         'pop_binary_raster_20_20.asc')

        generic_polygon_layer = read_layer(generic_polygon_path)
        population_layer = read_layer(population_path)

        impact_function = ClassifiedPolygonHazardPopulationFunction.instance()
        impact_function.hazard = SafeLayer(generic_polygon_layer)
        impact_function.exposure = SafeLayer(population_layer)
        impact_function.run()
        impact_layer = impact_function.impact
        # Check the question
        expected_question = ('In each of the hazard zones how many people '
                             'might be impacted.')
        message = 'The question should be %s, but it returns %s' % (
            expected_question, impact_function.question)
        self.assertEqual(expected_question, impact_function.question, message)
        # Count by hand
        expected_affected_population = 181
        result = numpy.nansum(impact_layer.get_data())
        self.assertEqual(expected_affected_population, result, message)
Example #12
0
    def test_run(self):
        function = FloodPolygonBuildingFunction.instance()

        hazard_path = test_data_path('hazard', 'flood_multipart_polygons.shp')
        # exposure_path = test_data_path('exposure', 'buildings.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Flood', 'ogr')
        # noinspection PyCallingNonCallable
        # exposure_layer = QgsVectorLayer(exposure_path, 'Buildings', 'ogr')

        exposure_layer = clone_shp_layer(
            name='buildings',
            include_keywords=True,
            source_directory=test_data_path('exposure'))
        # Let's set the extent to the hazard extent
        extent = hazard_layer.extent()
        rect_extent = [
            extent.xMinimum(),
            extent.yMaximum(),
            extent.xMaximum(),
            extent.yMinimum()
        ]

        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact

        # Count of flooded objects is calculated "by the hands"
        # total flooded = 27, total buildings = 129
        count = sum(impact.get_data(attribute=function.target_field))
        self.assertEquals(count, 33)
        count = len(impact.get_data())
        self.assertEquals(count, 176)
Example #13
0
    def test_run(self):
        """TestVolcanoPolygonPopulationFunction: Test running the IF."""
        merapi_krb_path = test_data_path('hazard', 'volcano_krb.shp')
        population_path = test_data_path(
            'exposure', 'pop_binary_raster_20_20.asc')

        merapi_krb_layer = read_layer(merapi_krb_path)
        population_layer = read_layer(population_path)

        impact_function = VolcanoPolygonPopulationFunction.instance()

        # 2. Run merapi krb
        impact_function.hazard = SafeLayer(merapi_krb_layer)
        impact_function.exposure = SafeLayer(population_layer)
        impact_function.run()
        impact_layer = impact_function.impact
        # Check the question
        expected_question = ('In the event of volcano krb how many population '
                             'might need evacuation')
        message = 'The question should be %s, but it returns %s' % (
            expected_question, impact_function.question)
        self.assertEqual(expected_question, impact_function.question, message)
        # Count by hand
        expected_affected_population = 181
        result = numpy.nansum(impact_layer.get_data())
        self.assertEqual(expected_affected_population, result, message)
Example #14
0
    def test_run(self):
        function = FloodPolygonRoadsFunction.instance()

        hazard_path = test_data_path('hazard', 'flood_multipart_polygons.shp')
        exposure_path = test_data_path('exposure', 'roads.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Flood', 'ogr')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Roads', 'ogr')

        # Let's set the extent to the hazard extent
        extent = hazard_layer.extent()
        rect_extent = [
            extent.xMinimum(),
            extent.yMaximum(),
            extent.xMaximum(),
            extent.yMinimum()
        ]
        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact

        # Count of flooded objects is calculated "by the hands"
        # the count = 69
        expected_feature_total = 69
        count = sum(impact.get_data(attribute=function.target_field))
        message = 'Expecting %s, but it returns %s' % (expected_feature_total,
                                                       count)
        self.assertEquals(count, expected_feature_total, message)
    def test_run(self):
        """TestVolcanoPointPopulationFunction: Test running the IF."""
        merapi_point_path = test_data_path('hazard', 'volcano_point.shp')
        population_path = test_data_path('exposure',
                                         'pop_binary_raster_20_20.asc')

        merapi_point_layer = read_layer(merapi_point_path)
        population_layer = read_layer(population_path)

        impact_function = VolcanoPointPopulationFunction.instance()

        # Run merapi point
        impact_function.hazard = SafeLayer(merapi_point_layer)
        impact_function.exposure = SafeLayer(population_layer)
        impact_function.run()
        impact_layer = impact_function.impact
        # Check the question
        expected_question = ('In the event of a volcano point how many '
                             'people might be impacted')
        message = 'The question should be %s, but it returns %s' % (
            expected_question, impact_function.question)
        self.assertEqual(expected_question, impact_function.question, message)
        # Count by hand
        expected_affected_population = 200
        result = numpy.nansum(impact_layer.get_data())
        message = 'Expecting %s, but it returns %s' % (
            expected_affected_population, result)
        self.assertEqual(expected_affected_population, result, message)
    def test_run_point_exposure(self):
        """Run the IF for point exposure.

        See https://github.com/AIFDR/inasafe/issues/2156.
        """
        generic_polygon_path = test_data_path(
            'hazard', 'classified_generic_polygon.shp')
        building_path = test_data_path('exposure', 'building-points.shp')

        hazard_layer = QgsVectorLayer(generic_polygon_path, 'Hazard', 'ogr')
        exposure_layer = QgsVectorLayer(building_path, 'Buildings', 'ogr')

        # Let's set the extent to the hazard extent
        extent = hazard_layer.extent()
        rect_extent = [
            extent.xMinimum(),
            extent.yMaximum(),
            extent.xMaximum(),
            extent.yMinimum()
        ]

        impact_function = ClassifiedPolygonHazardBuildingFunction.instance()
        impact_function.hazard = SafeLayer(hazard_layer)
        impact_function.exposure = SafeLayer(exposure_layer)
        impact_function.requested_extent = rect_extent
        impact_function.run()
        impact_layer = impact_function.impact

        # Check the question
        expected_question = ('In each of the hazard zones how many buildings '
                             'might be affected.')
        message = 'The question should be %s, but it returns %s' % (
            expected_question, impact_function.question)
        self.assertEqual(expected_question, impact_function.question, message)

        zone_sum = impact_layer.get_data(
            attribute=impact_function.target_field)
        high_zone_count = zone_sum.count('High Hazard Zone')
        medium_zone_count = zone_sum.count('Medium Hazard Zone')
        low_zone_count = zone_sum.count('Low Hazard Zone')
        # The result
        expected_high_count = 12
        expected_medium_count = 172
        expected_low_count = 3
        message = 'Expecting %s for High Hazard Zone, but it returns %s' % (
            high_zone_count, expected_high_count)
        self.assertEqual(high_zone_count, expected_high_count, message)

        message = 'Expecting %s for Medium Hazard Zone, but it returns %s' % (
            expected_medium_count, medium_zone_count)
        self.assertEqual(medium_zone_count, expected_medium_count, message)

        message = 'Expecting %s for Low Hazard Zone, but it returns %s' % (
            expected_low_count, low_zone_count)
        self.assertEqual(expected_low_count, low_zone_count, message)
Example #17
0
    def test_calculate_impact(self):
        """Test calculating impact."""
        eq_path = test_data_path('hazard', 'earthquake.tif')
        building_path = test_data_path('exposure', 'buildings.shp')

        eq_layer = read_layer(eq_path)
        building_layer = read_layer(building_path)

        impact_function = EarthquakeBuildingFunction.instance()
        impact_function.hazard = SafeLayer(eq_layer)
        impact_function.exposure = SafeLayer(building_layer)
        impact_layer = calculate_impact(impact_function)

        self.assertIsNotNone(impact_layer)
    def test_zero_intersection(self):
        hazard_path = test_data_path('hazard', 'continuous_flood_20_20.asc')
        exposure_path = test_data_path('exposure', 'roads.shp')

        # noinspection PyCallingNonCallable
        hazard_layer = QgsRasterLayer(hazard_path, 'Flood')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Roads', 'ogr')

        # Let's set the extent to the hazard extent
        function = FloodRasterRoadsFunction.instance()
        rect_extent = [106.831991, -6.170044, 106.834868, -6.167793]
        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.requested_extent = rect_extent
        with self.assertRaises(ZeroImpactException):
            function.run()
Example #19
0
    def test_run_failed(self):
        """Test run IF with missing keywords."""
        merapi_krb_path = standard_data_path('hazard', 'volcano_krb.shp')
        population_path = standard_data_path('exposure',
                                             'pop_binary_raster_20_20.asc')

        merapi_krb_layer = read_layer(merapi_krb_path)
        population_layer = read_layer(population_path)

        impact_function = VolcanoPolygonPopulationFunction.instance()

        # 2. Run merapi krb
        layer = SafeLayer(merapi_krb_layer)
        layer.keywords = {}
        impact_function.hazard = layer
        impact_function.exposure = SafeLayer(population_layer)
        self.assertRaises(KeywordNotFoundError, impact_function.run)
def direct_execution():

    arg = AnalysisArguments.read_arguments()

    register_impact_functions()

    registry = ImpactFunctionManager().registry

    function = registry.get_instance(arg.impact_function_name)
    function.hazard = SafeLayer(read_layer(arg.hazard_filename))
    function.exposure = SafeLayer(read_layer(arg.exposure_filename))

    impact = calculate_impact(function)
    qgis_impact = safe_to_qgis_layer(impact)

    generate_styles(impact, qgis_impact)

    copy_impact_layer(impact, arg.impact_filename)
Example #21
0
    def aggregation(self, layer):
        """Setter for aggregation layer property.

        :param layer: Aggregation layer to be used for the analysis.
        :type layer: SafeLayer
        """
        if isinstance(layer, SafeLayer):
            self._aggregation = layer
        elif isinstance(layer, QgsMapLayer):
            self._aggregation = SafeLayer(layer)
        else:
            self._aggregation = None
    def test_run(self):
        function = ClassifiedRasterHazardPopulationFunction.instance()

        hazard_path = test_data_path('hazard', 'classified_flood_20_20.asc')
        exposure_path = test_data_path('exposure',
                                       'pop_binary_raster_20_20.asc')
        hazard_layer = read_layer(hazard_path)
        exposure_layer = read_layer(exposure_path)

        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.run()
        impact_layer = function.impact

        impact_data = impact_layer.get_data()

        # Total people affected = 200
        expected = 200
        result = sum(sum(impact_data))
        message = 'Expecting %s, but it returns %s' % (expected, result)
        self.assertEqual(expected, result, message)
Example #23
0
    def test_run(self):
        """TestEarthquakeBuildingFunction: Test running the IF."""
        eq_path = test_data_path('hazard', 'earthquake.tif')
        building_path = test_data_path('exposure', 'buildings.shp')

        eq_layer = read_layer(eq_path)
        building_layer = read_layer(building_path)

        impact_function = EarthquakeBuildingFunction.instance()
        impact_function.hazard = SafeLayer(eq_layer)
        impact_function.exposure = SafeLayer(building_layer)
        impact_function.run()
        impact_layer = impact_function.impact
        # Check the question
        expected_question = (
            'In the event of earthquake how many buildings might be affected')
        message = 'The question should be %s, but it returns %s' % (
            expected_question, impact_function.question)
        self.assertEqual(expected_question, impact_function.question, message)
        # Count by hand,
        # 1 = low, 2 = medium, 3 = high
        impact = {
            1: 0,
            2: 181,
            3: 0
        }
        result = {
            1: 0,
            2: 0,
            3: 0
        }
        impact_features = impact_layer.get_data()
        for i in range(len(impact_features)):
            impact_feature = impact_features[i]
            level = impact_feature.get(impact_function.target_field)
            result[level] += 1

        message = 'Expecting %s, but it returns %s' % (impact, result)
        self.assertEqual(impact, result, message)
    def test_run(self):
        function = FloodEvacuationVectorHazardFunction.instance()

        hazard_path = test_data_path('hazard', 'flood_multipart_polygons.shp')
        exposure_path = test_data_path('exposure',
                                       'pop_binary_raster_20_20.asc')
        hazard_layer = read_layer(hazard_path)
        exposure_layer = read_layer(exposure_path)

        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)

        function.run()
        impact = function.impact

        keywords = impact.get_keywords()
        # print "keywords", keywords
        affected_population = numpy.nansum(impact.get_data())
        total_population = keywords['total_population']

        self.assertEqual(affected_population, 20)
        self.assertEqual(total_population, 200)
Example #25
0
    def test_run(self):
        function = TsunamiEvacuationFunction.instance()

        hazard_path = test_data_path('hazard', 'tsunami_wgs84.tif')
        exposure_path = test_data_path('exposure',
                                       'pop_binary_raster_20_20.asc')
        # We need clipping for both layers to be in the same dimension
        clipped_hazard, clipped_exposure = clip_layers(hazard_path,
                                                       exposure_path)

        hazard_layer = read_layer(clipped_hazard.source())
        exposure_layer = read_layer(clipped_exposure.source())

        # Let's set the extent to the hazard extent
        function.parameters['thresholds'].value = [0.7, 0.8, 0.9]
        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.run()
        impact = function.impact

        # Count of flooded objects is calculated "by the hands"
        # print "keywords", keywords
        keywords = impact.get_keywords()
        evacuated = float(keywords['evacuated'])
        total_needs_full = keywords['total_needs']
        total_needs_weekly = OrderedDict([[x['table name'], x['amount']]
                                          for x in total_needs_full['weekly']])
        total_needs_single = OrderedDict([[x['table name'], x['amount']]
                                          for x in total_needs_full['single']])

        # #FIXME: This doesn't make sense due to clipping above. Update
        # clip_layers
        expected_evacuated = 1198
        self.assertEqual(evacuated, expected_evacuated)
        self.assertEqual(total_needs_weekly['Rice [kg]'], 3355)
        self.assertEqual(total_needs_weekly['Family Kits'], 240)
        self.assertEqual(total_needs_weekly['Drinking Water [l]'], 20965)
        self.assertEqual(total_needs_weekly['Clean Water [l]'], 80266)
        self.assertEqual(total_needs_single['Toilets'], 60)
    def test_parameter(self):
        """Test for checking parameter is carried out"""
        eq_path = standard_data_path('hazard', 'earthquake.tif')
        population_path = standard_data_path('exposure',
                                             'pop_binary_raster_20_20.asc')

        # For EQ on Pops we need to clip the hazard and exposure first to the
        # same dimension
        clipped_hazard, clipped_exposure = clip_layers(eq_path,
                                                       population_path)

        # noinspection PyUnresolvedReferences
        eq_layer = read_layer(str(clipped_hazard.source()))
        # noinspection PyUnresolvedReferences
        population_layer = read_layer(str(clipped_exposure.source()))

        impact_function = ITBBayesianFatalityFunction.instance()
        impact_function.hazard = SafeLayer(eq_layer)
        impact_function.exposure = SafeLayer(population_layer)

        expected = {
            'postprocessors': {
                'Age': {
                    'Age': {
                        'Adult ratio': 0.659,
                        'Elderly ratio': 0.078,
                        'Youth ratio': 0.263
                    }
                },
                'Gender': {
                    'Gender': True
                },
                'MinimumNeeds': {
                    'MinimumNeeds': True
                }
            }
        }
        self.assertDictEqual(expected, impact_function.parameters_value())
Example #27
0
    def test_run_aggregation(self):
        """Test running the IF with aggregation with same attribute name #2750.
        """
        function = FloodPolygonRoadsFunction.instance()

        hazard_path = standard_data_path('hazard',
                                         'flood_multipart_polygons.shp')
        exposure_path = standard_data_path('exposure', 'roads.shp')
        aggregation_path = standard_data_path('boundaries', 'grid_jakarta.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Flood', 'ogr')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Roads', 'ogr')
        # noinspection PyCallingNonCallable
        aggregation_layer = QgsVectorLayer(aggregation_path, 'Grids', 'ogr')

        # Let's set the extent to the hazard extent
        extent = aggregation_layer.extent()
        rect_extent = [
            extent.xMinimum(),
            extent.yMaximum(),
            extent.xMaximum(),
            extent.yMinimum()
        ]
        function.hazard = SafeLayer(hazard_layer)
        function.exposure = SafeLayer(exposure_layer)
        function.aggregation = aggregation_layer

        function.requested_extent = rect_extent
        try:
            function._validate()
            function._prepare()
            function._impact = function._calculate_impact()
            function._run_aggregator()
        except KeyError as e:
            self.fail('KeyError because of %s' % e)
        except Exception as e:
            self.fail('Exception because of %s' % e)
Example #28
0
    def exposure(self, layer):
        """Setter for exposure layer property.

        :param layer: exposure layer to be used for the analysis.
        :type layer: SafeLayer
        """
        if isinstance(layer, SafeLayer):
            self._exposure = layer
        else:
            if self.function_type() == 'old-style':
                self._exposure = SafeLayer(convert_to_safe_layer(layer))
            elif self.function_type() == 'qgis2.0':
                # convert for new style impact function
                self._exposure = SafeLayer(layer)
            else:
                message = tr('Error: Impact Function has unknown style.')
                raise Exception(message)

        # Update the target field to a non-conflicting one
        if self.exposure.is_qgsvectorlayer():
            self._target_field = get_non_conflicting_attribute_name(
                self.target_field,
                self.exposure.layer.dataProvider().fieldNameMap().keys())
Example #29
0
    def test_safe_layer_attributes(self):
        """Test creating safe layer."""
        self.maxDiff = None
        building_path = standard_data_path('exposure', 'buildings.shp')

        building_layer = read_layer(building_path)

        exposure = SafeLayer(building_layer)
        # Expect InvalidLayerError
        self.assertRaises(InvalidLayerError, SafeLayer, None)
        # Expect KeywordNotFoundError
        self.assertRaises(KeywordNotFoundError, exposure.keyword, 'dummy')

        self.assertEquals(exposure.name, 'Buildings')
        expected_keywords = {
            'license': u'Open Data Commons Open Database License (ODbL)',
            'keyword_version': u'3.5',
            'value_mapping': {
                u'government': [u'Government'],
                u'residential': [u'Residential'],
                u'commercial': [u'Commercial'],
                u'health': [u'Clinic/Doctor'],
                u'education': [u'School'],
                u'place of worship': [u'Place of Worship - Islam']
            },
            'structure_class_field': u'TYPE',
            'title': u'Buildings',
            'source': u'OpenStreetMap - www.openstreetmap.org',
            'layer_geometry': u'polygon',
            'layer_purpose': u'exposure',
            'layer_mode': u'classified',
            'exposure': u'structure'
        }

        self.assertEquals(exposure.keywords, expected_keywords)
        self.assertFalse(exposure.is_qgsvectorlayer())
        self.assertTrue(isinstance(exposure.qgis_layer(), QgsMapLayer))
        self.assertTrue(isinstance(exposure.qgis_layer(), QgsVectorLayer))
        self.assertFalse(isinstance(exposure.qgis_layer(), QgsRasterLayer))
        self.assertEquals(exposure.crs().authid(), 'EPSG:4326')
        self.assertEquals(
            exposure.extent().asWktCoordinates(),
            u'106.80645110100005013 -6.18730753857923688, '
            u'106.82525023478235937 -6.17267712704860294')
        self.assertEquals(exposure.layer_type(), 0)
        self.assertEquals(exposure.geometry_type(), 2)
    def test_run(self):
        """TestITBBayesianEarthquakeFatalityFunction: Test running the IF."""
        # FIXME(Hyeuk): test requires more realistic hazard and population data
        eq_path = standard_data_path('hazard', 'earthquake.tif')
        population_path = standard_data_path('exposure',
                                             'pop_binary_raster_20_20.asc')

        # For EQ on Pops we need to clip the hazard and exposure first to the
        #  same dimension
        clipped_hazard, clipped_exposure = clip_layers(eq_path,
                                                       population_path)

        # noinspection PyUnresolvedReferences
        eq_layer = read_layer(str(clipped_hazard.source()))
        # noinspection PyUnresolvedReferences
        population_layer = read_layer(str(clipped_exposure.source()))

        impact_function = ITBBayesianFatalityFunction.instance()
        impact_function.hazard = SafeLayer(eq_layer)
        impact_function.exposure = SafeLayer(population_layer)
        impact_function.run()
        impact_layer = impact_function.impact
        # Check the question
        expected_question = (
            'In the event of earthquake how many population might die or '
            'be displaced according itb bayesian model?')
        self.assertEqual(expected_question, impact_function.question)

        expected_result = {
            'total_population': 200,
            'total_fatalities': 0,
            'total_displaced': 200
        }
        for key_ in expected_result.keys():
            result = impact_layer.get_keywords(key_)
            message = 'Expecting %s, but it returns %s' % (
                expected_result[key_], result)
            self.assertEqual(expected_result[key_], result, message)

        expected_result = {}
        expected_result['exposed_per_mmi'] = {
            2: 0,
            3: 0,
            4: 0,
            5: 0,
            6: 0,
            7: 0,
            8: 200,
            9: 0,
            10: 0
        }
        expected_result['displaced_per_mmi'] = {
            2: 0,
            3: 0,
            4: 0,
            5: 0,
            6: 0,
            7: 0,
            8: 199.6297,  # FIXME should be 200.0
            9: 0,
            10: 0
        }

        for key_ in expected_result.keys():
            result = impact_layer.get_keywords(key_)
            for item in expected_result[key_].keys():
                message = 'Expecting %s, but it returns %s' % (
                    expected_result[key_][item], result[item])
                self.assertAlmostEqual(expected_result[key_][item],
                                       result[item],
                                       places=4,
                                       msg=message)

        expected_result = [100.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        result = impact_layer.get_keywords('prob_fatality_mag')
        message = 'Expecting %s, but it returns %s' % (expected_result, result)
        self.assertEqual(expected_result, result, message)