27QString QgsRandomPointsOnLinesAlgorithm::name()
const
29 return QStringLiteral(
"randompointsonlines" );
32QString QgsRandomPointsOnLinesAlgorithm::displayName()
const
34 return QObject::tr(
"Random points on lines" );
37QStringList QgsRandomPointsOnLinesAlgorithm::tags()
const
39 return QObject::tr(
"seed,attributes,create" ).split(
',' );
42QString QgsRandomPointsOnLinesAlgorithm::group()
const
44 return QObject::tr(
"Vector creation" );
47QString QgsRandomPointsOnLinesAlgorithm::groupId()
const
49 return QStringLiteral(
"vectorcreation" );
52void QgsRandomPointsOnLinesAlgorithm::initAlgorithm(
const QVariantMap & )
56 numberPointsParam->setIsDynamic(
true );
58 numberPointsParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
59 addParameter( numberPointsParam.release() );
61 auto minDistParam = std::make_unique<QgsProcessingParameterDistance>( MIN_DISTANCE, QObject::tr(
"Minimum distance between points" ), 0, INPUT,
true, 0 );
62 minDistParam->setIsDynamic(
true );
64 minDistParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
65 addParameter( minDistParam.release() );
67 auto minDistGlobalParam = std::make_unique<QgsProcessingParameterDistance>( MIN_DISTANCE_GLOBAL, QObject::tr(
"Global minimum distance between points" ), 0, INPUT,
true, 0 );
69 addParameter( minDistGlobalParam.release() );
71 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 );
73 maxAttemptsParam->setIsDynamic(
true );
75 maxAttemptsParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
76 addParameter( maxAttemptsParam.release() );
80 addParameter( randomSeedParam.release() );
82 auto includeLineAttrParam = std::make_unique<QgsProcessingParameterBoolean>( INCLUDE_LINE_ATTRIBUTES, QObject::tr(
"Include line attributes" ),
true );
84 addParameter( includeLineAttrParam.release() );
90 addOutput(
new QgsProcessingOutputNumber( LINES_WITH_MISSED_POINTS, QObject::tr(
"Number of features with missed points" ) ) );
91 addOutput(
new QgsProcessingOutputNumber( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, QObject::tr(
"Number of features with empty or no geometry" ) ) );
94QString QgsRandomPointsOnLinesAlgorithm::shortHelpString()
const
96 return QObject::tr(
"<p>This algorithm creates a point layer with points placed randomly "
97 "on the lines of the <i>Input line layer</i>. "
98 "The default behavior is that the generated point features inherit "
99 "the attributes of the line feature on which they were generated.</p>"
100 "<p>Parameters / options:</p> "
102 "<li>For each feature in the <i><b>Input line layer</b></i>, the "
103 "algorithm attempts to add the specified <i><b>Number of points for "
104 "each feature</b></i> to the output layer.</li> "
105 "<li>A <i><b>Minimum distance between points</b></i> and a "
106 "<i><b>Global minimum distance between points</b></i> can be specified. "
107 "A point will not be added if there is an already generated point within "
108 "this (Euclidean) distance from the generated location. "
109 "With <i>Minimum distance between points</i>, only points on the same "
110 "line feature are considered, while for <i>Global minimum distance "
111 "between points</i> all previously generated points are considered. "
112 "If the <i>Global minimum distance between points</i> is set larger "
113 "than the (local) <i>Minimum distance between points</i>, the latter "
114 "has no effect.<br> "
115 "If the <i>Minimum distance between points</i> is too large, "
116 "it may not be possible to generate the specified <i>Number of points "
117 "for each feature</i>.</li> "
118 "<li>The <i><b>Maximum number of attempts per point</b></i> "
119 "is only relevant if <i>Minimum distance between points</i> or <i>Global "
120 "minimum distance between points</i> is greater than 0. "
121 "The total number of points will be<br> <b>number of input features</b> * "
122 "<b>Number of points for each feature</i><br> if there are no "
123 "misses and all features have proper geometries.</li> "
124 "<li>The seed for the random generator can be provided (<i>Random seed</i> "
125 "- integer, greater than 0).</li> "
126 "<li>The user can choose not to <i><b>Include line feature attributes</b></i> "
127 "in the generated point features.</li> "
129 "<p>Output from the algorithm:</p> "
131 "<li> A point layer containing the random points (<code>OUTPUT</code>).</li> "
132 "<li> The number of generated features (<code>POINTS_GENERATED</code>).</li> "
133 "<li> The number of missed points (<code>POINTS_MISSED</code>).</li> "
134 "<li> The number of features with non-empty geometry and missing points "
135 "(<code>LINES_WITH_MISSED_POINTS</code>).</li> "
136 "<li> The number of features with an empty or no geometry "
137 "(<code>LINES_WITH_EMPTY_OR_NO_GEOMETRY</code>).</li> "
142QString QgsRandomPointsOnLinesAlgorithm::shortDescription()
const
144 return QObject::tr(
"Creates a point layer with points placed randomly on the lines of an input layer." );
147QgsRandomPointsOnLinesAlgorithm *QgsRandomPointsOnLinesAlgorithm::createInstance()
const
149 return new QgsRandomPointsOnLinesAlgorithm();
154 mNumPoints = parameterAsInt( parameters, POINTS_NUMBER, context );
156 if ( mDynamicNumPoints )
157 mNumPointsProperty = parameters.value( POINTS_NUMBER ).value<
QgsProperty>();
159 mMinDistance = parameterAsDouble( parameters, MIN_DISTANCE, context );
161 if ( mDynamicMinDistance )
162 mMinDistanceProperty = parameters.value( MIN_DISTANCE ).value<
QgsProperty>();
164 mMaxAttempts = parameterAsInt( parameters, MAX_TRIES_PER_POINT, context );
166 if ( mDynamicMaxAttempts )
167 mMaxAttemptsProperty = parameters.value( MAX_TRIES_PER_POINT ).value<
QgsProperty>();
169 mMinDistanceGlobal = parameterAsDouble( parameters, MIN_DISTANCE_GLOBAL, context );
171 mUseRandomSeed = parameters.value( SEED ).isValid();
172 mRandSeed = parameterAsInt( parameters, SEED, context );
173 mIncludeLineAttr = parameterAsBoolean( parameters, INCLUDE_LINE_ATTRIBUTES, context );
179 std::unique_ptr<QgsProcessingFeatureSource> lineSource( parameterAsSource( parameters, INPUT, context ) );
184 fields.
append(
QgsField( QStringLiteral(
"rand_point_id" ), QMetaType::Type::LongLong ) );
185 if ( mIncludeLineAttr )
186 fields.
extend( lineSource->fields() );
189 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, OUTPUT, context, ldest, fields,
Qgis::WkbType::Point, lineSource->sourceCrs() ) );
193 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, lineSource.get() );
196 std::random_device rd;
197 std::mt19937 mt( !mUseRandomSeed ? rd() : mRandSeed );
198 std::uniform_real_distribution<> uniformDist( 0, 1 );
204 int missedPoints = 0;
206 int emptyOrNullGeom = 0;
208 const long numberOfFeatures = lineSource->featureCount();
209 long long desiredNumberOfPoints = 0;
210 const double featureProgressStep = 100.0 / ( numberOfFeatures > 0 ? numberOfFeatures : 1 );
211 double baseFeatureProgress = 0.0;
213 QgsFeatureIterator fitL = mIncludeLineAttr || mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts ? lineSource->getFeatures()
226 baseFeatureProgress += featureProgressStep;
231 if ( lGeom.isEmpty() )
235 baseFeatureProgress += featureProgressStep;
240 if ( mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts )
245 const double lineLength = lGeom.length();
246 int pointsAddedForThisFeature = 0;
248 int numberPointsForThisFeature = mNumPoints;
249 if ( mDynamicNumPoints )
250 numberPointsForThisFeature = mNumPointsProperty.valueAsInt( expressionContext, numberPointsForThisFeature );
251 desiredNumberOfPoints += numberPointsForThisFeature;
253 int maxAttemptsForThisFeature = mMaxAttempts;
254 if ( mDynamicMaxAttempts )
255 maxAttemptsForThisFeature = mMaxAttemptsProperty.
valueAsInt( expressionContext, maxAttemptsForThisFeature );
257 double minDistanceForThisFeature = mMinDistance;
258 if ( mDynamicMinDistance )
259 minDistanceForThisFeature = mMinDistanceProperty.
valueAsDouble( expressionContext, minDistanceForThisFeature );
261 const double pointProgressIncrement = featureProgressStep / ( numberPointsForThisFeature * maxAttemptsForThisFeature );
263 double pointProgress = 0.0;
266 for (
long pointIndex = 0; pointIndex < numberPointsForThisFeature; pointIndex++ )
273 int distCheckIterations = 0;
274 while ( distCheckIterations < maxAttemptsForThisFeature )
281 const double randPos = lineLength * uniformDist( mt );
283 distCheckIterations++;
284 pointProgress += pointProgressIncrement;
288 if ( ( minDistanceForThisFeature != 0 ) || ( mMinDistanceGlobal != 0 ) )
292 if ( ( minDistanceForThisFeature != 0 ) && ( pointsAddedForThisFeature > 0 ) )
294 const QList<QgsFeatureId> neighbors = localIndex.
nearestNeighbor( rpGeom, 1, minDistanceForThisFeature );
295 if ( !neighbors.empty() )
297 feedback->
setProgress( baseFeatureProgress + pointProgress );
302 if ( ( mMinDistanceGlobal != 0 ) && ( totNPoints > 0 ) )
304 const QList<QgsFeatureId> neighbors = index.
nearestNeighbor( rpGeom, 1, mMinDistanceGlobal );
305 if ( !neighbors.empty() )
307 feedback->
setProgress( baseFeatureProgress + pointProgress );
315 pAttrs.append( totNPoints );
316 if ( mIncludeLineAttr )
323 if ( mMinDistanceGlobal != 0 )
328 if ( minDistanceForThisFeature != 0 )
336 pointsAddedForThisFeature++;
337 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature - distCheckIterations );
342 feedback->
setProgress( baseFeatureProgress + pointProgress );
345 feedback->
setProgress( baseFeatureProgress + pointProgress );
347 baseFeatureProgress += featureProgressStep;
348 if ( pointsAddedForThisFeature < numberPointsForThisFeature )
354 missedPoints = desiredNumberOfPoints - totNPoints;
355 feedback->
pushInfo( QObject::tr(
"Total number of points generated: "
356 " %1\nNumber of missed points: %2\nFeatures with missing points: "
357 " %3\nFeatures with empty or missing geometries: %4"
362 .arg( emptyOrNullGeom ) );
367 outputs.insert( OUTPUT, ldest );
368 outputs.insert( OUTPUT_POINTS, totNPoints );
369 outputs.insert( POINTS_MISSED, missedPoints );
370 outputs.insert( LINES_WITH_MISSED_POINTS, missedLines );
371 outputs.insert( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, emptyOrNullGeom );
@ VectorPoint
Vector point layers.
@ VectorLine
Vector line layers.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
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...
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
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.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
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 ¶meters, 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.
@ 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.