Skip to content

Commit

Permalink
[needs-docs] Copy unique class field option from Points in Polygons U…
Browse files Browse the repository at this point in the history
…nique

to Points in Polygons

Again, it doesn't make sense for a whole separate algorithm just to
add a single option
  • Loading branch information
nyalldawson committed Jul 15, 2017
1 parent b67e525 commit dd38c52
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 158 deletions.
7 changes: 2 additions & 5 deletions python/plugins/processing/algs/help/qgis.yaml
Expand Up @@ -77,12 +77,9 @@ qgis:countpointsinpolygon: >

An optional weight field can be used to assign weights to each point. If set, the count generated will be the sum of the weight field for each point contained by the polygon.

qgis:countuniquepointsinpolygon: >
This algorithm takes a points layer and a polygon layer and counts the number of points from the first one in each polygon of the second one.
Alternatively, a unique class field can be specified. If set, points are classified based on the selected attribute, and if several points with the same attribute value are within the polygon, only one of them is counted. The final count of the point in a polygon is, therefore, the count of different classes that are found in it.

Points are classified based on an attribute, and if several points with the same attribute value are within the extent of the polygon, only one of them is counted. The final count of point in a polygon is, therefore, the count of different classes that are found in it.

A new polygons layer is generated, with the exact same content as the input polygons layer, but containing an additional field with the points count corresponding to each polygon.
Both the weight field and unique class field cannot be specified. If they are, the weight field will take precedence and the unique class field will be ignored.

qgis:createattributeindex: >
Creates an index to speed up queries made against a field in a table. Support for index creation is dependent on the layer's data provider and the field type.
Expand Down
33 changes: 27 additions & 6 deletions python/plugins/processing/algs/qgis/PointsInPolygon.py
Expand Up @@ -54,6 +54,7 @@ class PointsInPolygon(QgisAlgorithm):
OUTPUT = 'OUTPUT'
FIELD = 'FIELD'
WEIGHT = 'WEIGHT'
CLASSFIELD = 'CLASSFIELD'

def icon(self):
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'sum_points.png'))
Expand All @@ -71,6 +72,8 @@ def initAlgorithm(self, config=None):
self.tr('Points'), [QgsProcessing.TypeVectorPoint]))
self.addParameter(QgsProcessingParameterField(self.WEIGHT,
self.tr('Weight field'), parentLayerParameterName=self.POINTS, optional=True))
self.addParameter(QgsProcessingParameterField(self.CLASSFIELD,
self.tr('Class field'), parentLayerParameterName=self.POINTS, optional=True))
self.addParameter(QgsProcessingParameterString(self.FIELD,
self.tr('Count field name'), defaultValue='NUMPOINTS'))
self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT, self.tr('Count'), QgsProcessing.TypeVectorPolygon))
Expand All @@ -90,6 +93,11 @@ def processAlgorithm(self, parameters, context, feedback):
if weight_field:
weight_field_index = point_source.fields().lookupField(weight_field)

class_field = self.parameterAsString(parameters, self.CLASSFIELD, context)
class_field_index = -1
if class_field:
class_field_index = point_source.fields().lookupField(class_field)

field_name = self.parameterAsString(parameters, self.FIELD, context)

fields = poly_source.fields()
Expand All @@ -102,6 +110,12 @@ def processAlgorithm(self, parameters, context, feedback):

spatialIndex = QgsSpatialIndex(point_source.getFeatures(QgsFeatureRequest().setSubsetOfAttributes([]).setDestinationCrs(poly_source.sourceCrs())))

point_attribute_indices = []
if weight_field_index >= 0:
point_attribute_indices.append(weight_field_index)
if class_field_index >= 0:
point_attribute_indices.append(class_field_index)

features = poly_source.getFeatures()
total = 100.0 / poly_source.featureCount() if poly_source.featureCount() else 0
for current, polygon_feature in enumerate(features):
Expand All @@ -113,13 +127,12 @@ def processAlgorithm(self, parameters, context, feedback):
engine.prepareGeometry()

count = 0
classes = set()

points = spatialIndex.intersects(geom.boundingBox())
if len(points) > 0:
request = QgsFeatureRequest().setFilterFids(points).setDestinationCrs(poly_source.sourceCrs())
if weight_field_index >= 0:
request.setSubsetOfAttributes([weight_field_index])
else:
request.setSubsetOfAttributes([])
request.setSubsetOfAttributes(point_attribute_indices)
for point_feature in point_source.getFeatures(request):
if engine.contains(point_feature.geometry().geometry()):
if weight_field_index >= 0:
Expand All @@ -129,17 +142,25 @@ def processAlgorithm(self, parameters, context, feedback):
except:
# Ignore fields with non-numeric values
pass
elif class_field_index >= 0:
point_class = point_feature.attributes()[class_field_index]
if point_class not in classes:
classes.add(point_class)
else:
count += 1

output_feature.setGeometry(geom)

attrs = polygon_feature.attributes()

if class_field_index >= 0:
score = len(classes)
else:
score = count
if field_index == len(attrs):
attrs.append(count)
attrs.append(score)
else:
attrs[field_index] = count
attrs[field_index] = score
output_feature.setAttributes(attrs)
sink.addFeature(output_feature, QgsFeatureSink.FastInsert)

Expand Down
129 changes: 0 additions & 129 deletions python/plugins/processing/algs/qgis/PointsInPolygonUnique.py

This file was deleted.

2 changes: 0 additions & 2 deletions python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py
Expand Up @@ -86,7 +86,6 @@
from .ZonalStatistics import ZonalStatistics

# from .ExtractByLocation import ExtractByLocation
# from .PointsInPolygonUnique import PointsInPolygonUnique
# from .SumLines import SumLines
# from .NearestNeighbourAnalysis import NearestNeighbourAnalysis
# from .LinesIntersection import LinesIntersection
Expand Down Expand Up @@ -185,7 +184,6 @@ def __init__(self):

def getAlgs(self):
# algs = [SumLines(),
# PointsInPolygonUnique(),
# NearestNeighbourAnalysis(), MeanCoords(),
# LinesIntersection(), UniqueValues(), PointDistance(),
# ExportGeometryInfo(),
Expand Down
32 changes: 16 additions & 16 deletions python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml
Expand Up @@ -2186,22 +2186,22 @@ tests:
# name: points.gml
# type: vector
# results: {}
#
# - algorithm: qgis:countuniquepointsinpolygon
# name: standard count unique points in polygon
# params:
# CLASSFIELD: id2
# FIELD: NUMPOINTS
# POINTS:
# name: points.gml
# type: vector
# POLYGONS:
# name: polys.gml
# type: vector
# results:
# OUTPUT:
# name: expected/count_unique_points.gml
# type: vector

- algorithm: qgis:countpointsinpolygon
name: standard count unique points in polygon
params:
CLASSFIELD: id2
FIELD: NUMPOINTS
POINTS:
name: points.gml
type: vector
POLYGONS:
name: polys.gml
type: vector
results:
OUTPUT:
name: expected/count_unique_points.gml
type: vector

- algorithm: qgis:countpointsinpolygon
name: standard count points in polygon weighted
Expand Down

0 comments on commit dd38c52

Please sign in to comment.