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