23 static const QString INPUT = QStringLiteral(
"INPUT" );
24 static const QString POINTS_NUMBER = QStringLiteral(
"POINTS_NUMBER" );
25 static const QString MIN_DISTANCE_GLOBAL = QStringLiteral(
"MIN_DISTANCE_GLOBAL" );
26 static const QString MIN_DISTANCE = QStringLiteral(
"MIN_DISTANCE" );
27 static const QString MAX_TRIES_PER_POINT = QStringLiteral(
"MAX_TRIES_PER_POINT" );
28 static const QString SEED = QStringLiteral(
"SEED" );
29 static const QString INCLUDE_LINE_ATTRIBUTES = QStringLiteral(
"INCLUDE_LINE_ATTRIBUTES" );
30 static const QString OUTPUT = QStringLiteral(
"OUTPUT" );
31 static const QString OUTPUT_POINTS = QStringLiteral(
"OUTPUT_POINTS" );
32 static const QString POINTS_MISSED = QStringLiteral(
"POINTS_MISSED" );
33 static const QString LINES_WITH_MISSED_POINTS = QStringLiteral(
"LINES_WITH_MISSED_POINTS" );
34 static const QString FEATURES_WITH_EMPTY_OR_NO_GEOMETRY = QStringLiteral(
"FEATURES_WITH_EMPTY_OR_NO_GEOMETRY" );
38 QString QgsRandomPointsOnLinesAlgorithm::name()
const
40 return QStringLiteral(
"randompointsonlines" );
43 QString QgsRandomPointsOnLinesAlgorithm::displayName()
const
45 return QObject::tr(
"Random points on lines" );
48 QStringList QgsRandomPointsOnLinesAlgorithm::tags()
const
50 return QObject::tr(
"seed,attributes,create" ).split(
',' );
53 QString QgsRandomPointsOnLinesAlgorithm::group()
const
55 return QObject::tr(
"Vector creation" );
58 QString QgsRandomPointsOnLinesAlgorithm::groupId()
const
60 return QStringLiteral(
"vectorcreation" );
63 void QgsRandomPointsOnLinesAlgorithm::initAlgorithm(
const QVariantMap & )
66 std::unique_ptr< QgsProcessingParameterNumber > numberPointsParam = std::make_unique< QgsProcessingParameterNumber >( POINTS_NUMBER, QObject::tr(
"Number of points for each feature" ),
QgsProcessingParameterNumber::Integer, 1,
false, 1 );
67 numberPointsParam->setIsDynamic(
true );
69 numberPointsParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
70 addParameter( numberPointsParam.release() );
72 std::unique_ptr< QgsProcessingParameterDistance > minDistParam = std::make_unique< QgsProcessingParameterDistance >( MIN_DISTANCE, QObject::tr(
"Minimum distance between points" ), 0, INPUT,
true, 0 );
73 minDistParam->setIsDynamic(
true );
75 minDistParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
76 addParameter( minDistParam.release() );
78 std::unique_ptr< QgsProcessingParameterDistance > minDistGlobalParam = std::make_unique< QgsProcessingParameterDistance >( MIN_DISTANCE_GLOBAL, QObject::tr(
"Global minimum distance between points" ), 0, INPUT,
true, 0 );
80 addParameter( minDistGlobalParam.release() );
82 std::unique_ptr< QgsProcessingParameterNumber > maxAttemptsParam = std::make_unique< QgsProcessingParameterNumber >( MAX_TRIES_PER_POINT, QObject::tr(
"Maximum number of search attempts (for Min. dist. > 0)" ),
QgsProcessingParameterNumber::Integer, 10,
true, 1 );
84 maxAttemptsParam->setIsDynamic(
true );
86 maxAttemptsParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
87 addParameter( maxAttemptsParam.release() );
89 std::unique_ptr< QgsProcessingParameterNumber > randomSeedParam = std::make_unique< QgsProcessingParameterNumber >( SEED, QObject::tr(
"Random seed" ),
QgsProcessingParameterNumber::Integer, QVariant(),
true, 1 );
91 addParameter( randomSeedParam.release() );
93 std::unique_ptr< QgsProcessingParameterBoolean > includeLineAttrParam = std::make_unique< QgsProcessingParameterBoolean >( INCLUDE_LINE_ATTRIBUTES, QObject::tr(
"Include line attributes" ),
true );
95 addParameter( includeLineAttrParam.release() );
102 addOutput(
new QgsProcessingOutputNumber( LINES_WITH_MISSED_POINTS, QObject::tr(
"Number of features with missed points" ) ) );
103 addOutput(
new QgsProcessingOutputNumber( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, QObject::tr(
"Number of features with empty or no geometry" ) ) );
106 QString QgsRandomPointsOnLinesAlgorithm::shortHelpString()
const
108 return QObject::tr(
"<p>This algorithm creates a point layer, with points placed randomly "
109 "on the lines of the <i>Input line layer</i>. "
110 "The default behavior is that the generated point features inherit "
111 "the attributes of the line feature on which they were was generated.</p>"
112 "<p>Parameters / options:</p> "
114 "<li>For each feature in the <i><b>Input line layer</b></i>, the "
115 "algorithm attempts to add the specified <i><b>Number of points for "
116 "each feature</b></i> to the output layer.</li> "
117 "<li>A <i><b>Minimum distance between points</b></i> and a "
118 "<i><b>Global minimum distance between points</b></i> can be specified. "
119 "A point will not be added if there is an already generated point within "
120 "this (Euclidean) distance from the generated location. "
121 "With <i>Minimum distance between points</i>, only points on the same "
122 "line feature are considered, while for <i>Global minimum distance "
123 "between points</i> all previously generated points are considered. "
124 "If the <i>Global minimum distance between points</i> is set larger "
125 "than the (local) <i>Minimum distance between points</i>, the latter "
126 "has no effect.<br> "
127 "If the <i>Minimum distance between points</i> is too large, "
128 "it may not be possible to generate the specified <i>Number of points "
129 "for each feature</i>.</li> "
130 "<li>The <i><b>Maximum number of attempts per point</b></i> "
131 "is only relevant if <i>Minimum distance between points</i> or <i>Global "
132 "minimum distance between points</i> is greater than 0. "
133 "The total number of points will be<br> <b>number of input features</b> * "
134 "<b>Number of points for each feature</i><br> if there are no "
135 "misses and all features have proper geometries.</li> "
136 "<li>The seed for the random generator can be provided (<i>Random seed</i> "
137 "- integer, greater than 0).</li> "
138 "<li>The user can choose not to <i><b>Include line feature attributes</b></i> "
139 "in the generated point features.</li> "
141 "<p>Output from the algorithm:</p> "
143 "<li> A point layer containing the random points (<code>OUTPUT</code>).</li> "
144 "<li> The number of generated features (<code>POINTS_GENERATED</code>).</li> "
145 "<li> The number of missed points (<code>POINTS_MISSED</code>).</li> "
146 "<li> The number of features with non-empty geometry and missing points "
147 "(<code>LINES_WITH_MISSED_POINTS</code>).</li> "
148 "<li> The number of features with an empty or no geometry "
149 "(<code>LINES_WITH_EMPTY_OR_NO_GEOMETRY</code>).</li> "
155 QgsRandomPointsOnLinesAlgorithm *QgsRandomPointsOnLinesAlgorithm::createInstance()
const
157 return new QgsRandomPointsOnLinesAlgorithm();
162 mNumPoints = parameterAsInt( parameters, POINTS_NUMBER, context );
164 if ( mDynamicNumPoints )
165 mNumPointsProperty = parameters.value( POINTS_NUMBER ).value<
QgsProperty >();
167 mMinDistance = parameterAsDouble( parameters, MIN_DISTANCE, context );
169 if ( mDynamicMinDistance )
170 mMinDistanceProperty = parameters.value( MIN_DISTANCE ).value<
QgsProperty >();
172 mMaxAttempts = parameterAsInt( parameters, MAX_TRIES_PER_POINT, context );
174 if ( mDynamicMaxAttempts )
175 mMaxAttemptsProperty = parameters.value( MAX_TRIES_PER_POINT ).value<
QgsProperty >();
177 mMinDistanceGlobal = parameterAsDouble( parameters, MIN_DISTANCE_GLOBAL, context );
179 mUseRandomSeed = parameters.value( SEED ).isValid();
180 mRandSeed = parameterAsInt( parameters, SEED, context );
181 mIncludeLineAttr = parameterAsBoolean( parameters, INCLUDE_LINE_ATTRIBUTES, context );
185 QVariantMap QgsRandomPointsOnLinesAlgorithm::processAlgorithm(
const QVariantMap ¶meters,
188 std::unique_ptr< QgsProcessingFeatureSource > lineSource( parameterAsSource( parameters, INPUT, context ) );
193 fields.
append(
QgsField( QStringLiteral(
"rand_point_id" ), QVariant::LongLong ) );
194 if ( mIncludeLineAttr )
195 fields.
extend( lineSource->fields() );
198 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, OUTPUT,
203 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, lineSource.get() );
206 std::random_device rd;
207 std::mt19937 mt( !mUseRandomSeed ? rd() : mRandSeed );
208 std::uniform_real_distribution<> uniformDist( 0, 1 );
214 int missedPoints = 0;
216 int emptyOrNullGeom = 0;
218 long featureCount = 0;
219 const long numberOfFeatures = lineSource->featureCount();
220 long long desiredNumberOfPoints = 0;
221 const double featureProgressStep = 100.0 / ( numberOfFeatures > 0 ? numberOfFeatures : 1 );
222 double baseFeatureProgress = 0.0;
224 QgsFeatureIterator fitL = mIncludeLineAttr || mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts ? lineSource->getFeatures()
238 baseFeatureProgress += featureProgressStep;
243 if ( lGeom.isEmpty() )
248 baseFeatureProgress += featureProgressStep;
253 if ( mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts )
258 const double lineLength = lGeom.length();
259 int pointsAddedForThisFeature = 0;
261 int numberPointsForThisFeature = mNumPoints;
262 if ( mDynamicNumPoints )
263 numberPointsForThisFeature = mNumPointsProperty.valueAsInt( expressionContext, numberPointsForThisFeature );
264 desiredNumberOfPoints += numberPointsForThisFeature;
266 int maxAttemptsForThisFeature = mMaxAttempts;
267 if ( mDynamicMaxAttempts )
268 maxAttemptsForThisFeature = mMaxAttemptsProperty.
valueAsInt( expressionContext, maxAttemptsForThisFeature );
270 double minDistanceForThisFeature = mMinDistance;
271 if ( mDynamicMinDistance )
272 minDistanceForThisFeature = mMinDistanceProperty.
valueAsDouble( expressionContext, minDistanceForThisFeature );
274 const double pointProgressIncrement = featureProgressStep / ( numberPointsForThisFeature * maxAttemptsForThisFeature );
276 double pointProgress = 0.0;
279 for (
long pointIndex = 0; pointIndex < numberPointsForThisFeature; pointIndex++ )
286 int distCheckIterations = 0;
287 while ( distCheckIterations < maxAttemptsForThisFeature )
294 const double randPos = lineLength * uniformDist( mt );
296 distCheckIterations++;
297 pointProgress += pointProgressIncrement;
301 if ( ( minDistanceForThisFeature != 0 ) || ( mMinDistanceGlobal != 0 ) )
305 if ( ( minDistanceForThisFeature != 0 ) && ( pointsAddedForThisFeature > 0 ) )
307 const QList<QgsFeatureId> neighbors = localIndex.
nearestNeighbor( rpGeom, 1, minDistanceForThisFeature );
308 if ( !neighbors.empty() )
310 feedback->
setProgress( baseFeatureProgress + pointProgress );
315 if ( ( mMinDistanceGlobal != 0 ) && ( totNPoints > 0 ) )
317 const QList<QgsFeatureId> neighbors = index.
nearestNeighbor( rpGeom, 1, mMinDistanceGlobal );
318 if ( !neighbors.empty() )
320 feedback->
setProgress( baseFeatureProgress + pointProgress );
328 pAttrs.append( totNPoints );
329 if ( mIncludeLineAttr )
336 if ( mMinDistanceGlobal != 0 )
341 if ( minDistanceForThisFeature != 0 )
349 pointsAddedForThisFeature++;
350 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature - distCheckIterations );
355 feedback->
setProgress( baseFeatureProgress + pointProgress );
358 feedback->
setProgress( baseFeatureProgress + pointProgress );
360 baseFeatureProgress += featureProgressStep;
361 if ( pointsAddedForThisFeature < numberPointsForThisFeature )
368 missedPoints = desiredNumberOfPoints - totNPoints;
369 feedback->
pushInfo( QObject::tr(
"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 ).arg( totNPoints ).arg( missedPoints ).arg( missedLines ).arg( emptyOrNullGeom ) );
374 outputs.insert( OUTPUT, ldest );
375 outputs.insert( OUTPUT_POINTS, totNPoints );
376 outputs.insert( POINTS_MISSED, missedPoints );
377 outputs.insert( LINES_WITH_MISSED_POINTS, missedLines );
378 outputs.insert( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, emptyOrNullGeom );
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)
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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
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 SIP_HOLDGIL
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
void extend(const QgsFields &other)
Extends with fields from another QgsFields container.
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Appends a field. The field must have unique name, otherwise it is rejected (returns false)
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.
@ FlagAdvanced
Parameter is an advanced parameter which should be hidden from users by default.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
static bool isDynamic(const QVariantMap ¶meters, const QString &name)
Returns true if the parameter with matching name is a dynamic parameter, and must be evaluated once f...
@ TypeVectorLine
Vector line layers.
@ TypeVectorPoint
Vector point layers.
Definition for a property.
@ IntegerPositiveGreaterZero
Non-zero positive integer values.
@ IntegerPositive
Positive integer values (including 0)
@ DoublePositive
Positive double value (including 0)
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.