Skip to content

Commit

Permalink
[processing] Rework centroid algorithm to handle non-polygon layers
Browse files Browse the repository at this point in the history
The existing polygoncentroids algorithm has been deprecated
(and hidden from the toolbox), and a new, generic centroids
algorithm added which works with lines and multipoints
  • Loading branch information
nyalldawson committed Aug 11, 2016
1 parent d0faca1 commit e9423dc
Show file tree
Hide file tree
Showing 18 changed files with 595 additions and 23 deletions.
7 changes: 7 additions & 0 deletions python/plugins/processing/algs/help/qgis.yaml
Expand Up @@ -44,6 +44,11 @@ qgis:buildvirtualvector: >

The output virtual layer will not be open in the current project.

qgis:centroids: >
This algorithm creates a new point layer, with points representing the centroid of the geometries in an input layer.

The attributes associated to each point in the output layer are the same ones associated to the original features.

qgis:checkvalidity:
This algorithm performs a validity check on the geometries of a vector layer.

Expand Down Expand Up @@ -306,6 +311,8 @@ qgis:polygoncentroids: >

The attributes associated to each point in the output layer are the same ones associated to the original polygon.

NOTE: This algorithm is deprecated and the generic "centroids" algorithm (which works for line and multi geometry layers) should be used instead.


qgis:polygonfromlayerextent: >
This algorithm takes a vector layer and generate a new one with the minimum bounding box (rectangle with N-S orientation) that covers all the input features.
Expand Down
35 changes: 14 additions & 21 deletions python/plugins/processing/algs/qgis/Centroids.py
Expand Up @@ -29,10 +29,10 @@

from qgis.PyQt.QtGui import QIcon

from qgis.core import Qgis, QgsGeometry, QgsFeature, QgsWkbTypes
from qgis.core import QgsWkbTypes

from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from processing.core.ProcessingLog import ProcessingLog
from processing.core.parameters import ParameterVector
from processing.core.outputs import OutputVector
from processing.tools import dataobjects, vector
Expand All @@ -49,11 +49,11 @@ def getIcon(self):
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'centroids.png'))

def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('Polygon centroids')
self.name, self.i18n_name = self.trAlgorithm('Centroids')
self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools')

self.addParameter(ParameterVector(self.INPUT_LAYER,
self.tr('Input layer'), [ParameterVector.VECTOR_TYPE_POLYGON]))
self.tr('Input layer'), [ParameterVector.VECTOR_TYPE_ANY]))

self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Centroids')))

Expand All @@ -67,25 +67,18 @@ def processAlgorithm(self, progress):
QgsWkbTypes.Point,
layer.crs())

outFeat = QgsFeature()

features = vector.features(layer)
total = 100.0 / len(features)
for current, feat in enumerate(features):
inGeom = feat.geometry()
attrs = feat.attributes()

if inGeom.isEmpty():
outGeom = QgsGeometry(None)
else:
outGeom = QgsGeometry(inGeom.centroid())
if not outGeom:
raise GeoAlgorithmExecutionException(
self.tr('Error calculating centroid'))

outFeat.setGeometry(outGeom)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
for current, input_feature in enumerate(features):
output_feature = input_feature
if input_feature.geometry():
output_geometry = input_feature.geometry().centroid()
if not output_geometry:
ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
'Error calculating centroid for feature {}'.format(input_feature.id()))
output_feature.setGeometry(output_geometry)

writer.addFeature(output_feature)
progress.setPercentage(int(current * total))

del writer
96 changes: 96 additions & 0 deletions python/plugins/processing/algs/qgis/PolygonCentroids.py
@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
PolygonCentroids.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* 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__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'

# This will get replaced with a git SHA1 when you do a git archive323

__revision__ = '$Format:%H$'

import os

from qgis.PyQt.QtGui import QIcon

from qgis.core import Qgis, QgsGeometry, QgsFeature, QgsWkbTypes

from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from processing.core.parameters import ParameterVector
from processing.core.outputs import OutputVector
from processing.tools import dataobjects, vector

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


class PolygonCentroids(GeoAlgorithm):

INPUT_LAYER = 'INPUT_LAYER'
OUTPUT_LAYER = 'OUTPUT_LAYER'

def __init__(self):
GeoAlgorithm.__init__(self)
# this algorithm is deprecated - use Centroids instead
self.showInToolbox = False

def getIcon(self):
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'centroids.png'))

def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('Polygon centroids')
self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools')

self.addParameter(ParameterVector(self.INPUT_LAYER,
self.tr('Input layer'), [ParameterVector.VECTOR_TYPE_POLYGON]))

self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Centroids')))

def processAlgorithm(self, progress):
layer = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT_LAYER))

writer = self.getOutputFromName(
self.OUTPUT_LAYER).getVectorWriter(
layer.fields(),
QgsWkbTypes.Point,
layer.crs())

outFeat = QgsFeature()

features = vector.features(layer)
total = 100.0 / len(features)
for current, feat in enumerate(features):
inGeom = feat.geometry()
attrs = feat.attributes()

if inGeom.isEmpty():
outGeom = QgsGeometry(None)
else:
outGeom = QgsGeometry(inGeom.centroid())
if not outGeom:
raise GeoAlgorithmExecutionException(
self.tr('Error calculating centroid'))

outFeat.setGeometry(outGeom)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
progress.setPercentage(int(current * total))

del writer
3 changes: 2 additions & 1 deletion python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py
Expand Up @@ -151,6 +151,7 @@
from .Boundary import Boundary
from .PointOnSurface import PointOnSurface
from .OffsetLine import OffsetLine
from .PolygonCentroids import PolygonCentroids

pluginPath = os.path.normpath(os.path.join(
os.path.split(os.path.dirname(__file__))[0], os.pardir))
Expand Down Expand Up @@ -204,7 +205,7 @@ def __init__(self):
RectanglesOvalsDiamondsVariable(),
RectanglesOvalsDiamondsFixed(), MergeLines(),
BoundingBox(), Boundary(), PointOnSurface(),
OffsetLine()
OffsetLine(), PolygonCentroids()
]

if hasMatplotlib:
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/processing/gui/menus.py
Expand Up @@ -52,7 +52,7 @@
geometryToolsMenu = vectorMenu + "/" + Processing.tr('G&eometry Tools')
defaultMenuEntries.update({'qgis:checkvalidity': geometryToolsMenu,
'qgis:exportaddgeometrycolumns': geometryToolsMenu,
'qgis:polygoncentroids': geometryToolsMenu,
'qgis:centroids': geometryToolsMenu,
'qgis:delaunaytriangulation': geometryToolsMenu,
'qgis:voronoipolygons': geometryToolsMenu,
'qgis:simplifygeometries': geometryToolsMenu,
Expand Down
@@ -0,0 +1,15 @@
<GMLFeatureClassList>
<GMLFeatureClass>
<Name>centroid_lines</Name>
<ElementPath>centroid_lines</ElementPath>
<GeometryType>1</GeometryType>
<SRSName>EPSG:4326</SRSName>
<DatasetSpecificInfo>
<FeatureCount>7</FeatureCount>
<ExtentXMin>0.00000</ExtentXMin>
<ExtentXMax>8.75520</ExtentXMax>
<ExtentYMin>-3.00000</ExtentYMin>
<ExtentYMax>2.90165</ExtentYMax>
</DatasetSpecificInfo>
</GMLFeatureClass>
</GMLFeatureClassList>
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8" ?>
<ogr:FeatureCollection
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=""
xmlns:ogr="http://ogr.maptools.org/"
xmlns:gml="http://www.opengis.net/gml">
<gml:boundedBy>
<gml:Box>
<gml:coord><gml:X>0</gml:X><gml:Y>-3</gml:Y></gml:coord>
<gml:coord><gml:X>8.755203820042828</gml:X><gml:Y>2.901650429449553</gml:Y></gml:coord>
</gml:Box>
</gml:boundedBy>

<gml:featureMember>
<ogr:centroid_lines fid="lines.0">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>8.755203820042828,2.901650429449553</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_lines fid="lines.1">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>0,-1</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_lines fid="lines.2">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>2.375,1.625</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_lines fid="lines.3">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>4,1</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_lines fid="lines.4">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>8.5,-3.0</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_lines fid="lines.5">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>8,-1</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_lines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_lines fid="lines.6">
</ogr:centroid_lines>
</gml:featureMember>
</ogr:FeatureCollection>
@@ -0,0 +1,15 @@
<GMLFeatureClassList>
<GMLFeatureClass>
<Name>centroid_multilines</Name>
<ElementPath>centroid_multilines</ElementPath>
<GeometryType>1</GeometryType>
<SRSName>EPSG:4326</SRSName>
<DatasetSpecificInfo>
<FeatureCount>4</FeatureCount>
<ExtentXMin>0.00000</ExtentXMin>
<ExtentXMax>4.41936</ExtentXMax>
<ExtentYMin>-1.00000</ExtentYMin>
<ExtentYMax>2.68756</ExtentYMax>
</DatasetSpecificInfo>
</GMLFeatureClass>
</GMLFeatureClassList>
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8" ?>
<ogr:FeatureCollection
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=""
xmlns:ogr="http://ogr.maptools.org/"
xmlns:gml="http://www.opengis.net/gml">
<gml:boundedBy>
<gml:Box>
<gml:coord><gml:X>0</gml:X><gml:Y>-1</gml:Y></gml:coord>
<gml:coord><gml:X>4.41935638121706</gml:X><gml:Y>2.687560818469874</gml:Y></gml:coord>
</gml:Box>
</gml:boundedBy>

<gml:featureMember>
<ogr:centroid_multilines fid="lines.1">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>0,-1</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_multilines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_multilines fid="lines.2">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>4.41935638121706,1.293104104489945</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_multilines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_multilines fid="lines.3">
</ogr:centroid_multilines>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_multilines fid="lines.4">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>3.423678244400056,2.687560818469874</gml:coordinates></gml:Point></ogr:geometryProperty>
</ogr:centroid_multilines>
</gml:featureMember>
</ogr:FeatureCollection>
@@ -0,0 +1,19 @@
<GMLFeatureClassList>
<GMLFeatureClass>
<Name>centroid_multipoint</Name>
<ElementPath>centroid_multipoint</ElementPath>
<SRSName>EPSG:4326</SRSName>
<DatasetSpecificInfo>
<FeatureCount>5</FeatureCount>
<ExtentXMin>2.00000</ExtentXMin>
<ExtentXMax>4.50000</ExtentXMax>
<ExtentYMin>-3.00000</ExtentYMin>
<ExtentYMax>2.00000</ExtentYMax>
</DatasetSpecificInfo>
<PropertyDefn>
<Name>d</Name>
<ElementPath>d</ElementPath>
<Type>Integer</Type>
</PropertyDefn>
</GMLFeatureClass>
</GMLFeatureClassList>
@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8" ?>
<ogr:FeatureCollection
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=""
xmlns:ogr="http://ogr.maptools.org/"
xmlns:gml="http://www.opengis.net/gml">
<gml:boundedBy>
<gml:Box>
<gml:coord><gml:X>2</gml:X><gml:Y>-3</gml:Y></gml:coord>
<gml:coord><gml:X>4.5</gml:X><gml:Y>2</gml:Y></gml:coord>
</gml:Box>
</gml:boundedBy>

<gml:featureMember>
<ogr:centroid_multipoint fid="points.9">
<ogr:d>5</ogr:d>
</ogr:centroid_multipoint>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_multipoint fid="points.0">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>2,2</gml:coordinates></gml:Point></ogr:geometryProperty>
<ogr:d>1</ogr:d>
</ogr:centroid_multipoint>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_multipoint fid="points.3">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>4.5,1.5</gml:coordinates></gml:Point></ogr:geometryProperty>
<ogr:d>2</ogr:d>
</ogr:centroid_multipoint>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_multipoint fid="points.5">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>4,-3</gml:coordinates></gml:Point></ogr:geometryProperty>
<ogr:d>3</ogr:d>
</ogr:centroid_multipoint>
</gml:featureMember>
<gml:featureMember>
<ogr:centroid_multipoint fid="points.7">
<ogr:geometryProperty><gml:Point srsName="EPSG:4326"><gml:coordinates>3.5,-1.0</gml:coordinates></gml:Point></ogr:geometryProperty>
<ogr:d>4</ogr:d>
</ogr:centroid_multipoint>
</gml:featureMember>
</ogr:FeatureCollection>

0 comments on commit e9423dc

Please sign in to comment.