25static const QString INPUT = QStringLiteral(
"INPUT" );
26static const QString POINTS_NUMBER = QStringLiteral(
"POINTS_NUMBER" );
27static const QString MIN_DISTANCE_GLOBAL = QStringLiteral(
"MIN_DISTANCE_GLOBAL" );
28static const QString MIN_DISTANCE = QStringLiteral(
"MIN_DISTANCE" );
29static const QString MAX_TRIES_PER_POINT = QStringLiteral(
"MAX_TRIES_PER_POINT" );
30static const QString SEED = QStringLiteral(
"SEED" );
31static const QString INCLUDE_LINE_ATTRIBUTES = QStringLiteral(
"INCLUDE_LINE_ATTRIBUTES" );
32static const QString OUTPUT = QStringLiteral(
"OUTPUT" );
33static const QString OUTPUT_POINTS = QStringLiteral(
"OUTPUT_POINTS" );
34static const QString POINTS_MISSED = QStringLiteral(
"POINTS_MISSED" );
35static const QString LINES_WITH_MISSED_POINTS = QStringLiteral(
"LINES_WITH_MISSED_POINTS" );
36static const QString FEATURES_WITH_EMPTY_OR_NO_GEOMETRY = QStringLiteral(
"FEATURES_WITH_EMPTY_OR_NO_GEOMETRY" );
40QString QgsRandomPointsOnLinesAlgorithm::name()
const
42 return QStringLiteral(
"randompointsonlines" );
45QString QgsRandomPointsOnLinesAlgorithm::displayName()
const
47 return QObject::tr(
"Random points on lines" );
50QStringList QgsRandomPointsOnLinesAlgorithm::tags()
const
52 return QObject::tr(
"seed,attributes,create" ).split(
',' );
55QString QgsRandomPointsOnLinesAlgorithm::group()
const
57 return QObject::tr(
"Vector creation" );
60QString QgsRandomPointsOnLinesAlgorithm::groupId()
const
62 return QStringLiteral(
"vectorcreation" );
65void QgsRandomPointsOnLinesAlgorithm::initAlgorithm(
const QVariantMap & )
68 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 );
69 numberPointsParam->setIsDynamic(
true );
71 numberPointsParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
72 addParameter( numberPointsParam.release() );
74 std::unique_ptr< QgsProcessingParameterDistance > minDistParam = std::make_unique< QgsProcessingParameterDistance >( MIN_DISTANCE, QObject::tr(
"Minimum distance between points" ), 0, INPUT,
true, 0 );
75 minDistParam->setIsDynamic(
true );
77 minDistParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
78 addParameter( minDistParam.release() );
80 std::unique_ptr< QgsProcessingParameterDistance > minDistGlobalParam = std::make_unique< QgsProcessingParameterDistance >( MIN_DISTANCE_GLOBAL, QObject::tr(
"Global minimum distance between points" ), 0, INPUT,
true, 0 );
82 addParameter( minDistGlobalParam.release() );
84 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 );
86 maxAttemptsParam->setIsDynamic(
true );
88 maxAttemptsParam->setDynamicLayerParameterName( QStringLiteral(
"INPUT" ) );
89 addParameter( maxAttemptsParam.release() );
91 std::unique_ptr< QgsProcessingParameterNumber > randomSeedParam = std::make_unique< QgsProcessingParameterNumber >( SEED, QObject::tr(
"Random seed" ),
Qgis::ProcessingNumberParameterType::Integer, QVariant(),
true, 1 );
93 addParameter( randomSeedParam.release() );
95 std::unique_ptr< QgsProcessingParameterBoolean > includeLineAttrParam = std::make_unique< QgsProcessingParameterBoolean >( INCLUDE_LINE_ATTRIBUTES, QObject::tr(
"Include line attributes" ),
true );
97 addParameter( includeLineAttrParam.release() );
104 addOutput(
new QgsProcessingOutputNumber( LINES_WITH_MISSED_POINTS, QObject::tr(
"Number of features with missed points" ) ) );
105 addOutput(
new QgsProcessingOutputNumber( FEATURES_WITH_EMPTY_OR_NO_GEOMETRY, QObject::tr(
"Number of features with empty or no geometry" ) ) );
108QString QgsRandomPointsOnLinesAlgorithm::shortHelpString()
const
110 return QObject::tr(
"<p>This algorithm creates a point layer, with points placed randomly "
111 "on the lines of the <i>Input line layer</i>. "
112 "The default behavior is that the generated point features inherit "
113 "the attributes of the line feature on which they were was generated.</p>"
114 "<p>Parameters / options:</p> "
116 "<li>For each feature in the <i><b>Input line layer</b></i>, the "
117 "algorithm attempts to add the specified <i><b>Number of points for "
118 "each feature</b></i> to the output layer.</li> "
119 "<li>A <i><b>Minimum distance between points</b></i> and a "
120 "<i><b>Global minimum distance between points</b></i> can be specified. "
121 "A point will not be added if there is an already generated point within "
122 "this (Euclidean) distance from the generated location. "
123 "With <i>Minimum distance between points</i>, only points on the same "
124 "line feature are considered, while for <i>Global minimum distance "
125 "between points</i> all previously generated points are considered. "
126 "If the <i>Global minimum distance between points</i> is set larger "
127 "than the (local) <i>Minimum distance between points</i>, the latter "
128 "has no effect.<br> "
129 "If the <i>Minimum distance between points</i> is too large, "
130 "it may not be possible to generate the specified <i>Number of points "
131 "for each feature</i>.</li> "
132 "<li>The <i><b>Maximum number of attempts per point</b></i> "
133 "is only relevant if <i>Minimum distance between points</i> or <i>Global "
134 "minimum distance between points</i> is greater than 0. "
135 "The total number of points will be<br> <b>number of input features</b> * "
136 "<b>Number of points for each feature</i><br> if there are no "
137 "misses and all features have proper geometries.</li> "
138 "<li>The seed for the random generator can be provided (<i>Random seed</i> "
139 "- integer, greater than 0).</li> "
140 "<li>The user can choose not to <i><b>Include line feature attributes</b></i> "
141 "in the generated point features.</li> "
143 "<p>Output from the algorithm:</p> "
145 "<li> A point layer containing the random points (<code>OUTPUT</code>).</li> "
146 "<li> The number of generated features (<code>POINTS_GENERATED</code>).</li> "
147 "<li> The number of missed points (<code>POINTS_MISSED</code>).</li> "
148 "<li> The number of features with non-empty geometry and missing points "
149 "(<code>LINES_WITH_MISSED_POINTS</code>).</li> "
150 "<li> The number of features with an empty or no geometry "
151 "(<code>LINES_WITH_EMPTY_OR_NO_GEOMETRY</code>).</li> "
157QgsRandomPointsOnLinesAlgorithm *QgsRandomPointsOnLinesAlgorithm::createInstance()
const
159 return new QgsRandomPointsOnLinesAlgorithm();
164 mNumPoints = parameterAsInt( parameters, POINTS_NUMBER, context );
166 if ( mDynamicNumPoints )
167 mNumPointsProperty = parameters.value( POINTS_NUMBER ).value<
QgsProperty >();
169 mMinDistance = parameterAsDouble( parameters, MIN_DISTANCE, context );
171 if ( mDynamicMinDistance )
172 mMinDistanceProperty = parameters.value( MIN_DISTANCE ).value<
QgsProperty >();
174 mMaxAttempts = parameterAsInt( parameters, MAX_TRIES_PER_POINT, context );
176 if ( mDynamicMaxAttempts )
177 mMaxAttemptsProperty = parameters.value( MAX_TRIES_PER_POINT ).value<
QgsProperty >();
179 mMinDistanceGlobal = parameterAsDouble( parameters, MIN_DISTANCE_GLOBAL, context );
181 mUseRandomSeed = parameters.value( SEED ).isValid();
182 mRandSeed = parameterAsInt( parameters, SEED, context );
183 mIncludeLineAttr = parameterAsBoolean( parameters, INCLUDE_LINE_ATTRIBUTES, context );
187QVariantMap QgsRandomPointsOnLinesAlgorithm::processAlgorithm(
const QVariantMap ¶meters,
190 std::unique_ptr< QgsProcessingFeatureSource > lineSource( parameterAsSource( parameters, INPUT, context ) );
195 fields.
append(
QgsField( QStringLiteral(
"rand_point_id" ), QMetaType::Type::LongLong ) );
196 if ( mIncludeLineAttr )
197 fields.
extend( lineSource->fields() );
200 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, OUTPUT,
205 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, lineSource.get() );
208 std::random_device rd;
209 std::mt19937 mt( !mUseRandomSeed ? rd() : mRandSeed );
210 std::uniform_real_distribution<> uniformDist( 0, 1 );
216 int missedPoints = 0;
218 int emptyOrNullGeom = 0;
220 const long numberOfFeatures = lineSource->featureCount();
221 long long desiredNumberOfPoints = 0;
222 const double featureProgressStep = 100.0 / ( numberOfFeatures > 0 ? numberOfFeatures : 1 );
223 double baseFeatureProgress = 0.0;
225 QgsFeatureIterator fitL = mIncludeLineAttr || mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts ? lineSource->getFeatures()
238 baseFeatureProgress += featureProgressStep;
243 if ( lGeom.isEmpty() )
247 baseFeatureProgress += featureProgressStep;
252 if ( mDynamicNumPoints || mDynamicMinDistance || mDynamicMaxAttempts )
257 const double lineLength = lGeom.length();
258 int pointsAddedForThisFeature = 0;
260 int numberPointsForThisFeature = mNumPoints;
261 if ( mDynamicNumPoints )
262 numberPointsForThisFeature = mNumPointsProperty.valueAsInt( expressionContext, numberPointsForThisFeature );
263 desiredNumberOfPoints += numberPointsForThisFeature;
265 int maxAttemptsForThisFeature = mMaxAttempts;
266 if ( mDynamicMaxAttempts )
267 maxAttemptsForThisFeature = mMaxAttemptsProperty.
valueAsInt( expressionContext, maxAttemptsForThisFeature );
269 double minDistanceForThisFeature = mMinDistance;
270 if ( mDynamicMinDistance )
271 minDistanceForThisFeature = mMinDistanceProperty.
valueAsDouble( expressionContext, minDistanceForThisFeature );
273 const double pointProgressIncrement = featureProgressStep / ( numberPointsForThisFeature * maxAttemptsForThisFeature );
275 double pointProgress = 0.0;
278 for (
long pointIndex = 0; pointIndex < numberPointsForThisFeature; pointIndex++ )
285 int distCheckIterations = 0;
286 while ( distCheckIterations < maxAttemptsForThisFeature )
293 const double randPos = lineLength * uniformDist( mt );
295 distCheckIterations++;
296 pointProgress += pointProgressIncrement;
300 if ( ( minDistanceForThisFeature != 0 ) || ( mMinDistanceGlobal != 0 ) )
304 if ( ( minDistanceForThisFeature != 0 ) && ( pointsAddedForThisFeature > 0 ) )
306 const QList<QgsFeatureId> neighbors = localIndex.
nearestNeighbor( rpGeom, 1, minDistanceForThisFeature );
307 if ( !neighbors.empty() )
309 feedback->
setProgress( baseFeatureProgress + pointProgress );
314 if ( ( mMinDistanceGlobal != 0 ) && ( totNPoints > 0 ) )
316 const QList<QgsFeatureId> neighbors = index.
nearestNeighbor( rpGeom, 1, mMinDistanceGlobal );
317 if ( !neighbors.empty() )
319 feedback->
setProgress( baseFeatureProgress + pointProgress );
327 pAttrs.append( totNPoints );
328 if ( mIncludeLineAttr )
335 if ( mMinDistanceGlobal != 0 )
340 if ( minDistanceForThisFeature != 0 )
348 pointsAddedForThisFeature++;
349 pointProgress += pointProgressIncrement * ( maxAttemptsForThisFeature - distCheckIterations );
354 feedback->
setProgress( baseFeatureProgress + pointProgress );
357 feedback->
setProgress( baseFeatureProgress + pointProgress );
359 baseFeatureProgress += featureProgressStep;
360 if ( pointsAddedForThisFeature < numberPointsForThisFeature )
366 missedPoints = desiredNumberOfPoints - totNPoints;
367 feedback->
pushInfo( QObject::tr(
"Total number of points generated: "
368 " %1\nNumber of missed points: %2\nFeatures with missing points: "
369 " %3\nFeatures with empty or missing geometries: %4"
370 ).arg( totNPoints ).arg( missedPoints ).arg( missedLines ).arg( emptyOrNullGeom ) );
372 outputs.insert( OUTPUT, ldest );
373 outputs.insert( OUTPUT_POINTS, totNPoints );
374 outputs.insert( POINTS_MISSED, missedPoints );
375 outputs.insert( LINES_WITH_MISSED_POINTS, missedLines );
376 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.
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
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.