QGIS API Documentation 3.41.0-Master (3440c17df1d)
Loading...
Searching...
No Matches
qgsalgorithmrandompointsonlines.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrandompointsonlines.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#include "qgsspatialindex.h"
21
22#include <random>
23
24// The algorithm parameter names:
25static const QString INPUT = QStringLiteral( "INPUT" );
26static const QString POINTS_NUMBER = QStringLiteral( "POINTS_NUMBER" );
27static const QString MIN_DISTANCE_GLOBAL = QStringLiteral( "MIN_DISTANCE_GLOBAL" );
28static const QString MIN_DISTANCE = QStringLiteral( "MIN_DISTANCE" );
29static const QString MAX_TRIES_PER_POINT = QStringLiteral( "MAX_TRIES_PER_POINT" );
30static const QString SEED = QStringLiteral( "SEED" );
31static const QString INCLUDE_LINE_ATTRIBUTES = QStringLiteral( "INCLUDE_LINE_ATTRIBUTES" );
32static const QString OUTPUT = QStringLiteral( "OUTPUT" );
33static const QString OUTPUT_POINTS = QStringLiteral( "OUTPUT_POINTS" );
34static const QString POINTS_MISSED = QStringLiteral( "POINTS_MISSED" );
35static const QString LINES_WITH_MISSED_POINTS = QStringLiteral( "LINES_WITH_MISSED_POINTS" );
36static const QString FEATURES_WITH_EMPTY_OR_NO_GEOMETRY = QStringLiteral( "FEATURES_WITH_EMPTY_OR_NO_GEOMETRY" );
37
39
40QString QgsRandomPointsOnLinesAlgorithm::name() const
41{
42 return QStringLiteral( "randompointsonlines" );
43}
44
45QString QgsRandomPointsOnLinesAlgorithm::displayName() const
46{
47 return QObject::tr( "Random points on lines" );
48}
49
50QStringList QgsRandomPointsOnLinesAlgorithm::tags() const
51{
52 return QObject::tr( "seed,attributes,create" ).split( ',' );
53}
54
55QString QgsRandomPointsOnLinesAlgorithm::group() const
56{
57 return QObject::tr( "Vector creation" );
58}
59
60QString QgsRandomPointsOnLinesAlgorithm::groupId() const
61{
62 return QStringLiteral( "vectorcreation" );
63}
64
65void QgsRandomPointsOnLinesAlgorithm::initAlgorithm( const QVariantMap & )
66{
67 addParameter( new QgsProcessingParameterFeatureSource( INPUT, QObject::tr( "Input line layer" ), QList< int >() << static_cast< int >( Qgis::ProcessingSourceType::VectorLine ) ) );
68 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 );
69 numberPointsParam->setIsDynamic( true );
70 numberPointsParam->setDynamicPropertyDefinition( QgsPropertyDefinition( POINTS_NUMBER, QObject::tr( "Number of points for each feature" ), QgsPropertyDefinition::IntegerPositive ) );
71 numberPointsParam->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
72 addParameter( numberPointsParam.release() );
73
74 std::unique_ptr< QgsProcessingParameterDistance > minDistParam = std::make_unique< QgsProcessingParameterDistance >( MIN_DISTANCE, QObject::tr( "Minimum distance between points" ), 0, INPUT, true, 0 );
75 minDistParam->setIsDynamic( true );
76 minDistParam->setDynamicPropertyDefinition( QgsPropertyDefinition( MIN_DISTANCE, QObject::tr( "Minimum distance between points (per feature)" ), QgsPropertyDefinition::DoublePositive ) );
77 minDistParam->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
78 addParameter( minDistParam.release() );
79
80 std::unique_ptr< QgsProcessingParameterDistance > minDistGlobalParam = std::make_unique< QgsProcessingParameterDistance >( MIN_DISTANCE_GLOBAL, QObject::tr( "Global minimum distance between points" ), 0, INPUT, true, 0 );
81 minDistGlobalParam->setFlags( minDistGlobalParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
82 addParameter( minDistGlobalParam.release() );
83
84 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 );
85 maxAttemptsParam->setFlags( maxAttemptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
86 maxAttemptsParam->setIsDynamic( true );
87 maxAttemptsParam->setDynamicPropertyDefinition( QgsPropertyDefinition( MAX_TRIES_PER_POINT, QObject::tr( "Maximum number of search attempts (for Min. dist. > 0)" ), QgsPropertyDefinition::IntegerPositiveGreaterZero ) );
88 maxAttemptsParam->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
89 addParameter( maxAttemptsParam.release() );
90
91 std::unique_ptr< QgsProcessingParameterNumber > randomSeedParam = std::make_unique< QgsProcessingParameterNumber >( SEED, QObject::tr( "Random seed" ), Qgis::ProcessingNumberParameterType::Integer, QVariant(), true, 1 );
92 randomSeedParam->setFlags( randomSeedParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
93 addParameter( randomSeedParam.release() );
94
95 std::unique_ptr< QgsProcessingParameterBoolean > includeLineAttrParam = std::make_unique< QgsProcessingParameterBoolean >( INCLUDE_LINE_ATTRIBUTES, QObject::tr( "Include line attributes" ), true );
96 includeLineAttrParam->setFlags( includeLineAttrParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
97 addParameter( includeLineAttrParam.release() );
98
99 addParameter( new
100 QgsProcessingParameterFeatureSink( OUTPUT, QObject::tr( "Random points on lines" ), Qgis::ProcessingSourceType::VectorPoint ) );
101
102 addOutput( new QgsProcessingOutputNumber( OUTPUT_POINTS, QObject::tr( "Total number of points generated" ) ) );
103 addOutput( new QgsProcessingOutputNumber( POINTS_MISSED, QObject::tr( "Number of missed points" ) ) );
104 addOutput( new QgsProcessingOutputNumber( LINES_WITH_MISSED_POINTS, QObject::tr( "Number of features with missed points" ) ) );
105 addOutput( new QgsProcessingOutputNumber( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, QObject::tr( "Number of features with empty or no geometry" ) ) );
106}
107
108QString QgsRandomPointsOnLinesAlgorithm::shortHelpString() const
109{
110 return QObject::tr( "<p>This algorithm creates a point layer, with points placed randomly "
111 "on the lines of the <i>Input line layer</i>. "
112 "The default behavior is that the generated point features inherit "
113 "the attributes of the line feature on which they were was generated.</p>"
114 "<p>Parameters / options:</p> "
115 "<ul> "
116 "<li>For each feature in the <i><b>Input line layer</b></i>, the "
117 "algorithm attempts to add the specified <i><b>Number of points for "
118 "each feature</b></i> to the output layer.</li> "
119 "<li>A <i><b>Minimum distance between points</b></i> and a "
120 "<i><b>Global minimum distance between points</b></i> can be specified. "
121 "A point will not be added if there is an already generated point within "
122 "this (Euclidean) distance from the generated location. "
123 "With <i>Minimum distance between points</i>, only points on the same "
124 "line feature are considered, while for <i>Global minimum distance "
125 "between points</i> all previously generated points are considered. "
126 "If the <i>Global minimum distance between points</i> is set larger "
127 "than the (local) <i>Minimum distance between points</i>, the latter "
128 "has no effect.<br> "
129 "If the <i>Minimum distance between points</i> is too large, "
130 "it may not be possible to generate the specified <i>Number of points "
131 "for each feature</i>.</li> "
132 "<li>The <i><b>Maximum number of attempts per point</b></i> "
133 "is only relevant if <i>Minimum distance between points</i> or <i>Global "
134 "minimum distance between points</i> is greater than 0. "
135 "The total number of points will be<br> <b>number of input features</b> * "
136 "<b>Number of points for each feature</i><br> if there are no "
137 "misses and all features have proper geometries.</li> "
138 "<li>The seed for the random generator can be provided (<i>Random seed</i> "
139 "- integer, greater than 0).</li> "
140 "<li>The user can choose not to <i><b>Include line feature attributes</b></i> "
141 "in the generated point features.</li> "
142 "</ul> "
143 "<p>Output from the algorithm:</p> "
144 "<ul> "
145 "<li> A point layer containing the random points (<code>OUTPUT</code>).</li> "
146 "<li> The number of generated features (<code>POINTS_GENERATED</code>).</li> "
147 "<li> The number of missed points (<code>POINTS_MISSED</code>).</li> "
148 "<li> The number of features with non-empty geometry and missing points "
149 "(<code>LINES_WITH_MISSED_POINTS</code>).</li> "
150 "<li> The number of features with an empty or no geometry "
151 "(<code>LINES_WITH_EMPTY_OR_NO_GEOMETRY</code>).</li> "
152 "</ul>"
153 );
154}
155
156
157QgsRandomPointsOnLinesAlgorithm *QgsRandomPointsOnLinesAlgorithm::createInstance() const
158{
159 return new QgsRandomPointsOnLinesAlgorithm();
160}
161
162bool QgsRandomPointsOnLinesAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
163{
164 mNumPoints = parameterAsInt( parameters, POINTS_NUMBER, context );
165 mDynamicNumPoints = QgsProcessingParameters::isDynamic( parameters, POINTS_NUMBER );
166 if ( mDynamicNumPoints )
167 mNumPointsProperty = parameters.value( POINTS_NUMBER ).value< QgsProperty >();
168
169 mMinDistance = parameterAsDouble( parameters, MIN_DISTANCE, context );
170 mDynamicMinDistance = QgsProcessingParameters::isDynamic( parameters, MIN_DISTANCE );
171 if ( mDynamicMinDistance )
172 mMinDistanceProperty = parameters.value( MIN_DISTANCE ).value< QgsProperty >();
173
174 mMaxAttempts = parameterAsInt( parameters, MAX_TRIES_PER_POINT, context );
175 mDynamicMaxAttempts = QgsProcessingParameters::isDynamic( parameters, MAX_TRIES_PER_POINT );
176 if ( mDynamicMaxAttempts )
177 mMaxAttemptsProperty = parameters.value( MAX_TRIES_PER_POINT ).value< QgsProperty >();
178
179 mMinDistanceGlobal = parameterAsDouble( parameters, MIN_DISTANCE_GLOBAL, context );
180
181 mUseRandomSeed = parameters.value( SEED ).isValid();
182 mRandSeed = parameterAsInt( parameters, SEED, context );
183 mIncludeLineAttr = parameterAsBoolean( parameters, INCLUDE_LINE_ATTRIBUTES, context );
184 return true;
185}
186
187QVariantMap QgsRandomPointsOnLinesAlgorithm::processAlgorithm( const QVariantMap &parameters,
188 QgsProcessingContext &context, QgsProcessingFeedback *feedback )
189{
190 std::unique_ptr< QgsProcessingFeatureSource > lineSource( parameterAsSource( parameters, INPUT, context ) );
191 if ( !lineSource )
192 throw QgsProcessingException( invalidSourceError( parameters, INPUT ) );
193
194 QgsFields fields;
195 fields.append( QgsField( QStringLiteral( "rand_point_id" ), QMetaType::Type::LongLong ) );
196 if ( mIncludeLineAttr )
197 fields.extend( lineSource->fields() );
198
199 QString ldest;
200 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, OUTPUT,
201 context, ldest, fields, Qgis::WkbType::Point, lineSource->sourceCrs() ) );
202 if ( !sink )
203 throw QgsProcessingException( invalidSinkError( parameters, OUTPUT ) );
204
205 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, lineSource.get() );
206
207 // Initialize random engine
208 std::random_device rd;
209 std::mt19937 mt( !mUseRandomSeed ? rd() : mRandSeed );
210 std::uniform_real_distribution<> uniformDist( 0, 1 );
211
212 // Index for finding global close points (mMinDistance > 0)
213 QgsSpatialIndex index;
214
215 int totNPoints = 0;
216 int missedPoints = 0;
217 int missedLines = 0;
218 int emptyOrNullGeom = 0;
219
220 const long numberOfFeatures = lineSource->featureCount();
221 long long desiredNumberOfPoints = 0;
222 const double featureProgressStep = 100.0 / ( numberOfFeatures > 0 ? numberOfFeatures : 1 );
223 double baseFeatureProgress = 0.0;
224 QgsFeature lFeat;
225 QgsFeatureIterator fitL = mIncludeLineAttr || mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts ? lineSource->getFeatures()
226 : lineSource->getFeatures( QgsFeatureRequest().setNoAttributes() );
227 while ( fitL.nextFeature( lFeat ) )
228 {
229 if ( feedback->isCanceled() )
230 {
231 feedback->setProgress( 0 );
232 break;
233 }
234 if ( !lFeat.hasGeometry() )
235 {
236 // Increment invalid features count
237 emptyOrNullGeom++;
238 baseFeatureProgress += featureProgressStep;
239 feedback->setProgress( baseFeatureProgress );
240 continue;
241 }
242 const QgsGeometry lGeom( lFeat.geometry() );
243 if ( lGeom.isEmpty() )
244 {
245 // Increment invalid features count
246 emptyOrNullGeom++;
247 baseFeatureProgress += featureProgressStep;
248 feedback->setProgress( baseFeatureProgress );
249 continue;
250 }
251
252 if ( mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts )
253 {
254 expressionContext.setFeature( lFeat );
255 }
256
257 const double lineLength = lGeom.length();
258 int pointsAddedForThisFeature = 0;
259
260 int numberPointsForThisFeature = mNumPoints;
261 if ( mDynamicNumPoints )
262 numberPointsForThisFeature = mNumPointsProperty.valueAsInt( expressionContext, numberPointsForThisFeature );
263 desiredNumberOfPoints += numberPointsForThisFeature;
264
265 int maxAttemptsForThisFeature = mMaxAttempts;
266 if ( mDynamicMaxAttempts )
267 maxAttemptsForThisFeature = mMaxAttemptsProperty.valueAsInt( expressionContext, maxAttemptsForThisFeature );
268
269 double minDistanceForThisFeature = mMinDistance;
270 if ( mDynamicMinDistance )
271 minDistanceForThisFeature = mMinDistanceProperty.valueAsDouble( expressionContext, minDistanceForThisFeature );
272
273 const double pointProgressIncrement = featureProgressStep / ( numberPointsForThisFeature * maxAttemptsForThisFeature );
274
275 double pointProgress = 0.0;
276 QgsSpatialIndex localIndex;
277
278 for ( long pointIndex = 0; pointIndex < numberPointsForThisFeature; pointIndex++ )
279 {
280 if ( feedback->isCanceled() )
281 {
282 break;
283 }
284 // Try to add a point (mMaxAttempts attempts)
285 int distCheckIterations = 0;
286 while ( distCheckIterations < maxAttemptsForThisFeature )
287 {
288 if ( feedback->isCanceled() )
289 {
290 break;
291 }
292 // Generate a random point
293 const double randPos = lineLength * uniformDist( mt );
294 const QgsGeometry rpGeom = QgsGeometry( lGeom.interpolate( randPos ) );
295 distCheckIterations++;
296 pointProgress += pointProgressIncrement;
297
298 if ( !rpGeom.isNull() && !rpGeom.isEmpty() )
299 {
300 if ( ( minDistanceForThisFeature != 0 ) || ( mMinDistanceGlobal != 0 ) )
301 {
302 // Check minimum distance to existing points
303 // Per feature first
304 if ( ( minDistanceForThisFeature != 0 ) && ( pointsAddedForThisFeature > 0 ) )
305 {
306 const QList<QgsFeatureId> neighbors = localIndex.nearestNeighbor( rpGeom, 1, minDistanceForThisFeature );
307 if ( !neighbors.empty() )
308 {
309 feedback->setProgress( baseFeatureProgress + pointProgress );
310 continue;
311 }
312 }
313 // Then check globally
314 if ( ( mMinDistanceGlobal != 0 ) && ( totNPoints > 0 ) )
315 {
316 const QList<QgsFeatureId> neighbors = index.nearestNeighbor( rpGeom, 1, mMinDistanceGlobal );
317 if ( !neighbors.empty() )
318 {
319 feedback->setProgress( baseFeatureProgress + pointProgress );
320 continue;
321 }
322 }
323 }
324 // OK to add point
325 QgsFeature f = QgsFeature( totNPoints );
326 QgsAttributes pAttrs = QgsAttributes();
327 pAttrs.append( totNPoints );
328 if ( mIncludeLineAttr )
329 {
330 pAttrs.append( lFeat.attributes() );
331 }
332 f.setAttributes( pAttrs );
333 f.setGeometry( rpGeom );
334
335 if ( mMinDistanceGlobal != 0 )
336 {
337 if ( !index.addFeature( f ) )
338 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QString() ) );
339 }
340 if ( minDistanceForThisFeature != 0 )
341 {
342 if ( !localIndex.addFeature( f ) )
343 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QString() ) );
344 }
345 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
346 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
347 totNPoints++;
348 pointsAddedForThisFeature++;
349 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature - distCheckIterations );
350 break;
351 }
352 else
353 {
354 feedback->setProgress( baseFeatureProgress + pointProgress );
355 }
356 } // while not maxattempts
357 feedback->setProgress( baseFeatureProgress + pointProgress );
358 } // for points
359 baseFeatureProgress += featureProgressStep;
360 if ( pointsAddedForThisFeature < numberPointsForThisFeature )
361 {
362 missedLines++;
363 }
364 feedback->setProgress( baseFeatureProgress );
365 } // while features
366 missedPoints = desiredNumberOfPoints - totNPoints;
367 feedback->pushInfo( QObject::tr( "Total number of points generated: "
368 " %1\nNumber of missed points: %2\nFeatures with missing points: "
369 " %3\nFeatures with empty or missing geometries: %4"
370 ).arg( totNPoints ).arg( missedPoints ).arg( missedLines ).arg( emptyOrNullGeom ) );
371
372 sink->finalize();
373
374 QVariantMap outputs;
375 outputs.insert( OUTPUT, ldest );
376 outputs.insert( OUTPUT_POINTS, totNPoints );
377 outputs.insert( POINTS_MISSED, missedPoints );
378 outputs.insert( LINES_WITH_MISSED_POINTS, missedLines );
379 outputs.insert( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, emptyOrNullGeom );
380
381 return outputs;
382}
383
@ VectorPoint
Vector point layers.
@ VectorLine
Vector line layers.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
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.
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...
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:53
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:70
void extend(const QgsFields &other)
Extends with fields from another QgsFields container.
A geometry is the spatial representation of a feature.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
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.