当前位置: 首页>>代码示例>>Python>>正文


Python KeywordIO.read_keywords方法代码示例

本文整理汇总了Python中safe_qgis.utilities.keyword_io.KeywordIO.read_keywords方法的典型用法代码示例。如果您正苦于以下问题:Python KeywordIO.read_keywords方法的具体用法?Python KeywordIO.read_keywords怎么用?Python KeywordIO.read_keywords使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在safe_qgis.utilities.keyword_io.KeywordIO的用法示例。


在下文中一共展示了KeywordIO.read_keywords方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: show_keywords_editor

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
    def show_keywords_editor(self):
        """Show the keywords editor."""
        # import here only so that it is AFTER i18n set up
        from safe_qgis.tools.keywords_dialog import KeywordsDialog

        # Next block is a fix for #776
        if self.iface.activeLayer() is None:
            return

        try:
            keyword_io = KeywordIO()
            keyword_io.read_keywords(self.iface.activeLayer())
        except UnsupportedProviderError:
            # noinspection PyUnresolvedReferences,PyCallByClass
            QMessageBox.warning(
                None,
                self.tr('Unsupported layer type'),
                self.tr(
                    'The layer you have selected cannot be used for '
                    'analysis because its data type is unsupported.'))
            return
        # End of fix for #776
        # Fix for #793
        except NoKeywordsFoundError:
            # we will create them from scratch in the dialog
            pass
        # End of fix for #793

        dialog = KeywordsDialog(
            self.iface.mainWindow(),
            self.iface,
            self.dock_widget)
        dialog.exec_()  # modal
开发者ID:borysiasty,项目名称:inasafe,代码行数:35,代码来源:plugin.py

示例2: test_printImpactTable

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
 def test_printImpactTable(self):
     """Test that we can render html from impact table keywords."""
     LOGGER.debug('InaSAFE HtmlRenderer testing printImpactTable')
     myFilename = 'test_floodimpact.tif'
     myLayer, _ = load_layer(myFilename)
     myMessage = 'Layer is not valid: %s' % myFilename
     assert myLayer.isValid(), myMessage
     myPageDpi = 300
     myHtmlRenderer = HtmlRenderer(myPageDpi)
     myPath = unique_filename(prefix='impactTable',
                              suffix='.pdf',
                              dir=temp_dir('test'))
     myKeywordIO = KeywordIO()
     myKeywords = myKeywordIO.read_keywords(myLayer)
     myPath = myHtmlRenderer.print_impact_table(myKeywords,
                                              filename=myPath)
     myMessage = 'Rendered output does not exist: %s' % myPath
     assert os.path.exists(myPath), myMessage
     # pdf rendering is non deterministic so we can't do a hash check
     # test_renderComposition renders just the image instead of pdf
     # so we hash check there and here we just do a basic minimum file
     # size check.
     mySize = os.stat(myPath).st_size
     myExpectedSizes = [20936,  # as rendered on linux ub 12.04 64
                        21523,  # as rendered on linux ub 12.10 64
                        20605,  # as rendered on linux ub 13.04 64
                        21527,  # as rendered on Jenkins post 22 June 2013
                        377191,  # as rendered on OSX
                        252699L,  # as rendered on Windows 7 64 bit
                        251782L,  # as rendered on Windows 8 64 bit amd
                        21491,  # as rendered on Slackware64 14.0
                        ]
     print 'Output pdf to %s' % myPath
     self.assertIn(mySize, myExpectedSizes)
开发者ID:vdeparday,项目名称:inasafe,代码行数:36,代码来源:test_html_renderer.py

示例3: show_keywords_editor

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
    def show_keywords_editor(self):
        """Show the keywords editor."""
        # import here only so that it is AFTER i18n set up
        from safe_qgis.tools.keywords_dialog import KeywordsDialog

        # Next block is a fix for #776
        if self.iface.activeLayer() is None:
            return

        try:
            keyword_io = KeywordIO()
            keyword_io.read_keywords(self.iface.activeLayer())
        except UnsupportedProviderError:
            # noinspection PyUnresolvedReferences,PyCallByClass
            # noinspection PyTypeChecker,PyArgumentList
            QMessageBox.warning(
                None,
                self.tr('Unsupported layer type'),
                self.tr(
                    'The layer you have selected cannot be used for '
                    'analysis because its data type is unsupported.'))
            return
        # End of fix for #776
        # Fix for #793
        except NoKeywordsFoundError:
            # we will create them from scratch in the dialog
            pass
        # End of fix for #793
        # Fix for filtered-layer
        except InvalidParameterError, e:
            # noinspection PyTypeChecker,PyTypeChecker
            QMessageBox.warning(
                None,
                self.tr('Invalid Layer'),
                e.message)
            return
开发者ID:essc,项目名称:inasafe,代码行数:38,代码来源:plugin.py

示例4: QgisWrapper

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
class QgisWrapper():
    """Wrapper class to add keywords functionality to Qgis layers
    """
    def __init__(self, layer, name=None):
        """Create the wrapper

        :param layer:       Qgis layer
        :type layer:        QgsMapLayer

        :param name:        A layer's name
        :type name:         Basestring or None
        """

        self.data = layer
        self.keyword_io = KeywordIO()
        self.keywords = self.keyword_io.read_keywords(layer)
        if name is None:
            try:
                self.name = self.get_keywords(key='title')
            except KeywordNotFoundError:
                pass

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name = name

    def get_keywords(self, key=None):
        """Return a copy of the keywords dictionary

        Args:
            * key (optional): If specified value will be returned for key only
        """
        if key is None:
            return self.keywords.copy()
        else:
            if key in self.keywords:
                return self.keywords[key]
            else:
                msg = ('Keyword %s does not exist in %s: Options are '
                       '%s' % (key, self.get_name(), self.keywords.keys()))
                raise KeywordNotFoundError(msg)

    def get_layer(self):
        return self.data
开发者ID:borysiasty,项目名称:inasafe,代码行数:48,代码来源:qgis_layer_wrapper.py

示例5: test_print_impact_table

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
 def test_print_impact_table(self):
     """Test that we can render html from impact table keywords."""
     LOGGER.debug('InaSAFE HtmlRenderer testing printImpactTable')
     file_name = 'test_floodimpact.tif'
     layer, _ = load_layer(file_name)
     message = 'Layer is not valid: %s' % file_name
     self.assertTrue(layer.isValid(), message)
     page_dpi = 300
     html_renderer = HtmlRenderer(page_dpi)
     path = unique_filename(
         prefix='impact_table',
         suffix='.pdf',
         dir=temp_dir('test'))
     keyword_io = KeywordIO()
     keywords = keyword_io.read_keywords(layer)
     path = html_renderer.print_impact_table(keywords, filename=path)
     message = 'Rendered output does not exist: %s' % path
     self.assertTrue(os.path.exists(path), message)
     # pdf rendering is non deterministic so we can't do a hash check
     # test_renderComposition renders just the image instead of pdf
     # so we hash check there and here we just do a basic minimum file
     # size check.
     size = os.stat(path).st_size
     expected_sizes = [
         20936,  # as rendered on linux ub 12.04 64
         21523,  # as rendered on linux ub 12.10 64
         20605,  # as rendered on linux ub 13.04 64
         13965,  # as rendered on linux ub 13.10 64
         14220,  # as rendered on linux ub 13.04 64 MB
         11085,  # as rendered on linux ub 14.04 64 AG
         17306,  # as rendered on linux ub 14.04_64 TS
         17127,  # as rendered on linux ub 14.04_64 MB
         17295,  # as rendered on linux ub 14.04_64 IS
         18665,  # as rendered on Jenkins per 19 June 2014
         377191,  # as rendered on OSX
         17556,  # as rendered on Windows 7_32
         16163L,  # as rendered on Windows 7 64 bit Ultimate i3
         251782L,  # as rendered on Windows 8 64 bit amd
         21491,  # as rendered on Slackware64 14.0
         18667,  # as rendered on Linux Mint 14_64
     ]
     print 'Output pdf to %s' % path
     self.assertIn(size, expected_sizes)
开发者ID:cccs-ip,项目名称:inasafe,代码行数:45,代码来源:test_html_renderer.py

示例6: PostprocessorManager

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]

#.........这里部分代码省略.........
        feature_names_attribute = self.aggregator.attributes[
            self.aggregator.defaults['AGGR_ATTR_KEY']]
        if feature_names_attribute is None:
            self.attribute_title = self.tr('Aggregation unit')
        else:
            self.attribute_title = feature_names_attribute

        name_filed_index = self.aggregator.layer.fieldNameIndex(
            self.attribute_title)
        sum_field_index = self.aggregator.layer.fieldNameIndex(
            self._sum_field_name())

        user_defined_female_ratio = False
        female_ratio_field_index = None
        female_ratio = None

        if 'Gender' in postprocessors:
            # look if we need to look for a variable female ratio in a layer
            try:
                female_ration_field = self.aggregator.attributes[
                    self.aggregator.defaults['FEM_RATIO_ATTR_KEY']]
                female_ratio_field_index = self.aggregator.layer.fieldNameIndex(
                    female_ration_field)

                # something went wrong finding the female ratio field,
                # use defaults from below except block
                if female_ratio_field_index == -1:
                    raise KeyError

                user_defined_female_ratio = True

            except KeyError:
                try:
                    female_ratio = self.keyword_io.read_keywords(
                        self.aggregator.layer,
                        self.aggregator.defaults['FEM_RATIO_KEY'])
                except KeywordNotFoundError:
                    female_ratio = self.aggregator.defaults['FEM_RATIO']

        # iterate zone features
        request = QgsFeatureRequest()
        request.setFlags(QgsFeatureRequest.NoGeometry)
        provider = self.aggregator.layer.dataProvider()
        # start data retrieval: fetch no geometry and all attributes for each
        # feature
        polygon_index = 0
        for feature in provider.getFeatures(request):
            # if a feature has no field called
            if name_filed_index == -1:
                zone_name = str(feature.id())
            else:
                zone_name = feature[name_filed_index]

            # create dictionary of attributes to pass to postprocessor
            general_params = {
                'target_field': self.aggregator.target_field,
                'function_params': self.functionParams}

            if self.aggregator.statistics_type == 'class_count':
                general_params['impact_classes'] = (
                    self.aggregator.statistics_classes)
            elif self.aggregator.statistics_type == 'sum':
                impact_total = feature[sum_field_index]
                general_params['impact_total'] = impact_total

            try:
开发者ID:vdeparday,项目名称:inasafe,代码行数:70,代码来源:postprocessor_manager.py

示例7: PostprocessorManager

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]

#.........这里部分代码省略.........
        myFeatureNameAttribute = self.aggregator.attributes[
            self.aggregator.defaults['AGGR_ATTR_KEY']]
        if myFeatureNameAttribute is None:
            self.attributeTitle = self.tr('Aggregation unit')
        else:
            self.attributeTitle = myFeatureNameAttribute

        myNameFieldIndex = self.aggregator.layer.fieldNameIndex(
            self.attributeTitle)
        mySumFieldIndex = self.aggregator.layer.fieldNameIndex(
            self._sumFieldName())

        myFemaleRatioIsVariable = False
        myFemRatioFieldIndex = None
        myFemaleRatio = None

        if 'Gender' in myPostProcessors:
            # look if we need to look for a variable female ratio in a layer
            try:
                myFemRatioField = self.aggregator.attributes[
                    self.aggregator.defaults['FEM_RATIO_ATTR_KEY']]
                myFemRatioFieldIndex = self.aggregator.layer.fieldNameIndex(
                    myFemRatioField)

                # something went wrong finding the female ratio field,
                # use defaults from below except block
                if myFemRatioFieldIndex == -1:
                    raise KeyError

                myFemaleRatioIsVariable = True

            except KeyError:
                try:
                    myFemaleRatio = self.keywordIO.read_keywords(
                        self.aggregator.layer,
                        self.aggregator.defaults['FEM_RATIO_KEY'])
                except KeywordNotFoundError:
                    myFemaleRatio = self.aggregator.defaults['FEM_RATIO']

        # iterate zone features
        myRequest = QgsFeatureRequest()
        myRequest.setFlags(QgsFeatureRequest.NoGeometry)
        myProvider = self.aggregator.layer.dataProvider()
        # start data retrieval: fetch no geometry and all attributes for each
        # feature
        myPolygonIndex = 0
        for myFeature in myProvider.getFeatures(myRequest):
            # if a feature has no field called
            if myNameFieldIndex == -1:
                myZoneName = str(myFeature.id())
            else:
                myZoneName = myFeature[myNameFieldIndex]

            # create dictionary of attributes to pass to postprocessor
            myGeneralParams = {'target_field': self.aggregator.targetField,
                               'function_params': self.functionParams}

            if self.aggregator.statisticsType == 'class_count':
                myGeneralParams['impact_classes'] = (
                    self.aggregator.statisticsClasses)
            elif self.aggregator.statisticsType == 'sum':
                myImpactTotal = myFeature[mySumFieldIndex]
                myGeneralParams['impact_total'] = myImpactTotal

            try:
                myGeneralParams['impact_attrs'] = (
开发者ID:danylaksono,项目名称:inasafe,代码行数:70,代码来源:postprocessor_manager.py

示例8: Aggregator

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
class Aggregator(QtCore.QObject):
    """The aggregator class facilitates aggregation of impact function results.
    """

    def __init__(
            self,
            iface,
            theAggregationLayer):
        """Director for aggregation based operations.
        Args:
          theAggregationLayer: QgsMapLayer representing clipped
              aggregation. This will be converted to a memory layer inside
              this class. see self.layer
        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        """

        QtCore.QObject.__init__(self)

        self.hazardLayer = None
        self.exposureLayer = None
        self.safeLayer = None

        self.prefix = 'aggr_'
        self.attributes = {}
        self.attributeTitle = None

        self.iface = iface
        self.keywordIO = KeywordIO()
        self.defaults = defaults()
        self.errorMessage = None
        self.targetField = None
        self.impactLayerAttributes = []
        self.aoiMode = True

        # If this flag is not True, no aggregation or postprocessing will run
        # this is set as True by validateKeywords()
        self.isValid = False
        self.showIntermediateLayers = False

        # This is used to hold an *in memory copy* of the aggregation layer
        # or None if the clip extents should be used.
        if theAggregationLayer is None:
            self.aoiMode = True
            # Will be completed in _prepareLayer just before deintersect call
            self.layer = self._createPolygonLayer()
        else:
            self.aoiMode = False
            self.layer = theAggregationLayer

    def validateKeywords(self):
        """Check if the postprocessing layer has all needed attribute keywords.

        This is only applicable in the case where were are not using the AOI
        (in other words self.aoiMode is False). When self.aoiMode is True
        then we always use just the defaults and dont allow the user to
        create custom aggregation field mappings.

        This method is called on instance creation and should always be
        called if you change any state of the aggregator class.

        On completion of this method the self.isValid flag is set. If this
        flag is not True, then no aggregation or postprocessing work will be
        carried out (these methods will raise an InvalidAggregatorError).

        Args:
            None

        Returns:
            None

        Raises:
            Errors are propogated
        """

        # Otherwise get the attributes for the aggregation layer.
        # noinspection PyBroadException
        try:
            myKeywords = self.keywordIO.read_keywords(self.layer)
        #discussed with Tim,in this case its ok to be generic
        except Exception:  # pylint: disable=W0703
            myKeywords = {}

        if self.aoiMode:
            myKeywords[self.defaults['FEM_RATIO_ATTR_KEY']] = self.tr(
                'Use default')
            self.keywordIO.update_keywords(self.layer, myKeywords)
            self.isValid = True
            return
        else:
            myMessage = m.Message(
                m.Heading(
                    self.tr('Select attribute'), **PROGRESS_UPDATE_STYLE),
                m.Paragraph(self.tr(
                    'Please select which attribute you want to use as ID for '
                    'the aggregated results')))
            self._sendMessage(myMessage)

#.........这里部分代码省略.........
开发者ID:gsuhartono,项目名称:inasafe,代码行数:103,代码来源:aggregator.py

示例9: Map

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]

#.........这里部分代码省略.........
        self.composition.setPrintAsRaster(True)

    def make_pdf(self, filename):
        """Generate the printout for our final map.

        :param filename: Path on the file system to which the pdf should be
            saved. If None, a generated file name will be used.
        :type filename: str

        :returns: File name of the output file (equivalent to filename if
                provided).
        :rtype: str
        """
        LOGGER.debug('InaSAFE Map printToPdf called')
        if filename is None:
            map_pdf_path = unique_filename(
                prefix='report', suffix='.pdf', dir=temp_dir())
        else:
            # We need to cast to python string in case we receive a QString
            map_pdf_path = str(filename)

        self.load_template()
        self.composition.exportAsPDF(map_pdf_path)
        return map_pdf_path

    def map_title(self):
        """Get the map title from the layer keywords if possible.

        :returns: None on error, otherwise the title.
        :rtype: None, str
        """
        LOGGER.debug('InaSAFE Map getMapTitle called')
        try:
            title = self.keyword_io.read_keywords(self.layer, 'map_title')
            return title
        except KeywordNotFoundError:
            return None
        except Exception:
            return None

    def map_legend_attributes(self):
        """Get the map legend attribute from the layer keywords if possible.

        :returns: None on error, otherwise the attributes (notes and units).
        :rtype: None, str
        """
        LOGGER.debug('InaSAFE Map getMapLegendAttributes called')
        legend_attribute_list = [
            'legend_notes',
            'legend_units',
            'legend_title']
        legend_attribute_dict = {}
        for myLegendAttribute in legend_attribute_list:
            # noinspection PyBroadException
            try:
                legend_attribute_dict[myLegendAttribute] = \
                    self.keyword_io.read_keywords(
                        self.layer, myLegendAttribute)
            except KeywordNotFoundError:
                pass
            except Exception:
                pass
        return legend_attribute_dict

    def load_template(self):
        """Load a QgsComposer map from a template.
开发者ID:borysiasty,项目名称:inasafe,代码行数:70,代码来源:map.py

示例10: AggregatorTest

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]

#.........这里部分代码省略.........
                   useNativeZonalStats=False):
        """Helper to calculate aggregation.

        Expected results is split into two lists - one list contains numeric
        attributes, the other strings. This is done so that we can use numpy
        .testing.assert_allclose which doesn't work on strings
        """

        myExpectedStringResults = []
        myExpectedNumericResults = []

        for item in myExpectedResults:
            myItemNumResults = []
            myItemStrResults = []
            for field in item:
                try:
                    value = float(field)
                    myItemNumResults.append(value)
                except ValueError:
                    myItemStrResults.append(str(field))

            myExpectedNumericResults.append(myItemNumResults)
            myExpectedStringResults.append(myItemStrResults)

        myAggregationLayer = QgsVectorLayer(
            os.path.join(BOUNDDATA, 'kabupaten_jakarta.shp'),
            'test aggregation',
            'ogr')
        # create a copy of aggregation layer
        myGeoExtent = extent_to_geo_array(
            myAggregationLayer.extent(),
            myAggregationLayer.crs())

        myAggrAttribute = self.keywordIO.read_keywords(
            myAggregationLayer, self.defaults['AGGR_ATTR_KEY'])
        # noinspection PyArgumentEqualDefault
        myAggregationLayer = clip_layer(
            layer=myAggregationLayer,
            extent=myGeoExtent,
            explode_flag=True,
            explode_attribute=myAggrAttribute)

        myAggregator = Aggregator(None, myAggregationLayer)
        # setting up
        myAggregator.isValid = True
        myAggregator.layer = myAggregationLayer
        myAggregator.safeLayer = safe_read_layer(
            str(myAggregator.layer.source()))
        myAggregator.aoiMode = False
        myAggregator.useNativeZonalStats = useNativeZonalStats
        myAggregator.aggregate(myImpactLayer)

        myProvider = myAggregator.layer.dataProvider()
        myNumericResults = []
        myStringResults = []

        for myFeature in myProvider.getFeatures():
            myFeatureNumResults = []
            myFeatureStrResults = []
            myAttrs = myFeature.attributes()
            for attr in myAttrs:
                if isinstance(attr, (int, float)):
                    myFeatureNumResults.append(attr)
                else:
                    myFeatureStrResults.append(attr)
开发者ID:CharlesRethman,项目名称:inasafe,代码行数:69,代码来源:test_aggregator.py

示例11: SaveScenarioDialog

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]
class SaveScenarioDialog(QDialog):
    """Tools for saving an active scenario on the dock."""

    def __init__(self, iface, dock):
        """Constructor for the class."""
        QDialog.__init__(self)
        # Class Member
        self.iface = iface
        self.dock = dock
        self.output_directory = None
        self.exposure_layer = None
        self.hazard_layer = None
        self.aggregation_layer = None
        self.function_id = None
        self.keyword_io = KeywordIO()

        # Calling some init methods
        self.restore_state()

    def restore_state(self):
        """ Read last state of GUI from configuration file."""
        settings = QSettings()
        try:
            last_save_directory = settings.value(
                'inasafe/lastSourceDir', '.', type=str)
        except TypeError:
            last_save_directory = ''
        self.output_directory = last_save_directory

    def save_state(self):
        """ Store current state of GUI to configuration file """
        settings = QSettings()
        settings.setValue('inasafe/lastSourceDir', self.output_directory)

    def validate_input(self):
        """Validate the input before saving a scenario.

        Those validations are:
        1. self.exposure_layer must be not None
        2. self.hazard_layer must be not None
        3. self.function_id is not an empty string or None
        """
        self.exposure_layer = self.dock.get_exposure_layer()
        self.hazard_layer = self.dock.get_hazard_layer()
        self.function_id = self.dock.get_function_id(
            self.dock.cboFunction.currentIndex())
        self.aggregation_layer = self.dock.get_aggregation_layer()

        is_valid = True
        warning_message = None
        if self.exposure_layer is None:
            warning_message = self.tr(
                'Exposure layer is not found, can not save scenario. Please '
                'add exposure layer to do so.')
            is_valid = False

        if self.hazard_layer is None:
            warning_message = self.tr(
                'Hazard layer is not found, can not save scenario. Please add '
                'hazard layer to do so.')
            is_valid = False

        if self.function_id == '' or self.function_id is None:
            warning_message = self.tr(
                'The impact function is empty, can not save scenario')
            is_valid = False

        return is_valid, warning_message

    def save_scenario(self, scenario_file_path=None):
        """Save current scenario to a text file.

        You can use the saved scenario with the batch runner.

        :param scenario_file_path: A path to the scenario file.
        :type scenario_file_path: str
        """
        # Validate Input
        warning_title = self.tr('InaSAFE Save Scenario Warning')
        is_valid, warning_message = self.validate_input()
        if not is_valid:
            # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
            QtGui.QMessageBox.warning(self, warning_title, warning_message)
            return

        # Make extent to look like:
        # 109.829170982, -8.13333290561, 111.005344795, -7.49226294379
        extent = viewport_geo_array(self.iface.mapCanvas())
        extent_string = ', '.join(('%f' % x) for x in extent)

        exposure_path = str(self.exposure_layer.publicSource())
        hazard_path = str(self.hazard_layer.publicSource())
        title = self.keyword_io.read_keywords(self.hazard_layer, 'title')
        title = safeTr(title)
        default_filename = title.replace(
            ' ', '_').replace('(', '').replace(')', '')

        # Popup a dialog to request the filename if scenario_file_path = None
        dialog_title = self.tr('Save Scenario')
        if scenario_file_path is None:
#.........这里部分代码省略.........
开发者ID:D2KG,项目名称:FLOOgin,代码行数:103,代码来源:save_scenario.py

示例12: Map

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]

#.........这里部分代码省略.........
        :rtype: QGraphicsSceneItem
        """
        LOGGER.debug('InaSAFE Map drawImage called')
        desired_width_mm = width_mm  # mm
        desired_width_px = mm_to_points(desired_width_mm, self.page_dpi)
        actual_width_px = image.width()
        scale_factor = desired_width_px / actual_width_px

        LOGGER.debug('%s %s %s' % (
            scale_factor, actual_width_px, desired_width_px))
        transform = QtGui.QTransform()
        transform.scale(scale_factor, scale_factor)
        transform.rotate(0.5)
        # noinspection PyArgumentList
        item = self.composition.addPixmap(QtGui.QPixmap.fromImage(image))
        item.setTransform(transform)
        item.setOffset(
            left_offset / scale_factor, top_offset / scale_factor)
        return item

    def draw_host_and_time(self, top_offset):
        """Add a note with hostname and time to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keyword_io.readKeywords(self.layer, 'user')
        #myHost = self.keyword_io.readKeywords(self.layer, 'host_name')
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        tokens = date_time.split('_')
        date = tokens[0]
        time = tokens[1]
        #myElapsedTime = self.keyword_io.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])
        label_text = self.tr(
            'Date and time of assessment: %s %s\n'
            'Special note: This assessment is a guide - we strongly recommend '
            'that you ground truth the results shown here before deploying '
            'resources and / or personnel.\n'
            'Assessment carried out using InaSAFE release %s (QGIS '
            'plugin version).') % (date, time, version)
        font_size = 6
        font_weight = QtGui.QFont.Normal
        italics_flag = True
        font = QtGui.QFont(
            'verdana',
            font_size,
            font_weight,
            italics_flag)
        label = QgsComposerLabel(self.composition)
        label.setFont(font)
        label.setText(label_text)
        label.adjustSizeToText()
        label_height = 50.0  # mm determined using qgis map composer
        label_width = (self.page_width / 2) - self.page_margin
        left_offset = self.page_width / 2  # put in right half of page
        label.setItemPosition(
开发者ID:vdeparday,项目名称:inasafe,代码行数:70,代码来源:map.py

示例13: test_keywords_creation_wizard

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]

#.........这里部分代码省略.........
                   '%s') % (expected_subcategories, subcategories)
        self.assertEqual(
            set(subcategories), set(expected_subcategories), message)
        # The Next button should be on disabled state first
        self.assertTrue(
            not dialog.pbnNext.isEnabled(), 'Invalid Next button'
            ' state in step 2! Enabled while there\'s nothing selected yet')
        # Set to tsunami subcategories
        dialog.lstSubcategories.setCurrentRow(tsunami_index)
        message = ('Invalid Next button state in step 2! Still disabled after '
                   'an item selected')
        self.assertTrue(dialog.pbnNext.isEnabled(), message)
        # Click next button
        dialog.pbnNext.click()

        # step 3 of 7 - select tsunami units
        # Check if the number of unit for tsunami is 3
        count = dialog.lstUnits.count()
        message = ('Invalid unit count! There should be %d while there were: '
                   '%d') % (expected_unit_count, count)
        self.assertEqual(count, expected_unit_count, message)
        # Get all the units given and save the 'feet_depth' index
        units = []
        feet_unit_index = -1
        for i in range(expected_unit_count):
            unit_name = eval(
                dialog.lstUnits.item(i).data(Qt.UserRole))['id']
            units.append(unit_name)
            if unit_name == expected_chosen_unit:
                feet_unit_index = i
        # Check if units is the same with expected_units
        message = ('Invalid units! It should be "%s" while it was '
                   '%s') % (expected_units, units)
        self.assertEqual(
            set(expected_units), set(units), message)
        # The button should be on disabled state first
        message = ('Invalid Next button state in step 3! Enabled while '
                   'there\'s nothing selected yet')
        self.assertTrue(
            not dialog.pbnNext.isEnabled(), message)
        dialog.lstUnits.setCurrentRow(feet_unit_index)
        message = ('Invalid Next button state in step 3! Enabled while '
                   'there\'s nothing selected yet')
        self.assertTrue(
            dialog.pbnNext.isEnabled(), message)

        dialog.pbnNext.click()

        # step 4 of 7 - select data field for tsunami feet
        count = dialog.lstFields.count()
        message = ('Invalid field count! There should be %d while there were: '
                   '%d') % (expected_field_count, count)
        self.assertEqual(count, expected_field_count, message)
        # Get all the fields given and save the 'GRIDCODE' index
        fields = []
        gridcode_index = -1
        for i in range(expected_field_count):
            field_name = dialog.lstFields.item(i).text()
            fields.append(field_name)
            if field_name == expected_chosen_field:
                gridcode_index = i
        # Check if fields is the same with expected_fields
        message = ('Invalid fields! It should be "%s" while it was '
                   '%s') % (expected_fields, fields)
        self.assertEqual(
            set(expected_fields), set(fields), message)
        # The button should be on disabled first
        message = ('Invalid Next button state in step 4! Enabled while '
                   'there\'s nothing selected yet')
        self.assertTrue(not dialog.pbnNext.isEnabled(), message)
        dialog.lstFields.setCurrentRow(gridcode_index)
        message = ('Invalid Next button state in step 4! Still disabled after '
                   'an item selected')
        self.assertTrue(dialog.pbnNext.isEnabled(), message)
        # Click next
        dialog.pbnNext.click()

        # step 6 of 7 - enter source
        message = ('Invalid Next button state in step 6! Disabled while '
                   'source is optional')
        self.assertTrue(dialog.pbnNext.isEnabled(), message)
        dialog.leSource.setText('some source')
        dialog.pbnNext.click()

        # step 7 of 7 - enter title
        dialog.leTitle.setText('some title')
        message = ('Invalid Next button state in step 7! Still disabled '
                   'after a text entered')
        self.assertTrue(dialog.pbnNext.isEnabled(), message)
        dialog.pbnNext.click()

        # test the resulting keywords
        keyword_io = KeywordIO()
        # noinspection PyTypeChecker
        keywords = keyword_io.read_keywords(layer)

        message = 'Invalid metadata!\n Was: %s\n Should be: %s' % (
            unicode(keywords), unicode(expected_keywords))

        self.assertEqual(keywords, expected_keywords, message)
开发者ID:SamudraYe,项目名称:inasafe,代码行数:104,代码来源:test_wizard_dialog.py

示例14: KeywordIOTest

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]

#.........这里部分代码省略.........
        self.keywordIO.write_keywords_for_uri(PG_URI, myExpectedKeywords)
        # Test getting all keywords
        myKeywords = self.keywordIO.readKeywordFromUri(PG_URI)
        myMessage = 'Got: %s\n\nExpected %s\n\nDB: %s' % (
                    myKeywords, myExpectedKeywords, myFilename)
        assert myKeywords == myExpectedKeywords, myMessage
        # Test getting just a single keyword
        myKeyword = self.keywordIO.readKeywordFromUri(PG_URI, 'datatype')
        myExpectedKeyword = 'OSM'
        myMessage = 'Got: %s\n\nExpected %s\n\nDB: %s' % (
                    myKeyword, myExpectedKeyword, myFilename)
        assert myKeyword == myExpectedKeyword, myMessage
        # Test deleting keywords actually does delete
        self.keywordIO.delete_keywords_for_uri(PG_URI)
        try:
            myKeyword = self.keywordIO.readKeywordFromUri(PG_URI, 'datatype')
            #if the above didnt cause an exception then bad
            myMessage = 'Expected a HashNotFoundError to be raised'
            assert myMessage
        except HashNotFoundError:
            #we expect this outcome so good!
            pass

    def test_areKeywordsFileBased(self):
        """Can we correctly determine if keywords should be written to file or
        to database?"""
        assert not self.keywordIO.are_keywords_file_based(self.sqliteLayer)
        assert self.keywordIO.are_keywords_file_based(self.fileRasterLayer)
        assert self.keywordIO.are_keywords_file_based(self.fileVectorLayer)

    def test_readRasterFileKeywords(self):
        """Can we read raster file keywords using generic readKeywords method
        """
        myKeywords = self.keywordIO.read_keywords(self.fileRasterLayer)
        myExpectedKeywords = self.expectedRasterKeywords
        mySource = self.fileRasterLayer.source()
        myMessage = 'Got:\n%s\nExpected:\n%s\nSource:\n%s' % (
                    myKeywords, myExpectedKeywords, mySource)
        assert myKeywords == myExpectedKeywords, myMessage

    def test_readVectorFileKeywords(self):
        """Test read vector file keywords with the generic readKeywords method.
         """
        myKeywords = self.keywordIO.read_keywords(self.fileVectorLayer)
        myExpectedKeywords = self.expectedVectorKeywords
        mySource = self.fileVectorLayer.source()
        myMessage = 'Got: %s\n\nExpected %s\n\nSource: %s' % (
                    myKeywords, myExpectedKeywords, mySource)
        assert myKeywords == myExpectedKeywords, myMessage

    def test_appendKeywords(self):
        """Can we append file keywords with the generic readKeywords method."""
        myLayer, _ = makePadangLayerClone()
        myNewKeywords = {'category': 'exposure', 'test': 'TEST'}
        self.keywordIO.update_keywords(myLayer, myNewKeywords)
        myKeywords = self.keywordIO.read_keywords(myLayer)

        for myKey, myValue in myNewKeywords.iteritems():
            myMessage = (
                'Layer keywords misses appended key: %s\n'
                'Layer keywords:\n%s\n'
                'Appended keywords:\n%s\n' %
                (myKey,
                myKeywords,
                myNewKeywords))
            assert myKey in myKeywords, myMessage
开发者ID:gsuhartono,项目名称:inasafe,代码行数:70,代码来源:test_keyword_io.py

示例15: Map

# 需要导入模块: from safe_qgis.utilities.keyword_io import KeywordIO [as 别名]
# 或者: from safe_qgis.utilities.keyword_io.KeywordIO import read_keywords [as 别名]

#.........这里部分代码省略.........
            saved. If None, a generated file name will be used.
        :type filename: str

        :returns: File name of the output file (equivalent to filename if
                provided).
        :rtype: str
        """
        LOGGER.debug('InaSAFE Map printToPdf called')
        if filename is None:
            map_pdf_path = unique_filename(
                prefix='report', suffix='.pdf', dir=temp_dir())
        else:
            # We need to cast to python string in case we receive a QString
            map_pdf_path = str(filename)

        self.load_template()

        resolution = self.composition.printResolution()
        self.printer = setup_printer(map_pdf_path, resolution=resolution)
        _, image, rectangle = self.render()
        painter = QtGui.QPainter(self.printer)
        painter.drawImage(rectangle, image, rectangle)
        painter.end()
        return map_pdf_path

    def map_title(self):
        """Get the map title from the layer keywords if possible.

        :returns: None on error, otherwise the title.
        :rtype: None, str
        """
        LOGGER.debug('InaSAFE Map getMapTitle called')
        try:
            title = self.keyword_io.read_keywords(self.layer, 'map_title')
            return title
        except KeywordNotFoundError:
            return None
        except Exception:
            return None

    def map_legend_attributes(self):
        """Get the map legend attribute from the layer keywords if possible.

        :returns: None on error, otherwise the attributes (notes and units).
        :rtype: None, str
        """
        LOGGER.debug('InaSAFE Map getMapLegendAtributes called')
        legend_attribute_list = [
            'legend_notes',
            'legend_units',
            'legend_title']
        legend_attribute_dict = {}
        for myLegendAttribute in legend_attribute_list:
            try:
                legend_attribute_dict[myLegendAttribute] = \
                    self.keyword_io.read_keywords(
                        self.layer, myLegendAttribute)
            except KeywordNotFoundError:
                pass
            except Exception:
                pass
        return legend_attribute_dict

    def load_template(self):
        """Load a QgsComposer map from a template.
        """
开发者ID:opengeogroep,项目名称:inasafe,代码行数:70,代码来源:map.py


注:本文中的safe_qgis.utilities.keyword_io.KeywordIO.read_keywords方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。