QGIS API Documentation 3.99.0-Master (26c88405ac0)
Loading...
Searching...
No Matches
qgsalgorithmrandompointsinpolygons.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrandompointsinpolygons.cpp
3 ---------------------
4 begin : March 2020
5 copyright : (C) 2020 by HÃ¥vard Tveite
6 email : havard dot tveite at nmbu dot no
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
18
20
21#include <random>
22
23#include "qgsspatialindex.h"
24
26
27QString QgsRandomPointsInPolygonsAlgorithm::name() const
28{
29 return QStringLiteral( "randompointsinpolygons" );
30}
31
32QString QgsRandomPointsInPolygonsAlgorithm::displayName() const
33{
34 return QObject::tr( "Random points in polygons" );
35}
36
37QStringList QgsRandomPointsInPolygonsAlgorithm::tags() const
38{
39 return QObject::tr( "seed,attributes,create" ).split( ',' );
40}
41
42QString QgsRandomPointsInPolygonsAlgorithm::group() const
43{
44 return QObject::tr( "Vector creation" );
45}
46
47QString QgsRandomPointsInPolygonsAlgorithm::groupId() const
48{
49 return QStringLiteral( "vectorcreation" );
50}
51
52void QgsRandomPointsInPolygonsAlgorithm::initAlgorithm( const QVariantMap & )
53{
54 addParameter( new QgsProcessingParameterFeatureSource( INPUT, QObject::tr( "Input polygon layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
55 auto numberPointsParam = std::make_unique<QgsProcessingParameterNumber>( POINTS_NUMBER, QObject::tr( "Number of points for each feature" ), Qgis::ProcessingNumberParameterType::Integer, 1, false, 1 );
56 numberPointsParam->setIsDynamic( true );
57 numberPointsParam->setDynamicPropertyDefinition( QgsPropertyDefinition( POINTS_NUMBER, QObject::tr( "Number of points for each feature" ), QgsPropertyDefinition::IntegerPositive ) );
58 numberPointsParam->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
59 addParameter( numberPointsParam.release() );
60
61 auto minDistParam = std::make_unique<QgsProcessingParameterDistance>( MIN_DISTANCE, QObject::tr( "Minimum distance between points" ), 0, INPUT, true, 0 );
62 minDistParam->setIsDynamic( true );
63 minDistParam->setDynamicPropertyDefinition( QgsPropertyDefinition( MIN_DISTANCE, QObject::tr( "Minimum distance between points" ), QgsPropertyDefinition::DoublePositive ) );
64 minDistParam->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
65 addParameter( minDistParam.release() );
66
67 auto minDistGlobalParam = std::make_unique<QgsProcessingParameterDistance>( MIN_DISTANCE_GLOBAL, QObject::tr( "Global minimum distance between points" ), 0, INPUT, true, 0 );
68 minDistGlobalParam->setFlags( minDistGlobalParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
69 addParameter( minDistGlobalParam.release() );
70
71 auto maxAttemptsParam = std::make_unique<QgsProcessingParameterNumber>( MAX_TRIES_PER_POINT, QObject::tr( "Maximum number of search attempts (for Min. dist. > 0)" ), Qgis::ProcessingNumberParameterType::Integer, 10, true, 1 );
72 maxAttemptsParam->setFlags( maxAttemptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
73 maxAttemptsParam->setIsDynamic( true );
74 maxAttemptsParam->setDynamicPropertyDefinition( QgsPropertyDefinition( MAX_TRIES_PER_POINT, QObject::tr( "Maximum number of attempts per point (for Min. dist. > 0)" ), QgsPropertyDefinition::IntegerPositiveGreaterZero ) );
75 maxAttemptsParam->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
76 addParameter( maxAttemptsParam.release() );
77
78 auto randomSeedParam = std::make_unique<QgsProcessingParameterNumber>( SEED, QObject::tr( "Random seed" ), Qgis::ProcessingNumberParameterType::Integer, QVariant(), true, 1 );
79 randomSeedParam->setFlags( randomSeedParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
80 addParameter( randomSeedParam.release() );
81
82 auto includePolygonAttrParam = std::make_unique<QgsProcessingParameterBoolean>( INCLUDE_POLYGON_ATTRIBUTES, QObject::tr( "Include polygon attributes" ), true );
83 includePolygonAttrParam->setFlags( includePolygonAttrParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
84 addParameter( includePolygonAttrParam.release() );
85
86 addParameter( new QgsProcessingParameterFeatureSink( OUTPUT, QObject::tr( "Random points in polygons" ), Qgis::ProcessingSourceType::VectorPoint ) );
87
88 addOutput( new QgsProcessingOutputNumber( OUTPUT_POINTS, QObject::tr( "Total number of points generated" ) ) );
89 addOutput( new QgsProcessingOutputNumber( POINTS_MISSED, QObject::tr( "Number of missed points" ) ) );
90 addOutput( new QgsProcessingOutputNumber( POLYGONS_WITH_MISSED_POINTS, QObject::tr( "Number of polygons with missed points" ) ) );
91 addOutput( new QgsProcessingOutputNumber( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, QObject::tr( "Number of features with empty or no geometry" ) ) );
92}
93
94QString QgsRandomPointsInPolygonsAlgorithm::shortDescription() const
95{
96 return QObject::tr( "Creates a layer with a number of points placed randomly in each polygon of a given layer." );
97}
98
99QString QgsRandomPointsInPolygonsAlgorithm::shortHelpString() const
100{
101 return QObject::tr( "<p>This algorithm creates a point layer, with points placed randomly "
102 "in the polygons of the <i><b>Input polygon layer</b></i>.</p> "
103 "<ul><li>For each feature in the <i><b>Input polygon layer</b></i>, the algorithm attempts to add "
104 "the specified <i><b>Number of points for each feature</b></i> to the output layer.</li> "
105 "<li>A <i><b>Minimum distance between points</b></i> and a "
106 "<i><b>Global minimum distance between points</b></i> can be specified.<br> "
107 "A point will not be added if there is an already generated point within "
108 "this (Euclidean) distance from the generated location. "
109 "With <i>Minimum distance between points</i>, only points in the same "
110 "polygon feature are considered, while for <i>Global minimum distance "
111 "between points</i> all previously generated points are considered. "
112 "If the <i>Global minimum distance between points</i> is set equal to "
113 "or larger than the (local) <i>Minimum distance between points</i>, the "
114 "latter has no effect.<br> "
115 "If the <i>Minimum distance between points</i> is too large, "
116 "it may not be possible to generate the specified <i>Number of points "
117 "for each feature</i>, but all the generated points are returned.</li> "
118 "<li>The <i><b>Maximum number of attempts per point</b></i> can be specified.</li> "
119 "<li>The seed for the random generator can be provided (<b><i>Random seed</i></b> "
120 "- integer, greater than 0).</li> "
121 "<li>The user can choose not to <i><b>Include polygon feature attributes</b></i> in "
122 "the attributes of the generated point features.</li> "
123 "</ul> "
124 "The total number of points will be<br> <b>'number of input features'</b> * "
125 "<i><b>Number of points for each feature</b></i><br> if there are no misses. "
126 "The <i>Number of points for each feature</i>, <i>Minimum distance between points</i> "
127 "and <i>Maximum number of attempts per point</i> can be data defined. "
128 "<p>Output from the algorithm:</p> "
129 "<ul> "
130 "<li> The number of features with an empty or no geometry "
131 "(<code>FEATURES_WITH_EMPTY_OR_NO_GEOMETRY</code>).</li> "
132 "<li> A point layer containing the random points (<code>OUTPUT</code>).</li> "
133 "<li> The number of generated features (<code>OUTPUT_POINTS</code>).</li> "
134 "<li> The number of missed points (<code>POINTS_MISSED</code>).</li> "
135 "<li> The number of features with non-empty geometry and missing points "
136 "(<code>POLYGONS_WITH_MISSED_POINTS</code>).</li> "
137 "</ul>"
138 );
139}
140
141QgsRandomPointsInPolygonsAlgorithm *QgsRandomPointsInPolygonsAlgorithm::createInstance() const
142{
143 return new QgsRandomPointsInPolygonsAlgorithm();
144}
145
146bool QgsRandomPointsInPolygonsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
147{
148 mNumPoints = parameterAsInt( parameters, POINTS_NUMBER, context );
149 mDynamicNumPoints = QgsProcessingParameters::isDynamic( parameters, POINTS_NUMBER );
150 if ( mDynamicNumPoints )
151 mNumPointsProperty = parameters.value( POINTS_NUMBER ).value<QgsProperty>();
152
153 mMinDistance = parameterAsDouble( parameters, MIN_DISTANCE, context );
154 mDynamicMinDistance = QgsProcessingParameters::isDynamic( parameters, MIN_DISTANCE );
155 if ( mDynamicMinDistance )
156 mMinDistanceProperty = parameters.value( MIN_DISTANCE ).value<QgsProperty>();
157
158 mMaxAttempts = parameterAsInt( parameters, MAX_TRIES_PER_POINT, context );
159 mDynamicMaxAttempts = QgsProcessingParameters::isDynamic( parameters, MAX_TRIES_PER_POINT );
160 if ( mDynamicMaxAttempts )
161 mMaxAttemptsProperty = parameters.value( MAX_TRIES_PER_POINT ).value<QgsProperty>();
162
163 mMinDistanceGlobal = parameterAsDouble( parameters, MIN_DISTANCE_GLOBAL, context );
164
165 mUseRandomSeed = parameters.value( SEED ).isValid();
166 mRandSeed = parameterAsInt( parameters, SEED, context );
167 mIncludePolygonAttr = parameterAsBoolean( parameters, INCLUDE_POLYGON_ATTRIBUTES, context );
168 return true;
169}
170
171QVariantMap QgsRandomPointsInPolygonsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
172{
173 std::unique_ptr<QgsProcessingFeatureSource> polygonSource( parameterAsSource( parameters, INPUT, context ) );
174 if ( !polygonSource )
175 throw QgsProcessingException( invalidSourceError( parameters, INPUT ) );
176
177 QgsFields fields;
178 fields.append( QgsField( QStringLiteral( "rand_point_id" ), QMetaType::Type::LongLong ) );
179 if ( mIncludePolygonAttr )
180 fields.extend( polygonSource->fields() );
181
182 QString ldest;
183 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, OUTPUT, context, ldest, fields, Qgis::WkbType::Point, polygonSource->sourceCrs() ) );
184 if ( !sink )
185 throw QgsProcessingException( invalidSinkError( parameters, OUTPUT ) );
186
187 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, polygonSource.get() );
188
189 // Initialize random engine -- note that we only use this if the user has specified a fixed seed
190 std::random_device rd;
191 std::mt19937 mt( !mUseRandomSeed ? rd() : mRandSeed );
192 const std::uniform_real_distribution<> uniformDist( 0, 1 );
193 std::uniform_int_distribution<> uniformIntDist( 1, 999999999 );
194
195 // Index for finding global close points (mMinDistance != 0)
196 QgsSpatialIndex globalIndex;
197 int indexPoints = 0;
198
199 int totNPoints = 0;
200 int missedPoints = 0;
201 int missedPolygons = 0;
202 int emptyOrNullGeom = 0;
203
204 long long attempts = 0; // used for unique feature IDs in the indexes
205 const long numberOfFeatures = polygonSource->featureCount();
206 long long desiredNumberOfPoints = 0;
207 const double featureProgressStep = 100.0 / ( numberOfFeatures > 0 ? numberOfFeatures : 1 );
208 double baseFeatureProgress = 0.0;
209 QgsFeature polyFeat;
210 QgsFeatureIterator fitL = mIncludePolygonAttr || mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts ? polygonSource->getFeatures()
211 : polygonSource->getFeatures( QgsFeatureRequest().setNoAttributes() );
212 while ( fitL.nextFeature( polyFeat ) )
213 {
214 if ( feedback->isCanceled() )
215 {
216 feedback->setProgress( 0 );
217 break;
218 }
219 if ( !polyFeat.hasGeometry() )
220 {
221 // Increment invalid features count
222 emptyOrNullGeom++;
223 baseFeatureProgress += featureProgressStep;
224 feedback->setProgress( baseFeatureProgress );
225 continue;
226 }
227 const QgsGeometry polyGeom( polyFeat.geometry() );
228 if ( polyGeom.isEmpty() )
229 {
230 // Increment invalid features count
231 emptyOrNullGeom++;
232 baseFeatureProgress += featureProgressStep;
233 feedback->setProgress( baseFeatureProgress );
234 continue;
235 }
236 if ( mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts )
237 {
238 expressionContext.setFeature( polyFeat );
239 }
240 // (Re)initialize the local (per polygon) index
241 QgsSpatialIndex localIndex;
242 int localIndexPoints = 0;
243 int pointsAddedForThisFeature = 0;
244 // Get data defined parameters
245 int numberPointsForThisFeature = mNumPoints;
246 if ( mDynamicNumPoints )
247 {
248 numberPointsForThisFeature = mNumPointsProperty.valueAsInt( expressionContext, 0 );
249 }
250 desiredNumberOfPoints += numberPointsForThisFeature;
251 int maxAttemptsForThisFeature = mMaxAttempts;
252 if ( mDynamicMaxAttempts )
253 maxAttemptsForThisFeature = mMaxAttemptsProperty.valueAsInt( expressionContext, maxAttemptsForThisFeature );
254 double minDistanceForThisFeature = mMinDistance;
255 if ( mDynamicMinDistance )
256 minDistanceForThisFeature = mMinDistanceProperty.valueAsDouble( expressionContext, minDistanceForThisFeature );
257 const double pointProgressIncrement = featureProgressStep / ( numberPointsForThisFeature * maxAttemptsForThisFeature );
258 double pointProgress = 0.0;
259 // Check if we can avoid using the acceptPoint function
260 if ( ( minDistanceForThisFeature == 0 ) && ( mMinDistanceGlobal == 0 ) )
261 {
262 QVector<QgsPointXY> newPoints = polyGeom.randomPointsInPolygon( numberPointsForThisFeature, mUseRandomSeed ? uniformIntDist( mt ) : 0 );
263 for ( int i = 0; i < newPoints.length(); i++ )
264 {
265 // add the point
266 const QgsPointXY pt = newPoints[i];
267 QgsFeature f = QgsFeature( totNPoints );
268 QgsAttributes pAttrs = QgsAttributes();
269 pAttrs.append( totNPoints );
270 if ( mIncludePolygonAttr )
271 {
272 pAttrs.append( polyFeat.attributes() );
273 }
274 f.setAttributes( pAttrs );
275 const QgsGeometry newGeom = QgsGeometry::fromPointXY( pt );
276 f.setGeometry( newGeom );
277 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
278 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
279 totNPoints++;
280 pointsAddedForThisFeature++;
281 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature );
282 }
283 feedback->setProgress( baseFeatureProgress + pointProgress );
284 continue;
285 }
286 else
287 {
288 // Have to check for minimum distance, provide the acceptPoints function
289 QVector<QgsPointXY> newPoints = polyGeom.randomPointsInPolygon( numberPointsForThisFeature, [&]( const QgsPointXY &newPoint ) -> bool {
290 attempts++;
291 // May have to check minimum distance to existing points
292 // The first point can always be added
293 // Local first (if larger than global)
294 if ( minDistanceForThisFeature != 0 && mMinDistanceGlobal < minDistanceForThisFeature && localIndexPoints > 0 )
295 {
296 const QList<QgsFeatureId> neighbors = localIndex.nearestNeighbor( newPoint, 1, minDistanceForThisFeature );
297 //if ( totNPoints > 0 && !neighbors.empty() )
298 if ( !neighbors.empty() )
299 {
300 return false;
301 }
302 }
303 // The global
304 if ( mMinDistanceGlobal != 0.0 && indexPoints > 0 )
305 {
306 const QList<QgsFeatureId> neighbors = globalIndex.nearestNeighbor( newPoint, 1, mMinDistanceGlobal );
307 //if ( totNPoints > 0 && !neighbors.empty() )
308 if ( !neighbors.empty() )
309 {
310 return false;
311 }
312 }
313 // Point is accepted - add it to the indexes
314 QgsFeature f = QgsFeature( attempts );
315 QgsAttributes pAttrs = QgsAttributes();
316 pAttrs.append( attempts );
317 f.setAttributes( pAttrs );
318 const QgsGeometry newGeom = QgsGeometry::fromPointXY( newPoint );
319
320 f.setGeometry( newGeom );
321 //totNPoints++;
322
323 if ( minDistanceForThisFeature != 0 )
324 {
325 if ( !localIndex.addFeature( f ) )
326 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QString() ) );
327 localIndexPoints++;
328 }
329 if ( mMinDistanceGlobal != 0.0 )
330 {
331 if ( !globalIndex.addFeature( f ) )
332 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QString() ) );
333 indexPoints++;
334 }
335 return true; }, mUseRandomSeed ? uniformIntDist( mt ) : 0, feedback, maxAttemptsForThisFeature );
336
337 // create and output features for the generated points
338 for ( int i = 0; i < newPoints.length(); i++ )
339 {
340 const QgsPointXY pt = newPoints[i];
341 QgsFeature f = QgsFeature( totNPoints );
342 QgsAttributes pAttrs = QgsAttributes();
343 pAttrs.append( totNPoints );
344 if ( mIncludePolygonAttr )
345 {
346 pAttrs.append( polyFeat.attributes() );
347 }
348 f.setAttributes( pAttrs );
349 const QgsGeometry newGeom = QgsGeometry::fromPointXY( pt );
350 f.setGeometry( newGeom );
351 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
352 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
353 totNPoints++;
354 pointsAddedForThisFeature++;
355 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature );
356 }
357 feedback->setProgress( baseFeatureProgress + pointProgress );
358 }
359
360 baseFeatureProgress += featureProgressStep;
361 if ( pointsAddedForThisFeature < numberPointsForThisFeature )
362 {
363 missedPolygons++;
364 }
365 feedback->setProgress( baseFeatureProgress );
366 } // while features
367 missedPoints = desiredNumberOfPoints - totNPoints;
368 feedback->pushInfo( QObject::tr( "Total number of points generated: "
369 "%1\nNumber of missed points: "
370 "%2\nPolygons with missing points: "
371 "%3\nFeatures with empty or missing "
372 "geometries: %4"
373 )
374 .arg( totNPoints )
375 .arg( missedPoints )
376 .arg( missedPolygons )
377 .arg( emptyOrNullGeom ) );
378
379 sink->finalize();
380
381 QVariantMap outputs;
382 outputs.insert( OUTPUT, ldest );
383 outputs.insert( OUTPUT_POINTS, totNPoints );
384 outputs.insert( POINTS_MISSED, missedPoints );
385 outputs.insert( POLYGONS_WITH_MISSED_POINTS, missedPolygons );
386 outputs.insert( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, emptyOrNullGeom );
387
388 return outputs;
389}
390
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
@ Point
Point.
Definition qgis.h:279
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
A vector of attributes.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsAttributes attributes
Definition qgsfeature.h:67
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:73
void extend(const QgsFields &other)
Extends with fields from another QgsFields container.
A geometry is the spatial representation of a feature.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
Represents a 2D point.
Definition qgspointxy.h:60
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
A numeric output for processing algorithms.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
static bool isDynamic(const QVariantMap &parameters, const QString &name)
Returns true if the parameter with matching name is a dynamic parameter, and must be evaluated once f...
Definition for a property.
Definition qgsproperty.h:45
@ IntegerPositiveGreaterZero
Non-zero positive integer values.
Definition qgsproperty.h:54
@ IntegerPositive
Positive integer values (including 0).
Definition qgsproperty.h:53
@ DoublePositive
Positive double value (including 0).
Definition qgsproperty.h:56
A store for object properties.
double valueAsDouble(const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property and interprets it as a double.
int valueAsInt(const QgsExpressionContext &context, int defaultValue=0, bool *ok=nullptr) const
Calculates the current value of the property and interprets it as an integer.
A spatial index for QgsFeature objects.
QList< QgsFeatureId > nearestNeighbor(const QgsPointXY &point, int neighbors=1, double maxDistance=0) const
Returns nearest neighbors to a point.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a feature to the index.