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