26QString QgsRandomPointsInPolygonsAlgorithm::name()
const
28 return QStringLiteral(
"randompointsinpolygons" );
31QString QgsRandomPointsInPolygonsAlgorithm::displayName()
const
33 return QObject::tr(
"Random points in polygons" );
36QStringList QgsRandomPointsInPolygonsAlgorithm::tags()
const
38 return QObject::tr(
"seed,attributes,create" ).split(
',' );
41QString QgsRandomPointsInPolygonsAlgorithm::group()
const
43 return QObject::tr(
"Vector creation" );
46QString QgsRandomPointsInPolygonsAlgorithm::groupId()
const
48 return QStringLiteral(
"vectorcreation" );
51void QgsRandomPointsInPolygonsAlgorithm::initAlgorithm(
const QVariantMap & )
54 std::unique_ptr<QgsProcessingParameterNumber> numberPointsParam = std::make_unique<QgsProcessingParameterNumber>( POINTS_NUMBER, QObject::tr(
"Number of points for each feature" ),
Qgis::ProcessingNumberParameterType::Integer, 1,
false, 1 );
55 numberPointsParam->setIsDynamic(
true );
57 numberPointsParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
58 addParameter( numberPointsParam.release() );
60 std::unique_ptr<QgsProcessingParameterDistance> minDistParam = std::make_unique<QgsProcessingParameterDistance>( MIN_DISTANCE, QObject::tr(
"Minimum distance between points" ), 0, INPUT,
true, 0 );
61 minDistParam->setIsDynamic(
true );
63 minDistParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
64 addParameter( minDistParam.release() );
66 std::unique_ptr<QgsProcessingParameterDistance> minDistGlobalParam = std::make_unique<QgsProcessingParameterDistance>( MIN_DISTANCE_GLOBAL, QObject::tr(
"Global minimum distance between points" ), 0, INPUT,
true, 0 );
68 addParameter( minDistGlobalParam.release() );
70 std::unique_ptr<QgsProcessingParameterNumber> 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->setIsDynamic(
true );
74 maxAttemptsParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
75 addParameter( maxAttemptsParam.release() );
79 addParameter( randomSeedParam.release() );
81 std::unique_ptr<QgsProcessingParameterBoolean> includePolygonAttrParam = std::make_unique<QgsProcessingParameterBoolean>( INCLUDE_POLYGON_ATTRIBUTES, QObject::tr(
"Include polygon attributes" ),
true );
83 addParameter( includePolygonAttrParam.release() );
89 addOutput(
new QgsProcessingOutputNumber( POLYGONS_WITH_MISSED_POINTS, QObject::tr(
"Number of polygons with missed points" ) ) );
90 addOutput(
new QgsProcessingOutputNumber( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, QObject::tr(
"Number of features with empty or no geometry" ) ) );
93QString QgsRandomPointsInPolygonsAlgorithm::shortHelpString()
const
95 return QObject::tr(
"<p>This algorithm creates a point layer, with points placed randomly "
96 "in the polygons of the <i><b>Input polygon layer</b></i>.</p> "
97 "<ul><li>For each feature in the <i><b>Input polygon layer</b></i>, the algorithm attempts to add "
98 "the specified <i><b>Number of points for each feature</b></i> to the output layer.</li> "
99 "<li>A <i><b>Minimum distance between points</b></i> and a "
100 "<i><b>Global minimum distance between points</b></i> can be specified.<br> "
101 "A point will not be added if there is an already generated point within "
102 "this (Euclidean) distance from the generated location. "
103 "With <i>Minimum distance between points</i>, only points in the same "
104 "polygon feature are considered, while for <i>Global minimum distance "
105 "between points</i> all previously generated points are considered. "
106 "If the <i>Global minimum distance between points</i> is set equal to "
107 "or larger than the (local) <i>Minimum distance between points</i>, the "
108 "latter has no effect.<br> "
109 "If the <i>Minimum distance between points</i> is too large, "
110 "it may not be possible to generate the specified <i>Number of points "
111 "for each feature</i>, but all the generated points are returned.</li> "
112 "<li>The <i><b>Maximum number of attempts per point</b></i> can be specified.</li> "
113 "<li>The seed for the random generator can be provided (<b><i>Random seed</i></b> "
114 "- integer, greater than 0).</li> "
115 "<li>The user can choose not to <i><b>Include polygon feature attributes</b></i> in "
116 "the attributes of the generated point features.</li> "
118 "The total number of points will be<br> <b>'number of input features'</b> * "
119 "<i><b>Number of points for each feature</b></i><br> if there are no misses. "
120 "The <i>Number of points for each feature</i>, <i>Minimum distance between points</i> "
121 "and <i>Maximum number of attempts per point</i> can be data defined. "
122 "<p>Output from the algorithm:</p> "
124 "<li> The number of features with an empty or no geometry "
125 "(<code>FEATURES_WITH_EMPTY_OR_NO_GEOMETRY</code>).</li> "
126 "<li> A point layer containing the random points (<code>OUTPUT</code>).</li> "
127 "<li> The number of generated features (<code>OUTPUT_POINTS</code>).</li> "
128 "<li> The number of missed points (<code>POINTS_MISSED</code>).</li> "
129 "<li> The number of features with non-empty geometry and missing points "
130 "(<code>POLYGONS_WITH_MISSED_POINTS</code>).</li> "
136QgsRandomPointsInPolygonsAlgorithm *QgsRandomPointsInPolygonsAlgorithm::createInstance()
const
138 return new QgsRandomPointsInPolygonsAlgorithm();
143 mNumPoints = parameterAsInt( parameters, POINTS_NUMBER, context );
145 if ( mDynamicNumPoints )
146 mNumPointsProperty = parameters.value( POINTS_NUMBER ).value<
QgsProperty>();
148 mMinDistance = parameterAsDouble( parameters, MIN_DISTANCE, context );
150 if ( mDynamicMinDistance )
151 mMinDistanceProperty = parameters.value( MIN_DISTANCE ).value<
QgsProperty>();
153 mMaxAttempts = parameterAsInt( parameters, MAX_TRIES_PER_POINT, context );
155 if ( mDynamicMaxAttempts )
156 mMaxAttemptsProperty = parameters.value( MAX_TRIES_PER_POINT ).value<
QgsProperty>();
158 mMinDistanceGlobal = parameterAsDouble( parameters, MIN_DISTANCE_GLOBAL, context );
160 mUseRandomSeed = parameters.value( SEED ).isValid();
161 mRandSeed = parameterAsInt( parameters, SEED, context );
162 mIncludePolygonAttr = parameterAsBoolean( parameters, INCLUDE_POLYGON_ATTRIBUTES, context );
168 std::unique_ptr<QgsProcessingFeatureSource> polygonSource( parameterAsSource( parameters, INPUT, context ) );
169 if ( !polygonSource )
173 fields.
append(
QgsField( QStringLiteral(
"rand_point_id" ), QMetaType::Type::LongLong ) );
174 if ( mIncludePolygonAttr )
175 fields.
extend( polygonSource->fields() );
178 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, OUTPUT, context, ldest, fields,
Qgis::WkbType::Point, polygonSource->sourceCrs() ) );
182 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, polygonSource.get() );
185 std::random_device rd;
186 std::mt19937 mt( !mUseRandomSeed ? rd() : mRandSeed );
187 const std::uniform_real_distribution<> uniformDist( 0, 1 );
188 std::uniform_int_distribution<> uniformIntDist( 1, 999999999 );
195 int missedPoints = 0;
196 int missedPolygons = 0;
197 int emptyOrNullGeom = 0;
199 long long attempts = 0;
200 const long numberOfFeatures = polygonSource->featureCount();
201 long long desiredNumberOfPoints = 0;
202 const double featureProgressStep = 100.0 / ( numberOfFeatures > 0 ? numberOfFeatures : 1 );
203 double baseFeatureProgress = 0.0;
205 QgsFeatureIterator fitL = mIncludePolygonAttr || mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts ? polygonSource->getFeatures()
218 baseFeatureProgress += featureProgressStep;
223 if ( polyGeom.isEmpty() )
227 baseFeatureProgress += featureProgressStep;
231 if ( mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts )
237 int localIndexPoints = 0;
238 int pointsAddedForThisFeature = 0;
240 int numberPointsForThisFeature = mNumPoints;
241 if ( mDynamicNumPoints )
243 numberPointsForThisFeature = mNumPointsProperty.valueAsInt( expressionContext, 0 );
245 desiredNumberOfPoints += numberPointsForThisFeature;
246 int maxAttemptsForThisFeature = mMaxAttempts;
247 if ( mDynamicMaxAttempts )
248 maxAttemptsForThisFeature = mMaxAttemptsProperty.
valueAsInt( expressionContext, maxAttemptsForThisFeature );
249 double minDistanceForThisFeature = mMinDistance;
250 if ( mDynamicMinDistance )
251 minDistanceForThisFeature = mMinDistanceProperty.
valueAsDouble( expressionContext, minDistanceForThisFeature );
252 const double pointProgressIncrement = featureProgressStep / ( numberPointsForThisFeature * maxAttemptsForThisFeature );
253 double pointProgress = 0.0;
255 if ( ( minDistanceForThisFeature == 0 ) && ( mMinDistanceGlobal == 0 ) )
257 QVector<QgsPointXY> newPoints = polyGeom.randomPointsInPolygon( numberPointsForThisFeature, mUseRandomSeed ? uniformIntDist( mt ) : 0 );
258 for (
int i = 0; i < newPoints.length(); i++ )
264 pAttrs.append( totNPoints );
265 if ( mIncludePolygonAttr )
275 pointsAddedForThisFeature++;
276 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature );
278 feedback->
setProgress( baseFeatureProgress + pointProgress );
284 QVector<QgsPointXY> newPoints = polyGeom.randomPointsInPolygon( numberPointsForThisFeature, [&](
const QgsPointXY &newPoint ) ->
bool {
289 if ( minDistanceForThisFeature != 0 && mMinDistanceGlobal < minDistanceForThisFeature && localIndexPoints > 0 )
291 const QList<QgsFeatureId> neighbors = localIndex.
nearestNeighbor( newPoint, 1, minDistanceForThisFeature );
293 if ( !neighbors.empty() )
299 if ( mMinDistanceGlobal != 0.0 && indexPoints > 0 )
301 const QList<QgsFeatureId> neighbors = globalIndex.
nearestNeighbor( newPoint, 1, mMinDistanceGlobal );
303 if ( !neighbors.empty() )
311 pAttrs.append( attempts );
318 if ( minDistanceForThisFeature != 0 )
324 if ( mMinDistanceGlobal != 0.0 )
330 return true; }, mUseRandomSeed ? uniformIntDist( mt ) : 0, feedback, maxAttemptsForThisFeature );
333 for (
int i = 0; i < newPoints.length(); i++ )
338 pAttrs.append( totNPoints );
339 if ( mIncludePolygonAttr )
349 pointsAddedForThisFeature++;
350 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature );
352 feedback->
setProgress( baseFeatureProgress + pointProgress );
355 baseFeatureProgress += featureProgressStep;
356 if ( pointsAddedForThisFeature < numberPointsForThisFeature )
362 missedPoints = desiredNumberOfPoints - totNPoints;
363 feedback->
pushInfo( QObject::tr(
"Total number of points generated: "
364 "%1\nNumber of missed points: "
365 "%2\nPolygons with missing points: "
366 "%3\nFeatures with empty or missing "
371 .arg( missedPolygons )
372 .arg( emptyOrNullGeom ) );
377 outputs.insert( OUTPUT, ldest );
378 outputs.insert( OUTPUT_POINTS, totNPoints );
379 outputs.insert( POINTS_MISSED, missedPoints );
380 outputs.insert( POLYGONS_WITH_MISSED_POINTS, missedPolygons );
381 outputs.insert( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, emptyOrNullGeom );
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
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.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
@ 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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
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.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
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.
A class to represent a 2D point.
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 ¶meters, 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.
@ IntegerPositiveGreaterZero
Non-zero positive integer values.
@ IntegerPositive
Positive integer values (including 0)
@ DoublePositive
Positive double value (including 0)
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.