• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python core.QgsField类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中qgis.core.QgsField的典型用法代码示例。如果您正苦于以下问题:Python QgsField类的具体用法?Python QgsField怎么用?Python QgsField使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: copy_fields

def copy_fields(layer, fields_to_copy):
    """Copy fields inside an attribute table.

    :param layer: The vector layer.
    :type layer: QgsVectorLayer

    :param fields_to_copy: Dictionary of fields to copy.
    :type fields_to_copy: dict
    """
    for field in fields_to_copy:

        index = layer.fields().lookupField(field)
        if index != -1:

            layer.startEditing()

            source_field = layer.fields().at(index)
            new_field = QgsField(source_field)
            new_field.setName(fields_to_copy[field])

            layer.addAttribute(new_field)

            new_index = layer.fields().lookupField(fields_to_copy[field])

            for feature in layer.getFeatures():
                attributes = feature.attributes()
                source_value = attributes[index]
                layer.changeAttributeValue(
                    feature.id(), new_index, source_value)

            layer.commitChanges()
            layer.updateFields()  # Avoid crash #4729
开发者ID:inasafe,项目名称:inasafe,代码行数:32,代码来源:tools.py


示例2: addField

 def addField(name):
     """
     Adds a field to the output, keeping the same data type as the value_field
     """
     field = QgsField(value_field)
     field.setName(name)
     fields.append(field)
开发者ID:m-kuhn,项目名称:QGIS,代码行数:7,代码来源:StatisticsByCategories.py


示例3: addFieldKeepType

 def addFieldKeepType(original, stat):
     """
     Adds a field to the output, keeping the same data type as the original
     """
     field = QgsField(original)
     field.setName(field.name() + '_' + stat)
     fields_to_join.append(field)
开发者ID:Cracert,项目名称:Quantum-GIS,代码行数:7,代码来源:SpatialJoinSummary.py


示例4: addField

 def addField(original, stat, type):
     """
     Adds a field to the output, with a specified type
     """
     field = QgsField(original)
     field.setName(field.name() + '_' + stat)
     field.setType(type)
     if type == QVariant.Double:
         field.setLength(20)
         field.setPrecision(6)
     fields_to_join.append(field)
开发者ID:Cracert,项目名称:Quantum-GIS,代码行数:11,代码来源:SpatialJoinSummary.py


示例5: test04_EditShapefile1

  def test04_EditShapefile1(self):
    """Load a file, edit and overwrite. edits: add a field, set values to the field, and then remove the field"""
    self._testAvailable() or self.skipTest("Not available")
    fieldName = u'\u6587\u5b57\u52172'
    c0 = ord(u'\u30a2')

    infile = self.testDataPath(self.layerName)
    for ignore in [True, False]:
      setSettingValue("/qgis/ignoreShapeEncoding", ignore)

      # copy a set of shapefile
      layerName = u"{}_edit{}".format(self.layerName, 1 if ignore else 2)
      workfile = self.testDataPath(layerName, output=True)
      copyFileSet(infile, workfile, [".shp", ".shx", ".dbf", ".prj", ".cpg"])

      # load the copy
      layer = self._testLayer(workfile + ".shp", output=True)

      # add a field
      layer.startEditing()
      f = QgsField(fieldName, QVariant.String, len=20)
      assert layer.addAttribute(f), "failed to add a field"
      fldIdx = layer.fieldNameIndex(fieldName)

      # set strings with Japanese characters to the field
      c = c0
      for f in layer.getFeatures():
        val = "".join([unichr(c + i) for i in range(5)])
        assert layer.changeAttributeValue(f.id(), fldIdx, val), "failed to change attribute value"
        c += 5

      # save and reload the shapefile
      assert layer.commitChanges(), "failed to commit changes"
      del layer
      layer = self._testLayer(workfile + ".shp", output=True)

      # check the values of the field
      c = c0
      for f in layer.getFeatures():
        val = "".join([unichr(c + i) for i in range(5)])
        self.assertEqual(f.attribute(fieldName), val)
        c += 5

      # remove the added field
      layer.startEditing()
      layer.deleteAttribute(fldIdx)
      assert layer.commitChanges(), "failed to commit changes"

      # compare the file set with source
      c = compareFileSet(infile, workfile, [".shp", ".shx", ".dbf", ".prj", ".cpg"])
      self.assertEqual(c, [], "input and output do not match: {}".format(str(c)))

      print 'with "ignore..." option = {}...success'.format(ignore)
开发者ID:minorua,项目名称:QGISTesterA,代码行数:53,代码来源:test_02_vector.py


示例6: getFields

 def getFields():
   atts = [
     { 'name': 'id_add', 'type': QVariant.Int },
     { 'name': 'total_imgs', 'type':QVariant.Int },
     { 'name': 'images', 'type': QVariant.String, 'len': 254 },
     { 'name': 'user', 'type': QVariant.String, 'len': 20 },
     { 'name': 'date_add', 'type': QVariant.String, 'len': 20 },
     { 'name': 'crs_map', 'type': QVariant.String, 'len': 50 },
     { 'name': 'extent_map', 'type': QVariant.String, 'len': 200 },
     { 'name': 'annotation', 'type': QVariant.String, 'len': 100 }
   ]
   fields = QgsFields()
   for att in atts:
     f = QgsField( att['name'], att['type'] )
     if 'len' in att:
       f.setLength( att['len'])
     fields.append( f )
   return fields
开发者ID:lmotta,项目名称:gimpselectionfeature_plugin,代码行数:18,代码来源:gimpselectionfeature.py


示例7: combineVectorFields

def combineVectorFields(layerA, layerB):
    """Create single field map from two input field maps.
    """
    fields = []
    fieldsA = layerA.pendingFields()
    fields.extend(fieldsA)
    namesA = [unicode(f.name()).lower() for f in fieldsA]
    fieldsB = layerB.pendingFields()
    for field in fieldsB:
        name = unicode(field.name()).lower()
        if name in namesA:
            idx = 2
            newName = name + '_' + unicode(idx)
            while newName in namesA:
                idx += 1
                newName = name + '_' + unicode(idx)
            field = QgsField(newName, field.type(), field.typeName())
        fields.append(field)

    return fields
开发者ID:a11656358,项目名称:QGIS,代码行数:20,代码来源:vector.py


示例8: combineFields

def combineFields(fieldsA, fieldsB):
    """Create single field map from two input field maps.
    """
    fields = []
    fields.extend(fieldsA)
    namesA = [str(f.name()).lower() for f in fieldsA]
    for field in fieldsB:
        name = str(field.name()).lower()
        if name in namesA:
            idx = 2
            newName = name + '_' + str(idx)
            while newName in namesA:
                idx += 1
                newName = name + '_' + str(idx)
            field = QgsField(newName, field.type(), field.typeName())
        fields.append(field)

    real_fields = QgsFields()
    for f in fields:
        real_fields.append(f)
    return real_fields
开发者ID:exlimit,项目名称:QGIS,代码行数:21,代码来源:vector.py


示例9: testFieldTooltip

 def testFieldTooltip(self):
     f = QgsField('my_string', QVariant.String, 'string')
     self.assertEqual(QgsFieldModel.fieldToolTip(f), '<b>my_string</b><p>string</p>')
     f.setAlias('my alias')
     self.assertEqual(QgsFieldModel.fieldToolTip(f), '<b>my alias</b> (my_string)<p>string</p>')
     f.setLength(20)
     self.assertEqual(QgsFieldModel.fieldToolTip(f), '<b>my alias</b> (my_string)<p>string (20)</p>')
     f = QgsField('my_real', QVariant.Double, 'real', 8, 3)
     self.assertEqual(QgsFieldModel.fieldToolTip(f), '<b>my_real</b><p>real (8, 3)</p>')
开发者ID:jonnyforestGIS,项目名称:QGIS,代码行数:9,代码来源:test_qgsfieldmodel.py


示例10: createQgsField

 def createQgsField(self):
     qgsField = None
     if self.type.attributeType == GeoCsvAttributeType.integer:
         qgsField = QgsField(self.name, QVariant.Int)
     elif self.type.attributeType == GeoCsvAttributeType.easting or self.type.attributeType == GeoCsvAttributeType.northing or self.type.attributeType == GeoCsvAttributeType.real:
         qgsField = QgsField(self.name, QVariant.Double)
     else:
         qgsField = QgsField(self.name, QVariant.String)
     if not self.type.length == 0:
         qgsField.setLength(self.type.length)
     if not self.type.precision == 0:
         qgsField.setPrecision(self.type.precision) 
     return qgsField     
开发者ID:geometalab,项目名称:Editable-GeoCSV-QGIS-Plugin,代码行数:13,代码来源:geocsv_model.py


示例11: test_find_attribute_id

 def test_find_attribute_id(self):
     field_names = ['first', 'second']
     field_one = QgsField(field_names[0], QVariant.String)
     field_one.setTypeName(STRING_FIELD_TYPE_NAME)
     field_two = QgsField(field_names[1], QVariant.Int)
     field_two.setTypeName(INT_FIELD_TYPE_NAME)
     attributes = [field_one, field_two]
     ProcessLayer(self.layer).add_attributes(attributes)
     added_field_names = [field.name() for field in self.dp.fields()]
     # Double-check that add_attributes is working properly
     assert added_field_names == field_names
     # Check that both attributes are correctly found
     for attr_name in field_names:
         try:
             ProcessLayer(self.layer).find_attribute_id(attr_name)
         except AttributeError:
             print "We would expect both attributes to be found!"
             raise
     # Check that an inexistent field doesn't get found and that the
     # AttributeError exception is correctly raised
     with self.assertRaises(AttributeError):
         ProcessLayer(self.layer).add_attributes('dummy')
开发者ID:preinh,项目名称:qt-experiments,代码行数:22,代码来源:test_process_layer.py


示例12: calculate_iri

def calculate_iri(
    iface, current_layer, project_definition, svi_attr_id, aal_field_name, discarded_feats_ids, iri_operator=None
):
    """
    Copy the AAL and calculate an IRI attribute to the current layer
    """

    # set default
    if iri_operator is None:
        iri_operator = DEFAULT_COMBINATION

    aal_weight = project_definition["children"][0]["weight"]
    svi_weight = project_definition["children"][1]["weight"]

    iri_attr_name = "IRI"
    iri_field = QgsField(iri_attr_name, QVariant.Double)
    iri_field.setTypeName(DOUBLE_FIELD_TYPE_NAME)

    attr_names = ProcessLayer(current_layer).add_attributes([iri_field])

    # get the id of the new attributes
    iri_attr_id = ProcessLayer(current_layer).find_attribute_id(attr_names[iri_attr_name])

    discarded_aal_feats_ids = []

    try:
        with LayerEditingManager(current_layer, "Add IRI", DEBUG):
            for feat in current_layer.getFeatures():
                feat_id = feat.id()
                svi_value = feat.attributes()[svi_attr_id]
                aal_value = feat[aal_field_name]
                if aal_value == QPyNullVariant(float) or feat_id in discarded_feats_ids:
                    iri_value = QPyNullVariant(float)
                    discarded_aal_feats_ids.append(feat_id)
                elif iri_operator == "Sum (simple)":
                    iri_value = svi_value + aal_value
                elif iri_operator == "Multiplication (simple)":
                    iri_value = svi_value * aal_value
                elif iri_operator == "Sum (weighted)":
                    iri_value = svi_value * svi_weight + aal_value * aal_weight
                elif iri_operator == "Multiplication (weighted)":
                    iri_value = svi_value * svi_weight * aal_value * aal_weight
                elif iri_operator == "Average (equal weights)":
                    # For "Average (equal weights)" it's equivalent to use
                    # equal weights, or to sum the indices (all weights 1)
                    # and divide by the number of indices (we use
                    # the latter solution)
                    iri_value = (svi_value + aal_value) / 2.0
                # store IRI
                current_layer.changeAttributeValue(feat_id, iri_attr_id, iri_value)
        project_definition["iri_operator"] = iri_operator
        # set the field name for the copied AAL layer
        project_definition["aal_field"] = aal_field_name
        project_definition["iri_field"] = attr_names[iri_attr_name]
        msg = (
            "The IRI has been calculated for fields containing "
            "non-NULL values and it was added to the layer as "
            "a new attribute called %s"
        ) % attr_names[iri_attr_name]
        iface.messageBar().pushMessage(tr("Info"), tr(msg), level=QgsMessageBar.INFO)
        widget = toggle_select_features_widget(
            tr("Warning"),
            tr("Invalid values were found in some features while calculating " "IRI"),
            tr("Select invalid features"),
            current_layer,
            discarded_aal_feats_ids,
            current_layer.selectedFeaturesIds(),
        )
        iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING)
        return iri_attr_id

    except TypeError as e:
        current_layer.dataProvider().deleteAttributes([iri_attr_id])
        msg = "Could not calculate IRI due to data problems: %s" % e

        iface.messageBar().pushMessage(tr("Error"), tr(msg), level=QgsMessageBar.CRITICAL)
开发者ID:preinh,项目名称:qt-experiments,代码行数:76,代码来源:calculate_utils.py


示例13: saveAutoField

    def saveAutoField( self ):
        """ Do some validation and then call AutoFieldManager """

        # Check layers
        if not self.tblLayers.selectedItems():
            self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
                "[Warning] Please first select a layer." ), 'warning' )
            return

        # Check expression
        expression = u''
        if self.optXCoord.isChecked():
            expression = u'$x'
        elif self.optYCoord.isChecked():
            expression = u'$y'
        elif self.optLength.isChecked():
            expression = u'$length'
        elif self.optPerimeter.isChecked():
            expression = u'$perimeter'
        elif self.optArea.isChecked():
            expression = u'$area'
        elif self.optDate.isChecked():
            expression = u'now()'
        elif self.optCustomExpression.isChecked():
            if self.expressionDlg:
                expression = self.expressionDlg.expression
            if not self.expressionDlg or not expression:
                self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
                    "[Warning] Please first set a valid custom expression." ),
                    'warning' )
                return
        else: # optSpatialValue
            pass

        # Check fields
        fieldName = ''
        if self.optNewField.isChecked():
            if self.txtFieldName.text():

                fieldName = self.txtFieldName.text().strip()
                newField = QgsField( fieldName,
                    self.cboFieldType.itemData( self.cboFieldType.currentIndex(), Qt.UserRole) )

                length = self.txtFieldLength.value()
                precision = self.txtFieldPrecision.value()
                # Ensure length and precision are valid values when dealing with Real numbers
                if self.fieldTypesDict[self.cboFieldType.currentIndex()] == 'Real':
                    if precision > length:
                        precision = length
                newField.setLength( length )
                newField.setPrecision( precision )

                for item in self.tblLayers.selectedItems():
                    if item.column() == 1: # It's the layer name item
                        layer = QgsMapLayerRegistry.instance().mapLayer( item.data( Qt.UserRole ) )
                        if layer.fieldNameIndex( fieldName ) != -1:
                            self.msg.show(
                                QApplication.translate( "AutoFieldsDockWidgetPy",
                                    "[Error] The field " ) + fieldName + \
                                QApplication.translate( "AutoFieldsDockWidgetPy",
                                    " already exists in layer " ) + layer.name() + ". " + \
                                QApplication.translate( "AutoFieldsDockWidgetPy",
                                    " If you want to create an AutoField on it, you need to choose it from 'Existing Field' list." ),
                                'warning' )
                        else:
                            res = layer.dataProvider().addAttributes( [ newField ] )
                            if res:
                                layer.updateFields()

                                # Check if fieldName is preserved by the provider after field creation.
                                if layer.fieldNameIndex( fieldName ) == -1:
                                    self.msg.show(
                                        QApplication.translate( "AutoFieldsDockWidgetPy",
                                            "[Error] The field " ) + fieldName + \
                                        QApplication.translate( "AutoFieldsDockWidgetPy",
                                            " was probably created with another name by the layer (" ) + \
                                        layer.name() + \
                                        QApplication.translate( "AutoFieldsDockWidgetPy",
                                            ") provider. " ) + \
                                        QApplication.translate( "AutoFieldsDockWidgetPy",
                                            " If you want to create an AutoField on it, you need to choose it from 'Existing Field' list." ),
                                        'warning' )
                                else:

                                    self.doSaveAutoField( layer, fieldName, expression )

                            else:
                                self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
                                    "[Error] Couldn't create " ) + newField.name() + \
                                    QApplication.translate( "AutoFieldsDockWidgetPy",
                                        " field in " ) + layer.name() + \
                                    QApplication.translate( "AutoFieldsDockWidgetPy", " layer." ),
                                    'warning' )

                # Some fields might have been created, update the field list once
                self.updateFieldList()

            else:
                self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
                    "[Warning] Please first set a name for the new field." ), 'warning' )
#.........这里部分代码省略.........
开发者ID:gacarrillor,项目名称:AutoFields,代码行数:101,代码来源:AutoFieldsDockWidget.py


示例14: testQgsFieldRepr

 def testQgsFieldRepr(self):
     f = QgsField('field_name', QVariant.Double, 'double')
     self.assertEqual(f.__repr__(), "<QgsField: field_name (double)>")
开发者ID:anitagraser,项目名称:QGIS,代码行数:3,代码来源:test_python_repr.py


示例15: run

    def run(self):
        """Specific stuff at tool activating."""

        cur_carhab_lyr = CarhabLayerRegistry.instance().getCurrentCarhabLayer()
        if not cur_carhab_lyr:
            no_carhab_lyr_msg()
            return
        csv_dir = QFileDialog.getExistingDirectory(None, "Select a folder:", None, QFileDialog.ShowDirsOnly)
        if csv_dir:
            now = time.strftime("%Y-%m-%d-%H%M%S")
            directory = os.path.join(csv_dir, cur_carhab_lyr.getName() + "_" + now)
            if not os.path.exists(directory):
                os.makedirs(directory)

            for tbl_name, desc in Config.DB_STRUCTURE:
                file_name = desc.get("std_name")
                tbl_fields = desc.get("fields")
                if file_name:
                    if not desc.get("spatial"):
                        csv_name = file_name if file_name.endswith(".csv") else file_name + ".csv"
                        csv_path = os.path.join(directory, csv_name)
                        field_names = [row[1].get("std_name") for row in tbl_fields if row[1].get("std_name")]
                        db = DbManager(cur_carhab_lyr.dbPath)
                        r = Recorder(db, tbl_name)
                        tbl_rows = r.select_all()
                        csv_rows = []
                        for tbl_row in tbl_rows:
                            csv_row = {}
                            for dbf, value in tbl_row.items():
                                for field in desc.get("fields"):
                                    if dbf == field[0] and field[1].get("std_name"):
                                        csv_row[encode(field[1].get("std_name"))] = encode(value)
                                        break
                            csv_rows.append(csv_row)

                        with open(csv_path, "wb") as csv_file:
                            writer = csv.DictWriter(csv_file, field_names)
                            writer.writeheader()
                            writer.writerows(csv_rows)
                    else:
                        for vlyr in cur_carhab_lyr.getQgisLayers():
                            vlyr_tbl = QgsDataSourceURI(vlyr.dataProvider().dataSourceUri()).table()
                            if tbl_name == vlyr_tbl:
                                shp_name = file_name if file_name.endswith(".shp") else file_name + ".shp"
                                shp_path = os.path.join(directory, shp_name)
                                QgsVectorFileWriter.writeAsVectorFormat(vlyr, shp_path, "utf-8", None)
                                shp_lyr = QgsVectorLayer(shp_path, "", "ogr")
                                shapefile = shp_lyr.dataProvider()
                                features = shapefile.getFeatures()
                                attrs_to_del = []
                                for attr, attr_desc in tbl_fields:
                                    std_attr = attr_desc.get("std_name")
                                    if not std_attr == attr:
                                        if std_attr:
                                            cur_field = shapefile.fields().field(attr)
                                            new_field = QgsField(cur_field)
                                            new_field.setName(std_attr)
                                            shapefile.addAttributes([new_field])
                                            for feat in features:
                                                idx = shapefile.fields().indexFromName(std_attr)
                                                update_map = {feat.id(): {idx: feat[attr]}}
                                                shapefile.changeAttributeValues(update_map)
                                        attrs_to_del.append(shapefile.fields().indexFromName(attr))
                                shapefile.deleteAttributes(attrs_to_del)
            popup("Export effectué")
开发者ID:IGNF,项目名称:saisie_carhab,代码行数:65,代码来源:fse.py


示例16: create_field_from_definition

def create_field_from_definition(field_definition, name=None, sub_name=None):
    """Helper to create a field from definition.

    :param field_definition: The definition of the field (see:
        safe.definitions.fields).
    :type field_definition: dict

    :param name: The name is required if the field name is dynamic and need a
        string formatting.
    :type name: basestring

    :param sub_name: The name is required if the field name is dynamic and need
        a string formatting.
    :type sub_name: basestring

    :return: The new field.
    :rtype: QgsField
    """
    field = QgsField()

    if name and not sub_name:
        field.setName(field_definition['field_name'] % name)
    elif name and sub_name:
        field.setName(field_definition['field_name'] % (name, sub_name))
    else:
        field.setName(field_definition['field_name'])

    if isinstance(field_definition['type'], list):
        # Use the first element in the list of type
        field.setType(field_definition['type'][0])
    else:
        field.setType(field_definition['type'])
    field.setLength(field_definition['length'])
    field.setPrecision(field_definition['precision'])
    return field
开发者ID:inasafe,项目名称:inasafe,代码行数:35,代码来源:tools.py


示例17: reclassify

def reclassify(layer, exposure_key=None):
    """Reclassify a continuous vector layer.

    This function will modify the input.

    For instance if you want to reclassify like this table :
            Original Value     |   Class
            - ∞ < val <= 0     |     1
            0   < val <= 0.5   |     2
            0.5 < val <= 5     |     3
            5   < val <  + ∞   |     6

    You need a dictionary :
        ranges = OrderedDict()
        ranges[1] = [None, 0]
        ranges[2] = [0.0, 0.5]
        ranges[3] = [0.5, 5]
        ranges[6] = [5, None]

    :param layer: The raster layer.
    :type layer: QgsRasterLayer

    :param exposure_key: The exposure key.
    :type exposure_key: str

    :return: The classified vector layer.
    :rtype: QgsVectorLayer

    .. versionadded:: 4.0
    """
    output_layer_name = reclassify_vector_steps['output_layer_name']
    output_layer_name = output_layer_name % layer.keywords['title']

    # This layer should have this keyword, or it's a mistake from the dev.
    inasafe_fields = layer.keywords['inasafe_fields']
    continuous_column = inasafe_fields[hazard_value_field['key']]

    if exposure_key:
        classification_key = active_classification(
            layer.keywords, exposure_key)
        thresholds = active_thresholds_value_maps(layer.keywords, exposure_key)
        layer.keywords['thresholds'] = thresholds
        layer.keywords['classification'] = classification_key
    else:
        classification_key = layer.keywords.get('classification')
        thresholds = layer.keywords.get('thresholds')

    if not thresholds:
        raise InvalidKeywordsForProcessingAlgorithm(
            'thresholds are missing from the layer %s'
            % layer.keywords['layer_purpose'])

    continuous_index = layer.fields().lookupField(continuous_column)

    classified_field = QgsField()
    classified_field.setType(hazard_class_field['type'])
    classified_field.setName(hazard_class_field['field_name'])
    classified_field.setLength(hazard_class_field['length'])
    classified_field.setPrecision(hazard_class_field['precision'])

    layer.startEditing()
    layer.addAttribute(classified_field)

    classified_field_index = layer.fields(). \
        lookupField(classified_field.name())

    for feature in layer.getFeatures():
        attributes = feature.attributes()
        source_value = attributes[continuous_index]
        classified_value = reclassify_value(source_value, thresholds)
        if (classified_value is None
                or (hasattr(classified_value, 'isNull')
                    and classified_value.isNull())):
            layer.deleteFeature(feature.id())
        else:
            layer.changeAttributeValue(
                feature.id(), classified_field_index, classified_value)

    layer.commitChanges()
    layer.updateFields()

    # We transfer keywords to the output.
    inasafe_fields[hazard_class_field['key']] = (
        hazard_class_field['field_name'])

    value_map = {}

    hazard_classes = definition(classification_key)['classes']
    for hazard_class in reversed(hazard_classes):
        value_map[hazard_class['key']] = [hazard_class['value']]

    layer.keywords['value_map'] = value_map
    layer.keywords['title'] = output_layer_name

    check_layer(layer)
    return layer
开发者ID:inasafe,项目名称:inasafe,代码行数:96,代码来源:reclassify.py


示例18: calculate_svi

def calculate_svi(
    iface, current_layer, project_definition, indicators_operator=None, themes_operator=None, reuse_field=False
):
    """
    add an SVI attribute to the current layer
    """
    # set default
    if indicators_operator is None:
        indicators_operator = DEFAULT_COMBINATION
    if themes_operator is None:
        themes_operator = DEFAULT_COMBINATION

    themes = project_definition["children"][1]["children"]

    if reuse_field and "svi_field" in project_definition:
        svi_attr_name = project_definition["svi_field"]
        if DEBUG:
            print "Reusing %s" % svi_attr_name
    else:
        svi_attr_name = "SVI"
        svi_field = QgsField(svi_attr_name, QVariant.Double)
        svi_field.setTypeName(DOUBLE_FIELD_TYPE_NAME)
        attr_names = ProcessLayer(current_layer).add_attributes([svi_field])
        svi_attr_name = attr_names[svi_attr_name]

    # get the id of the new attribute
    svi_attr_id = ProcessLayer(current_layer).find_attribute_id(svi_attr_name)

    discarded_feats_ids = []
    try:
        with LayerEditingManager(current_layer, "Add SVI", DEBUG):
            for feat in current_layer.getFeatures():
                # If a feature contains any NULL value, discard_feat will
                # be set to True and the corresponding SVI will be set to
                # NULL
                discard_feat = False
                feat_id = feat.id()

                # init svi_value to the correct value depending on
                # themes_operator
                if themes_operator in SUM_BASED_COMBINATIONS:
                    svi_value = 0
                elif themes_operator in MUL_BASED_COMBINATIONS:
                    svi_value = 1

                # iterate all themes of SVI
                for theme in themes:
                    indicators = theme["children"]

                    # init theme_result to the correct value depending on
                    # indicators_operator
                    if indicators_operator in SUM_BASED_COMBINATIONS:
                        theme_result = 0
                    elif indicators_operator in MUL_BASED_COMBINATIONS:
                        theme_result = 1

                    # iterate all indicators of a theme
                    for indicator in indicators:
                        if feat[indicator["field"]] == QPyNullVariant(float):
                            discard_feat = True
                            discarded_feats_ids.append(feat_id)
                            break
                        # For "Average (equal weights)" it's equivalent to use
                        # equal weights, or to sum the indicators
                        # (all weights 1)
                        # and divide by the number of indicators (we use
                        # the latter solution)
                        if indicators_operator in (
                            "Sum (simple)",
                            "Average (equal weights)",
                            "Multiplication (simple)",
                        ):
                            indicator_weighted = feat[indicator["field"]]
                        else:
                            indicator_weighted = feat[indicator["field"]] * indicator["weight"]

                        if indicators_operator in SUM_BASED_COMBINATIONS:
                            theme_result += indicator_weighted
                        elif indicators_operator in MUL_BASED_COMBINATIONS:
                            theme_result *= indicator_weighted
                        else:
                            error_message = "invalid indicators_operator: %s" % indicators_operator
                            raise RuntimeError(error_message)
                    if discard_feat:
                        break
                    if indicators_operator == "Average (equal weights)":
                        theme_result /= len(indicators)

                    # combine the indicators of each theme
                    # For "Average (equal weights)" it's equivalent to use
                    # equal weights, or to sum the themes (all weights 1)
                    # and divide by the number of themes (we use
                    # the latter solution)
                    if themes_operator in ("Sum (simple)", "Average (equal weights)", "Multiplication (simple)"):
                        theme_weighted = theme_result
                    else:
                        theme_weighted = theme_result * theme["weight"]

                    if themes_operator in SUM_BASED_COMBINATIONS:
                        svi_value += theme_weighted
#.........这里部分代码省略.........
开发者ID:preinh,项目名称:qt-experiments,代码行数:101,代码来源:calculate_utils.py


示例19: on_btnRun_clicked

    def on_btnRun_clicked(self):
        
        #Check for combo and list box selections
        if self.ui.cmbBaseLayer.count() < 1 or self.ui.cmbProcessLayer.count() < 1:
            QMessageBox.critical(self, 'Vector Geoprocessor', 'Invalid layer selection.')
            return
        if len(self.ui.listFields.selectedItems()) < 1:
            QMessageBox.critical(self, 'Vector Geoprocessor', 'Invalid field selection.')
            return            
      
        #Initializations
        self.ui.ProgressBar.setValue(0)
        self.setCursor(Qt.WaitCursor)
        data = []
            
        #Add new attributes to base layer
        bprovider = self.blayer.dataProvider()
        pprovider = self.player.dataProvider()
        pfields = pprovider.fields()
        for item in self.ui.listFields.selectedItems():
            fname = item.text()
            for fld in pfields.toList():
                if fname == fld.name():                                               
                    newfield = QgsField()
                    newfield.setName(fld.name())
                    newfield.setType(fld.type())
                    newfield.setTypeName(fld.typeName())
                    newfield.setLength(fld.length())
                    newfield.setPrecision(fld.precision())
                    newfield.setComment(fld.comment())
                    bprovider.addAttributes([newfield])            

        #Create a spatial index for faster processing
        spindex = QgsSpatialIndex()
        for pfeat in pprovider.getFeatures():
            spindex.insertFeature(pfeat)
        
        #Find the intersection of process layer features with base layer
        #To increase speed, intersect with a bounding box rectangle first
        #Then further process within the geometric shape
        #Add requested processed information to base layer                
        featreq = QgsFeatureRequest()
        bfields = bprovider.fields()
        ddic = {}
        len1 = len(self.ui.listFields.selectedItems())
        len2 = len(bfields)
        b1 = 0
        b2 = bprovider.featureCount()
        attr={}
        for bfeat in bprovider.getFeatures():
            b1+=1
            attr.clear()
            bgeom = bfeat.geometry()                                          
            intersect = spindex.intersects(bgeom.boundingBox())
            data[:] = []
            for fid in intersect:               
                pfeat = self.player.getFeatures(featreq.setFilterFid(fid)).next()
                if pfeat.geometry().intersects(bgeom) == False:
                    data.append(fid)           
            for fid in data:        
                intersect.pop(intersect.index(fid))
                              
            count = 0
            for item in self.ui.listFields.selectedItems():
                pfindx = pprovider.fieldNameIndex(item.text())
                if pfindx < 0:
                    self.setCursor(Qt.ArrowCursor)
                    QMessageBox.critical(self, 'Vector Geoprocessor', 'Processing error.')
                    return
                data[:] = []
                for fid in intersect:
                    pfeat = self.player.getFeatures(featreq.setFilterFid(fid)).next()
                    if self.oindex in [0,1,2,3,4]:
                        data.append(float(pfeat.attribute(item.text())))
                    elif self.oindex in [5,6]:
                        data.append(str(pfeat.attribute(item.text())))
                if len(data) == 0:
                    value = None
                elif self.oindex == 0: #Find mean value of points within polygons
                    value = sum(data)/float(len(data))
                elif self.oindex == 1: #Find median value of points within polygons
                    data = sorted(data)
                    lendata = len(data)
                    if lendata % 2:
                        value = data[(lendata+1)/2-1]
                    else:
                        d1 = data[lendata/2-1]
                        d2 = data[lendata/2]
                        value = (d1 + d2)/2.0
                elif self.oindex == 2: #Find maximum value of points within polygons
                    value = max(data)
                elif self.oindex == 3: #Find minimum value of points within polygons
                    value = min(data)
                elif self.oindex == 4: #Find mean value (area-weighted) of polygons within polygons
                    value = 0.0
                    totalarea = 0.0
                    for fid in intersect:
                        pfeat = self.player.getFeatures(featreq.setFilterFid(fid)).next()
                        pgeom = pfeat.geometry()
                        isect = bgeom.intersection(pgeom)
#.........这里部分代码省略.........
开发者ID:npcasler,项目名称:phenomics,代码行数:101,代码来源:GeoprocessorDlg.py


示例20: processAlgorithm

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python core.QgsFieldModel类代码示例发布时间:2022-05-26
下一篇:
Python core.QgsFeedback类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap