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