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


Python QgsFeature.attributeMap方法代码示例

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


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

示例1: test_AddAttribute

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
 def test_AddAttribute(self):
     feat = QgsFeature()
     feat.addAttribute(1, "text")
     myCount = len(feat.attributeMap())
     myExpectedCount = 1
     myMessage = '\nExpected: %s\nGot: %s' % (myExpectedCount, myCount)
     assert myCount == myExpectedCount, myMessage        
开发者ID:homann,项目名称:Quantum-GIS,代码行数:9,代码来源:test_qgsfeature.py

示例2: gotFeatureForIdentification

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
 def gotFeatureForIdentification(self, pos):
     """Show a dialog with road information """
     #pos is a rectangle
     self.mem_layer_obj.select()
     ftr = QgsFeature()
     ftr_ids = []
     while self.mem_layer_obj.nextFeature(ftr):
         if ftr.geometry().intersects(pos):
             ftr_ids.append(ftr.id())
     self.chosenFOIGeoms = []
     self.info = QgsMessageViewer()
     if ftr_ids != []:
         f = QgsFeature()
         foi_type = self.foi_type.lower()
         if foi_type == 'areaofinterestdefiner':
             ftrData = "You have selected the following feature(s) for use as an Area of Interest:\n\n"
         if foi_type == 'lineofinterestdefiner':
             ftrData = "You have selected the following feature(s) for use as a Line of Interest:\n\n"
         if foi_type == 'pointofinterestdefiner':
             ftrData = "You have selected the following feature(s) for use as a Point of Interest:\n\n"
         for fid in ftr_ids:
             self.mem_layer_obj.dataProvider().featureAtId(fid, f,  True)
             ftrData += f.attributeMap()[0].toString()
             ftrData += "\n_____________________________\n"
             self.chosenFOIGeoms.append(f.geometry())
             id_fid = self.addGeomToMemoryLayer(f.geometry())
         self.info.setMessageAsPlainText(ftrData)
     else:
         self.info.setMessageAsPlainText("no data to show")
     self.info.show()
     return
开发者ID:ict4eo,项目名称:eo4vistrails,代码行数:33,代码来源:AOI_Utils.py

示例3: layer_multifields_stats

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
def layer_multifields_stats(layer, fields):
    """ return value distribution for field in given vector layer """
    provider = layer.dataProvider()
    if provider is None:
        return False
    # retrieve index for all fields
    f_indices = []
    for field in fields:
        idx = layer_field_index(layer, field)
        if idx == -1:
            return False
        f_indices.append(idx)
        
    f = QgsFeature()
    stats = {}
    provider.select(f_indices, provider.extent())
    provider.rewind()
    for _idx in range(provider.featureCount()):
        provider.nextFeature(f)
        # create compound key
        _key = ''
        for idx in f_indices:
            if _key != '':
                _key = _key + '_'
            _key += str(f.attributeMap()[idx].toString()).upper()
        # update stats based on compound key
        if stats.has_key(_key):
            stats[_key]+=1
        else:
            stats[_key]=1
    return stats
开发者ID:ImageCatInc,项目名称:sidd,代码行数:33,代码来源:shapefile.py

示例4: test_ChangeAttribute

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
 def test_ChangeAttribute(self):
     feat = QgsFeature()
     feat.addAttribute(1, "text")
     feat.changeAttribute(1, "changed")
     myChangedAttribute = feat.attributeMap()[1].toString()
     myExpectedAttribute = "changed"
     myMessage = '\nExpected: %s\nGot: %s' % (myExpectedAttribute, 
         myChangedAttribute)
     assert myChangedAttribute == myExpectedAttribute, myMessage        
开发者ID:homann,项目名称:Quantum-GIS,代码行数:11,代码来源:test_qgsfeature.py

示例5: showInfo

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
    @pyqtSlot(QPoint, QObject)
    def showInfo(self, point, mouseButton):
        """
        event handler for toolInfo
        @see QGIS tutorial for detail
        point-polygon search on currently selected layer  
        """
        cur_layer_name = self.ui.cb_layer_selector.currentText()
        if cur_layer_name.isEmpty():
            return
        try:
            cur_layer_idx = self.LAYER_NAMES.index(cur_layer_name)
            cur_layer = self.map_layers[cur_layer_idx]
            
            # if layer is not in same projection as map canvas
            # need to project query point
            if cur_layer.crs() != self.canvas.mapRenderer().destinationCrs():
                transform = QgsCoordinateTransform(self.canvas.mapRenderer().destinationCrs(), cur_layer.crs())
                point = transform.transform(point)
            
            # do query
            provider = cur_layer.dataProvider() 
            provider.rewind()
            feature = QgsFeature()
            colonIndexes = provider.attributeIndexes()
        
            # search using point as center of rectangle polygon
            search_buffer_x = self.canvas.extent().width() * self.SEARCH_BUFFER / self.canvas.width()
            search_buffer_y = self.canvas.extent().height() * self.SEARCH_BUFFER / self.canvas.height()
            provider.select(colonIndexes,
                            QgsRectangle(point.x()-search_buffer_x,
                                         point.y()-search_buffer_y,
                                         point.x()+search_buffer_x,
                                         point.y()+search_buffer_y),
                            True)
            # get selected and display in result detail dialog box 
            selected = []        
            while provider.nextFeature(feature):            
                # for polygons, only show geometry containing query point            
                if cur_layer.geometryType() == QGis.Polygon:                
                    if feature.geometry() is not None and not feature.geometry().contains (point):
                        continue
                selected.append(feature.attributeMap())

            if len(selected)>0:
                # display result if exists
                if cur_layer_idx == self.EXPOSURE:
                    self.dlgResultDetail.showExposureData(provider.fields(), selected)                    
                else:
                    self.dlgResultDetail.showInfoData(provider.fields(), selected)
                self.dlgResultDetail.exec_()
            else:
                logUICall.log(get_ui_string("widget.result.info.notfound"), logUICall.WARNING)
        except Exception as err:
            # point-in-polygon search is not critical, continue on error 
开发者ID:ImageCatInc,项目名称:sidd,代码行数:57,代码来源:wdg_result.py

示例6: testAddFeatures

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
    def testAddFeatures(self):
        layer = QgsVectorLayer("Point", "test", "memory")
        provider = layer.dataProvider()

        res = provider.addAttributes([QgsField("name", QVariant.String,),
                                      QgsField("age",  QVariant.Int),
                                      QgsField("size", QVariant.Double)])
        assert res, "Failed to add attributes"

        myMessage = ('Expected: %s\nGot: %s\n' %
                      (3, provider.fieldCount()))

        assert provider.fieldCount() == 3, myMessage

        ft = QgsFeature()
        ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(10,10)))
        ft.setAttributeMap({0 : QVariant("Johny"),
                            1 : QVariant(20),
                            2 : QVariant(0.3)})
        res, t = provider.addFeatures([ft])

        assert res, "Failed to add feature"

        myMessage = ('Expected: %s\nGot: %s\n' %
                      (1, provider.featureCount()))
        assert provider.featureCount() == 1, myMessage

        f = QgsFeature()
        provider.select()
        while provider.nextFeature(f):
            attrMap = f.attributeMap()
            myMessage = ('Expected: %s\nGot: %s\n' %
                        ("Johny", str(attrMap[0].toString())))

            assert str(attrMap[0].toString()) == "Johny", myMessage

            myMessage = ('Expected: %s\nGot: %s\n' %
                        (20, attrMap[1].toInt()[0]))

            assert attrMap[1].toInt()[0] == 20, myMessage

            myMessage = ('Expected: %s\nGot: %s\n' %
                        (0.3, attrMap[2].toFloat()[0]))

            assert (attrMap[0].toFloat()[0] - 0.3) < 0.0000001, myMessage

            geom = f.geometry()

            myMessage = ('Expected: %s\nGot: %s\n' %
                        ("POINT(10.0 10.0)", str(geom.exportToWkt())))

            assert str(geom.exportToWkt()) == "POINT(10.0 10.0)", myMessage
开发者ID:Nald,项目名称:Quantum-GIS,代码行数:54,代码来源:test_qgsmemoryprovider.py

示例7: testLocalCities

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
    def testLocalCities(self):
        """Test that we can retrieve the cities local to the event"""
        myShakeId = '20120726022003'
        myShakeEvent = ShakeEvent(myShakeId)
        # Get teh mem layer
        myCitiesLayer = myShakeEvent.localCitiesMemoryLayer()
        myProvider = myCitiesLayer.dataProvider()

        myFeature = QgsFeature()
        myAttributes = myProvider.attributeIndexes()
        myProvider.select(myAttributes)
        myExpectedFeatureCount = 6
        self.assertEquals(myProvider.featureCount(), myExpectedFeatureCount)
        myStrings = []
        while myProvider.nextFeature(myFeature):
            # fetch map of attributes
            myAttributes = myFeature.attributeMap()
            for (myKey, myValue) in myAttributes.iteritems():
                myStrings.append("%d: %s\n" % (myKey, myValue.toString()))
            myStrings.append('------------------\n')
        LOGGER.debug('Mem table:\n %s' % myStrings)
        myFilePath = unique_filename(prefix='testLocalCities',
                                     suffix='.txt',
                                     dir=temp_dir('test'))
        myFile = file(myFilePath, 'wt')
        myFile.writelines(myStrings)
        myFile.close()

        myFixturePath = os.path.join(dataDir(), 'tests', 'testLocalCities.txt')
        myFile = file(myFixturePath, 'rt')
        myExpectedString = myFile.readlines()
        myFile.close()

        myDiff = difflib.unified_diff(myStrings, myExpectedString)
        myDiffList = list(myDiff)
        myDiffString = ''
        for _, myLine in enumerate(myDiffList):
            myDiffString += myLine

        myMessage = ('Diff is not zero length:\n'
                     'Control file: %s\n'
                     'Test file: %s\n'
                     'Diff:\n%s'
                     % (myFixturePath,
                        myFilePath,
                        myDiffString))
        self.assertEqual(myDiffString, '', myMessage)
开发者ID:gijs,项目名称:inasafe,代码行数:49,代码来源:test_shake_event.py

示例8: do_dbf_import

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
	def do_dbf_import(self):
		""" last step: create table and import data """
		
		QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

		tablename = unicode(self.field("tablename").toString())
		pkey = unicode(self.field("pkey").toString())
		if pkey == "(none)": pkey = None
		
		try:
			# create the table
			self.db.create_table(tablename, self.dbf_fields, pkey)
			
			cursor = self.db.con.cursor()
				
			# now let's get the features and import them to database
			pr = self.vlayer.dataProvider()
			flds = pr.fields()
			pr.enableGeometrylessFeatures(True)
			pr.select(pr.attributeIndexes(), QgsRectangle(), False) # all attrs, no geometry
			f = QgsFeature()
			while pr.nextFeature(f):
				attrs = f.attributeMap()
				values = []
				for (i,val) in attrs.iteritems():
					vartype = flds[i].type()
					if val.isNull():
						values.append("NULL")
					elif vartype == QVariant.Int:
						values.append(str(val.toInt()[0]))
					elif vartype == QVariant.Double:
						values.append(str(val.toDouble()[0]))
					else: # string or something else
						values.append("'%s'" % str(val.toString().toUtf8()).replace("'","''").replace("\\", "\\\\"))
				self.db.insert_table_row(tablename, values, None, cursor)
				
			# commit changes to DB
			self.db.con.commit()

		except postgis_utils.DbError, e:
			QApplication.restoreOverrideCursor()
			
			DlgDbError.showError(e, self)
			return False
开发者ID:brushtyler,项目名称:postgis_manager,代码行数:46,代码来源:WizardImport.py

示例9: _aggregate

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
    def _aggregate(self, myImpactLayer, myExpectedResults):
        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.aggregate(myImpactLayer)

        myProvider = myAggregator.layer.dataProvider()
        myProvider.select(myProvider.attributeIndexes())
        myFeature = QgsFeature()
        myResults = []

        while myProvider.nextFeature(myFeature):
            myFeatureResults = {}
            myAtMap = myFeature.attributeMap()
            for (k, attr) in myAtMap.iteritems():
                myFeatureResults[k] = str(attr.toString())
            myResults.append(myFeatureResults)

        self.assertEqual(myExpectedResults, myResults)
开发者ID:feyeandal,项目名称:inasafe,代码行数:43,代码来源:test_aggregator.py

示例10: test_AttributeMap

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
 def test_AttributeMap(self):
     myPath = os.path.join(unitTestDataPath(), 'lines.shp')
     myLayer = QgsVectorLayer(myPath, 'Lines', 'ogr')
     provider = myLayer.dataProvider()
     allAttrs = provider.attributeIndexes()
     provider.select(allAttrs)
     feat = QgsFeature()
     provider.nextFeature(feat)
     
     myAttributeMap = feat.attributeMap()
     myExpectedAttributeMap = {0: QVariant("Highway"), 1: QVariant(1)}
     
     # Only for printing purposes 
     myAttributeDict = {
         0:str(myAttributeMap[0].toString()),
         1:int(myAttributeMap[1].toString())}
     myExpectedAttributeDict = {0: "Highway", 1: 1}
     myMessage = '\nExpected: %s\nGot: %s' % (myExpectedAttributeDict, 
         myAttributeDict)
         
     assert myAttributeMap == myExpectedAttributeMap, myMessage
开发者ID:homann,项目名称:Quantum-GIS,代码行数:23,代码来源:test_qgsfeature.py

示例11: _clip_vector_layer

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]

#.........这里部分代码省略.........
        myMessage = tr('Could not obtain data provider from '
                       'layer "%s"' % layer.source())
        raise Exception(myMessage)

    # Get the layer field list, select by our extent then write to disk
    # .. todo:: FIXME - for different geometry types we should implement
    #    different clipping behaviour e.g. reject polygons that
    #    intersect the edge of the bbox. Tim
    myAttributes = myProvider.attributeIndexes()
    myFetchGeometryFlag = True
    myUseIntersectFlag = True
    myProvider.select(
        myAttributes,
        myProjectedExtent,
        myFetchGeometryFlag,
        myUseIntersectFlag)

    myFieldList = myProvider.fields()

    myWriter = QgsVectorFileWriter(
        myFilename,
        'UTF-8',
        myFieldList,
        layer.wkbType(),
        myGeoCrs,
        #'SQLite')  # FIXME (Ole): This works but is far too slow
        'ESRI Shapefile')
    if myWriter.hasError() != QgsVectorFileWriter.NoError:
        myMessage = tr('Error when creating shapefile: <br>Filename:'
                       '%s<br>Error: %s' %
                       (myFilename, myWriter.hasError()))
        raise Exception(myMessage)

    # Reverse the coordinate xform now so that we can convert
    # geometries from layer crs to geocrs.
    myXForm = QgsCoordinateTransform(layer.crs(), myGeoCrs)
    # Retrieve every feature with its geometry and attributes
    myFeature = QgsFeature()
    myCount = 0
    myHasMultipart = False

    if explode_attribute is not None:
        theExplodeAttributeIndex = myProvider.fieldNameIndex(
            explode_attribute)

    while myProvider.nextFeature(myFeature):
        myGeometry = myFeature.geometry()
        if explode_attribute is not None:
            myAttrs = myFeature.attributeMap()
        # Loop through the parts adding them to the output file
        # we write out single part features unless explode_flag is False
        if explode_flag:
            myGeometryList = explode_multipart_geometry(myGeometry)
        else:
            myGeometryList = [myGeometry]

        for myPartIndex, myPart in enumerate(myGeometryList):
            myPart.transform(myXForm)
            if hard_clip_flag:
                # Remove any dangling bits so only intersecting area is
                # kept.
                myPart = clip_geometry(myClipPolygon, myPart)
            if myPart is None:
                continue

            myFeature.setGeometry(myPart)
            # There are multiple parts and we want to show it in the
            # explode_attribute
            if myPartIndex > 0 and explode_attribute is not None:
                myHasMultipart = True
                myPartAttr = QVariant(
                    '%s #%s' % (myAttrs[theExplodeAttributeIndex].toString(),
                                myPartIndex))
                myFeature.changeAttribute(theExplodeAttributeIndex, myPartAttr)

            myWriter.addFeature(myFeature)
        myCount += 1
    del myWriter  # Flush to disk

    if myCount < 1:
        myMessage = tr(
            'No features fall within the clip extents. Try panning / zooming '
            'to an area containing data and then try to run your analysis '
            'again. If hazard and exposure data doesn\'t overlap at all, it '
            'is not possible to do an analysis. Another possibility is that '
            'the layers do overlap but because they may have different '
            'spatial references, they appear to be disjointed. If this is the '
            'case, try to turn on reproject on-the-fly in QGIS.')
        raise NoFeaturesInExtentError(myMessage)

    myKeywordIO = KeywordIO()
    if extra_keywords is None:
        extra_keywords = {}
    extra_keywords['HAD_MULTIPART_POLY'] = myHasMultipart
    myKeywordIO.copy_keywords(
        layer, myFilename, extra_keywords=extra_keywords)
    myBaseName = '%s clipped' % layer.name()
    myLayer = QgsVectorLayer(myFilename, myBaseName, 'ogr')

    return myLayer
开发者ID:lptorres,项目名称:inasafe,代码行数:104,代码来源:clipper.py

示例12: addStakeholdersFromLayer

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
    def addStakeholdersFromLayer(self):
        """
        Import all stakeholders from the active layer to the Land Observatory
        platform.
        It is not (yet) tested if a stakeholder already exists or not.
        """

        # Connect to the protocol to get noticed as soon as the stakeholder has
        # been created
        self.connect(self.stakeholderProtocol, SIGNAL("created( bool, int, QString"), self.addStakeholdersFinished)

        # Get the dict maps the attribute names from the landmatrix input Shapefile to the
        # fields defined in the global definition yaml
        identifierColumn, transformMap, groups = self.getTagGroupsConfiguration("landmatrix.stakeholder.ini")

        # Get the active layer and its data provider
        layer = self.iface.activeLayer()
        provider = layer.dataProvider()

        # The current feature
        feature = QgsFeature()

        # List of attribute indexes to select
        attributeIndexes = []
        # Dict that maps the field index to the fields defined in the global YAML
        fieldIndexMap = {}
        for (i, field) in provider.fields().iteritems():
            if str(field.name()) in transformMap:
                attributeIndexes.append(i)
                fieldIndexMap[i] = transformMap[str(field.name())]

        # Start data retreival: fetch geometry and necessary attributes for each feature
        provider.select(attributeIndexes)

        stakeholders = []

        # retreive every feature with its geometry and attributes
        while provider.nextFeature(feature):

            tagGroups = list(TagGroup() for i in range(len(groups)))

            # fetch map of attributes
            attrs = feature.attributeMap()

            # attrs is a dictionary: key = field index, value = QgsFeatureAttribute
            # show all attributes and their values
            for (k, attr) in attrs.iteritems():
                self.log("%s: %s" % (fieldIndexMap[k], attr.toString()))

                # First search the correct taggroup to append
                attributeName = provider.fields()[k].name()
                currentTagGroup = 0
                for g in groups:
                    if attributeName in g:
                        break
                    else:
                        currentTagGroup += 1

                if attr is not None and attr.toString() != '':
                    tag = Tag(key=fieldIndexMap[k], value=attr.toString())
                    tagGroups[currentTagGroup].addTag(tag)
                    if tagGroups[currentTagGroup].mainTag() is None:
                        tagGroups[currentTagGroup].setMainTag(tag)

            s = Stakeholder()
            for tg in tagGroups:
                if len(tg.tags) > 0:
                    s.addTagGroup(tg)

            stakeholders.append(s)

        msg, rawBody = self.stakeholderProtocol.add(stakeholders)
        self.log(msg)
        self.log(rawBody)

        # Disconnect the signal
        self.disconnect(self.stakeholderProtocol, SIGNAL("created( bool, int, QString"), self.addStakeholdersFinished)
开发者ID:CDE-UNIBE,项目名称:lo-editor,代码行数:79,代码来源:StakeholderRequestManager.py

示例13: _preparePolygonLayer

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]

#.........这里部分代码省略.........
                    # check if myPoly is all E,W,N,S of myPostprocPolygon
                    if ((myPolyMinx > myPostprocPolygonMaxx) or
                            (myPolyMaxx < myPostprocPolygonMinx) or
                            (myPolyMiny > myPostprocPolygonMaxy) or
                            (myPolyMaxy < myPostprocPolygonMiny)):
                        #polygon is surely outside
                        myOutsidePolygons.append(myMappedIndex)
                        # we need this polygon in the next iteration
                        myNextIterPolygons.append(i)
                    else:
                        # polygon might be outside or intersecting. consider
                        # it intersecting so it goes into further analysis
                        doIntersection = True
                else:
                    # some vertices are outside some inside -> polygon is
                    # intersecting
                    doIntersection = True

                #intersect using qgis
                if doIntersection:
#                    LOGGER.debug('Intersecting polygon %s' % myMappedIndex)
                    myIntersectingPolygons.append(myMappedIndex)

                    ok = polygonsProvider.featureAtId(myFeatId,
                                                      myQgisFeat,
                                                      True,
                                                      allPolygonAttrs)
                    if not ok:
                        LOGGER.debug('Couldn\'t fetch feature: %s' % myFeatId)
                        LOGGER.debug([str(error) for error in
                                      polygonsProvider.errors()])

                    myQgisPolyGeom = QgsGeometry(myQgisFeat.geometry())
                    myAtMap = myQgisFeat.attributeMap()
#                    for (k, attr) in myAtMap.iteritems():
#                        LOGGER.debug( "%d: %s" % (k, attr.toString()))

                    # make intersection of the myQgisFeat and the postprocPoly
                    # write the inside part to a shp file and the outside part
                    # back to the original QGIS layer
                    try:
                        myIntersec = myQgisPostprocGeom.intersection(
                            myQgisPolyGeom)
#                        if myIntersec is not None:
                        myIntersecGeom = QgsGeometry(myIntersec)

                        #from ftools
                        myUnknownGeomType = 0
                        if myIntersecGeom.wkbType() == myUnknownGeomType:
                            int_com = myQgisPostprocGeom.combine(
                                myQgisPolyGeom)
                            int_sym = myQgisPostprocGeom.symDifference(
                                myQgisPolyGeom)
                            myIntersecGeom = QgsGeometry(
                                int_com.difference(int_sym))
#                        LOGGER.debug('wkbType type of intersection: %s' %
# myIntersecGeom.wkbType())
                        polygonTypesList = [QGis.WKBPolygon,
                                            QGis.WKBMultiPolygon]
                        if myIntersecGeom.wkbType() in polygonTypesList:
                            myInsideFeat.setGeometry(myIntersecGeom)
                            myInsideFeat.setAttributeMap(myAtMap)
                            mySHPWriter.addFeature(myInsideFeat)
                            self.preprocessedFeatureCount += 1
                        else:
                            pass
开发者ID:gsuhartono,项目名称:inasafe,代码行数:70,代码来源:aggregator.py

示例14: aggregate

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
    def aggregate(self, theSafeImpactLayer):
        """Do any requested aggregation post processing.

        Performs Aggregation postprocessing step by

            * creating a copy of the dataset clipped by the impactlayer
              bounding box
            * stripping all attributes beside the aggregation attribute
            * delegating to the appropriate aggregator for raster and vectors

        :raises: ReadLayerError
        """

        if not self.isValid:
            raise InvalidAggregatorError

        myMessage = m.Message(
            m.Heading(self.tr('Aggregating results'), **PROGRESS_UPDATE_STYLE),
            m.Paragraph(self.tr(
                'This may take a little while - we are aggregating the impact'
                ' by %1').arg(self.layer.name())))
        self._sendMessage(myMessage)

        myQGISImpactLayer = safe_to_qgis_layer(theSafeImpactLayer)
        if not myQGISImpactLayer.isValid():
            myMessage = self.tr('Error when reading %1').arg(myQGISImpactLayer)
            # noinspection PyExceptionInherit
            raise ReadLayerError(myMessage)
        myLayerName = str(self.tr('%1 aggregated to %2').arg(
            myQGISImpactLayer.name()).arg(self.layer.name()))

        #delete unwanted fields
        myProvider = self.layer.dataProvider()
        myFields = myProvider.fields()

        #mark important attributes as needed
        self._setPersistantAttributes()
        myUnneededAttributes = []

        for i in myFields:
            if (myFields[i].name() not in
                    self.attributes.values()):
                myUnneededAttributes.append(i)
        LOGGER.debug('Removing this attributes: ' + str(myUnneededAttributes))
        # noinspection PyBroadException
        try:
            self.layer.startEditing()
            myProvider.deleteAttributes(myUnneededAttributes)
            self.layer.commitChanges()
        # FIXME (Ole): Disable pylint check for the moment
        # Need to work out what exceptions we will catch here, though.
        except:  # pylint: disable=W0702
            myMessage = self.tr('Could not remove the unneeded fields')
            LOGGER.debug(myMessage)

        del myUnneededAttributes, myProvider, myFields
        self.keywordIO.update_keywords(
            self.layer, {'title': myLayerName})

        self.statisticsType, self.statisticsClasses = (
            self.keywordIO.get_statistics(myQGISImpactLayer))

        #call the correct aggregator
        if myQGISImpactLayer.type() == QgsMapLayer.VectorLayer:
            self._aggregateVectorImpact(myQGISImpactLayer, theSafeImpactLayer)
        elif myQGISImpactLayer.type() == QgsMapLayer.RasterLayer:
            self._aggregateRasterImpact(myQGISImpactLayer)
        else:
            myMessage = self.tr('%1 is %2 but it should be either vector or '
                                'raster').\
                arg(myQGISImpactLayer.name()).arg(myQGISImpactLayer.type())
            # noinspection PyExceptionInherit
            raise ReadLayerError(myMessage)

        # show a styled aggregation layer
        if self.showIntermediateLayers:
            if self.statisticsType == 'sum':
                #style layer if we are summing
                myProvider = self.layer.dataProvider()
                myAttr = self._sumFieldName()
                myAttrIndex = myProvider.fieldNameIndex(myAttr)
                myProvider.select([myAttrIndex], QgsRectangle(), False)
                myFeature = QgsFeature()
                myHighestVal = 0

                while myProvider.nextFeature(myFeature):
                    myAttrMap = myFeature.attributeMap()
                    myVal, ok = myAttrMap[myAttrIndex].toInt()
                    if ok and myVal > myHighestVal:
                        myHighestVal = myVal

                myClasses = []
                myColors = ['#fecc5c', '#fd8d3c', '#f31a1c']
                myStep = int(myHighestVal / len(myColors))
                myCounter = 0
                for myColor in myColors:
                    myMin = myCounter
                    myCounter += myStep
                    myMax = myCounter

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

示例15: processing

# 需要导入模块: from qgis.core import QgsFeature [as 别名]
# 或者: from qgis.core.QgsFeature import attributeMap [as 别名]
    def processing(self):
        #check edit mode
        if not self.active_layer.isEditable():
            QMessageBox.warning(self, self.tr("FieldPyculator warning"),
                                 self.tr("Layer is not in edit mode! Please start editing the layer!"))
            return    
        
        start =  datetime.datetime.now()
        new_ns = {}
        
        #run global code
        if self.ui.grpGlobalExpression.isChecked():
            try:
                code = unicode(self.ui.txtGlobalExp.toPlainText())
                bytecode = compile(code, '<string>', 'exec')
                exec bytecode in new_ns
            except:
                QMessageBox.critical(self, self.tr("FieldPyculator code execute error"),
                            (self.tr("Global code block can't be executed!\n%1: %2"))
                            .arg(unicode(sys.exc_info()[0].__name__))
                            .arg(unicode(sys.exc_info()[1])))
                return
            
        
        code = unicode(self.ui.txtFieldExp.toPlainText())
        
        #TODO: check 'result' existing in text of code???!!!
            
        #replace all fields tags
        field_map = self.data_provider.fields()
        for num, field in field_map.iteritems():
            field_name = unicode(field.name())
            replval = '__attr[' + str(num) + ']'
            code = code.replace("<"+field_name+">", replval)

        #replace all special vars
        code = code.replace('$id', '__id')
        code = code.replace('$geom', '__geom')
        #is it need: $area, $length, $x, $y????

        #print code #debug

        #search needed vars (hmmm... comments?!)
        need_id = code.find("__id") != -1
        need_geom = code.find("__geom") != -1
        need_attrs = code.find("__attr") != -1


        #compile
        try:
            bytecode = compile(code, '<string>', 'exec')
        except:
            QMessageBox.critical(self, self.tr("FieldPyculator code execute error"),
                                 self.tr("Field code block can't be executed!\n%1: %2")
                                 .arg(unicode(sys.exc_info()[0].__name__))
                                 .arg(unicode(sys.exc_info()[1])))
            return
        
        
        #get num of updating field
        field_num = self.data_provider.fieldNameIndex(self.ui.cmbUpdateField.currentText())
        
        #setup progress bar       
        self.ui.prgTotal.setValue(0)
        
        #run
        if not self.ui.chkOnlySelected.isChecked():
            #select all features
            features_for_update = self.data_provider.featureCount()
            if  features_for_update > 0:
                self.ui.prgTotal.setMaximum(features_for_update)
            
            feat = QgsFeature()
            if need_attrs:
                attr_ind = self.data_provider.attributeIndexes()
            else:
                attr_ind = []
            self.data_provider.select(attr_ind, QgsRectangle(), need_geom)
            
            while self.data_provider.nextFeature( feat ):
                feat_id = feat.id()
                
                #add needed vars
                if need_id:
                    new_ns['__id'] = feat_id

                if need_geom:
                    geom = feat.geometry()
                    new_ns['__geom'] = geom

                if need_attrs:
                    attr_map = feat.attributeMap()
                    attr = []
                    for num, a in attr_map.iteritems():
                        attr.append(self.qvar2py(a))
                    new_ns['__attr'] = attr
                
                #clear old result
                if new_ns.has_key(self.RESULT_VAR_NAME):
                    del new_ns[self.RESULT_VAR_NAME]
#.........这里部分代码省略.........
开发者ID:viktorijasolovjova,项目名称:FieldPyculator,代码行数:103,代码来源:field_pyculator_dialog.py


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