27using namespace Qt::StringLiterals;
31QString QgsRandomPointsInPolygonsAlgorithm::name()
const
33 return u
"randompointsinpolygons"_s;
36QString QgsRandomPointsInPolygonsAlgorithm::displayName()
const
38 return QObject::tr(
"Random points in polygons" );
41QStringList QgsRandomPointsInPolygonsAlgorithm::tags()
const
43 return QObject::tr(
"seed,attributes,create" ).split(
',' );
46QString QgsRandomPointsInPolygonsAlgorithm::group()
const
48 return QObject::tr(
"Vector creation" );
51QString QgsRandomPointsInPolygonsAlgorithm::groupId()
const
53 return u
"vectorcreation"_s;
56void QgsRandomPointsInPolygonsAlgorithm::initAlgorithm(
const QVariantMap & )
60 numberPointsParam->setIsDynamic(
true );
62 numberPointsParam->setDynamicLayerParameterName( u
"INPUT"_s );
63 addParameter( numberPointsParam.release() );
65 auto minDistParam = std::make_unique<QgsProcessingParameterDistance>( MIN_DISTANCE, QObject::tr(
"Minimum distance between points" ), 0, INPUT,
true, 0 );
66 minDistParam->setIsDynamic(
true );
68 minDistParam->setDynamicLayerParameterName( u
"INPUT"_s );
69 addParameter( minDistParam.release() );
71 auto minDistGlobalParam = std::make_unique<QgsProcessingParameterDistance>( MIN_DISTANCE_GLOBAL, QObject::tr(
"Global minimum distance between points" ), 0, INPUT,
true, 0 );
73 addParameter( minDistGlobalParam.release() );
75 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 );
77 maxAttemptsParam->setIsDynamic(
true );
79 maxAttemptsParam->setDynamicLayerParameterName( u
"INPUT"_s );
80 addParameter( maxAttemptsParam.release() );
84 addParameter( randomSeedParam.release() );
86 auto includePolygonAttrParam = std::make_unique<QgsProcessingParameterBoolean>( INCLUDE_POLYGON_ATTRIBUTES, QObject::tr(
"Include polygon attributes" ),
true );
88 addParameter( includePolygonAttrParam.release() );
94 addOutput(
new QgsProcessingOutputNumber( POLYGONS_WITH_MISSED_POINTS, QObject::tr(
"Number of polygons with missed points" ) ) );
95 addOutput(
new QgsProcessingOutputNumber( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, QObject::tr(
"Number of features with empty or no geometry" ) ) );
98QString QgsRandomPointsInPolygonsAlgorithm::shortDescription()
const
100 return QObject::tr(
"Creates a layer with a number of points placed randomly in each polygon of a given layer." );
103QString QgsRandomPointsInPolygonsAlgorithm::shortHelpString()
const
105 return QObject::tr(
"<p>This algorithm creates a point layer, with points placed randomly "
106 "in the polygons of the <i><b>Input polygon layer</b></i>.</p> "
107 "<ul><li>For each feature in the <i><b>Input polygon layer</b></i>, the algorithm attempts to add "
108 "the specified <i><b>Number of points for each feature</b></i> to the output layer.</li> "
109 "<li>A <i><b>Minimum distance between points</b></i> and a "
110 "<i><b>Global minimum distance between points</b></i> can be specified.<br> "
111 "A point will not be added if there is an already generated point within "
112 "this (Euclidean) distance from the generated location. "
113 "With <i>Minimum distance between points</i>, only points in the same "
114 "polygon feature are considered, while for <i>Global minimum distance "
115 "between points</i> all previously generated points are considered. "
116 "If the <i>Global minimum distance between points</i> is set equal to "
117 "or larger than the (local) <i>Minimum distance between points</i>, the "
118 "latter has no effect.<br> "
119 "If the <i>Minimum distance between points</i> is too large, "
120 "it may not be possible to generate the specified <i>Number of points "
121 "for each feature</i>, but all the generated points are returned.</li> "
122 "<li>The <i><b>Maximum number of attempts per point</b></i> can be specified.</li> "
123 "<li>The seed for the random generator can be provided (<b><i>Random seed</i></b> "
124 "- integer, greater than 0).</li> "
125 "<li>The user can choose not to <i><b>Include polygon feature attributes</b></i> in "
126 "the attributes of the generated point features.</li> "
128 "The total number of points will be<br> <b>'number of input features'</b> * "
129 "<i><b>Number of points for each feature</b></i><br> if there are no misses. "
130 "The <i>Number of points for each feature</i>, <i>Minimum distance between points</i> "
131 "and <i>Maximum number of attempts per point</i> can be data defined. "
132 "<p>Output from the algorithm:</p> "
134 "<li> The number of features with an empty or no geometry "
135 "(<code>FEATURES_WITH_EMPTY_OR_NO_GEOMETRY</code>).</li> "
136 "<li> A point layer containing the random points (<code>OUTPUT</code>).</li> "
137 "<li> The number of generated features (<code>OUTPUT_POINTS</code>).</li> "
138 "<li> The number of missed points (<code>POINTS_MISSED</code>).</li> "
139 "<li> The number of features with non-empty geometry and missing points "
140 "(<code>POLYGONS_WITH_MISSED_POINTS</code>).</li> "
145QgsRandomPointsInPolygonsAlgorithm *QgsRandomPointsInPolygonsAlgorithm::createInstance()
const
147 return new QgsRandomPointsInPolygonsAlgorithm();
152 mNumPoints = parameterAsInt( parameters, POINTS_NUMBER, context );
154 if ( mDynamicNumPoints )
155 mNumPointsProperty = parameters.value( POINTS_NUMBER ).value<
QgsProperty>();
157 mMinDistance = parameterAsDouble( parameters, MIN_DISTANCE, context );
159 if ( mDynamicMinDistance )
160 mMinDistanceProperty = parameters.value( MIN_DISTANCE ).value<
QgsProperty>();
162 mMaxAttempts = parameterAsInt( parameters, MAX_TRIES_PER_POINT, context );
164 if ( mDynamicMaxAttempts )
165 mMaxAttemptsProperty = parameters.value( MAX_TRIES_PER_POINT ).value<
QgsProperty>();
167 mMinDistanceGlobal = parameterAsDouble( parameters, MIN_DISTANCE_GLOBAL, context );
169 mUseRandomSeed = parameters.value( SEED ).isValid();
170 mRandSeed = parameterAsInt( parameters, SEED, context );
171 mIncludePolygonAttr = parameterAsBoolean( parameters, INCLUDE_POLYGON_ATTRIBUTES, context );
177 std::unique_ptr<QgsProcessingFeatureSource> polygonSource( parameterAsSource( parameters, INPUT, context ) );
178 if ( !polygonSource )
182 fields.
append(
QgsField( u
"rand_point_id"_s, QMetaType::Type::LongLong ) );
183 if ( mIncludePolygonAttr )
184 fields.
extend( polygonSource->fields() );
187 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, OUTPUT, context, ldest, fields,
Qgis::WkbType::Point, polygonSource->sourceCrs() ) );
191 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, polygonSource.get() );
194 std::random_device rd;
195 std::mt19937 mt( !mUseRandomSeed ? rd() : mRandSeed );
196 const std::uniform_real_distribution<> uniformDist( 0, 1 );
197 std::uniform_int_distribution<> uniformIntDist( 1, 999999999 );
204 int missedPoints = 0;
205 int missedPolygons = 0;
206 int emptyOrNullGeom = 0;
208 long long attempts = 0;
209 const long numberOfFeatures = polygonSource->featureCount();
210 long long desiredNumberOfPoints = 0;
211 const double featureProgressStep = 100.0 / ( numberOfFeatures > 0 ? numberOfFeatures : 1 );
212 double baseFeatureProgress = 0.0;
214 QgsFeatureIterator fitL = mIncludePolygonAttr || mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts ? polygonSource->getFeatures()
227 baseFeatureProgress += featureProgressStep;
232 if ( polyGeom.isEmpty() )
236 baseFeatureProgress += featureProgressStep;
240 if ( mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts )
246 int localIndexPoints = 0;
247 int pointsAddedForThisFeature = 0;
249 int numberPointsForThisFeature = mNumPoints;
250 if ( mDynamicNumPoints )
252 numberPointsForThisFeature = mNumPointsProperty.valueAsInt( expressionContext, 0 );
254 desiredNumberOfPoints += numberPointsForThisFeature;
255 int maxAttemptsForThisFeature = mMaxAttempts;
256 if ( mDynamicMaxAttempts )
257 maxAttemptsForThisFeature = mMaxAttemptsProperty.
valueAsInt( expressionContext, maxAttemptsForThisFeature );
258 double minDistanceForThisFeature = mMinDistance;
259 if ( mDynamicMinDistance )
260 minDistanceForThisFeature = mMinDistanceProperty.
valueAsDouble( expressionContext, minDistanceForThisFeature );
261 const double pointProgressIncrement = featureProgressStep / ( numberPointsForThisFeature * maxAttemptsForThisFeature );
262 double pointProgress = 0.0;
264 if ( ( minDistanceForThisFeature == 0 ) && ( mMinDistanceGlobal == 0 ) )
266 QVector<QgsPointXY> newPoints = polyGeom.randomPointsInPolygon( numberPointsForThisFeature, mUseRandomSeed ? uniformIntDist( mt ) : 0 );
267 for (
int i = 0; i < newPoints.length(); i++ )
273 pAttrs.append( totNPoints );
274 if ( mIncludePolygonAttr )
284 pointsAddedForThisFeature++;
285 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature );
287 feedback->
setProgress( baseFeatureProgress + pointProgress );
293 QVector<QgsPointXY> newPoints = polyGeom.randomPointsInPolygon( numberPointsForThisFeature, [&](
const QgsPointXY &newPoint ) ->
bool {
298 if ( minDistanceForThisFeature != 0 && mMinDistanceGlobal < minDistanceForThisFeature && localIndexPoints > 0 )
300 const QList<QgsFeatureId> neighbors = localIndex.
nearestNeighbor( newPoint, 1, minDistanceForThisFeature );
302 if ( !neighbors.empty() )
308 if ( mMinDistanceGlobal != 0.0 && indexPoints > 0 )
310 const QList<QgsFeatureId> neighbors = globalIndex.
nearestNeighbor( newPoint, 1, mMinDistanceGlobal );
312 if ( !neighbors.empty() )
320 pAttrs.append( attempts );
327 if ( minDistanceForThisFeature != 0 )
333 if ( mMinDistanceGlobal != 0.0 )
339 return true; }, mUseRandomSeed ? uniformIntDist( mt ) : 0, feedback, maxAttemptsForThisFeature );
342 for (
int i = 0; i < newPoints.length(); i++ )
347 pAttrs.append( totNPoints );
348 if ( mIncludePolygonAttr )
358 pointsAddedForThisFeature++;
359 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature );
361 feedback->
setProgress( baseFeatureProgress + pointProgress );
364 baseFeatureProgress += featureProgressStep;
365 if ( pointsAddedForThisFeature < numberPointsForThisFeature )
371 missedPoints = desiredNumberOfPoints - totNPoints;
372 feedback->
pushInfo( QObject::tr(
"Total number of points generated: "
373 "%1\nNumber of missed points: "
374 "%2\nPolygons with missing points: "
375 "%3\nFeatures with empty or missing "
380 .arg( missedPolygons )
381 .arg( emptyOrNullGeom ) );
386 outputs.insert( OUTPUT, ldest );
387 outputs.insert( OUTPUT_POINTS, totNPoints );
388 outputs.insert( POINTS_MISSED, missedPoints );
389 outputs.insert( POLYGONS_WITH_MISSED_POINTS, missedPolygons );
390 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.
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...
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.
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.