本文整理汇总了Python中qgis.core.QgsWKBTypes类的典型用法代码示例。如果您正苦于以下问题:Python QgsWKBTypes类的具体用法?Python QgsWKBTypes怎么用?Python QgsWKBTypes使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QgsWKBTypes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: mergeLines
def mergeLines(self, line_a, line_b, layer):
"""
Merge 2 lines of the same layer (it is assumed that they share the same set od attributes - except for ID and geometry).
In case sets are different, the set of attributes from line_a will be kept. If geometries don't touch, method is not applicable.
:param line_a: (QgsFeature) main line of merging process.
:param line_b: (QgsFeature) line to be merged to line_a.
:param layer: (QgsVectorLayer) layer containing given lines.
:return: (bool) True if method runs OK or False, if lines do not touch.
"""
# check if original layer is a multipart
isMulti = QgsWKBTypes.isMultiType(int(layer.wkbType()))
# retrieve lines geometries
geometry_a = line_a.geometry()
geometry_b = line_b.geometry()
# checking the spatial predicate touches
if geometry_a.touches(geometry_b):
# this generates a multi geometry
geometry_a = geometry_a.combine(geometry_b)
# this make a single line string if the multi geometries are neighbors
geometry_a = geometry_a.mergeLines()
if isMulti:
# making a "single" multi geometry (EDGV standard)
geometry_a.convertToMultiType()
# updating feature
line_a.setGeometry(geometry_a)
# remove the aggregated line to avoid overlapping
layer.deleteFeature(line_b.id())
# updating layer
layer.updateFeature(line_a)
return True
return False
示例2: __init__
def __init__(self, table, parent=None):
TableDataModel.__init__(self, table, parent)
self.layer = None
if isinstance(table, LVectorTable):
self.layer = VLayerRegistry.instance().getLayer(table.name)
else:
self.layer = VLayerRegistry.instance().getLayer(table)
if not self.layer:
return
# populate self.resdata
self.resdata = []
for f in self.layer.getFeatures():
a = f.attributes()
# add the geometry type
if f.geometry():
a.append(QgsWKBTypes.displayString(QGis.fromOldWkbType(f.geometry().wkbType())))
else:
a.append('None')
self.resdata.append(a)
self.fetchedFrom = 0
self.fetchedCount = len(self.resdata)
示例3: getFeatureNodes
def getFeatureNodes(self, layer, feature, geomType=None):
"""
Inverts the flow from a given feature. THE GIVEN FEATURE IS ALTERED. Standard behaviour is to not
refresh canvas map.
:param layer: layer containing the target feature for flipping.
:param feature: feature to be flipped.
:param geomType: if layer geometry type is not given, it'll calculate it (0,1 or 2).
:returns: feature as of a list of points (nodes).
"""
if not geomType:
geomType = layer.geometryType()
# getting whether geometry is multipart or not
isMulti = QgsWKBTypes.isMultiType(int(layer.wkbType()))
geom = feature.geometry()
if geomType == 0:
if isMulti:
nodes = geom.asMultiPoint()
else:
nodes = geom.asPoint()
elif geomType == 1:
if isMulti:
nodes = geom.asMultiPolyline()
else:
nodes = geom.asPolyline()
elif geomType == 2:
if isMulti:
nodes = geom.asMultiPolygon()
else:
nodes = geom.asPolygon()
return nodes
示例4: processAlgorithm
def processAlgorithm(self, progress):
vlayerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT))
vlayerB = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT2))
vproviderA = vlayerA.dataProvider()
fields = vector.combineVectorFields(vlayerA, vlayerB)
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
fields, vproviderA.geometryType(), vproviderA.crs()
)
inFeatA = QgsFeature()
inFeatB = QgsFeature()
outFeat = QgsFeature()
index = vector.spatialindex(vlayerB)
nElement = 0
selectionA = vector.features(vlayerA)
nFeat = len(selectionA)
for inFeatA in selectionA:
nElement += 1
progress.setPercentage(nElement / float(nFeat) * 100)
geom = QgsGeometry(inFeatA.geometry())
atMapA = inFeatA.attributes()
intersects = index.intersects(geom.boundingBox())
for i in intersects:
request = QgsFeatureRequest().setFilterFid(i)
inFeatB = vlayerB.getFeatures(request).next()
tmpGeom = QgsGeometry(inFeatB.geometry())
try:
if geom.intersects(tmpGeom):
atMapB = inFeatB.attributes()
int_geom = QgsGeometry(geom.intersection(tmpGeom))
if (
int_geom.wkbType() == QGis.WKBUnknown
or QgsWKBTypes.flatType(int_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection
):
int_com = geom.combine(tmpGeom)
int_sym = geom.symDifference(tmpGeom)
int_geom = QgsGeometry(int_com.difference(int_sym))
try:
if int_geom.wkbType() in wkbTypeGroups[wkbTypeGroups[int_geom.wkbType()]]:
outFeat.setGeometry(int_geom)
attrs = []
attrs.extend(atMapA)
attrs.extend(atMapB)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
except:
ProcessingLog.addToLog(
ProcessingLog.LOG_INFO,
self.tr(
"Feature geometry error: One or more output features ignored due to invalid geometry."
),
)
continue
except:
break
del writer
示例5: flipFeature
def flipFeature(self, layer, feature, geomType=None, refreshCanvas=False):
"""
Inverts the flow from a given feature. THE GIVEN FEATURE IS ALTERED. Standard behaviour is to not
refresh canvas map.
:param layer: layer containing the target feature for flipping.
:param feature: feature to be flipped.
:param geomType: if layer geometry type is not given, it'll calculate it (0,1 or 2)
:param refreshCanvas: indicates whether the canvas should be refreshed after flipping feature.
:returns: flipped feature as of [layer, feature, geometry_type].
"""
if not geomType:
geomType = layer.geometryType()
# getting whether geometry is multipart or not
isMulti = QgsWKBTypes.isMultiType(int(layer.wkbType()))
geom = feature.geometry()
if geomType == 0:
if isMulti:
nodes = geom.asMultiPoint()
# inverting the point list by parts
for idx, part in enumerate(nodes):
nodes[idx] = part[::-1]
# setting flipped geometry
flippedFeatureGeom = QgsGeometry.fromMultiPoint(nodes)
else:
# inverting the point list
nodes = geom.asPoint()
nodes = nodes[::-1]
flippedFeatureGeom = QgsGeometry.fromPoint(nodes)
elif geomType == 1:
if isMulti:
nodes = geom.asMultiPolyline()
for idx, part in enumerate(nodes):
nodes[idx] = part[::-1]
flippedFeatureGeom = QgsGeometry.fromMultiPolyline(nodes)
else:
nodes = geom.asPolyline()
nodes = nodes[::-1]
flippedFeatureGeom = QgsGeometry.fromPolyline(nodes)
elif geomType == 2:
if isMulti:
nodes = geom.asMultiPolygon()
for idx, part in enumerate(nodes):
nodes[idx] = part[::-1]
flippedFeatureGeom = QgsGeometry.fromMultiPolygon(nodes)
else:
nodes = geom.asPolygon()
nodes = nodes[::-1]
flippedFeatureGeom = QgsGeometry.fromPolygon(nodes)
# setting feature geometry to the flipped one
# feature.setGeometry(flippedFeatureGeom)
# layer.updateFeature(feature)
layer.changeGeometry(feature.id(), flippedFeatureGeom)
if refreshCanvas:
self.iface.mapCanvas().refresh()
return [layer, feature, geomType]
示例6: processAlgorithm
def processAlgorithm(self, progress):
vlayerA = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT))
vlayerB = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT2))
vproviderA = vlayerA.dataProvider()
geomType = vproviderA.geometryType()
if geomType in GEOM_25D:
raise GeoAlgorithmExecutionException(
self.tr('Input layer has unsupported geometry type {}').format(geomType))
fields = vector.combineVectorFields(vlayerA, vlayerB)
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields,
geomType, vproviderA.crs())
outFeat = QgsFeature()
index = vector.spatialindex(vlayerB)
selectionA = vector.features(vlayerA)
total = 100.0 / len(selectionA)
for current, inFeatA in enumerate(selectionA):
progress.setPercentage(int(current * total))
geom = QgsGeometry(inFeatA.geometry())
atMapA = inFeatA.attributes()
intersects = index.intersects(geom.boundingBox())
for i in intersects:
request = QgsFeatureRequest().setFilterFid(i)
inFeatB = vlayerB.getFeatures(request).next()
tmpGeom = QgsGeometry(inFeatB.geometry())
if geom.intersects(tmpGeom):
atMapB = inFeatB.attributes()
int_geom = QgsGeometry(geom.intersection(tmpGeom))
if int_geom.wkbType() == QGis.WKBUnknown or QgsWKBTypes.flatType(int_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection:
int_com = geom.combine(tmpGeom)
int_sym = geom.symDifference(tmpGeom)
int_geom = QgsGeometry(int_com.difference(int_sym))
if int_geom.isGeosEmpty() or not int_geom.isGeosValid():
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
self.tr('GEOS geoprocessing error: One or '
'more input features have invalid '
'geometry.'))
break
try:
if int_geom.wkbType() in wkbTypeGroups[wkbTypeGroups[int_geom.wkbType()]]:
outFeat.setGeometry(int_geom)
attrs = []
attrs.extend(atMapA)
attrs.extend(atMapB)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
except:
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.'))
continue
del writer
示例7: processAlgorithm
def processAlgorithm(self, progress):
layerA = dataobjects.getObjectFromUri(
self.getParameterValue(Difference.INPUT))
layerB = dataobjects.getObjectFromUri(
self.getParameterValue(Difference.OVERLAY))
ignoreInvalid = self.getParameterValue(Difference.IGNORE_INVALID)
geomType = QgsWKBTypes.multiType(QGis.fromOldWkbType(layerA.wkbType()))
writer = self.getOutputFromName(
Difference.OUTPUT).getVectorWriter(layerA.pendingFields(),
geomType,
layerA.crs())
outFeat = QgsFeature()
index = vector.spatialindex(layerB)
selectionA = vector.features(layerA)
total = 100.0 / len(selectionA) if len(selectionA) > 0 else 1
for current, inFeatA in enumerate(selectionA):
add = True
geom = QgsGeometry(inFeatA.geometry())
diff_geom = QgsGeometry(geom)
attrs = inFeatA.attributes()
intersections = index.intersects(geom.boundingBox())
for i in intersections:
request = QgsFeatureRequest().setFilterFid(i)
inFeatB = layerB.getFeatures(request).next()
tmpGeom = QgsGeometry(inFeatB.geometry())
if diff_geom.intersects(tmpGeom):
diff_geom = QgsGeometry(diff_geom.difference(tmpGeom))
if diff_geom.isGeosEmpty():
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature with NULL geometry found.'))
if not diff_geom.isGeosValid():
if ignoreInvalid:
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
self.tr('GEOS geoprocessing error: One or more input features have invalid geometry.'))
add = False
else:
raise GeoAlgorithmExecutionException(self.tr('Features with invalid geometries found. Please fix these errors or specify the "Ignore invalid input features" flag'))
break
if add:
try:
outFeat.setGeometry(diff_geom)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
except:
ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.'))
continue
progress.setPercentage(int(current * total))
del writer
示例8: clip
def clip(layer_to_clip, mask_layer, callback=None):
"""Clip a vector layer with another.
Issue https://github.com/inasafe/inasafe/issues/3186
Note : This algorithm is copied from :
https://github.com/qgis/QGIS/blob/master/python/plugins/processing/algs/
qgis/Clip.py
:param layer_to_clip: The vector layer to clip.
:type layer_to_clip: QgsVectorLayer
:param mask_layer: The vector layer to use for clipping.
:type mask_layer: QgsVectorLayer
:param callback: A function to all to indicate progress. The function
should accept params 'current' (int), 'maximum' (int) and 'step' (str).
Defaults to None.
:type callback: function
:return: The clip vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = clip_steps['output_layer_name']
output_layer_name = output_layer_name % (
layer_to_clip.keywords['layer_purpose'])
processing_step = clip_steps['step_name']
writer = create_memory_layer(
output_layer_name,
layer_to_clip.geometryType(),
layer_to_clip.crs(),
layer_to_clip.fields()
)
writer.startEditing()
# Begin copy/paste from Processing plugin.
# Please follow their code as their code is optimized.
# The code below is not following our coding standards because we want to
# be able to track any diffs from QGIS easily.
# first build up a list of clip geometries
clip_geometries = []
request = QgsFeatureRequest().setSubsetOfAttributes([])
for mask_feature in mask_layer.getFeatures(request):
clip_geometries.append(QgsGeometry(mask_feature.geometry()))
# are we clipping against a single feature? if so,
# we can show finer progress reports
if len(clip_geometries) > 1:
# noinspection PyTypeChecker,PyCallByClass,PyArgumentList
combined_clip_geom = QgsGeometry.unaryUnion(clip_geometries)
single_clip_feature = False
else:
combined_clip_geom = clip_geometries[0]
single_clip_feature = True
# use prepared geometries for faster intersection tests
# noinspection PyArgumentList
engine = QgsGeometry.createGeometryEngine(combined_clip_geom.geometry())
engine.prepareGeometry()
tested_feature_ids = set()
for i, clip_geom in enumerate(clip_geometries):
request = QgsFeatureRequest().setFilterRect(clip_geom.boundingBox())
input_features = [f for f in layer_to_clip.getFeatures(request)]
if not input_features:
continue
if single_clip_feature:
total = 100.0 / len(input_features)
else:
total = 0
for current, in_feat in enumerate(input_features):
if not in_feat.geometry():
continue
if in_feat.id() in tested_feature_ids:
# don't retest a feature we have already checked
continue
tested_feature_ids.add(in_feat.id())
if not engine.intersects(in_feat.geometry().geometry()):
continue
if not engine.contains(in_feat.geometry().geometry()):
cur_geom = in_feat.geometry()
new_geom = combined_clip_geom.intersection(cur_geom)
if new_geom.wkbType() == QgsWKBTypes.Unknown \
or QgsWKBTypes.flatType(
new_geom.geometry().wkbType()) == \
QgsWKBTypes.GeometryCollection:
int_com = in_feat.geometry().combine(new_geom)
int_sym = in_feat.geometry().symDifference(new_geom)
#.........这里部分代码省略.........
示例9: processAlgorithm
def processAlgorithm(self, progress):
vlayerA = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT))
vlayerB = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT2))
ignoreNull = self.getParameterValue(Intersection.IGNORE_NULL)
geomType = QgsWKBTypes.multiType(QGis.fromOldWkbType(vlayerA.wkbType()))
fields = vector.combineVectorFields(vlayerA, vlayerB)
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields,
geomType, vlayerA.crs())
outFeat = QgsFeature()
index = vector.spatialindex(vlayerB)
selectionA = vector.features(vlayerA)
total = 100.0 / len(selectionA) if len(selectionA) > 0 else 1
for current, inFeatA in enumerate(selectionA):
progress.setPercentage(int(current * total))
geom = inFeatA.geometry()
if not geom:
if ignoreNull:
continue
else:
raise GeoAlgorithmExecutionException(
self.tr('Input layer A contains NULL geometries. '
'Please check "Ignore NULL geometries" '
'if you want to run this algorithm anyway.'))
if not geom.isGeosValid():
raise GeoAlgorithmExecutionException(
self.tr('Input layer A contains invalid geometries '
'(feature {}). Unable to complete intersection '
'algorithm.'.format(inFeatA.id())))
atMapA = inFeatA.attributes()
intersects = index.intersects(geom.boundingBox())
for inFeatB in vlayerB.getFeatures(QgsFeatureRequest().setFilterFids(intersects)):
tmpGeom = QgsGeometry(inFeatB.geometry())
if not geom:
if ignoreNull:
continue
else:
raise GeoAlgorithmExecutionException(
self.tr('Input layer B contains NULL geometries. '
'Please check "Ignore NULL geometries" '
'if you want to run this algorithm anyway.'))
if not geom.isGeosValid():
raise GeoAlgorithmExecutionException(
self.tr('Input layer B contains invalid geometries '
'(feature {}). Unable to complete intersection '
'algorithm.'.format(inFeatB.id())))
if geom.intersects(tmpGeom):
atMapB = inFeatB.attributes()
int_geom = QgsGeometry(geom.intersection(tmpGeom))
if int_geom.wkbType() == QGis.WKBUnknown or QgsWKBTypes.flatType(int_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection:
int_com = geom.combine(tmpGeom)
int_geom = QgsGeometry()
if int_com is not None:
int_sym = geom.symDifference(tmpGeom)
if int_sym:
diff_geom = int_com.difference(int_sym)
int_geom = QgsGeometry(diff_geom)
if int_geom.isGeosEmpty() or not int_geom.isGeosValid():
raise GeoAlgorithmExecutionException(
self.tr('GEOS geoprocessing error: One or '
'more input features have invalid '
'geometry.'))
try:
if int_geom.wkbType() in wkbTypeGroups[wkbTypeGroups[int_geom.wkbType()]]:
outFeat.setGeometry(int_geom)
attrs = []
attrs.extend(atMapA)
attrs.extend(atMapB)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
except:
raise GeoAlgorithmExecutionException(
self.tr('Feature geometry error: one or '
'more output features ignored due '
'to invalid geometry.'))
del writer
示例10: union
#.........这里部分代码省略.........
_write_feature(at_map_a, geom, writer, not_null_field_index)
except:
# This really shouldn't happen, as we haven't
# edited the input geom at all
LOGGER.debug(
tr('Feature geometry error: One or more output features '
'ignored due to invalid geometry.'))
else:
request = QgsFeatureRequest().setFilterFids(intersects)
engine = QgsGeometry.createGeometryEngine(geom.geometry())
engine.prepareGeometry()
for in_feat_b in union_b.getFeatures(request):
count += 1
at_map_b = in_feat_b.attributes()
tmp_geom = geometry_checker(in_feat_b.geometry())
if engine.intersects(tmp_geom.geometry()):
int_geom = geometry_checker(geom.intersection(tmp_geom))
list_intersecting_b.append(QgsGeometry(tmp_geom))
if not int_geom:
# There was a problem creating the intersection
# LOGGER.debug(
# tr('GEOS geoprocessing error: One or more input '
# 'features have invalid geometry.'))
pass
int_geom = QgsGeometry()
else:
int_geom = QgsGeometry(int_geom)
if int_geom.wkbType() == QgsWKBTypes.Unknown\
or QgsWKBTypes.flatType(
int_geom.geometry().wkbType()) == \
QgsWKBTypes.GeometryCollection:
# Intersection produced different geometry types
temp_list = int_geom.asGeometryCollection()
for i in temp_list:
if i.type() == geom.type():
int_geom = QgsGeometry(geometry_checker(i))
try:
_write_feature(
at_map_a + at_map_b,
int_geom,
writer,
not_null_field_index,
)
except:
LOGGER.debug(
tr('Feature geometry error: One or '
'more output features ignored due '
'to invalid geometry.'))
else:
# Geometry list: prevents writing error
# in geometries of different types
# produced by the intersection
# fix #3549
if int_geom.wkbType() in wkb_type_groups[
wkb_type_groups[int_geom.wkbType()]]:
try:
_write_feature(
at_map_a + at_map_b,
int_geom,
writer,
示例11: processAlgorithm
def processAlgorithm(self, progress):
vlayerA = dataobjects.getObjectFromUri(self.getParameterValue(Union.INPUT))
vlayerB = dataobjects.getObjectFromUri(self.getParameterValue(Union.INPUT2))
vproviderA = vlayerA.dataProvider()
geomType = vproviderA.geometryType()
fields = vector.combineVectorFields(vlayerA, vlayerB)
writer = self.getOutputFromName(Union.OUTPUT).getVectorWriter(fields,
geomType, vproviderA.crs())
inFeatA = QgsFeature()
inFeatB = QgsFeature()
outFeat = QgsFeature()
indexA = vector.spatialindex(vlayerB)
indexB = vector.spatialindex(vlayerA)
count = 0
nElement = 0
featuresA = vector.features(vlayerA)
nFeat = len(featuresA)
for inFeatA in featuresA:
progress.setPercentage(nElement / float(nFeat) * 50)
nElement += 1
lstIntersectingB = []
geom = QgsGeometry(inFeatA.geometry())
atMapA = inFeatA.attributes()
intersects = indexA.intersects(geom.boundingBox())
if len(intersects) < 1:
try:
outFeat.setGeometry(geom)
outFeat.setAttributes(atMapA)
writer.addFeature(outFeat)
except:
# This really shouldn't happen, as we haven't
# edited the input geom at all
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.'))
else:
for id in intersects:
count += 1
request = QgsFeatureRequest().setFilterFid(id)
inFeatB = vlayerB.getFeatures(request).next()
atMapB = inFeatB.attributes()
tmpGeom = QgsGeometry(inFeatB.geometry())
if geom.intersects(tmpGeom):
int_geom = geom.intersection(tmpGeom)
lstIntersectingB.append(tmpGeom)
if int_geom is None:
# There was a problem creating the intersection
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('GEOS geoprocessing error: One or more input features have invalid geometry.'))
int_geom = QgsGeometry()
else:
int_geom = QgsGeometry(int_geom)
if int_geom.wkbType() == Qgis.WKBUnknown or QgsWKBTypes.flatType(int_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection:
# Intersection produced different geomety types
temp_list = int_geom.asGeometryCollection()
for i in temp_list:
if i.type() == geom.type():
int_geom = QgsGeometry(i)
try:
outFeat.setGeometry(int_geom)
outFeat.setAttributes(atMapA + atMapB)
writer.addFeature(outFeat)
except:
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.'))
else:
# Geometry list: prevents writing error
# in geometries of different types
# produced by the intersection
# fix #3549
if int_geom.wkbType() in wkbTypeGroups[wkbTypeGroups[int_geom.wkbType()]]:
try:
outFeat.setGeometry(int_geom)
outFeat.setAttributes(atMapA + atMapB)
writer.addFeature(outFeat)
except:
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.'))
# the remaining bit of inFeatA's geometry
# if there is nothing left, this will just silently fail and we're good
diff_geom = QgsGeometry(geom)
if len(lstIntersectingB) != 0:
intB = QgsGeometry.unaryUnion(lstIntersectingB)
diff_geom = diff_geom.difference(intB)
if diff_geom.isGeosEmpty() or not diff_geom.isGeosValid():
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
self.tr('GEOS geoprocessing error: One or more input features have invalid geometry.'))
if diff_geom.wkbType() == 0 or QgsWKBTypes.flatType(diff_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection:
temp_list = diff_geom.asGeometryCollection()
for i in temp_list:
if i.type() == geom.type():
diff_geom = QgsGeometry(i)
try:
#.........这里部分代码省略.........
示例12: processAlgorithm
def processAlgorithm(self, progress):
layerA = dataobjects.getObjectFromUri(
self.getParameterValue(Clip.INPUT))
layerB = dataobjects.getObjectFromUri(
self.getParameterValue(Clip.OVERLAY))
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
layerA.pendingFields(),
layerA.dataProvider().geometryType(),
layerA.dataProvider().crs())
inFeatA = QgsFeature()
inFeatB = QgsFeature()
outFeat = QgsFeature()
index = vector.spatialindex(layerB)
selectionA = vector.features(layerA)
current = 0
total = 100.0 / float(len(selectionA))
for inFeatA in selectionA:
geom = QgsGeometry(inFeatA.geometry())
attrs = inFeatA.attributes()
intersects = index.intersects(geom.boundingBox())
first = True
found = False
if len(intersects) > 0:
for i in intersects:
layerB.getFeatures(
QgsFeatureRequest().setFilterFid(i)).nextFeature(
inFeatB)
tmpGeom = QgsGeometry(inFeatB.geometry())
if tmpGeom.intersects(geom):
found = True
if first:
outFeat.setGeometry(QgsGeometry(tmpGeom))
first = False
else:
try:
cur_geom = QgsGeometry(outFeat.geometry())
new_geom = QgsGeometry(
cur_geom.combine(tmpGeom))
outFeat.setGeometry(QgsGeometry(new_geom))
except:
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
self.tr('GEOS geoprocessing error: One or '
'more input features have invalid '
'geometry.'))
break
if found:
try:
cur_geom = QgsGeometry(outFeat.geometry())
new_geom = QgsGeometry(geom.intersection(cur_geom))
if new_geom.wkbType() == QGis.WKBUnknown or QgsWKBTypes.flatType(new_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection:
int_com = QgsGeometry(geom.combine(cur_geom))
int_sym = QgsGeometry(geom.symDifference(cur_geom))
new_geom = QgsGeometry(int_com.difference(int_sym))
try:
outFeat.setGeometry(new_geom)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
except:
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
self.tr('Feature geometry error: One or more '
'output features ignored due to '
'invalid geometry.'))
continue
except:
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
self.tr('GEOS geoprocessing error: One or more '
'input features have invalid geometry.'))
continue
current += 1
progress.setPercentage(int(current * total))
del writer
示例13: processAlgorithm
def processAlgorithm(self, progress):
vlayerA = dataobjects.getObjectFromUri(self.getParameterValue(Union.INPUT))
vlayerB = dataobjects.getObjectFromUri(self.getParameterValue(Union.INPUT2))
geomType = vlayerA.wkbType()
fields = vector.combineVectorFields(vlayerA, vlayerB)
writer = self.getOutputFromName(Union.OUTPUT).getVectorWriter(fields,
geomType,
vlayerA.crs())
inFeatA = QgsFeature()
inFeatB = QgsFeature()
outFeat = QgsFeature()
indexA = vector.spatialindex(vlayerB)
indexB = vector.spatialindex(vlayerA)
count = 0
nElement = 0
featuresA = vector.features(vlayerA)
nFeat = len(featuresA) if len(featuresA) > 0 else 1
for inFeatA in featuresA:
progress.setPercentage(nElement / float(nFeat) * 50)
nElement += 1
lstIntersectingB = []
geom = QgsGeometry(inFeatA.geometry())
atMapA = inFeatA.attributes()
intersects = indexA.intersects(geom.boundingBox())
if len(intersects) < 1:
try:
outFeat.setGeometry(geom)
outFeat.setAttributes(atMapA)
writer.addFeature(outFeat)
except:
# This really shouldn't happen, as we haven't
# edited the input geom at all
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.'))
else:
for id in intersects:
count += 1
request = QgsFeatureRequest().setFilterFid(id)
inFeatB = vlayerB.getFeatures(request).next()
atMapB = inFeatB.attributes()
tmpGeom = QgsGeometry(inFeatB.geometry())
if geom.intersects(tmpGeom):
int_geom = geom.intersection(tmpGeom)
lstIntersectingB.append(tmpGeom)
if int_geom is None:
# There was a problem creating the intersection
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('GEOS geoprocessing error: One or more input features have invalid geometry.'))
int_geom = QgsGeometry()
else:
int_geom = QgsGeometry(int_geom)
# TODO: the result may have a different dimension (e.g. intersection of two polygons may result in a single point)
# or the result may be a collection of geometries (e.g. intersection of two polygons results in three polygons and one linestring).
# We need to filter out all acceptable geometries into a single (possibly multi-part) geometry - and we need
# to do it consistently also in the code further below
if int_geom.wkbType() == QGis.WKBUnknown or QgsWKBTypes.flatType(int_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection:
# Intersection produced different geomety types
temp_list = int_geom.asGeometryCollection()
for i in temp_list:
if i.type() == geom.type():
int_geom = QgsGeometry(i)
try:
outFeat.setGeometry(int_geom)
outFeat.setAttributes(atMapA + atMapB)
writer.addFeature(outFeat)
except:
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.'))
else:
# Geometry list: prevents writing error
# in geometries of different types
# produced by the intersection
# fix #3549
if int_geom.wkbType() in wkbTypeGroups[wkbTypeGroups[int_geom.wkbType()]]:
try:
outFeat.setGeometry(int_geom)
outFeat.setAttributes(atMapA + atMapB)
writer.addFeature(outFeat)
except:
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.'))
# the remaining bit of inFeatA's geometry
# if there is nothing left, this will just silently fail and we're good
diff_geom = QgsGeometry(geom)
if len(lstIntersectingB) != 0:
intB = QgsGeometry.unaryUnion(lstIntersectingB)
diff_geom = diff_geom.difference(intB)
if diff_geom is None:
ProcessingLog.addToLog(ProcessingLog.LOG_INFO,
self.tr('GEOS geoprocessing error: One or more input features have invalid geometry.'))
diff_geom = QgsGeometry()
if diff_geom.isGeosEmpty() or not diff_geom.isGeosValid():
ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
#.........这里部分代码省略.........
示例14: processAlgorithm
def processAlgorithm(self, progress):
vlayerA = dataobjects.getObjectFromUri(self.getParameterValue(Union.INPUT))
vlayerB = dataobjects.getObjectFromUri(self.getParameterValue(Union.INPUT2))
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
vproviderA = vlayerA.dataProvider()
fields = vector.combineVectorFields(vlayerA, vlayerB)
names = [field.name() for field in fields]
ProcessingLog.addToLog(ProcessingLog.LOG_INFO, unicode(names))
writer = self.getOutputFromName(Union.OUTPUT).getVectorWriter(fields,
vproviderA.geometryType(), vproviderA.crs())
inFeatA = QgsFeature()
inFeatB = QgsFeature()
outFeat = QgsFeature()
indexA = vector.spatialindex(vlayerB)
indexB = vector.spatialindex(vlayerA)
count = 0
nElement = 0
featuresA = vector.features(vlayerA)
nFeat = len(featuresA)
for inFeatA in featuresA:
progress.setPercentage(nElement / float(nFeat) * 50)
nElement += 1
lstIntersectingB = []
geom = QgsGeometry(inFeatA.geometry())
atMapA = inFeatA.attributes()
intersects = indexA.intersects(geom.boundingBox())
if len(intersects) < 1:
try:
outFeat.setGeometry(geom)
outFeat.setAttributes(atMapA)
writer.addFeature(outFeat)
except:
# This really shouldn't happen, as we haven't
# edited the input geom at all
raise GeoAlgorithmExecutionException(
self.tr('Feature exception while computing union'))
else:
for id in intersects:
count += 1
request = QgsFeatureRequest().setFilterFid(id)
inFeatB = vlayerB.getFeatures(request).next()
atMapB = inFeatB.attributes()
tmpGeom = QgsGeometry(inFeatB.geometry())
if geom.intersects(tmpGeom):
int_geom = geom.intersection(tmpGeom)
lstIntersectingB.append(tmpGeom)
if int_geom is None:
# There was a problem creating the intersection
raise GeoAlgorithmExecutionException(
self.tr('Geometry exception while computing '
'intersection'))
else:
int_geom = QgsGeometry(int_geom)
if int_geom.wkbType() == QGis.WKBUnknown or QgsWKBTypes.flatType(int_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection:
# Intersection produced different geomety types
temp_list = int_geom.asGeometryCollection()
for i in temp_list:
if i.type() == geom.type():
int_geom = QgsGeometry(i)
try:
outFeat.setGeometry(int_geom)
attrs = []
attrs.extend(atMapA)
attrs.extend(atMapB)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
except Exception as err:
raise GeoAlgorithmExecutionException(
self.tr('Feature exception while computing union'))
try:
# the remaining bit of inFeatA's geometry
# if there is nothing left, this will just silently fail and we're good
diff_geom = QgsGeometry(geom)
if len(lstIntersectingB) != 0:
intB = QgsGeometry.unaryUnion(lstIntersectingB)
diff_geom = diff_geom.difference(intB)
if diff_geom.wkbType() == 0 or QgsWKBTypes.flatType(int_geom.geometry().wkbType()) == QgsWKBTypes.GeometryCollection:
temp_list = diff_geom.asGeometryCollection()
for i in temp_list:
if i.type() == geom.type():
diff_geom = QgsGeometry(i)
outFeat.setGeometry(diff_geom)
outFeat.setAttributes(atMapA)
writer.addFeature(outFeat)
except Exception as err:
raise GeoAlgorithmExecutionException(
self.tr('Feature exception while computing union'))
length = len(vproviderA.fields())
featuresA = vector.features(vlayerB)
nFeat = len(featuresA)
#.........这里部分代码省略.........
示例15: intersection
def intersection(source, mask, callback=None):
"""Intersect two layers.
Issue https://github.com/inasafe/inasafe/issues/3186
Note : This algorithm is copied from :
https://github.com/qgis/QGIS/blob/master/python/plugins/processing/algs/
qgis/Intersection.py
:param source: The vector layer to clip.
:type source: QgsVectorLayer
:param mask: The vector layer to use for clipping.
:type mask: QgsVectorLayer
:param callback: A function to all to indicate progress. The function
should accept params 'current' (int), 'maximum' (int) and 'step' (str).
Defaults to None.
:type callback: function
:return: The clip vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = intersection_steps['output_layer_name']
output_layer_name = output_layer_name % (
source.keywords['layer_purpose'])
processing_step = intersection_steps['step_name']
fields = source.fields()
fields.extend(mask.fields())
writer = create_memory_layer(
output_layer_name,
source.geometryType(),
source.crs(),
fields
)
writer.startEditing()
# Begin copy/paste from Processing plugin.
# Please follow their code as their code is optimized.
# The code below is not following our coding standards because we want to
# be able to track any diffs from QGIS easily.
out_feature = QgsFeature()
index = create_spatial_index(mask)
# Todo callback
# total = 100.0 / len(selectionA)
for current, in_feature in enumerate(source.getFeatures()):
# progress.setPercentage(int(current * total))
geom = in_feature.geometry()
attributes = in_feature.attributes()
intersects = index.intersects(geom.boundingBox())
for i in intersects:
request = QgsFeatureRequest().setFilterFid(i)
feature_mask = next(mask.getFeatures(request))
tmp_geom = feature_mask.geometry()
if geom.intersects(tmp_geom):
mask_attributes = feature_mask.attributes()
int_geom = QgsGeometry(geom.intersection(tmp_geom))
if int_geom.wkbType() == QgsWKBTypes.Unknown\
or QgsWKBTypes.flatType(
int_geom.geometry().wkbType()) ==\
QgsWKBTypes.GeometryCollection:
int_com = geom.combine(tmp_geom)
int_geom = QgsGeometry()
if int_com:
int_sym = geom.symDifference(tmp_geom)
int_geom = QgsGeometry(int_com.difference(int_sym))
if int_geom.isGeosEmpty() or not int_geom.isGeosValid():
# LOGGER.debug(
# tr('GEOS geoprocessing error: One or more input '
# 'features have invalid geometry.'))
pass
try:
geom_types = wkb_type_groups[
wkb_type_groups[int_geom.wkbType()]]
if int_geom.wkbType() in geom_types:
if int_geom.type() == source.geometryType():
# We got some features which have not the same
# kind of geometry. We want to skip them.
out_feature.setGeometry(int_geom)
attrs = []
attrs.extend(attributes)
attrs.extend(mask_attributes)
out_feature.setAttributes(attrs)
writer.addFeature(out_feature)
except:
LOGGER.debug(
tr('Feature geometry error: One or more output '
'features ignored due to invalid geometry.'))
continue
# End copy/paste from Processing plugin.
writer.commitChanges()
#.........这里部分代码省略.........