Skip to content
Permalink
Browse files

Port Polygonize to new API

  • Loading branch information
nyalldawson committed Jul 27, 2017
1 parent 504cc1f commit 9b3f8a8b09cb54dfde1a5b1190e270e7993d83b3
@@ -25,30 +25,24 @@

__revision__ = '$Format:%H$'

from qgis.PyQt.QtCore import QVariant
from qgis.core import (QgsApplication,
QgsFields,
QgsField,
from qgis.core import (QgsFields,
QgsFeature,
QgsFeatureSink,
QgsGeometry,
QgsWkbTypes,
QgsFeatureRequest,
QgsProcessingUtils)
QgsProcessing,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterBoolean,
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 ParameterBoolean
from processing.core.outputs import OutputVector
from processing.tools import dataobjects


class Polygonize(QgisAlgorithm):

INPUT = 'INPUT'
OUTPUT = 'OUTPUT'
FIELDS = 'FIELDS'
GEOMETRY = 'GEOMETRY'
KEEP_FIELDS = 'KEEP_FIELDS'

def tags(self):
return self.tr('create,lines,polygons,convert').split(',')
@@ -60,13 +54,11 @@ def __init__(self):
super().__init__()

def initAlgorithm(self, config=None):
self.addParameter(ParameterVector(self.INPUT,
self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE]))
self.addParameter(ParameterBoolean(self.FIELDS,
self.tr('Keep table structure of line layer'), False))
self.addParameter(ParameterBoolean(self.GEOMETRY,
self.tr('Create geometry columns'), True))
self.addOutput(OutputVector(self.OUTPUT, self.tr('Polygons from lines'), datatype=[dataobjects.TYPE_VECTOR_POLYGON]))
self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
self.tr('Input layer'), types=[QgsProcessing.TypeVectorLine]))
self.addParameter(QgsProcessingParameterBoolean(self.KEEP_FIELDS,
self.tr('Keep table structure of line layer'), defaultValue=False, optional=True))
self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT, self.tr('Polygons from lines'), QgsProcessing.TypeVectorPolygon))

def name(self):
return 'polygonize'
@@ -75,22 +67,23 @@ def displayName(self):
return self.tr('Polygonize')

def processAlgorithm(self, parameters, context, feedback):
vlayer = QgsProcessingUtils.mapLayerFromString(self.getParameterValue(self.INPUT), context)
output = self.getOutputFromName(self.OUTPUT)
if self.getParameterValue(self.FIELDS):
fields = vlayer.fields()
source = self.parameterAsSource(parameters, self.INPUT, context)
if self.parameterAsBool(parameters, self.KEEP_FIELDS, context):
fields = source.fields()
else:
fields = QgsFields()
if self.getParameterValue(self.GEOMETRY):
fieldsCount = fields.count()
fields.append(QgsField('area', QVariant.Double, 'double', 16, 2))
fields.append(QgsField('perimeter', QVariant.Double,
'double', 16, 2))

(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
fields, QgsWkbTypes.Polygon, source.sourceCrs())

allLinesList = []
features = QgsProcessingUtils.getFeatures(vlayer, context, QgsFeatureRequest().setSubsetOfAttributes([]))
features = source.getFeatures(QgsFeatureRequest().setSubsetOfAttributes([]))
feedback.pushInfo(self.tr('Processing lines...'))
total = 40.0 / QgsProcessingUtils.featureCount(vlayer, context)
total = (40.0 / source.featureCount()) if source.featureCount() else 1
for current, inFeat in enumerate(features):
if feedback.isCanceled():
break

if inFeat.geometry():
allLinesList.append(inFeat.geometry())
feedback.setProgress(int(current * total))
@@ -99,24 +92,27 @@ def processAlgorithm(self, parameters, context, feedback):

feedback.pushInfo(self.tr('Noding lines...'))
allLines = QgsGeometry.unaryUnion(allLinesList)
if feedback.isCanceled():
return {}

feedback.setProgress(45)
feedback.pushInfo(self.tr('Polygonizing...'))
polygons = QgsGeometry.polygonize([allLines])
if polygons.isEmpty():
raise GeoAlgorithmExecutionException(self.tr('No polygons were created!'))
feedback.reportError(self.tr('No polygons were created!'))
feedback.setProgress(50)

feedback.pushInfo('Saving polygons...')
writer = output.getVectorWriter(fields, QgsWkbTypes.Polygon, vlayer.crs(), context)
total = 50.0 / polygons.geometry().numGeometries()
for i in range(polygons.geometry().numGeometries()):
outFeat = QgsFeature()
geom = QgsGeometry(polygons.geometry().geometryN(i).clone())
outFeat.setGeometry(geom)
if self.getParameterValue(self.GEOMETRY):
outFeat.setAttributes([None] * fieldsCount + [geom.geometry().area(),
geom.geometry().perimeter()])
writer.addFeature(outFeat, QgsFeatureSink.FastInsert)
feedback.setProgress(50 + int(current * total))
del writer
if not polygons.isEmpty():
feedback.pushInfo('Saving polygons...')
total = 50.0 / polygons.geometry().numGeometries()
for i in range(polygons.geometry().numGeometries()):
if feedback.isCanceled():
break

outFeat = QgsFeature()
geom = QgsGeometry(polygons.geometry().geometryN(i).clone())
outFeat.setGeometry(geom)
sink.addFeature(outFeat, QgsFeatureSink.FastInsert)
feedback.setProgress(50 + int(current * total))

return {self.OUTPUT: dest_id}
@@ -82,6 +82,7 @@
from .PointsInPolygon import PointsInPolygon
from .PointsLayerFromTable import PointsLayerFromTable
from .PoleOfInaccessibility import PoleOfInaccessibility
from .Polygonize import Polygonize
from .PolygonsToLines import PolygonsToLines
from .PostGISExecuteSQL import PostGISExecuteSQL
from .RandomExtract import RandomExtract
@@ -166,7 +167,6 @@
# from .TinInterpolation import TinInterpolation
# from .ExtractSpecificNodes import ExtractSpecificNodes
# from .RasterCalculator import RasterCalculator
# from .Polygonize import Polygonize
# from .ExecuteSQL import ExecuteSQL
# from .FindProjection import FindProjection
# from .TopoColors import TopoColor
@@ -216,7 +216,6 @@ def getAlgs(self):
# IdwInterpolation(), TinInterpolation(),
# ExtractSpecificNodes(),
# RasterCalculator(),
# Polygonize(),
# ExecuteSQL(), FindProjection(),
# TopoColor(), EliminateSelection()
# ]
@@ -262,6 +261,7 @@ def getAlgs(self):
PointsInPolygon(),
PointsLayerFromTable(),
PoleOfInaccessibility(),
Polygonize(),
PolygonsToLines(),
PostGISExecuteSQL(),
RandomExtract(),
@@ -12,15 +12,5 @@
<ExtentYMin>-0.31429</ExtentYMin>
<ExtentYMax>0.60000</ExtentYMax>
</DatasetSpecificInfo>
<PropertyDefn>
<Name>area</Name>
<ElementPath>area</ElementPath>
<Type>Real</Type>
</PropertyDefn>
<PropertyDefn>
<Name>perimeter</Name>
<ElementPath>perimeter</ElementPath>
<Type>Real</Type>
</PropertyDefn>
</GMLFeatureClass>
</GMLFeatureClassList>
@@ -14,22 +14,16 @@
<gml:featureMember>
<ogr:polygonize fid="polygonize.0">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>-0.6,0.2 0.0,0.2 0.6,0.2 -0.6,-0.314285714285714 -0.6,0.2</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:area>0.31</ogr:area>
<ogr:perimeter>3.02</ogr:perimeter>
</ogr:polygonize>
</gml:featureMember>
<gml:featureMember>
<ogr:polygonize fid="polygonize.1">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>0.0,0.2 -0.6,0.2 -0.6,0.4 0.0,0.4 0.0,0.2</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:area>0.12</ogr:area>
<ogr:perimeter>1.60</ogr:perimeter>
</ogr:polygonize>
</gml:featureMember>
<gml:featureMember>
<ogr:polygonize fid="polygonize.2">
<ogr:geometryProperty><gml:Polygon srsName="EPSG:4326"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>-0.6,0.4 -0.6,0.6 0.0,0.6 0.0,0.4 -0.6,0.4</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty>
<ogr:area>0.12</ogr:area>
<ogr:perimeter>1.60</ogr:perimeter>
</ogr:polygonize>
</gml:featureMember>
</ogr:FeatureCollection>
@@ -2392,18 +2392,17 @@ tests:
name: expected/valid.gml
type: vector

# - algorithm: qgis:polygonize
# name: Polygonize
# params:
# FIELDS: false
# GEOMETRY: true
# INPUT:
# name: custom/polygonize_lines.gml
# type: vector
# results:
# OUTPUT:
# name: expected/polygonize.gml
# type: vector
- algorithm: qgis:polygonize
name: Polygonize
params:
KEEP_FIELDS: false
INPUT:
name: custom/polygonize_lines.gml
type: vector
results:
OUTPUT:
name: expected/polygonize.gml
type: vector

- algorithm: qgis:voronoipolygons
name: Standard voronoi

0 comments on commit 9b3f8a8

Please sign in to comment.
You can’t perform that action at this time.