Nyall Dawson 1e13d733c2 Move declaration of algorithm parameters/outputs to a new virtual
initAlgorithm() method

This allows 2 benefits:
- algorithms can be subclassed and have subclasses add additional
parameters/outputs to the algorithm. With the previous approach
of declaring parameters/outputs in the constructor, it's not
possible to call virtual methods to add additional parameters/
outputs (since you can't call virtual methods from a constructor).

- initAlgorithm takes a variant map argument, allowing the algorithm
to dynamically adjust its declared parameters and outputs according
to this configuration map. This potentially allows model algorithms which
can be configured to have variable numbers of parameters and
outputs at run time. E.g. a "router" algorithm which directs
features to one of any number of output sinks depending on some
user configured criteria.
2017-07-10 16:31:14 +10:00

123 lines
5.1 KiB
Python

# -*- coding: utf-8 -*-
"""
***************************************************************************
Polygonize.py
---------------------
Date : March 2013
Copyright : (C) 2013 by Piotr Pociask
Email : ppociask at o2 dot pl
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Piotr Pociask'
__date__ = 'March 2013'
__copyright__ = '(C) 2013, Piotr Pociask'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.PyQt.QtCore import QVariant
from qgis.core import (QgsApplication,
QgsFields,
QgsField,
QgsFeature,
QgsFeatureSink,
QgsGeometry,
QgsWkbTypes,
QgsFeatureRequest,
QgsProcessingUtils)
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'
def tags(self):
return self.tr('create,lines,polygons,convert').split(',')
def group(self):
return self.tr('Vector geometry tools')
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]))
def name(self):
return 'polygonize'
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()
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))
allLinesList = []
features = QgsProcessingUtils.getFeatures(vlayer, context, QgsFeatureRequest().setSubsetOfAttributes([]))
feedback.pushInfo(self.tr('Processing lines...'))
total = 40.0 / QgsProcessingUtils.featureCount(vlayer, context)
for current, inFeat in enumerate(features):
if inFeat.geometry():
allLinesList.append(inFeat.geometry())
feedback.setProgress(int(current * total))
feedback.setProgress(40)
feedback.pushInfo(self.tr('Noding lines...'))
allLines = QgsGeometry.unaryUnion(allLinesList)
feedback.setProgress(45)
feedback.pushInfo(self.tr('Polygonizing...'))
polygons = QgsGeometry.polygonize([allLines])
if polygons.isEmpty():
raise GeoAlgorithmExecutionException(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