def test_functions_for_constraint(self):
        """Test functions_for_constraint."""
        ifm = ImpactFunctionManager()
        impact_functions = ifm.functions_for_constraint(
            'earthquake',
            'population',
            'raster',
            'raster',
            'continuous',
            'continuous',
        )
        expected = [
            ITBFatalityFunction.metadata().as_dict(),
            ITBBayesianFatalityFunction.metadata().as_dict(),
            PAGFatalityFunction.metadata().as_dict(),
            ContinuousHazardPopulationFunction.metadata().as_dict()]

        for key in impact_functions[0].keys():
            if key == 'parameters':
                # We do not check the parameters since they are mutable.
                continue
            result = [x[key] for x in impact_functions]
            hope = [x[key] for x in expected]
            message = key
            self.assertItemsEqual(result, hope, message)
 def test_exposure_units_for_layer(self):
     """Test for exposure_units_for_layer"""
     impact_function_manager = ImpactFunctionManager()
     exposure_units = impact_function_manager.exposure_units_for_layer(
         'population', 'raster', 'continuous')
     expected = [count_exposure_unit, density_exposure_unit]
     self.assertItemsEqual(exposure_units, expected)
    def test_hazards_for_layer(self):
        """Test for hazards_for_layer"""
        impact_function_manager = ImpactFunctionManager()
        hazards = impact_function_manager.hazards_for_layer(
            'polygon', 'single_event')
        # print [x['key'] for x in hazards]
        expected = [
            hazard_flood,
            hazard_tsunami,
            hazard_earthquake,
            hazard_volcano,
            hazard_volcanic_ash,
            hazard_generic
        ]
        self.assertItemsEqual(hazards, expected)

        hazards = impact_function_manager.hazards_for_layer('polygon')
        expected = [hazard_flood, hazard_tsunami, hazard_earthquake,
                    hazard_volcano, hazard_volcanic_ash, hazard_generic]
        self.assertItemsEqual(hazards, expected)

        hazards = impact_function_manager.hazards_for_layer(
            'point', 'single_event')
        expected = [hazard_volcano]
        self.assertItemsEqual(hazards, expected)
    def test_available_hazards(self):
        """Test available_hazards API."""
        impact_function_manager = ImpactFunctionManager()

        result = impact_function_manager.available_hazards(
            'single_event')
        print [x['key'] for x in result]
    def test_get_functions_for_constraint(self):
        """Test get_functions_for_constraint."""
        impact_function_manager = ImpactFunctionManager()
        hazard = hazard_earthquake
        exposure = exposure_structure

        expected_result = [
            EarthquakeBuildingImpactFunction.Metadata.get_metadata(),
            ClassifiedHazardBuildingImpactFunction.Metadata.get_metadata()]
        result = impact_function_manager.get_functions_for_constraint(
            hazard, exposure)
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(expected_result, result, message)

        hazard_constraint = layer_raster_continuous
        exposure_constraint = None

        expected_result = [
            EarthquakeBuildingImpactFunction.Metadata.get_metadata()]
        result = impact_function_manager.get_functions_for_constraint(
            hazard, exposure, hazard_constraint, exposure_constraint)
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(expected_result, result, message)

        hazard_constraint = layer_vector_polygon
        exposure_constraint = layer_vector_line

        expected_result = []
        result = impact_function_manager.get_functions_for_constraint(
            hazard, exposure, hazard_constraint, exposure_constraint)
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(expected_result, result, message)
    def test_available_exposure_layer_modes(self):
        """Test for available_exposure_layer_modes."""
        ifm = ImpactFunctionManager()
        exposure_layer_mode = ifm.available_exposure_layer_modes(
            'population', 'raster')
        expected = [layer_mode_continuous]

        self.assertItemsEqual(exposure_layer_mode, expected)
    def test_available_hazard_layer_modes(self):
        """Test for available_hazard_layer_modes."""
        ifm = ImpactFunctionManager()
        hazard_layer_mode = ifm.available_hazard_layer_modes(
            'earthquake', 'raster', 'single_event')
        expected = [layer_mode_continuous, layer_mode_classified]

        self.assertItemsEqual(hazard_layer_mode, expected)
 def test_available_exposures(self):
     """Test available_exposures API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.available_exposures()
     expected_result = [
         exposure_structure, exposure_road, exposure_population]
     message = ('I expect %s but I got %s.' % (expected_result, result))
     self.assertItemsEqual(result, expected_result, message)
Exemple #9
0
def analysis_setup(command_line_arguments, hazard, exposure, aggregation=None):
    """Sets up an analysis object.

    .. versionadded:: 3.2

    :param command_line_arguments: User inputs.
    :type command_line_arguments: CommandLineArguments

    :param hazard: Hazard layer
    :type hazard: QgsLayer

    :param exposure: Exposure Layer
    :type exposure: QgsLayer

    :param aggregation: Aggregation Layer
    :type aggregation: QgsLayer

    :raises: Exception
    """
    # IF
    impact_function_manager = ImpactFunctionManager()
    impact_function = impact_function_manager.get(command_line_arguments.impact_function)
    keyword_io = KeywordIO()

    try:
        from safe.utilities.analysis import Analysis
    except ImportError as ie:
        LOGGER.debug("Import error for Analysis module")
        print ie.message
        raise ImportError
    analysis = Analysis()
    analysis.impact_function = impact_function
    analysis.hazard = hazard
    analysis.exposure = exposure
    analysis.aggregation = aggregation
    # analysis.hazard_keyword = keyword_io.read_keywords(hazard)
    # analysis.exposure_keyword = keyword_io.read_keywords(exposure)
    analysis.clip_hard = False
    analysis.show_intermediate_layers = False
    analysis.run_in_thread_flag = False
    analysis.map_canvas = CANVAS
    # QSetting context
    settings = QSettings()
    crs = settings.value("inasafe/analysis_extent_crs", "", type=str)
    analysis.user_extent_crs = QgsCoordinateReferenceSystem(crs)
    try:
        analysis.user_extent = QgsRectangle(
            float(command_line_arguments.extent[0]),
            float(command_line_arguments.extent[1]),
            float(command_line_arguments.extent[2]),
            float(command_line_arguments.extent[3]),
        )
    except AttributeError:
        print "No extents"
        pass
    analysis.setup_analysis()
    return analysis
Exemple #10
0
 def __init__(self):
     """Constructor for the impact calculator."""
     QObject.__init__(self)
     self.impact_function_manager = ImpactFunctionManager()
     self._hazard_layer = None
     self._exposure_layer = None
     self._impact_function = None
     self._filename = None
     self._result = None
     self._extent = None
    def test_available_exposure_constraints(self):
        """Test for available_exposure_constraints."""
        ifm = ImpactFunctionManager()
        exposure_constraints = ifm.available_exposure_constraints(
            'population')
        expected = [
            (layer_mode_continuous, layer_geometry_raster),
        ]

        self.assertItemsEqual(exposure_constraints, expected)
    def test_exposure_additional_keywords(self):
        """Test for exposure_additional_keywords."""
        ifm = ImpactFunctionManager()
        additional_keywords = ifm.exposure_additional_keywords(
            layer_mode_key='classified',
            layer_geometry_key='polygon',
            exposure_key='structure')
        expected = []

        self.assertItemsEqual(additional_keywords, expected)
    def test_exposures_for_layer(self):
        """Test for exposures_for_layer"""
        impact_function_manager = ImpactFunctionManager()
        exposures = impact_function_manager.exposures_for_layer('polygon')
        expected = [exposure_structure, exposure_population]
        self.assertItemsEqual(exposures, expected)

        exposures = impact_function_manager.exposures_for_layer('line')
        expected = [exposure_road]
        self.assertItemsEqual(exposures, expected)
Exemple #14
0
 def test_available_exposure_constraints(self):
     """Test for available_exposure_constraints."""
     self.maxDiff = None
     ifm = ImpactFunctionManager()
     exposure_constraints = ifm.available_exposure_constraints(
         'population')
     expected = [
         (layer_mode_continuous, layer_geometry_raster),
         (layer_mode_continuous, layer_geometry_polygon)
     ]
     self.assertItemsEqual(exposure_constraints, expected)
Exemple #15
0
 def test_available_exposures(self):
     """Test available_exposures API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.available_exposures()
     expected_result = [
         exposure_structure,
         exposure_road,
         exposure_population,
         exposure_place,
         exposure_land_cover]
     self.assertItemsEqual(result, expected_result)
    def test_exposure_class_fields(self):
        """Test for exposure_class_fields."""
        ifm = ImpactFunctionManager()
        additional_keywords = ifm.exposure_class_fields(
            layer_mode_key='classified',
            layer_geometry_key='polygon',
            exposure_key='structure'
        )
        expected = [structure_class_field]

        self.assertItemsEqual(additional_keywords, expected)
Exemple #17
0
    def test_hazard_additional_keywords(self):
        """Test for hazard_additional_keywords."""
        ifm = ImpactFunctionManager()
        additional_keywords = ifm.hazard_additional_keywords(
            layer_mode_key='classified',
            layer_geometry_key='polygon',
            hazard_category_key='single_event',
            hazard_key='flood')
        expected = []

        self.assertItemsEqual(additional_keywords, expected)
Exemple #18
0
 def test_allowed_subcategories(self):
     """Test allowed_subcategories API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.allowed_subcategories()
     expected_result = [
         exposure_structure, hazard_earthquake, exposure_population,
         hazard_flood, hazard_tsunami, exposure_road, hazard_volcano,
         hazard_volcanic_ash, hazard_generic
     ]
     message = ('I expect %s but I got %s.' % (expected_result, result))
     self.assertItemsEqual(result, expected_result, message)
 def test_available_exposures(self):
     """Test available_exposures API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.available_exposures()
     expected_result = [
         exposure_structure,
         exposure_road,
         exposure_population,
         exposure_place,
         exposure_land_cover]
     self.assertItemsEqual(result, expected_result)
    def test_exposures_for_layer(self):
        """Test for exposures_for_layer"""
        impact_function_manager = ImpactFunctionManager()
        exposures = impact_function_manager.exposures_for_layer(
            'polygon')
        expected = [exposure_structure]
        self.assertItemsEqual(exposures, expected)

        exposures = impact_function_manager.exposures_for_layer(
            'line')
        expected = [exposure_road]
        self.assertItemsEqual(exposures, expected)
    def test_available_hazard_constraints(self):
        """Test for available_hazard_constraints."""
        ifm = ImpactFunctionManager()
        hazard_constraints = ifm.available_hazard_constraints(
            'earthquake', 'single_event')
        expected = [
            (layer_mode_continuous, layer_geometry_raster),
            (layer_mode_classified, layer_geometry_raster),
            (layer_mode_classified, layer_geometry_polygon),
        ]

        print [(x[0]['key'], x[1]['key']) for x in hazard_constraints]
def analysis_execution():

    from safe.test.utilities import get_qgis_app

    # get_qgis_app must be called before importing Analysis
    QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()

    from safe.utilities.analysis import Analysis
    from safe.utilities.keyword_io import KeywordIO

    analysis = Analysis()

    arg = AnalysisArguments.read_arguments()

    register_impact_functions()

    registry = ImpactFunctionManager().registry

    function = registry.get_instance(arg.impact_function_name)

    hazard_layer = safe_to_qgis_layer(read_layer(arg.hazard_filename))
    exposure_layer = safe_to_qgis_layer(read_layer(arg.exposure_filename))
    if arg.aggregation_filename:
        aggregation_layer = safe_to_qgis_layer(read_layer(
            arg.aggregation_filename))

    keywords_io = KeywordIO()

    try:
        analysis.map_canvas = IFACE.mapCanvas()
        analysis.hazard_layer = hazard_layer
        analysis.hazard_keyword = keywords_io.read_keywords(hazard_layer)
        analysis.exposure_layer = exposure_layer
        analysis.exposure_keyword = keywords_io.read_keywords(exposure_layer)
        if aggregation_layer:
            analysis.aggregation_layer = aggregation_layer
            analysis.aggregation_keyword = keywords_io.read_keywords(
                aggregation_layer)
        analysis.impact_function = function

        analysis.setup_analysis()
        print 'Setup analysis done'
        analysis.run_analysis()
        print 'Analysis done'
    except Exception as e:
        print e.message

    impact = analysis.impact_layer
    qgis_impact = safe_to_qgis_layer(impact)

    generate_styles(impact, qgis_impact)

    copy_impact_layer(impact, arg.impact_filename)
Exemple #23
0
    def test_available_hazards(self):
        """Test available_hazards API."""
        impact_function_manager = ImpactFunctionManager()

        result = impact_function_manager.available_hazards('single_event')
        # print [x['key'] for x in result]
        expected_result = [
            hazard_flood, hazard_tsunami, hazard_earthquake, hazard_generic,
            hazard_volcanic_ash, hazard_volcano
        ]
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)
def analysis_execution():

    from safe.test.utilities import get_qgis_app

    # get_qgis_app must be called before importing Analysis
    QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()

    from safe.utilities.analysis import Analysis
    from safe.utilities.keyword_io import KeywordIO

    analysis = Analysis()

    arg = AnalysisArguments.read_arguments()

    register_impact_functions()

    registry = ImpactFunctionManager().registry

    function = registry.get_instance(arg.impact_function_name)

    hazard_layer = safe_to_qgis_layer(read_layer(arg.hazard_filename))
    exposure_layer = safe_to_qgis_layer(read_layer(arg.exposure_filename))
    if arg.aggregation_filename:
        aggregation_layer = safe_to_qgis_layer(
            read_layer(arg.aggregation_filename))

    keywords_io = KeywordIO()

    try:
        analysis.map_canvas = IFACE.mapCanvas()
        analysis.hazard_layer = hazard_layer
        analysis.hazard_keyword = keywords_io.read_keywords(hazard_layer)
        analysis.exposure_layer = exposure_layer
        analysis.exposure_keyword = keywords_io.read_keywords(exposure_layer)
        if aggregation_layer:
            analysis.aggregation_layer = aggregation_layer
            analysis.aggregation_keyword = keywords_io.read_keywords(
                aggregation_layer)
        analysis.impact_function = function

        analysis.setup_analysis()
        print 'Setup analysis done'
        analysis.run_analysis()
        print 'Analysis done'
    except Exception as e:
        print e.message

    impact = analysis.impact_layer
    qgis_impact = safe_to_qgis_layer(impact)

    generate_styles(impact, qgis_impact)

    copy_impact_layer(impact, arg.impact_filename)
    def test_hazard_additional_keywords(self):
        """Test for hazard_additional_keywords."""
        ifm = ImpactFunctionManager()
        additional_keywords = ifm.hazard_additional_keywords(
            layer_mode_key='classified',
            layer_geometry_key='polygon',
            hazard_category_key='single_event',
            hazard_key='flood'
        )
        expected = []

        self.assertItemsEqual(additional_keywords, expected)
 def test_get_functions_for_exposure_id(self):
     """Test get_functions_for_exposure_id API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.get_functions_for_exposure_id(
         exposure_structure['id'])
     expected_result = [
         VolcanoBuildingImpact.Metadata.get_metadata(),
         EarthquakeBuildingImpactFunction.Metadata.get_metadata(),
         FloodBuildingImpactFunction.Metadata.get_metadata(),
         FloodNativePolygonExperimentalFunction.Metadata.get_metadata(),
         ClassifiedHazardBuildingImpactFunction.Metadata.get_metadata()]
     message = ('I expect %s but I got %s.' % (expected_result, result))
     self.assertItemsEqual(result, expected_result, message)
 def test_get_functions_for_hazard_id(self):
     """Test get_functions_for_hazard_id API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.get_functions_for_hazard_id(
         hazard_volcano['id'])
     expected_result = [
         VolcanoBuildingImpact.Metadata.get_metadata(),
         VolcanoPolygonHazardPopulation.Metadata.get_metadata(),
         ContinuousHazardPopulationImpactFunction.Metadata.get_metadata(),
         ClassifiedHazardBuildingImpactFunction.Metadata.get_metadata(),
         ClassifiedHazardPopulationImpactFunction.Metadata.get_metadata()]
     message = ('I expect %s but I got %s.' % (expected_result, result))
     self.assertItemsEqual(result, expected_result, message)
Exemple #28
0
    def test_available_hazard_constraints(self):
        """Test for available_hazard_constraints."""
        ifm = ImpactFunctionManager()
        hazard_constraints = ifm.available_hazard_constraints(
            'earthquake', 'single_event')
        expected = [
            (layer_mode_continuous, layer_geometry_raster),
            (layer_mode_classified, layer_geometry_raster),
            (layer_mode_classified, layer_geometry_polygon),
        ]

        # print [(x[0]['key'], x[1]['key']) for x in hazard_constraints]
        self.assertItemsEqual(hazard_constraints, expected)
 def test_get_functions_for_hazard_id(self):
     """Test get_functions_for_hazard_id API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.get_functions_for_hazard_id(
         hazard_volcano['id'])
     expected_result = [
         VolcanoBuildingImpact.Metadata.get_metadata(),
         VolcanoPolygonHazardPopulation.Metadata.get_metadata(),
         ContinuousHazardPopulationImpactFunction.Metadata.get_metadata(),
         ClassifiedHazardBuildingImpactFunction.Metadata.get_metadata(),
         ClassifiedHazardPopulationImpactFunction.Metadata.get_metadata()]
     message = ('I expect %s but I got %s.' % (expected_result, result))
     self.assertItemsEqual(result, expected_result, message)
Exemple #30
0
    def calculate_specified_impact(self, function_id, hazard_layer,
                                   exposure_layer, output_basename):
        LOGGER.info('Calculate %s' % function_id)
        if_manager = ImpactFunctionManager()
        impact_function = if_manager.get_instance(function_id)

        impact_function.hazard = hazard_layer

        extent = impact_function.hazard.extent()
        hazard_extent = [
            extent.xMinimum(),
            extent.yMinimum(),
            extent.xMaximum(),
            extent.yMaximum()
        ]

        # clip exposure if required (if it is too large)
        if isinstance(exposure_layer, QgsRasterLayer):
            cell_size, _ = get_wgs84_resolution(exposure_layer)
        else:
            cell_size = None
        clipped_exposure = clip_layer(layer=exposure_layer,
                                      extent=hazard_extent,
                                      cell_size=cell_size)
        exposure_layer = clipped_exposure

        impact_function.exposure = exposure_layer
        impact_function.requested_extent = hazard_extent
        impact_function.requested_extent_crs = impact_function.hazard.crs()
        impact_function.force_memory = True

        try:
            impact_function.run_analysis()
            impact_layer = impact_function.impact

            if impact_layer:
                self.set_impact_style(impact_layer)

                # copy results of impact to report_path directory
                self.copy_layer(impact_layer, output_basename)
        except ZeroImpactException as e:
            # in case zero impact, just return
            LOGGER.info('No impact detected')
            LOGGER.info(e.message)
            return False
        except Exception as e:
            LOGGER.info('Calculation error')
            LOGGER.exception(e)
            return False
        LOGGER.info('Calculation completed.')
        return True
 def test_get_functions_for_exposure_id(self):
     """Test get_functions_for_exposure_id API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.get_functions_for_exposure_id(
         exposure_structure['id'])
     expected_result = [
         VolcanoBuildingImpact.Metadata.get_metadata(),
         EarthquakeBuildingImpactFunction.Metadata.get_metadata(),
         FloodRasterBuildingImpactFunction.Metadata.get_metadata(),
         FloodVectorBuildingImpactFunction.Metadata.get_metadata(),
         FloodNativePolygonExperimentalFunction.Metadata.get_metadata(),
         ClassifiedHazardBuildingImpactFunction.Metadata.get_metadata()]
     message = ('I expect %s but I got %s.' % (expected_result, result))
     self.assertItemsEqual(result, expected_result, message)
    def test_get_available_hazards(self):
        """Test get_available_hazards API."""
        impact_function_manager = ImpactFunctionManager()

        result = impact_function_manager.get_available_hazards()
        expected_result = hazard_all
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        impact_function = EarthquakeBuildingImpactFunction()
        result = impact_function_manager.get_available_hazards(impact_function)
        expected_result = [hazard_earthquake]
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)
Exemple #33
0
    def test_get_available_hazards(self):
        """Test get_available_hazards API."""
        impact_function_manager = ImpactFunctionManager()

        result = impact_function_manager.get_available_hazards()
        expected_result = hazard_all
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        impact_function = EarthquakeBuildingImpactFunction()
        result = impact_function_manager.get_available_hazards(impact_function)
        expected_result = [hazard_earthquake]
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)
Exemple #34
0
def show_impact_function_names(impact_functions):
    """Prints a list of impact functions.

    .. versionadded:: 3.2

    :param impact_functions: A list of impact function ids.
    :type: list of strings.
    """
    manager = ImpactFunctionManager()
    print ""
    print "Available Impact Function:"
    for impact_function in impact_functions:
        print manager.get_function_id(impact_function)
    print ""
Exemple #35
0
    def test_allowed_data_types(self):
        """Test allowed_data_types API."""
        impact_function_manager = ImpactFunctionManager()
        result = impact_function_manager.allowed_data_types('flood')
        expected_result = ['polygon', 'continuous', 'classified']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('volcano')
        expected_result = ['point', 'polygon', 'continuous', 'classified']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('structure')
        expected_result = ['polygon', 'point']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('earthquake')
        expected_result = ['continuous', 'classified']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('tsunami')
        expected_result = ['polygon', 'continuous', 'classified']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('population')
        expected_result = ['continuous']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)
Exemple #36
0
def show_impact_function_names(impact_functions):
    """Prints a list of impact functions.

    .. versionadded:: 3.2

    :param impact_functions: A list of impact function ids.
    :type: list of strings.
    """
    manager = ImpactFunctionManager()
    print ""
    print "Available Impact Function:"
    for impact_function in impact_functions:
        print manager.get_function_id(impact_function)
    print ""
    def test_available_hazards(self):
        """Test available_hazards API."""
        impact_function_manager = ImpactFunctionManager()

        result = impact_function_manager.available_hazards(
            'single_event')
        # print [x['key'] for x in result]
        expected_result = [hazard_flood,
                           hazard_tsunami,
                           hazard_earthquake,
                           hazard_generic,
                           hazard_volcanic_ash,
                           hazard_volcano]
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)
Exemple #38
0
def impact_function_setup(command_line_arguments,
                          hazard,
                          exposure,
                          aggregation=None):
    """Sets up an analysis object.

    .. versionadded:: 3.2

    :param command_line_arguments: User inputs.
    :type command_line_arguments: CommandLineArguments

    :param hazard: Hazard layer
    :type hazard: QgsLayer

    :param exposure: Exposure Layer
    :type exposure: QgsLayer

    :param aggregation: Aggregation Layer
    :type aggregation: QgsLayer

    :raises: Exception
    """
    # IF
    impact_function_manager = ImpactFunctionManager()
    impact_function = impact_function_manager.get(
        command_line_arguments.impact_function)

    impact_function.hazard = hazard
    impact_function.exposure = exposure
    impact_function.aggregation = aggregation
    impact_function.clip_hard = False
    impact_function.show_intermediate_layers = False
    impact_function.run_in_thread_flag = False
    impact_function.map_canvas = CANVAS
    # QSetting context
    settings = QSettings()
    crs = settings.value('inasafe/analysis_extent_crs', '', type=str)
    impact_function.requested_extent_crs = QgsCoordinateReferenceSystem(crs)
    try:
        impact_function.requested_extent = QgsRectangle(
            float(command_line_arguments.extent[0]),
            float(command_line_arguments.extent[1]),
            float(command_line_arguments.extent[2]),
            float(command_line_arguments.extent[3]))
    except AttributeError:
        print "No extents"
        pass
    return impact_function
Exemple #39
0
    def test_keywords(self):
        """Test filtering IF from layer keywords"""

        exposure_keywords = {
            'layer_purpose': 'exposure',
            'layer_mode': 'classified',
            'layer_geometry': 'point',
            'exposure': 'place',
            'exposure_unit': 'count'
        }

        hazard_keywords = {
            'layer_purpose': 'hazard',
            'layer_mode': 'continuous',
            'layer_geometry': 'raster',
            'hazard': 'volcanic_ash',
            'hazard_category': 'single_event',
            'continuous_hazard_unit': 'centimetres'
        }

        impact_functions = ImpactFunctionManager().filter_by_keywords(
            hazard_keywords, exposure_keywords)
        message = 'There should be 1 impact function, but there are: %s' % \
                  len(impact_functions)
        self.assertEqual(1, len(impact_functions), message)
    def test_keywords(self):

        exposure_keywords = {
            'layer_purpose': 'exposure',
            'layer_mode': 'classified',
            'layer_geometry': 'polygon',
            'exposure': 'land_cover',
            'field': 'FCODE',
        }

        hazard_keywords = {
            'layer_purpose': 'hazard',
            'layer_mode': 'classified',
            'layer_geometry': 'polygon',
            'hazard': 'generic',
            'hazard_category': 'multiple_event',
            'field': 'level',
            'vector_hazard_classification': 'generic_vector_hazard_classes',
        }

        impact_functions = ImpactFunctionManager().filter_by_keywords(
            hazard_keywords, exposure_keywords)
        message = 'There should be 1 impact function, but there are: %s' % \
                  len(impact_functions)
        self.assertEqual(1, len(impact_functions), message)
Exemple #41
0
    def test_keywords(self):
        """TestClassifiedPolygonPeopleFunction: Test keywords IF"""

        exposure_keywords = {
            'layer_purpose': 'exposure',
            'layer_mode': 'continuous',
            'layer_geometry': 'polygon',
            'exposure': 'population',
            'structure_class_field': '',
            'exposure_unit': 'count'
        }

        hazard_keywords = {
            'layer_purpose': 'hazard',
            'layer_mode': 'classified',
            'layer_geometry': 'polygon',
            'hazard': 'generic',
            'hazard_category': 'multiple_event',
            'field': 'h_zone',
            'vector_hazard_classification': 'generic_vector_hazard_classes',
        }

        impact_functions = ImpactFunctionManager().filter_by_keywords(
            hazard_keywords, exposure_keywords)
        message = 'There should be 1 impact function, but there are: %s' % \
                  len(impact_functions)
        self.assertEqual(1, len(impact_functions), message)
    def __init__(self, parent):
        """Constructor for the class.

        :param parent: Parent widget i.e. the wizard dialog.
        :type parent: QWidget
        """

        QtCore.QObject.__init__(self)
        self.parent = parent
        # Do not delete this
        self.iface = parent.iface
        self.keyword_io = KeywordIO()
        self.impact_function_manager = ImpactFunctionManager()
        self.extent = Extent(self.iface)
        self.analysis = None

        # Values for settings these get set in read_settings.
        self.run_in_thread_flag = None
        self.zoom_to_impact_flag = None
        self.hide_exposure_flag = None
        self.clip_hard = None
        self.show_intermediate_layers = None
        self.show_rubber_bands = False

        self.last_analysis_rubberband = None
        # This is a rubber band to show what the AOI of the
        # next analysis will be. Also added in 2.1.0
        self.next_analysis_rubberband = None

        self.read_settings()
Exemple #43
0
    def test_hazard_categories_for_layer(self):
        """Test for hazard_categories_for_layer"""
        impact_function_manager = ImpactFunctionManager()
        hazard_categories = impact_function_manager.\
            hazard_categories_for_layer('polygon')
        expected = [
            hazard_category_single_event, hazard_category_multiple_event
        ]
        self.assertItemsEqual(hazard_categories, expected)

        hazard_categories = impact_function_manager.\
            hazard_categories_for_layer('line')
        expected = []
        self.assertItemsEqual(hazard_categories, expected)

        hazard_categories = impact_function_manager.\
            hazard_categories_for_layer('point')
        expected = [
            hazard_category_multiple_event, hazard_category_single_event
        ]
        self.assertItemsEqual(hazard_categories, expected)

        hazard_categories = impact_function_manager.\
            hazard_categories_for_layer('raster')
        expected = [
            hazard_category_single_event, hazard_category_multiple_event
        ]
        self.assertItemsEqual(hazard_categories, expected)

        hazard_categories = impact_function_manager. \
            hazard_categories_for_layer('raster', 'earthquake')
        expected = [
            hazard_category_single_event, hazard_category_multiple_event
        ]
        self.assertItemsEqual(hazard_categories, expected)
Exemple #44
0
    def __init__(self):
        super(TsunamiEvacuationFunction, self).__init__()
        self.impact_function_manager = ImpactFunctionManager()

        # AG: Use the proper minimum needs, update the parameters
        self.parameters = add_needs_parameters(self.parameters)
        self.no_data_warning = False
Exemple #45
0
def impact_function_setup(
        command_line_arguments, hazard, exposure, aggregation=None):
    """Sets up an analysis object.

    .. versionadded:: 3.2

    :param command_line_arguments: User inputs.
    :type command_line_arguments: CommandLineArguments

    :param hazard: Hazard layer
    :type hazard: QgsLayer

    :param exposure: Exposure Layer
    :type exposure: QgsLayer

    :param aggregation: Aggregation Layer
    :type aggregation: QgsLayer

    :raises: Exception
    """
    # IF
    impact_function_manager = ImpactFunctionManager()
    impact_function = impact_function_manager.get(
        command_line_arguments.impact_function)

    impact_function.hazard = hazard
    impact_function.exposure = exposure
    impact_function.aggregation = aggregation
    impact_function.clip_hard = False
    impact_function.show_intermediate_layers = False
    impact_function.run_in_thread_flag = False
    impact_function.map_canvas = CANVAS
    # QSetting context
    settings = QSettings()
    crs = settings.value('inasafe/analysis_extent_crs', '', type=str)
    impact_function.requested_extent_crs = QgsCoordinateReferenceSystem(crs)
    try:
        impact_function.requested_extent = QgsRectangle(
            float(command_line_arguments.extent[0]),
            float(command_line_arguments.extent[1]),
            float(command_line_arguments.extent[2]),
            float(command_line_arguments.extent[3])
        )
    except AttributeError:
        print "No extents"
        pass
    return impact_function
Exemple #46
0
    def __init__(self):
        super(ContinuousHazardPopulationFunction, self).__init__()
        PopulationExposureReportMixin.__init__(self)
        self.impact_function_manager = ImpactFunctionManager()

        # AG: Use the proper minimum needs, update the parameters
        self.parameters = add_needs_parameters(self.parameters)
        self.no_data_warning = False
Exemple #47
0
 def test_get_function_title(self):
     """TestImpactFunctionManager: Test getting function title."""
     impact_function_title = ImpactFunctionManager().get_function_title(
         FloodPolygonBuildingFunction)
     expected_title = 'Be flooded'
     message = 'Expecting %s but got %s' % (impact_function_title,
                                            expected_title)
     self.assertEqual(impact_function_title, expected_title, message)
 def test_allowed_subcategories(self):
     """Test allowed_subcategories API."""
     impact_function_manager = ImpactFunctionManager()
     result = impact_function_manager.allowed_subcategories()
     expected_result = [
         exposure_structure,
         hazard_earthquake,
         exposure_population,
         hazard_flood,
         hazard_tsunami,
         exposure_road,
         hazard_volcano,
         hazard_tephra,
         hazard_generic]
     message = (
         'I expect %s but I got %s.' % (expected_result, result))
     self.assertItemsEqual(result, expected_result, message)
Exemple #49
0
    def test_get_available_exposures(self):
        """Test get_available_exposures API."""
        impact_function_manager = ImpactFunctionManager()

        result = impact_function_manager.get_available_exposures()
        expected_result = [
            exposure_population, exposure_road, exposure_structure
        ]
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        impact_function = EarthquakeBuildingImpactFunction()
        result = impact_function_manager.get_available_exposures(
            impact_function)
        expected_result = [exposure_structure]
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)
Exemple #50
0
    def __init__(self):
        """Constructor."""
        super(FloodEvacuationRasterHazardFunction, self).__init__()
        self.target_field = 'population'
        self.impact_function_manager = ImpactFunctionManager()

        # AG: Use the proper minimum needs, update the parameters
        self.parameters = add_needs_parameters(self.parameters)
    def test_allowed_data_types(self):
        """TestImpactFunctionManager: Test allowed_data_types API."""
        impact_function_manager = ImpactFunctionManager()
        result = impact_function_manager.allowed_data_types("flood")
        expected_result = ["polygon", "continuous", "classified"]
        message = "I expect %s but I got %s." % (expected_result, result)
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types("volcano")
        expected_result = ["point", "polygon", "continuous", "classified"]
        message = "I expect %s but I got %s." % (expected_result, result)
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types("structure")
        expected_result = ["polygon", "point"]
        message = "I expect %s but I got %s." % (expected_result, result)
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types("earthquake")
        expected_result = ["continuous", "classified", "polygon"]
        message = "I expect %s but I got %s." % (expected_result, result)
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types("tsunami")
        expected_result = ["polygon", "continuous", "classified"]
        message = "I expect %s but I got %s." % (expected_result, result)
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types("population")
        expected_result = ["continuous"]
        message = "I expect %s but I got %s." % (expected_result, result)
        self.assertItemsEqual(result, expected_result, message)
    def test_allowed_data_types(self):
        """Test allowed_data_types API."""
        impact_function_manager = ImpactFunctionManager()
        result = impact_function_manager.allowed_data_types('flood')
        expected_result = ['polygon', 'numeric']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('volcano')
        expected_result = ['point', 'polygon', 'numeric']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('structure')
        expected_result = ['polygon', 'point']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('earthquake')
        expected_result = ['polygon', 'numeric']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('tsunami')
        expected_result = ['polygon', 'numeric']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        result = impact_function_manager.allowed_data_types('population')
        expected_result = ['numeric']
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)
 def test_init(self):
     """Test initialize ImpactFunctionManager."""
     impact_function_manager = ImpactFunctionManager()
     expected_result = 15
     result = len(impact_function_manager.impact_functions)
     message = (
         'I expect %s but I got %s, please check the number of current '
         'enabled impact functions' % (expected_result, result))
     self.assertEqual(result, expected_result, message)
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)
Exemple #55
0
 def test_continuous_hazards_units_for_layer(self):
     """Test for continuous_hazards_units_for_layer"""
     impact_function_manager = ImpactFunctionManager()
     continuous_hazards_units = impact_function_manager.\
         continuous_hazards_units_for_layer(
             'tsunami', 'raster', 'continuous', 'single_event')
     # print [x['key'] for x in continuous_hazards_units]
     expected = [unit_metres, unit_feet, unit_generic]
     self.assertItemsEqual(continuous_hazards_units, expected)
    def test_purposes_for_layer(self):
        """Test for purposes_for_layer"""
        impact_function_manager = ImpactFunctionManager()
        layer_purposes = impact_function_manager.purposes_for_layer('polygon')
        expected = [layer_purpose_hazard, layer_purpose_exposure]
        self.assertItemsEqual(layer_purposes, expected)

        layer_purposes = impact_function_manager.purposes_for_layer('line')
        expected = [layer_purpose_exposure]
        self.assertItemsEqual(layer_purposes, expected)

        layer_purposes = impact_function_manager.purposes_for_layer('point')
        expected = [layer_purpose_hazard, layer_purpose_exposure]
        self.assertItemsEqual(layer_purposes, expected)

        layer_purposes = impact_function_manager.purposes_for_layer('raster')
        expected = [layer_purpose_hazard, layer_purpose_exposure]
        self.assertItemsEqual(layer_purposes, expected)
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)
    def test_get_available_exposures(self):
        """Test get_available_exposures API."""
        impact_function_manager = ImpactFunctionManager()

        result = impact_function_manager.get_available_exposures()
        expected_result = [
            exposure_population,
            exposure_road,
            exposure_structure]
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)

        impact_function = EarthquakeBuildingImpactFunction()
        result = impact_function_manager.get_available_exposures(
            impact_function)
        expected_result = [exposure_structure]
        message = ('I expect %s but I got %s.' % (expected_result, result))
        self.assertItemsEqual(result, expected_result, message)
Exemple #59
0
    def __init__(self):
        """Constructor."""
        super(FloodEvacuationRasterHazardFunction, self).__init__()
        self.impact_function_manager = ImpactFunctionManager()

        # AG: Use the proper minimum needs, update the parameters
        self.parameters = add_needs_parameters(self.parameters)

        # Initialize instance attributes for readability (pylint)
        self.no_data_warning = False
Exemple #60
0
    def __init__(self, parent=None):
        """Constructor

        :param parent: parent - widget to use as parent.
        :type parent: QWidget
        """
        QWidget.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)

        self.keyword_io = KeywordIO()
        self.impact_function_manager = ImpactFunctionManager()