Example #1
0
    def set_style(self):
        # Get requested style for impact layer of either kind
        impact = self.impact_layer
        style = impact.get_style_info()
        style_type = impact.get_style_type()

        # Determine styling for QGIS layer
        qgis_impact_layer = impact.as_qgis_native()
        if impact.is_vector:
            LOGGER.debug('myEngineImpactLayer.is_vector')
            if not style:
                # Set default style if possible
                pass
            elif style_type == 'categorizedSymbol':
                LOGGER.debug('use categorized')
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == 'graduatedSymbol':
                LOGGER.debug('use graduated')
                set_vector_graduated_style(qgis_impact_layer, style)

        elif impact.is_raster:
            LOGGER.debug('myEngineImpactLayer.is_raster')
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
            else:
                setRasterStyle(qgis_impact_layer, style)
Example #2
0
    def test_issue_121(self):
        """Test that point symbol size can be set from style (issue 121).
        .. seealso:: https://github.com/AIFDR/inasafe/issues/121
        """
        layer = clone_shp_layer(name='volcano_point',
                                include_keywords=True,
                                source_directory=test_data_path('hazard'))

        # Note the float quantity values below
        style_info = {
            'target_field':
            'KEPADATAN',
            'style_classes': [{
                'opacity': 1,
                'max': 200,
                'colour': '#fecc5c',
                'min': 45,
                'label': 'Low',
                'size': 1
            }, {
                'opacity': 1,
                'max': 350,
                'colour': '#fd8d3c',
                'min': 201,
                'label': 'Medium',
                'size': 2
            }, {
                'opacity': 1,
                'max': 539,
                'colour': '#f31a1c',
                'min': 351,
                'label': 'High',
                'size': 3
            }]
        }

        print 'Setting style with point sizes should work.'
        set_vector_graduated_style(layer, style_info)

        # Now validate the size values were set as expected

        # new symbology - subclass of QgsFeatureRendererV2 class
        renderer = layer.rendererV2()
        layer_type = renderer.type()
        assert layer_type == 'graduatedSymbol'
        size = 1
        for renderer_range in renderer.ranges():
            symbol = renderer_range.symbol()
            symbol_layer = symbol.symbolLayer(0)
            actual_size = symbol_layer.size()
            message = (('Expected symbol layer 0 for range %s to have'
                        ' a size of %s, got %s') % (size, size, actual_size))
            assert size == actual_size, message
            size += 1
Example #3
0
def generate_styles(safe_impact_layer, qgis_impact_layer):
    # Get requested style for impact layer of either kind
    style = safe_impact_layer.get_style_info()
    style_type = safe_impact_layer.get_style_type()

    # Determine styling for QGIS layer
    if safe_impact_layer.is_vector:
        if not style:
            # Set default style if possible
            pass
        elif style_type == 'categorizedSymbol':
            set_vector_categorized_style(qgis_impact_layer, style)
        elif style_type == 'graduatedSymbol':
            set_vector_graduated_style(qgis_impact_layer, style)

    elif safe_impact_layer.is_raster:
        if not style:
            qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
        else:
            setRasterStyle(qgis_impact_layer, style)
Example #4
0
def generate_styles(safe_impact_layer, qgis_impact_layer):
    # Get requested style for impact layer of either kind
    style = safe_impact_layer.get_style_info()
    style_type = safe_impact_layer.get_style_type()

    # Determine styling for QGIS layer
    if safe_impact_layer.is_vector:
        if not style:
            # Set default style if possible
            pass
        elif style_type == 'categorizedSymbol':
            set_vector_categorized_style(qgis_impact_layer, style)
        elif style_type == 'graduatedSymbol':
            set_vector_graduated_style(qgis_impact_layer, style)

    elif safe_impact_layer.is_raster:
        if not style:
            qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
        else:
            setRasterStyle(qgis_impact_layer, style)
    def test_issue_121(self):
        """Test that point symbol size can be set from style (issue 121).
        .. seealso:: https://github.com/AIFDR/inasafe/issues/121
        """
        layer = clone_shp_layer(
            name='volcano_point',
            include_keywords=True,
            source_directory=test_data_path('hazard'))

        # Note the float quantity values below
        style_info = {
            'target_field': 'KEPADATAN',
            'style_classes': [
                {'opacity': 1, 'max': 200, 'colour': '#fecc5c',
                 'min': 45, 'label': 'Low', 'size': 1},
                {'opacity': 1, 'max': 350, 'colour': '#fd8d3c',
                 'min': 201, 'label': 'Medium', 'size': 2},
                {'opacity': 1, 'max': 539, 'colour': '#f31a1c',
                 'min': 351, 'label': 'High', 'size': 3}]}

        print 'Setting style with point sizes should work.'
        set_vector_graduated_style(layer, style_info)

        # Now validate the size values were set as expected

        # new symbology - subclass of QgsFeatureRendererV2 class
        renderer = layer.rendererV2()
        layer_type = renderer.type()
        assert layer_type == 'graduatedSymbol'
        size = 1
        for renderer_range in renderer.ranges():
            symbol = renderer_range.symbol()
            symbol_layer = symbol.symbolLayer(0)
            actual_size = symbol_layer.size()
            message = ((
                'Expected symbol layer 0 for range %s to have'
                ' a size of %s, got %s') % (size, size, actual_size))
            assert size == actual_size, message
            size += 1
Example #6
0
    def set_impact_style(cls, impact):
        # Determine styling for QGIS layer
        qgis_impact_layer = impact.as_qgis_native()
        style = impact.get_style_info()
        style_type = impact.get_style_type()
        if impact.is_vector:
            LOGGER.debug("myEngineImpactLayer.is_vector")
            if not style:
                # Set default style if possible
                pass
            elif style_type == "categorizedSymbol":
                LOGGER.debug("use categorized")
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == "graduatedSymbol":
                LOGGER.debug("use graduated")
                set_vector_graduated_style(qgis_impact_layer, style)

        elif impact.is_raster:
            LOGGER.debug("myEngineImpactLayer.is_raster")
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
            else:
                setRasterStyle(qgis_impact_layer, style)
    def show_results(self, qgis_impact_layer, engine_impact_layer):
        """Helper function for slot activated when the process is done.

        .. note:: Adapted from the dock

        :param qgis_impact_layer: A QGIS layer representing the impact.
        :type qgis_impact_layer: QgsMapLayer, QgsVectorLayer, QgsRasterLayer

        :param engine_impact_layer: A safe_layer representing the impact.
        :type engine_impact_layer: ReadLayer

        :returns: Provides a report for writing to the dock.
        :rtype: str
        """
        keywords = self.keyword_io.read_keywords(qgis_impact_layer)

        # write postprocessing report to keyword
        output = self.analysis.postprocessor_manager.get_output(
            self.analysis.aggregator.aoi_mode)
        keywords['postprocessing_report'] = output.to_html(
            suppress_newlines=True)
        self.keyword_io.write_keywords(qgis_impact_layer, keywords)

        # Get tabular information from impact layer
        report = m.Message()
        report.add(LOGO_ELEMENT)
        report.add(m.Heading(self.tr(
            'Analysis Results'), **INFO_STYLE))
        report.add(self.keyword_io.read_keywords(
            qgis_impact_layer, 'impact_summary'))

        # Get requested style for impact layer of either kind
        style = engine_impact_layer.get_style_info()
        style_type = engine_impact_layer.get_style_type()

        # Determine styling for QGIS layer
        if engine_impact_layer.is_vector:
            LOGGER.debug('myEngineImpactLayer.is_vector')
            if not style:
                # Set default style if possible
                pass
            elif style_type == 'categorizedSymbol':
                LOGGER.debug('use categorized')
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == 'graduatedSymbol':
                LOGGER.debug('use graduated')
                set_vector_graduated_style(qgis_impact_layer, style)

        elif engine_impact_layer.is_raster:
            LOGGER.debug('myEngineImpactLayer.is_raster')
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
                # qgis_impact_layer.setColorShadingAlgorithm(
                #    QgsRasterLayer.PseudoColorShader)
            else:
                setRasterStyle(qgis_impact_layer, style)

        else:
            message = self.tr(
                'Impact layer %s was neither a raster or a vector layer') % (
                    qgis_impact_layer.source())
            # noinspection PyExceptionInherit
            raise ReadLayerError(message)

        # Add layers to QGIS
        layers_to_add = []
        if self.show_intermediate_layers:
            layers_to_add.append(self.analysis.aggregator.layer)
        layers_to_add.append(qgis_impact_layer)
        QgsMapLayerRegistry.instance().addMapLayers(layers_to_add)
        # make sure it is active in the legend - needed since QGIS 2.4
        self.iface.setActiveLayer(qgis_impact_layer)
        # then zoom to it
        if self.zoom_to_impact_flag:
            self.iface.zoomToActiveLayer()
        if self.hide_exposure_flag:
            exposure_layer = self.analysis.exposure_layer
            legend = self.iface.legendInterface()
            legend.setLayerVisible(exposure_layer, False)

        # append postprocessing report
        report.add(output.to_html())
        # Layer attribution comes last
        report.add(impact_attribution(keywords).to_html(True))
        # Return text to display in report panel
        return report
Example #8
0
    def show_results(self):
        """Helper function for slot activated when the process is done.

        .. versionchanged:: 3.4 - removed parameters.

        .. note:: If you update this function, please report your change to
            safe.gui.widgets.dock.show_results too.

        :returns: Provides a report for writing to the dock.
        :rtype: str
        """
        qgis_exposure = self.impact_function.exposure.qgis_layer()
        qgis_hazard = self.impact_function.hazard.qgis_layer()
        qgis_aggregation = self.impact_function.aggregation.qgis_layer()

        safe_impact_layer = self.impact_function.impact
        qgis_impact_layer = read_impact_layer(safe_impact_layer)

        keywords = self.keyword_io.read_keywords(qgis_impact_layer)
        json_path = os.path.splitext(qgis_impact_layer.source())[0] + '.json'

        # write postprocessing report to keyword
        postprocessor_data = self.impact_function.postprocessor_manager.\
            get_json_data(self.impact_function.aggregator.aoi_mode)
        post_processing_report = m.Message()
        if os.path.exists(json_path):
            with open(json_path) as json_file:
                impact_data = json.load(
                    json_file, object_pairs_hook=OrderedDict)
                impact_data['post processing'] = postprocessor_data
                with open(json_path, 'w') as json_file_2:
                    json.dump(impact_data, json_file_2, indent=2)
        else:
            post_processing_report = self.impact_function.\
                postprocessor_manager.get_output(
                    self.impact_function.aggregator.aoi_mode)
            keywords['postprocessing_report'] = post_processing_report.to_html(
                suppress_newlines=True)
            self.keyword_io.write_keywords(qgis_impact_layer, keywords)

        # Get tabular information from impact layer
        report = m.Message()
        report.add(LOGO_ELEMENT)
        report.add(m.Heading(self.tr('Analysis Results'), **INFO_STYLE))
        # If JSON Impact Data Exist, use JSON
        json_path = qgis_impact_layer.source()[:-3] + 'json'
        LOGGER.debug('JSON Path %s' % json_path)
        if os.path.exists(json_path):
            impact_template = get_report_template(json_file=json_path)
            impact_report = impact_template.generate_message_report()
            report.add(impact_report)
        else:
            report.add(self.keyword_io.read_keywords(
                qgis_impact_layer, 'impact_summary'))
            # append postprocessing report
            report.add(post_processing_report.to_html())

        # Layer attribution comes last
        report.add(impact_attribution(keywords).to_html(True))

        # Get requested style for impact layer of either kind
        style = safe_impact_layer.get_style_info()
        style_type = safe_impact_layer.get_style_type()

        # Determine styling for QGIS layer
        if safe_impact_layer.is_vector:
            if not style:
                # Set default style if possible
                pass
            elif style_type == 'categorizedSymbol':
                LOGGER.debug('use categorized')
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == 'graduatedSymbol':
                LOGGER.debug('use graduated')
                set_vector_graduated_style(qgis_impact_layer, style)

        elif safe_impact_layer.is_raster:
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
            else:
                setRasterStyle(qgis_impact_layer, style)

        else:
            message = self.tr(
                'Impact layer %s was neither a raster or a vector layer') % (
                    qgis_impact_layer.source())
            # noinspection PyExceptionInherit
            raise ReadLayerError(message)

        legend = self.iface.legendInterface()

        # Insert the aggregation output above the input aggregation layer
        if self.show_intermediate_layers:
            add_above_layer(
                self.impact_function.aggregator.layer,
                qgis_aggregation)
            legend.setLayerVisible(self.impact_function.aggregator.layer, True)

        if self.hide_exposure_flag:
            # Insert the impact always above the hazard
            add_above_layer(
                qgis_impact_layer,
                qgis_hazard)
        else:
            # Insert the impact above the hazard and the exposure if
            # we don't hide the exposure. See #2899
            add_above_layer(
                qgis_impact_layer,
                qgis_exposure,
                qgis_hazard)

        # In QGIS 2.14.2 and GDAL 1.11.3, if the exposure is in 3857,
        # the impact layer is in 54004, we need to change it. See issue #2790.
        if qgis_exposure.crs().authid() == 'EPSG:3857':
            if qgis_impact_layer.crs().authid() != 'EPSG:3857':
                epsg_3857 = QgsCoordinateReferenceSystem(3857)
                qgis_impact_layer.setCrs(epsg_3857)

        # make sure it is active in the legend - needed since QGIS 2.4
        self.iface.setActiveLayer(qgis_impact_layer)
        # then zoom to it
        if self.zoom_to_impact_flag:
            self.iface.zoomToActiveLayer()
        if self.hide_exposure_flag:
            exposure_layer = self.get_exposure_layer()
            legend.setLayerVisible(exposure_layer, False)

        # Make the layer visible. Might be hidden by default. See #2925
        legend.setLayerVisible(qgis_impact_layer, True)

        # Return text to display in report panel
        return report
Example #9
0
    def show_results(self, qgis_impact_layer, engine_impact_layer):
        """Helper function for slot activated when the process is done.

        .. note:: Adapted from the dock

        :param qgis_impact_layer: A QGIS layer representing the impact.
        :type qgis_impact_layer: QgsMapLayer, QgsVectorLayer, QgsRasterLayer

        :param engine_impact_layer: A safe_layer representing the impact.
        :type engine_impact_layer: ReadLayer

        :returns: Provides a report for writing to the dock.
        :rtype: str
        """
        keywords = self.keyword_io.read_keywords(qgis_impact_layer)

        # write postprocessing report to keyword
        output = self.analysis.postprocessor_manager.get_output(
            self.analysis.aggregator.aoi_mode)
        keywords['postprocessing_report'] = output.to_html(
            suppress_newlines=True)
        self.keyword_io.write_keywords(qgis_impact_layer, keywords)

        # Get tabular information from impact layer
        report = m.Message()
        report.add(LOGO_ELEMENT)
        report.add(m.Heading(self.tr('Analysis Results'), **INFO_STYLE))
        report.add(
            self.keyword_io.read_keywords(qgis_impact_layer, 'impact_summary'))

        # Get requested style for impact layer of either kind
        style = engine_impact_layer.get_style_info()
        style_type = engine_impact_layer.get_style_type()

        # Determine styling for QGIS layer
        if engine_impact_layer.is_vector:
            LOGGER.debug('myEngineImpactLayer.is_vector')
            if not style:
                # Set default style if possible
                pass
            elif style_type == 'categorizedSymbol':
                LOGGER.debug('use categorized')
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == 'graduatedSymbol':
                LOGGER.debug('use graduated')
                set_vector_graduated_style(qgis_impact_layer, style)

        elif engine_impact_layer.is_raster:
            LOGGER.debug('myEngineImpactLayer.is_raster')
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
                # qgis_impact_layer.setColorShadingAlgorithm(
                #    QgsRasterLayer.PseudoColorShader)
            else:
                setRasterStyle(qgis_impact_layer, style)

        else:
            message = self.tr(
                'Impact layer %s was neither a raster or a vector layer') % (
                    qgis_impact_layer.source())
            # noinspection PyExceptionInherit
            raise ReadLayerError(message)

        # Add layers to QGIS
        layers_to_add = []
        if self.show_intermediate_layers:
            layers_to_add.append(self.analysis.aggregator.layer)
        layers_to_add.append(qgis_impact_layer)
        QgsMapLayerRegistry.instance().addMapLayers(layers_to_add)
        # make sure it is active in the legend - needed since QGIS 2.4
        self.iface.setActiveLayer(qgis_impact_layer)
        # then zoom to it
        if self.zoom_to_impact_flag:
            self.iface.zoomToActiveLayer()
        if self.hide_exposure_flag:
            exposure_layer = self.parent.get_exposure_layer()
            legend = self.iface.legendInterface()
            legend.setLayerVisible(exposure_layer, False)

        # append postprocessing report
        report.add(output.to_html())
        # Layer attribution comes last
        report.add(impact_attribution(keywords).to_html(True))
        # Return text to display in report panel
        return report
Example #10
0
    def test_issue230(self):
        """Verify that we give informative errors when style is not correct
           .. seealso:: https://github.com/AIFDR/inasafe/issues/230
        """
        vector_layer = clone_shp_layer(
            name='polygons_for_styling',
            include_keywords=True,
            source_directory=test_data_path('impact'))

        style = {
            'legend_title':
            u'Population Count',
            'target_field':
            'population',
            'style_classes': [
                {
                    'transparency': 0,
                    'min': [0],  # <--intentionally broken list not number!
                    'max': 139904.08186340332,
                    'colour': '#FFFFFF',
                    'size': 1,
                    'label': u'Nil'
                },
                {
                    'transparency': 0,
                    'min': 139904.08186340332,
                    'max': 279808.16372680664,
                    'colour': '#38A800',
                    'size': 1,
                    'label': u'Low'
                },
                {
                    'transparency': 0,
                    'min': 279808.16372680664,
                    'max': 419712.24559020996,
                    'colour': '#79C900',
                    'size': 1,
                    'label': u'Low'
                },
                {
                    'transparency': 0,
                    'min': 419712.24559020996,
                    'max': 559616.32745361328,
                    'colour': '#CEED00',
                    'size': 1,
                    'label': u'Low'
                },
                {
                    'transparency': 0,
                    'min': 559616.32745361328,
                    'max': 699520.4093170166,
                    'colour': '#FFCC00',
                    'size': 1,
                    'label': u'Medium'
                },
                {
                    'transparency': 0,
                    'min': 699520.4093170166,
                    'max': 839424.49118041992,
                    'colour': '#FF6600',
                    'size': 1,
                    'label': u'Medium'
                },
                {
                    'transparency': 0,
                    'min': 839424.49118041992,
                    'max': 979328.57304382324,
                    'colour': '#FF0000',
                    'size': 1,
                    'label': u'Medium'
                },
                {
                    'transparency': 0,
                    'min': 979328.57304382324,
                    'max': 1119232.6549072266,
                    'colour': '#7A0000',
                    'size': 1,
                    'label': u'High'
                }
            ]
        }
        try:
            set_vector_graduated_style(vector_layer, style)
        except StyleError:
            # Exactly what should have happened
            return
        except Exception, e:  # pylint: disable=broad-except
            print str(e)
Example #11
0
    def set_style(self):
        # get requested style of impact

        qml_path = self.flood_fixtures_dir('impact-template.qml')
        target_style_path = os.path.join(self.report_path,
                                         'population_aggregate.qml')
        keyword_io = KeywordIO()
        qgis_exposure_layer = self.exposure_layer.as_qgis_native()
        attribute_field = keyword_io.read_keywords(qgis_exposure_layer,
                                                   'field')
        with open(qml_path) as f_template:
            str_template = f_template.read()

            # search max_population in an RW
            # use generator for memory efficiency
            maximum_population = max(
                f[attribute_field] for f in qgis_exposure_layer.getFeatures())
            range_increment = maximum_population / 5
            legend_expressions = {}
            for i in range(5):
                if i == 0:
                    marker_label = '&lt; %s' % format_int(range_increment)
                elif i < 4:
                    marker_label = '%s - %s' % (format_int(
                        range_increment *
                        i), format_int(range_increment * (i + 1)))
                else:
                    marker_label = '> %s' % format_int(range_increment * 4)
                marker_size = \
                    'scale_linear(' \
                    'attribute($currentfeature, &quot;%s&quot;) ' \
                    ', %d, %d, %d, %d)' % (
                        self.affect_field,
                        int(range_increment * i),
                        int(range_increment * (i + 1)),
                        i * 2,
                        (i + 1) * 2,
                    )
                marker_color = \
                    "set_color_part(" \
                    "set_color_part('0,0,255','saturation', %d ), 'alpha', " \
                    "if(attribute($currentfeature, '%s') = 0, " \
                    "0, 255))" % (i * 20, self.affect_field)
                marker_border = \
                    "set_color_part(" \
                    "'0,0,0','alpha', " \
                    "if (to_int(attribute(" \
                    "$currentfeature, '%s')) = 0, 0, 255))" % \
                    self.affect_field

                legend_expressions['marker-min-range-%d' % i] = \
                    '%s' % (range_increment * i)
                legend_expressions['marker-max-range-%d' % i] = \
                    '%s' % (range_increment * (i + 1))
                legend_expressions['marker-label-%d' % i] = marker_label
                legend_expressions['marker-size-%d' % i] = marker_size
                legend_expressions['marker-color-%d' % i] = marker_color
                legend_expressions['marker-border-%d' % i] = marker_border

            for k, v in legend_expressions.iteritems():
                str_template = str_template.replace('[%s]' % k, v)

            with open(target_style_path, mode='w') as target_f:
                target_f.write(str_template)

        # Get requested style for impact layer of either kind
        impact = self.impact_layer
        style = impact.get_style_info()
        style_type = impact.get_style_type()

        # Determine styling for QGIS layer
        qgis_impact_layer = impact.as_qgis_native()
        if impact.is_vector:
            LOGGER.debug('myEngineImpactLayer.is_vector')
            if not style:
                # Set default style if possible
                pass
            elif style_type == 'categorizedSymbol':
                LOGGER.debug('use categorized')
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == 'graduatedSymbol':
                LOGGER.debug('use graduated')
                set_vector_graduated_style(qgis_impact_layer, style)

        elif impact.is_raster:
            LOGGER.debug('myEngineImpactLayer.is_raster')
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
            else:
                setRasterStyle(qgis_impact_layer, style)
Example #12
0
    def test_issue230(self):
        """Verify that we give informative errors when style is not correct
           .. seealso:: https://github.com/AIFDR/inasafe/issues/230
        """
        vector_layer = clone_shp_layer(
            name='polygons_for_styling',
            include_keywords=True,
            source_directory=test_data_path('impact'))

        style = {
            'legend_title': u'Population Count',
            'target_field': 'population',
            'style_classes':
                [
                    {
                        'transparency': 0,
                        'min': [0],  # <--intentionally broken list not number!
                        'max': 139904.08186340332,
                        'colour': '#FFFFFF',
                        'size': 1,
                        'label': u'Nil'},
                    {
                        'transparency': 0,
                        'min': 139904.08186340332,
                        'max': 279808.16372680664,
                        'colour': '#38A800',
                        'size': 1,
                        'label': u'Low'},
                    {
                        'transparency': 0,
                        'min': 279808.16372680664,
                        'max': 419712.24559020996,
                        'colour': '#79C900',
                        'size': 1,
                        'label': u'Low'},
                    {
                        'transparency': 0,
                        'min': 419712.24559020996,
                        'max': 559616.32745361328,
                        'colour': '#CEED00',
                        'size': 1,
                        'label': u'Low'},
                    {
                        'transparency': 0,
                        'min': 559616.32745361328,
                        'max': 699520.4093170166,
                        'colour': '#FFCC00',
                        'size': 1,
                        'label': u'Medium'},
                    {
                        'transparency': 0,
                        'min': 699520.4093170166,
                        'max': 839424.49118041992,
                        'colour': '#FF6600',
                        'size': 1,
                        'label': u'Medium'},
                    {
                        'transparency': 0,
                        'min': 839424.49118041992,
                        'max': 979328.57304382324,
                        'colour': '#FF0000',
                        'size': 1,
                        'label': u'Medium'},
                    {
                        'transparency': 0,
                        'min': 979328.57304382324,
                        'max': 1119232.6549072266,
                        'colour': '#7A0000',
                        'size': 1,
                        'label': u'High'}]}
        try:
            set_vector_graduated_style(vector_layer, style)
        except StyleError:
            # Exactly what should have happened
            return
        except Exception, e:  # pylint: disable=broad-except
            print str(e)
Example #13
0
    def set_style(self):
        # get requested style of impact

        qml_path = self.flood_fixtures_dir(
            'impact-template.qml')
        target_style_path = os.path.join(
            self.report_path, 'population_aggregate.qml')
        keyword_io = KeywordIO()
        qgis_exposure_layer = self.exposure_layer.as_qgis_native()
        attribute_field = keyword_io.read_keywords(
            qgis_exposure_layer, 'field')
        with open(qml_path) as f_template:
            str_template = f_template.read()

            # search max_population in an RW
            # use generator for memory efficiency
            maximum_population = max(
                f[attribute_field] for f
                in qgis_exposure_layer.getFeatures()
            )
            range_increment = maximum_population / 5
            legend_expressions = {}
            for i in range(5):
                if i == 0:
                    marker_label = '&lt; %s' % format_int(range_increment)
                elif i < 4:
                    marker_label = '%s - %s' % (
                        format_int(range_increment * i),
                        format_int(range_increment * (i + 1))
                    )
                else:
                    marker_label = '> %s' % format_int(range_increment * 4)
                marker_size = \
                    'scale_linear(' \
                    'attribute($currentfeature, &quot;%s&quot;) ' \
                    ', %d, %d, %d, %d)' % (
                        self.affect_field,
                        int(range_increment * i),
                        int(range_increment * (i + 1)),
                        i * 2,
                        (i + 1) * 2,
                    )
                marker_color = \
                    "set_color_part(" \
                    "set_color_part('0,0,255','saturation', %d ), 'alpha', " \
                    "if(attribute($currentfeature, '%s') = 0, " \
                    "0, 255))" % (i * 20, self.affect_field)
                marker_border = \
                    "set_color_part(" \
                    "'0,0,0','alpha', " \
                    "if (to_int(attribute(" \
                    "$currentfeature, '%s')) = 0, 0, 255))" % \
                    self.affect_field

                legend_expressions['marker-min-range-%d' % i] = \
                    '%s' % (range_increment * i)
                legend_expressions['marker-max-range-%d' % i] = \
                    '%s' % (range_increment * (i + 1))
                legend_expressions['marker-label-%d' % i] = marker_label
                legend_expressions['marker-size-%d' % i] = marker_size
                legend_expressions['marker-color-%d' % i] = marker_color
                legend_expressions['marker-border-%d' % i] = marker_border

            for k, v in legend_expressions.iteritems():
                str_template = str_template.replace('[%s]' % k, v)

            with open(target_style_path, mode='w') as target_f:
                target_f.write(str_template)

        # Get requested style for impact layer of either kind
        impact = self.impact_layer
        style = impact.get_style_info()
        style_type = impact.get_style_type()

        # Determine styling for QGIS layer
        qgis_impact_layer = impact.as_qgis_native()
        if impact.is_vector:
            LOGGER.debug('myEngineImpactLayer.is_vector')
            if not style:
                # Set default style if possible
                pass
            elif style_type == 'categorizedSymbol':
                LOGGER.debug('use categorized')
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == 'graduatedSymbol':
                LOGGER.debug('use graduated')
                set_vector_graduated_style(qgis_impact_layer, style)

        elif impact.is_raster:
            LOGGER.debug('myEngineImpactLayer.is_raster')
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
            else:
                setRasterStyle(qgis_impact_layer, style)
Example #14
0
    def show_results(self):
        """Helper function for slot activated when the process is done.

        .. versionchanged:: 3.4 - removed parameters.

        .. note:: If you update this function, please report your change to
            safe.gui.widgets.dock.show_results too.

        :returns: Provides a report for writing to the dock.
        :rtype: str
        """
        qgis_exposure = self.impact_function.exposure.qgis_layer()
        qgis_hazard = self.impact_function.hazard.qgis_layer()
        qgis_aggregation = self.impact_function.aggregation.qgis_layer()

        safe_impact_layer = self.impact_function.impact
        qgis_impact_layer = read_impact_layer(safe_impact_layer)

        keywords = self.keyword_io.read_keywords(qgis_impact_layer)
        json_path = os.path.splitext(qgis_impact_layer.source())[0] + '.json'

        # write postprocessing report to keyword
        postprocessor_data = self.impact_function.postprocessor_manager.\
            get_json_data(self.impact_function.aggregator.aoi_mode)
        post_processing_report = m.Message()
        if os.path.exists(json_path):
            with open(json_path) as json_file:
                impact_data = json.load(json_file,
                                        object_pairs_hook=OrderedDict)
                impact_data['post processing'] = postprocessor_data
                write_json(impact_data, json_path)
        else:
            post_processing_report = self.impact_function.\
                postprocessor_manager.get_output(
                    self.impact_function.aggregator.aoi_mode)
            keywords['postprocessing_report'] = post_processing_report.to_html(
                suppress_newlines=True)
            self.keyword_io.write_keywords(qgis_impact_layer, keywords)

        # Get tabular information from impact layer
        report = m.Message()
        report.add(LOGO_ELEMENT)
        report.add(m.Heading(self.tr('Analysis Results'), **INFO_STYLE))
        # If JSON Impact Data Exist, use JSON
        json_path = qgis_impact_layer.source()[:-3] + 'json'
        LOGGER.debug('JSON Path %s' % json_path)
        if os.path.exists(json_path):
            impact_template = get_report_template(json_file=json_path)
            impact_report = impact_template.generate_message_report()
            report.add(impact_report)
        else:
            report.add(
                self.keyword_io.read_keywords(qgis_impact_layer,
                                              'impact_summary'))
            # append postprocessing report
            report.add(post_processing_report.to_html())

        # Layer attribution comes last
        report.add(impact_attribution(keywords).to_html(True))

        # Get requested style for impact layer of either kind
        style = safe_impact_layer.get_style_info()
        style_type = safe_impact_layer.get_style_type()

        # Determine styling for QGIS layer
        if safe_impact_layer.is_vector:
            if not style:
                # Set default style if possible
                pass
            elif style_type == 'categorizedSymbol':
                LOGGER.debug('use categorized')
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == 'graduatedSymbol':
                LOGGER.debug('use graduated')
                set_vector_graduated_style(qgis_impact_layer, style)

        elif safe_impact_layer.is_raster:
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
            else:
                setRasterStyle(qgis_impact_layer, style)

        else:
            message = self.tr(
                'Impact layer %s was neither a raster or a vector layer') % (
                    qgis_impact_layer.source())
            # noinspection PyExceptionInherit
            raise ReadLayerError(message)

        legend = self.iface.legendInterface()

        # Insert the aggregation output above the input aggregation layer
        if self.show_intermediate_layers:
            add_above_layer(self.impact_function.aggregator.layer,
                            qgis_aggregation)
            legend.setLayerVisible(self.impact_function.aggregator.layer, True)

        if self.hide_exposure_flag:
            # Insert the impact always above the hazard
            add_above_layer(qgis_impact_layer, qgis_hazard)
        else:
            # Insert the impact above the hazard and the exposure if
            # we don't hide the exposure. See #2899
            add_above_layer(qgis_impact_layer, qgis_exposure, qgis_hazard)

        # In QGIS 2.14.2 and GDAL 1.11.3, if the exposure is in 3857,
        # the impact layer is in 54004, we need to change it. See issue #2790.
        if qgis_exposure.crs().authid() == 'EPSG:3857':
            if qgis_impact_layer.crs().authid() != 'EPSG:3857':
                epsg_3857 = QgsCoordinateReferenceSystem(3857)
                qgis_impact_layer.setCrs(epsg_3857)

        # make sure it is active in the legend - needed since QGIS 2.4
        self.iface.setActiveLayer(qgis_impact_layer)
        # then zoom to it
        if self.zoom_to_impact_flag:
            self.iface.zoomToActiveLayer()
        if self.hide_exposure_flag:
            exposure_layer = self.get_exposure_layer()
            legend.setLayerVisible(exposure_layer, False)

        # Make the layer visible. Might be hidden by default. See #2925
        legend.setLayerVisible(qgis_impact_layer, True)

        # Return text to display in report panel
        return report