QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
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 QGS_MARK_ALGORITHM_SOURCE
188
189 std::unique_ptr<QgsProcessingFeatureSource> lineSource( parameterAsSource( parameters, INPUT, context ) );
190 if ( !lineSource )
191 throw QgsProcessingException( invalidSourceError( parameters, INPUT ) );
192
193 QgsFields fields;
194 fields.append( QgsField( u"rand_point_id"_s, QMetaType::Type::LongLong ) );
195 if ( mIncludeLineAttr )
196 fields.extend( lineSource->fields() );
197
198 QString ldest;
199 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, OUTPUT, context, ldest, fields, Qgis::WkbType::Point, lineSource->sourceCrs() ) );
200 if ( !sink )
201 throw QgsProcessingException( invalidSinkError( parameters, OUTPUT ) );
202
203 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, lineSource.get() );
204
205 // Initialize random engine
206 std::random_device rd;
207 std::mt19937 mt( !mUseRandomSeed ? rd() : mRandSeed );
208 std::uniform_real_distribution<> uniformDist( 0, 1 );
209
210 // Index for finding global close points (mMinDistance > 0)
211 QgsSpatialIndex index;
212
213 int totNPoints = 0;
214 int missedPoints = 0;
215 int missedLines = 0;
216 int emptyOrNullGeom = 0;
217
218 const long numberOfFeatures = lineSource->featureCount();
219 long long desiredNumberOfPoints = 0;
220 const double featureProgressStep = 100.0 / ( numberOfFeatures > 0 ? numberOfFeatures : 1 );
221 double baseFeatureProgress = 0.0;
222 QgsFeature lFeat;
223 QgsFeatureIterator fitL = mIncludeLineAttr || mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts ? lineSource->getFeatures()
224 : lineSource->getFeatures( QgsFeatureRequest().setNoAttributes() );
225 while ( fitL.nextFeature( lFeat ) )
226 {
227 if ( feedback->isCanceled() )
228 {
229 feedback->setProgress( 0 );
230 break;
231 }
232 if ( !lFeat.hasGeometry() )
233 {
234 // Increment invalid features count
235 emptyOrNullGeom++;
236 baseFeatureProgress += featureProgressStep;
237 feedback->setProgress( baseFeatureProgress );
238 continue;
239 }
240 const QgsGeometry lGeom( lFeat.geometry() );
241 if ( lGeom.isEmpty() )
242 {
243 // Increment invalid features count
244 emptyOrNullGeom++;
245 baseFeatureProgress += featureProgressStep;
246 feedback->setProgress( baseFeatureProgress );
247 continue;
248 }
249
250 if ( mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts )
251 {
252 expressionContext.setFeature( lFeat );
253 }
254
255 const double lineLength = lGeom.length();
256 int pointsAddedForThisFeature = 0;
257
258 int numberPointsForThisFeature = mNumPoints;
259 if ( mDynamicNumPoints )
260 numberPointsForThisFeature = mNumPointsProperty.valueAsInt( expressionContext, numberPointsForThisFeature );
261 desiredNumberOfPoints += numberPointsForThisFeature;
262
263 int maxAttemptsForThisFeature = mMaxAttempts;
264 if ( mDynamicMaxAttempts )
265 maxAttemptsForThisFeature = mMaxAttemptsProperty.valueAsInt( expressionContext, maxAttemptsForThisFeature );
266
267 double minDistanceForThisFeature = mMinDistance;
268 if ( mDynamicMinDistance )
269 minDistanceForThisFeature = mMinDistanceProperty.valueAsDouble( expressionContext, minDistanceForThisFeature );
270
271 const double pointProgressIncrement = featureProgressStep / ( numberPointsForThisFeature * maxAttemptsForThisFeature );
272
273 double pointProgress = 0.0;
274 QgsSpatialIndex localIndex;
275
276 for ( long pointIndex = 0; pointIndex < numberPointsForThisFeature; pointIndex++ )
277 {
278 if ( feedback->isCanceled() )
279 {
280 break;
281 }
282 // Try to add a point (mMaxAttempts attempts)
283 int distCheckIterations = 0;
284 while ( distCheckIterations < maxAttemptsForThisFeature )
285 {
286 if ( feedback->isCanceled() )
287 {
288 break;
289 }
290 // Generate a random point
291 const double randPos = lineLength * uniformDist( mt );
292 const QgsGeometry rpGeom = QgsGeometry( lGeom.interpolate( randPos ) );
293 distCheckIterations++;
294 pointProgress += pointProgressIncrement;
295
296 if ( !rpGeom.isNull() && !rpGeom.isEmpty() )
297 {
298 if ( ( minDistanceForThisFeature != 0 ) || ( mMinDistanceGlobal != 0 ) )
299 {
300 // Check minimum distance to existing points
301 // Per feature first
302 if ( ( minDistanceForThisFeature != 0 ) && ( pointsAddedForThisFeature > 0 ) )
303 {
304 const QList<QgsFeatureId> neighbors = localIndex.nearestNeighbor( rpGeom, 1, minDistanceForThisFeature );
305 if ( !neighbors.empty() )
306 {
307 feedback->setProgress( baseFeatureProgress + pointProgress );
308 continue;
309 }
310 }
311 // Then check globally
312 if ( ( mMinDistanceGlobal != 0 ) && ( totNPoints > 0 ) )
313 {
314 const QList<QgsFeatureId> neighbors = index.nearestNeighbor( rpGeom, 1, mMinDistanceGlobal );
315 if ( !neighbors.empty() )
316 {
317 feedback->setProgress( baseFeatureProgress + pointProgress );
318 continue;
319 }
320 }
321 }
322 // OK to add point
323 QgsFeature f = QgsFeature( totNPoints );
324 QgsAttributes pAttrs = QgsAttributes();
325 pAttrs.append( totNPoints );
326 if ( mIncludeLineAttr )
327 {
328 pAttrs.append( lFeat.attributes() );
329 }
330 f.setAttributes( pAttrs );
331 f.setGeometry( rpGeom );
332
333 if ( mMinDistanceGlobal != 0 )
334 {
335 if ( !index.addFeature( f ) )
336 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QString() ) );
337 }
338 if ( minDistanceForThisFeature != 0 )
339 {
340 if ( !localIndex.addFeature( f ) )
341 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QString() ) );
342 }
343 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
344 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
345 else
346 feedback->featureAddedToSink( u"OUTPUT"_s );
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(
368 QObject::tr(
369 "Total number of points generated: "
370 " %1\nNumber of missed points: %2\nFeatures with missing points: "
371 " %3\nFeatures with empty or missing geometries: %4"
372 )
373 .arg( totNPoints )
374 .arg( missedPoints )
375 .arg( missedLines )
376 .arg( emptyOrNullGeom )
377 );
378
379 sink->finalize();
380 feedback->featureSinkFinalized( u"OUTPUT"_s );
381
382 QVariantMap outputs;
383 outputs.insert( OUTPUT, ldest );
384 outputs.insert( OUTPUT_POINTS, totNPoints );
385 outputs.insert( POINTS_MISSED, missedPoints );
386 outputs.insert( LINES_WITH_MISSED_POINTS, missedLines );
387 outputs.insert( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, emptyOrNullGeom );
388
389 return outputs;
390}
391
@ VectorPoint
Vector point layers.
Definition qgis.h:3750
@ VectorLine
Vector line layers.
Definition qgis.h:3751
@ Point
Point.
Definition qgis.h:296
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3982
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:64
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:66
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:45
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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
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.