Skip to content

Commit

Permalink
Port Eliminate Selection to new API
Browse files Browse the repository at this point in the history
  • Loading branch information
nyalldawson committed Aug 5, 2017
1 parent 7132faa commit 03bae59
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 29 deletions.
68 changes: 41 additions & 27 deletions python/plugins/processing/algs/qgis/EliminateSelection.py
Expand Up @@ -34,15 +34,14 @@
QgsFeature,
QgsFeatureSink,
QgsGeometry,
QgsMessageLog,
QgsProcessingUtils)
QgsProcessingException,
QgsProcessingUtils,
QgsProcessingParameterVectorLayer,
QgsProcessingParameterEnum,
QgsProcessing,
QgsProcessingParameterFeatureSink)

from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from processing.core.parameters import ParameterVector
from processing.core.parameters import ParameterSelection
from processing.core.outputs import OutputVector
from processing.tools import dataobjects

pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]

Expand All @@ -67,16 +66,17 @@ def __init__(self):
super().__init__()

def initAlgorithm(self, config=None):
self.modes = [self.tr('Largest area'),
self.modes = [self.tr('Largest Area'),
self.tr('Smallest Area'),
self.tr('Largest common boundary')]
self.tr('Largest Common Boundary')]

self.addParameter(ParameterVector(self.INPUT,
self.tr('Input layer'), [dataobjects.TYPE_VECTOR_POLYGON]))
self.addParameter(ParameterSelection(self.MODE,
self.tr('Merge selection with the neighbouring polygon with the'),
self.modes))
self.addOutput(OutputVector(self.OUTPUT, self.tr('Eliminated'), datatype=[dataobjects.TYPE_VECTOR_POLYGON]))
self.addParameter(QgsProcessingParameterVectorLayer(self.INPUT,
self.tr('Input layer'), [QgsProcessing.TypeVectorPolygon]))
self.addParameter(QgsProcessingParameterEnum(self.MODE,
self.tr('Merge selection with the neighbouring polygon with the'),
options=self.modes))

self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT, self.tr('Eliminated'), QgsProcessing.TypeVectorPolygon))

def name(self):
return 'eliminateselectedpolygons'
Expand All @@ -85,29 +85,32 @@ def displayName(self):
return self.tr('Eliminate selected polygons')

def processAlgorithm(self, parameters, context, feedback):
inLayer = QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.INPUT), context)
boundary = self.getParameterValue(self.MODE) == self.MODE_BOUNDARY
smallestArea = self.getParameterValue(self.MODE) == self.MODE_SMALLEST_AREA
inLayer = self.parameterAsVectorLayer(parameters, self.INPUT, context)
boundary = self.parameterAsEnum(parameters, self.MODE, context) == self.MODE_BOUNDARY
smallestArea = self.parameterAsEnum(parameters, self.MODE, context) == self.MODE_SMALLEST_AREA

if inLayer.selectedFeatureCount() == 0:
QgsMessageLog.logMessage(self.tr('{0}: (No selection in input layer "{1}")').format(self.displayName(), self.getParameterValue(self.INPUT)),
self.tr('Processing'), QgsMessageLog.WARNING)
feedback.reportError(self.tr('{0}: (No selection in input layer "{1}")').format(self.displayName(), parameters[self.INPUT]))

featToEliminate = []
selFeatIds = inLayer.selectedFeatureIds()
output = self.getOutputFromName(self.OUTPUT)
writer = output.getVectorWriter(inLayer.fields(), inLayer.wkbType(), inLayer.crs(), context)

(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
inLayer.fields(), inLayer.wkbType(), inLayer.sourceCrs())

for aFeat in inLayer.getFeatures():
if feedback.isCanceled():
break

if aFeat.id() in selFeatIds:
# Keep references to the features to eliminate
featToEliminate.append(aFeat)
else:
# write the others to output
writer.addFeature(aFeat, QgsFeatureSink.FastInsert)
sink.addFeature(aFeat, QgsFeatureSink.FastInsert)

# Delete all features to eliminate in processLayer
processLayer = output.layer
processLayer = QgsProcessingUtils.mapLayerFromString(dest_id, context)
processLayer.startEditing()

# ANALYZE
Expand All @@ -129,6 +132,9 @@ def processAlgorithm(self, parameters, context, feedback):

# Iterate over the polygons to eliminate
for i in range(len(featToEliminate)):
if feedback.isCanceled():
break

feat = featToEliminate.pop()
geom2Eliminate = feat.geometry()
bbox = geom2Eliminate.boundingBox()
Expand All @@ -145,6 +151,9 @@ def processAlgorithm(self, parameters, context, feedback):
engine.prepareGeometry()

while fit.nextFeature(selFeat):
if feedback.isCanceled():
break

selGeom = selFeat.geometry()

if engine.intersects(selGeom.geometry()):
Expand Down Expand Up @@ -193,7 +202,7 @@ def processAlgorithm(self, parameters, context, feedback):
if processLayer.changeGeometry(mergeWithFid, newGeom):
madeProgress = True
else:
raise GeoAlgorithmExecutionException(
raise QgsProcessingException(
self.tr('Could not replace geometry of feature with id {0}').format(mergeWithFid))

start = start + add
Expand All @@ -207,7 +216,12 @@ def processAlgorithm(self, parameters, context, feedback):

# End while
if not processLayer.commitChanges():
raise GeoAlgorithmExecutionException(self.tr('Could not commit changes'))
raise QgsProcessingException(self.tr('Could not commit changes'))

for feature in featNotEliminated:
writer.addFeature(feature, QgsFeatureSink.FastInsert)
if feedback.isCanceled():
break

sink.addFeature(feature, QgsFeatureSink.FastInsert)

return {self.OUTPUT: dest_id}
4 changes: 2 additions & 2 deletions python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py
Expand Up @@ -60,6 +60,7 @@
from .Difference import Difference
from .DropGeometry import DropGeometry
from .DropMZValues import DropMZValues
from .EliminateSelection import EliminateSelection
from .EquivalentNumField import EquivalentNumField
from .Explode import Explode
from .ExportGeometryInfo import ExportGeometryInfo
Expand Down Expand Up @@ -170,7 +171,6 @@
# from .RasterCalculator import RasterCalculator
# from .ExecuteSQL import ExecuteSQL
# from .FindProjection import FindProjection
# from .EliminateSelection import EliminateSelection

pluginPath = os.path.normpath(os.path.join(
os.path.split(os.path.dirname(__file__))[0], os.pardir))
Expand Down Expand Up @@ -206,7 +206,6 @@ def getAlgs(self):
# IdwInterpolation(), TinInterpolation(),
# RasterCalculator(),
# ExecuteSQL(), FindProjection(),
# EliminateSelection()
# ]
algs = [AddTableField(),
Aspect(),
Expand All @@ -228,6 +227,7 @@ def getAlgs(self):
Difference(),
DropGeometry(),
DropMZValues(),
EliminateSelection(),
EquivalentNumField(),
Explode(),
ExportGeometryInfo(),
Expand Down

0 comments on commit 03bae59

Please sign in to comment.