예제 #1
0
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)
예제 #2
0
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)
예제 #3
0
def run_analysis(hazard,
                 exposure,
                 function,
                 aggregation=None,
                 generate_report=False):
    """Run analysis"""
    hazard_file = download_layer(hazard)
    exposure_file = download_layer(exposure)
    aggregation_file = None
    if aggregation:
        aggregation_file = download_layer(aggregation)
    arguments = CommandLineArguments()
    arguments.hazard = hazard_file
    arguments.exposure = exposure_file
    arguments.aggregation = aggregation_file
    arguments.impact_function = function

    # generate names for impact results
    # create date timestamp
    date_folder = datetime.datetime.now().strftime('%Y%m%d')
    deploy_dir = os.path.join(DEPLOY_OUTPUT_DIR, date_folder)
    try:
        os.mkdir(deploy_dir)
    except:
        pass

    # create temporary file name without extension
    tmp = tempfile.mktemp(dir=deploy_dir)
    arguments.output_file = tmp
    impact_layer = run_impact_function(arguments)

    if impact_layer.is_raster:
        new_name = '%s.tif' % tmp
    else:
        new_name = '%s.shp' % tmp

    # if asked to generate report
    if generate_report:
        arguments.report_template = ''
        arguments.output_file = new_name
        build_report(arguments)

    # generating qml styles file
    qgis_impact_layer = safe_to_qgis_layer(impact_layer)
    generate_styles(impact_layer, qgis_impact_layer)

    # archiving the layer
    new_name = archive_layer(new_name)
    # new_name is a file path to archived layer
    # we need to return the url
    new_basename = os.path.basename(new_name)
    output_url = urlparse.urljoin(DEPLOY_OUTPUT_URL,
                                  '%s/%s' % (date_folder, new_basename))
    return output_url
예제 #4
0
def run_analysis(hazard, exposure, function, aggregation=None,
                 generate_report=False):
    """Run analysis"""
    hazard_file = download_layer(hazard)
    exposure_file = download_layer(exposure)
    aggregation_file = None
    if aggregation:
        aggregation_file = download_layer(aggregation)
    arguments = CommandLineArguments()
    arguments.hazard = hazard_file
    arguments.exposure = exposure_file
    arguments.aggregation = aggregation_file
    arguments.impact_function = function

    # generate names for impact results
    # create date timestamp
    date_folder = datetime.datetime.now().strftime('%Y%m%d')
    deploy_dir = os.path.join(DEPLOY_OUTPUT_DIR, date_folder)
    try:
        os.mkdir(deploy_dir)
    except:
        pass

    # create temporary file name without extension
    tmp = tempfile.mktemp(dir=deploy_dir)
    arguments.output_file = tmp
    impact_layer = run_impact_function(arguments)

    if impact_layer.is_raster:
        new_name = '%s.tif' % tmp
    else:
        new_name = '%s.shp' % tmp

    # if asked to generate report
    if generate_report:
        arguments.report_template = ''
        arguments.output_file = new_name
        build_report(arguments)

    # generating qml styles file
    qgis_impact_layer = safe_to_qgis_layer(impact_layer)
    generate_styles(impact_layer, qgis_impact_layer)

    # archiving the layer
    new_name = archive_layer(new_name)
    # new_name is a file path to archived layer
    # we need to return the url
    new_basename = os.path.basename(new_name)
    output_url = urlparse.urljoin(
        DEPLOY_OUTPUT_URL,
        '%s/%s' % (date_folder, new_basename)
    )
    return output_url
    def test_run(self):
        function = TsunamiRasterLandcoverFunction.instance()

        hazard_path = test_data_path('hazard', 'tsunami_wgs84.tif')
        exposure_path = test_data_path('exposure', 'landcover.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsRasterLayer(hazard_path, 'Tsunami')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Land Cover', 'ogr')
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        rect_extent = [106.5, -6.5, 107, -6]
        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        self.assertEqual(impact.dataProvider().featureCount(), 72)
        features = {}
        exposure_field = function.exposure.keyword('field')
        for f in impact.getFeatures():
            type_tuple = f[exposure_field], f[function.target_field]
            features[type_tuple] = round(f.geometry().area(), 1)

        expected_features = {
            (u'Population', u'Dry Zone'): 7977390.3,
            (u'Population', u'Low Hazard Zone'): 403.8,
            (u'Population', u'Medium Hazard Zone'): 156692.3,
            (u'Population', u'High Hazard Zone'): 298791.1,
            (u'Population', u'Very High Hazard Zone'): 8884.6,
            (u'Water', u'Dry Zone'): 403.8,
            (u'Water', u'Low Hazard Zone'): 65836.7,
            (u'Water', u'Medium Hazard Zone'): 34746.7,
            (u'Water', u'High Hazard Zone'): 9310.4,
            (u'Water', u'Very High Hazard Zone'): 807.7,
            (u'Meadow', u'Dry Zone'): 2512444.0,
            (u'Forest', u'Dry Zone'): 1000000.0
        }
        self.assertEqual(len(expected_features.keys()), len(features.keys()))
        for key, value in expected_features.iteritems():
            result = features[key]
            msg = '%s is different than %s, I got %s' % (key, value, result)
            self.assertEqual(value, result, msg)
예제 #6
0
    def test_run(self):
        function = ClassifiedPolygonHazardLandCoverFunction.instance()

        hazard_path = standard_data_path('hazard', 'landcover_hazard.shp')
        exposure_path = standard_data_path('exposure', 'landcover.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Hazard', 'ogr')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Land Cover', 'ogr')
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        rect_extent = [106.5, -6.5, 107, -6]
        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        self.assertEqual(impact.dataProvider().featureCount(), 7)
        features = {}
        exposure_field = function.exposure.keyword('field')
        for f in impact.getFeatures():
            type_tuple = f[exposure_field], f[function.target_field]
            features[type_tuple] = round(f.geometry().area(), 1)
        expected_features = {
            (u'Water', u'High Hazard Zone'): 500000.0,
            (u'Water', u'Medium Hazard Zone'): 500000.0,
            (u'Population', u'High Hazard Zone'): 3000000.0,
            (u'Population', u'Medium Hazard Zone'): 1500000.0,
            (u'Population', u'Low Hazard Zone'): 1500000.0,
            (u'Forest', u'High Hazard Zone'): 500000.0,
            (u'Forest', u'Low Hazard Zone'): 500000.0,
        }
        self.assertEqual(len(expected_features.keys()), len(features.keys()))
        for key, value in expected_features.iteritems():
            result = features[key]
            msg = '%s is different than %s, I got %s' % (key, value, result)
            self.assertEqual(value, result, msg)

        # check if generic notes are returned
        self.assertIn(
                u'Areas reported for land cover have not been rounded.',
                function.notes())
    def test_run(self):
        function = ClassifiedPolygonHazardLandCoverFunction.instance()

        hazard_path = standard_data_path('hazard', 'landcover_hazard.shp')
        exposure_path = standard_data_path('exposure', 'landcover.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Hazard', 'ogr')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Land Cover', 'ogr')
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        rect_extent = [106.5, -6.5, 107, -6]
        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        self.assertEqual(impact.dataProvider().featureCount(), 7)
        features = {}
        exposure_field = function.exposure.keyword('field')
        for f in impact.getFeatures():
            type_tuple = f[exposure_field], f[function.target_field]
            features[type_tuple] = round(f.geometry().area(), 1)
        expected_features = {
            (u'Water', u'High Hazard Zone'): 500000.0,
            (u'Water', u'Medium Hazard Zone'): 500000.0,
            (u'Population', u'High Hazard Zone'): 3000000.0,
            (u'Population', u'Medium Hazard Zone'): 1500000.0,
            (u'Population', u'Low Hazard Zone'): 1500000.0,
            (u'Forest', u'High Hazard Zone'): 500000.0,
            (u'Forest', u'Low Hazard Zone'): 500000.0,
        }
        self.assertEqual(len(expected_features.keys()), len(features.keys()))
        for key, value in expected_features.iteritems():
            result = features[key]
            msg = '%s is different than %s, I got %s' % (key, value, result)
            self.assertEqual(value, result, msg)

        # check if generic notes are returned
        self.assertIn(u'Areas reported for land cover have not been rounded.',
                      function.notes())
예제 #8
0
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)
예제 #9
0
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)
예제 #10
0
    def test_run(self):
        function = AshRasterLandCoverFunction.instance()

        hazard_path = standard_data_path('hazard', 'ash_raster_wgs84.tif')
        exposure_path = standard_data_path('exposure', 'landcover.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsRasterLayer(hazard_path, 'Ash')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Land Cover', 'ogr')
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        rect_extent = [106.5, -6.5, 107, -6]
        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        self.assertEqual(impact.dataProvider().featureCount(), 7L)
        features = {}
        exposure_field = function.exposure.keyword('field')
        for f in impact.getFeatures():
            type_tuple = f[exposure_field], f[function.target_field]
            features[type_tuple] = round(f.geometry().area(), 1)

        expected_features = {
            (u'Forest', u'Low'): 1000000.0,
            (u'Population', u'High'): 18721.0,
            (u'Population', u'Moderate'): 589677.8,
            (u'Water', u'Low'): 2000000.0,
            (u'Meadow', u'Low'): 3971158.6,
            (u'Meadow', u'Moderate'): 28841.4,
            (u'Population', u'Low'): 8391601.2
        }
        self.assertEqual(len(expected_features.keys()), len(features.keys()))
        for key, value in expected_features.iteritems():
            result = features[key]
            msg = '%s is different than %s, I got %s' % (key, value, result)
            self.assertEqual(value, result, msg)
예제 #11
0
    def test_run(self):
        function = AshRasterLandCoverFunction.instance()

        hazard_path = standard_data_path('hazard', 'ash_raster_wgs84.tif')
        exposure_path = standard_data_path('exposure', 'landcover.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsRasterLayer(hazard_path, 'Ash')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Land Cover', 'ogr')
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        rect_extent = [106.5, -6.5, 107, -6]
        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        self.assertEqual(impact.dataProvider().featureCount(), 7L)
        features = {}
        exposure_field = function.exposure.keyword('field')
        for f in impact.getFeatures():
            type_tuple = f[exposure_field], f[function.target_field]
            features[type_tuple] = round(f.geometry().area(), 1)

        expected_features = {
            (u'Forest', u'Low'): 1000000.0,
            (u'Population', u'High'): 18721.0,
            (u'Population', u'Moderate'): 589677.8,
            (u'Water', u'Low'): 2000000.0,
            (u'Meadow', u'Low'): 3971158.6,
            (u'Meadow', u'Moderate'): 28841.4,
            (u'Population', u'Low'): 8391601.2
        }
        self.assertEqual(len(expected_features.keys()), len(features.keys()))
        for key, value in expected_features.iteritems():
            result = features[key]
            msg = '%s is different than %s, I got %s' % (key, value, result)
            self.assertEqual(value, result, msg)
예제 #12
0
def run_impact_function(command_line_arguments):
    """Runs an analysis and delegates producing pdf and .shp results.

        An impact layer object is created and used to write a shapefile.
        The shapefile path is given by user and used by build_report
        function to read from.

    .. versionadded:: 3.2

    :param command_line_arguments: User inputs.
    :type command_line_arguments: CommandLineArguments
    """
    hazard = get_hazard(command_line_arguments)
    exposure = get_exposure(command_line_arguments)
    aggregation = get_layer(command_line_arguments.aggregation)
    analysis = analysis_setup(command_line_arguments, hazard, exposure, aggregation)
    analysis.run_analysis()
    impact_layer = analysis.impact_layer
    qgis_impact_layer = safe_to_qgis_layer(impact_layer)
    write_results(command_line_arguments, impact_layer)

    return impact_layer
예제 #13
0
파일: inasafe.py 프로젝트: vck/inasafe
def run_impact_function(command_line_arguments):
    """Runs an analysis and delegates producing pdf and .shp results.

        An impact layer object is created and used to write a shapefile.
        The shapefile path is given by user and used by build_report
        function to read from.

    .. versionadded:: 3.2

    :param command_line_arguments: User inputs.
    :type command_line_arguments: CommandLineArguments
    """
    hazard = get_hazard(command_line_arguments)
    exposure = get_exposure(command_line_arguments)
    aggregation = get_layer(command_line_arguments.aggregation)
    analysis = analysis_setup(command_line_arguments, hazard, exposure,
                              aggregation)
    analysis.run_analysis()
    impact_layer = analysis.impact_layer
    qgis_impact_layer = safe_to_qgis_layer(impact_layer)
    write_results(command_line_arguments, impact_layer)

    return impact_layer
예제 #14
0
    def test_run(self):
        """TestClassifiedPolygonPeopleFunction: Test running the IF."""

        # 1. Initializing function with necessary data
        function = ClassifiedPolygonHazardPolygonPeopleFunction.instance()

        hazard_path = standard_data_path('hazard',
                                         'classified_generic_polygon.shp')
        exposure_path = standard_data_path('exposure', 'census.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Hazard', 'ogr')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Exposure', 'ogr')

        # 1.1 Asserting if the provided data are valid
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        # 2.Choosing the extent to run analysis
        extent = hazard_layer.extent()
        rect_extent = [
            extent.xMinimum(),
            extent.yMaximum(),
            extent.xMaximum(),
            extent.yMinimum()
        ]

        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent

        # 3. Running the analysis
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        # Asserting for the number of features in the impact
        # layer

        self.assertEqual(impact.dataProvider().featureCount(), 6L)

        # 4. Asserting about the results found
        features = {}
        for feature in impact.getFeatures():
            area = feature.geometry().area() * 1e8
            features[feature['id']] = round(area, 1)

        # expected features changes accordingly
        # to the impact features
        expected_features = {1: 6438.5, 2: 5894.1, 3: 8534.3}
        self.assertEqual(features, expected_features)
        expected_results = [[u'High Hazard Zone', 7271.431538053051],
                            [u'Medium Hazard Zone', 72852.05080801852],
                            [u'Low Hazard Zone', 11459.170311153292],
                            [u'Total affected people', 91583.0],
                            [u'Unaffected people', 17269.0],
                            [u'Total people', 108852]]

        result = function.generate_data()['impact summary']['fields']

        for expected_result in expected_results:
            self.assertIn(expected_result, result)
예제 #15
0
    def test_run(self):
        function = TsunamiRasterLandcoverFunction.instance()

        hazard_path = standard_data_path('hazard', 'tsunami_wgs84.tif')
        exposure_path = standard_data_path('exposure', 'landcover.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsRasterLayer(hazard_path, 'Tsunami')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Land Cover', 'ogr')
        self.assertTrue(hazard_layer.isValid())
        self.assertTrue(exposure_layer.isValid())

        rect_extent = [106.5, -6.5, 107, -6]
        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact
        impact = safe_to_qgis_layer(impact)

        expected = {
            'data':
            [[u'Population', u'Dry Zone', None, 793.6916054134609],
             [u'Water', u'Low Hazard Zone', None, 16.298813953855912],
             [
                 u'Population', u'Very High Hazard Zone', None,
                 12.45623642166847
             ],
             [u'Water', u'Very High Hazard Zone', None, 0.08036139883589728],
             [u'Water', u'Medium Hazard Zone', None, 12.1033540507973],
             [u'Population', u'Low Hazard Zone', None, 28.866862427357326],
             [u'Water', u'Dry Zone', None, 164.67113858186028],
             [u'Meadow', u'Dry Zone', None, 249.95443689559693],
             [u'Population', u'Medium Hazard Zone', None, 30.69211822286981],
             [u'Water', u'High Hazard Zone', None, 5.835228232982915],
             [u'Population', u'High Hazard Zone', None, 29.72789895440279],
             [u'Forest', u'Dry Zone', None, 99.489344261353]],
            'groups': ('landcover', 'hazard', 'zone')
        }
        ordered_columns = function.impact.impact_data.get('ordered columns')
        affected_columns = function.impact.impact_data.get('affected columns')
        expected = FlatTable().from_dict(
            groups=expected['groups'],
            data=expected['data'],
        )
        expected = PivotTable(expected,
                              row_field='landcover',
                              column_field='hazard',
                              columns=ordered_columns,
                              affected_columns=affected_columns)

        self.assertEqual(impact.dataProvider().featureCount(), 72)
        table = function.impact.impact_data['impact table']
        table = FlatTable().from_dict(
            groups=table['groups'],
            data=table['data'],
        )
        table = PivotTable(table,
                           row_field='landcover',
                           column_field='hazard',
                           columns=ordered_columns,
                           affected_columns=affected_columns)
        for index, value in enumerate(expected.total_rows):
            self.assertAlmostEqual(value, table.total_rows[index])
        for index, value in enumerate(expected.total_columns):
            self.assertAlmostEqual(value, table.total_columns[index])
        for index, value in enumerate(expected.total_rows_affected):
            self.assertAlmostEqual(value, table.total_rows_affected[index])
        for index, value in enumerate(expected.rows):
            self.assertAlmostEqual(value, table.rows[index])
        for index, value in enumerate(expected.columns):
            self.assertAlmostEqual(value, table.columns[index])
        for index, value in enumerate(expected.affected_columns):
            self.assertAlmostEqual(value, table.affected_columns[index])
        # This is a list of list so we unpack both
        for index, value in enumerate(expected.data):
            for value_index, value_value in enumerate(value):
                self.assertAlmostEqual(value_value,
                                       table.data[index][value_index])
        self.assertAlmostEqual(expected.total_affected, table.total_affected)
    def test_run(self):
        """TestClassifiedPolygonPeopleFunction: Test running the IF."""

        # 1. Initializing function with necessary data
        function = ClassifiedPolygonHazardPolygonPeopleFunction.instance()

        hazard_path = test_data_path(
                'hazard', 'classified_generic_polygon.shp')
        exposure_path = test_data_path('exposure', 'census.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Hazard', 'ogr')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Exposure', 'ogr')

        # 1.1 Asserting if the provided data are valid
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        # 2.Choosing the extent to run analysis
        extent = hazard_layer.extent()
        rect_extent = [
            extent.xMinimum(), extent.yMaximum(),
            extent.xMaximum(), extent.yMinimum()]

        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent

        # 3. Running the analysis
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        # Asserting for the number of features in the impact
        # layer

        self.assertEqual(impact.dataProvider().featureCount(), 6L)

        # 4. Asserting about the results found
        features = {}
        for feature in impact.getFeatures():
            area = feature.geometry().area() * 1e8
            features[feature['id']] = round(area, 1)

        # expected features changes accordingly
        # to the impact features
        expected_features = {
            1: 6438.5,
            2: 5894.1,
            3: 8534.3
        }
        self.assertEqual(features, expected_features)
        expected_results = [
            [u'High Hazard Zone', 7271.431538053051],
            [u'Medium Hazard Zone', 72852.05080801852],
            [u'Low Hazard Zone', 11459.170311153292],
            [u'Total affected people', 91583.0],
            [u'Unaffected people', 17269.0],
            [u'Total people', 108852]
        ]

        result = function.generate_data()['impact summary']['fields']

        for expected_result in expected_results:
            self.assertIn(expected_result, result)
    def test_run(self):
        function = TsunamiRasterLandcoverFunction.instance()

        hazard_path = standard_data_path('hazard', 'tsunami_wgs84.tif')
        exposure_path = standard_data_path('exposure', 'landcover.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsRasterLayer(hazard_path, 'Tsunami')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Land Cover', 'ogr')
        self.assertTrue(hazard_layer.isValid())
        self.assertTrue(exposure_layer.isValid())

        rect_extent = [106.5, -6.5, 107, -6]
        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent
        function.run()
        impact = function.impact
        impact = safe_to_qgis_layer(impact)

        expected = {
            'data':
                [[u'Population', u'Dry Zone', None, 793.6916054134609],
                 [u'Water', u'Low Hazard Zone', None, 16.298813953855912],
                 [u'Population', u'Very High Hazard Zone', None,
                  12.45623642166847],
                 [u'Water', u'Very High Hazard Zone', None,
                  0.08036139883589728],
                 [u'Water', u'Medium Hazard Zone', None, 12.1033540507973],
                 [u'Population', u'Low Hazard Zone', None, 28.866862427357326],
                 [u'Water', u'Dry Zone', None, 164.67113858186028],
                 [u'Meadow', u'Dry Zone', None, 249.95443689559693],
                 [u'Population', u'Medium Hazard Zone', None,
                  30.69211822286981],
                 [u'Water', u'High Hazard Zone', None, 5.835228232982915],
                 [u'Population', u'High Hazard Zone', None, 29.72789895440279],
                 [u'Forest', u'Dry Zone', None, 99.489344261353]],
            'groups': ('landcover', 'hazard', 'zone')}
        ordered_columns = function.impact.impact_data.get('ordered columns')
        affected_columns = function.impact.impact_data.get('affected columns')
        expected = FlatTable().from_dict(
                groups=expected['groups'],
                data=expected['data'],)
        expected = PivotTable(
            expected,
            row_field='landcover',
            column_field='hazard',
            columns=ordered_columns,
            affected_columns=affected_columns)

        self.assertEqual(impact.dataProvider().featureCount(), 72)
        table = function.impact.impact_data['impact table']
        table = FlatTable().from_dict(
            groups=table['groups'],
            data=table['data'],)
        table = PivotTable(
            table,
            row_field='landcover',
            column_field='hazard',
            columns=ordered_columns,
            affected_columns=affected_columns)
        for index, value in enumerate(expected.total_rows):
            self.assertAlmostEqual(value, table.total_rows[index])
        for index, value in enumerate(expected.total_columns):
            self.assertAlmostEqual(value, table.total_columns[index])
        for index, value in enumerate(expected.total_rows_affected):
            self.assertAlmostEqual(value, table.total_rows_affected[index])
        for index, value in enumerate(expected.rows):
            self.assertAlmostEqual(value, table.rows[index])
        for index, value in enumerate(expected.columns):
            self.assertAlmostEqual(value, table.columns[index])
        for index, value in enumerate(expected.affected_columns):
            self.assertAlmostEqual(value, table.affected_columns[index])
        # This is a list of list so we unpack both
        for index, value in enumerate(expected.data):
            for value_index, value_value in enumerate(value):
                self.assertAlmostEqual(
                        value_value, table.data[index][value_index])
        self.assertAlmostEqual(expected.total_affected, table.total_affected)
예제 #18
0
    def test_run(self):
        """TestClassifiedPolygonPeopleFunction: Test running the IF."""

        # 1. Initializing function with necessary data
        function = ClassifiedPolygonHazardPolygonPeopleFunction.instance()

        hazard_path = test_data_path('hazard',
                                     'classified_generic_polygon.shp')
        exposure_path = test_data_path('exposure', 'census.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Hazard', 'ogr')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Exposure', 'ogr')

        # 1.1 Asserting if the provided data are valid
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        # 2.Choosing the extent to run analysis
        extent = hazard_layer.extent()
        rect_extent = [
            extent.xMinimum(),
            extent.yMaximum(),
            extent.xMaximum(),
            extent.yMinimum()
        ]

        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent

        # 3. Running the analysis
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        # Asserting for the number of features in the impact
        # layer

        self.assertEqual(impact.dataProvider().featureCount(), 6L)

        # 4. Asserting about the results found
        features = {}
        for feature in impact.getFeatures():
            area = feature.geometry().area() * 1e8
            features[feature['id']] = round(area, 1)

        # expected features changes accordingly
        # to the impact features
        expected_features = {1: 6438.5, 2: 5894.1, 3: 8534.3}
        self.assertEqual(features, expected_features)
        expected_impact_summary = [
            '**High Hazard Zone**, 4,600------',
            '**Medium Hazard Zone**, 65,700------',
            '**Low Hazard Zone**, 11,500------',
            '**Total affected people**, 81,600------',
            '**Unaffected people**, 17,300------',
            '**Total people**, 98,900---'
        ]
        for row in expected_impact_summary:
            self.assertIn(row, function.impact_summary().to_text())
    def test_run(self):
        """TestClassifiedPolygonPeopleFunction: Test running the IF."""

        # 1. Initializing function with necessary data
        function = ClassifiedPolygonHazardPolygonPeopleFunction.instance()

        hazard_path = test_data_path(
                'hazard', 'classified_generic_polygon.shp')
        exposure_path = test_data_path('exposure', 'census.shp')
        # noinspection PyCallingNonCallable
        hazard_layer = QgsVectorLayer(hazard_path, 'Hazard', 'ogr')
        # noinspection PyCallingNonCallable
        exposure_layer = QgsVectorLayer(exposure_path, 'Exposure', 'ogr')

        # 1.1 Asserting if the provided data are valid
        self.assertEqual(hazard_layer.isValid(), True)
        self.assertEqual(exposure_layer.isValid(), True)

        # 2.Choosing the extent to run analysis
        extent = hazard_layer.extent()
        rect_extent = [
            extent.xMinimum(), extent.yMaximum(),
            extent.xMaximum(), extent.yMinimum()]

        function.hazard = hazard_layer
        function.exposure = exposure_layer
        function.requested_extent = rect_extent

        # 3. Running the analysis
        function.run()
        impact = function.impact

        impact = safe_to_qgis_layer(impact)

        # Asserting for the number of features in the impact
        # layer

        self.assertEqual(impact.dataProvider().featureCount(), 6L)

        # 4. Asserting about the results found
        features = {}
        for feature in impact.getFeatures():
            area = feature.geometry().area() * 1e8
            features[feature['id']] = round(area, 1)

        # expected features changes accordingly
        # to the impact features
        expected_features = {
            1: 6438.5,
            2: 5894.1,
            3: 8534.3
        }
        self.assertEqual(features, expected_features)
        expected_impact_summary = [
            '**High Hazard Zone**, 4,600------',
            '**Medium Hazard Zone**, 65,700------',
            '**Low Hazard Zone**, 11,500------',
            '**Total affected people**, 81,600------',
            '**Unaffected people**, 17,300------',
            '**Total people**, 98,900---'
        ]
        for row in expected_impact_summary:
            self.assertIn(row, function.impact_summary().to_text())