QGIS API Documentation 3.41.0-Master (57ec4277f5e)
Loading...
Searching...
No Matches
qgsalgorithmrandompointsextent.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrandompointsextent.cpp
3 ---------------------
4 begin : November 2019
5 copyright : (C) 2019 by Clemens Raffler
6 email : clemens dot raffler at gmail dot com
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//Disclaimer: The algorithm optimizes the original Random points in extent algorithm, (C) Alexander Bruy, 2014
19
21#include "qgsspatialindex.h"
22
23#include <random>
24
26
27QString QgsRandomPointsExtentAlgorithm::name() const
28{
29 return QStringLiteral( "randompointsinextent" );
30}
31
32QString QgsRandomPointsExtentAlgorithm::displayName() const
33{
34 return QObject::tr( "Random points in extent" );
35}
36
37QStringList QgsRandomPointsExtentAlgorithm::tags() const
38{
39 return QObject::tr( "random,points,extent,create" ).split( ',' );
40}
41
42QString QgsRandomPointsExtentAlgorithm::group() const
43{
44 return QObject::tr( "Vector creation" );
45}
46
47QString QgsRandomPointsExtentAlgorithm::groupId() const
48{
49 return QStringLiteral( "vectorcreation" );
50}
51
52void QgsRandomPointsExtentAlgorithm::initAlgorithm( const QVariantMap & )
53{
54 addParameter( new QgsProcessingParameterExtent( QStringLiteral( "EXTENT" ), QObject::tr( "Input extent" ) ) );
55 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "POINTS_NUMBER" ), QObject::tr( "Number of points" ), Qgis::ProcessingNumberParameterType::Integer, 1, false, 1 ) );
56 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "MIN_DISTANCE" ), QObject::tr( "Minimum distance between points" ), 0, QStringLiteral( "TARGET_CRS" ), true, 0 ) );
57 addParameter( new QgsProcessingParameterCrs( QStringLiteral( "TARGET_CRS" ), QObject::tr( "Target CRS" ), QStringLiteral( "ProjectCrs" ), false ) );
58
59 std::unique_ptr<QgsProcessingParameterNumber> maxAttempts_param = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "MAX_ATTEMPTS" ), QObject::tr( "Maximum number of search attempts given the minimum distance" ), Qgis::ProcessingNumberParameterType::Integer, 200, true, 1 );
60 maxAttempts_param->setFlags( maxAttempts_param->flags() | Qgis::ProcessingParameterFlag::Advanced );
61 addParameter( maxAttempts_param.release() );
62
63 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Random points" ), Qgis::ProcessingSourceType::VectorPoint ) );
64}
65
66QString QgsRandomPointsExtentAlgorithm::shortHelpString() const
67{
68 return QObject::tr( "This algorithm creates a new point layer with a given "
69 "number of random points, all of them within a given extent. "
70 "A distance factor can be specified, to avoid points being "
71 "too close to each other. If the minimum distance between points "
72 "makes it impossible to create new points, either "
73 "distance can be decreased or the maximum number of attempts may be "
74 "increased."
75 );
76}
77
78QgsRandomPointsExtentAlgorithm *QgsRandomPointsExtentAlgorithm::createInstance() const
79{
80 return new QgsRandomPointsExtentAlgorithm();
81}
82
83bool QgsRandomPointsExtentAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
84{
85 mCrs = parameterAsCrs( parameters, QStringLiteral( "TARGET_CRS" ), context );
86 mExtent = parameterAsExtent( parameters, QStringLiteral( "EXTENT" ), context, mCrs );
87 mNumPoints = parameterAsInt( parameters, QStringLiteral( "POINTS_NUMBER" ), context );
88 mDistance = parameterAsDouble( parameters, QStringLiteral( "MIN_DISTANCE" ), context );
89 mMaxAttempts = parameterAsInt( parameters, QStringLiteral( "MAX_ATTEMPTS" ), context );
90
91 return true;
92}
93
94QVariantMap QgsRandomPointsExtentAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
95{
96 QgsFields fields = QgsFields();
97 fields.append( QgsField( QStringLiteral( "id" ), QMetaType::Type::LongLong ) );
98
99 QString dest;
100 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::Point, mCrs ) );
101 if ( !sink )
102 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
103
104 //initialize random engine
105 std::random_device random_device;
106 const std::mt19937 mersenne_twister( random_device() );
107
108 std::uniform_real_distribution<double> x_distribution( mExtent.xMinimum(), mExtent.xMaximum() );
109 std::uniform_real_distribution<double> y_distribution( mExtent.yMinimum(), mExtent.yMaximum() );
110
111 if ( mDistance == 0 )
112 {
113 int i = 0;
114 while ( i < mNumPoints )
115 {
116 if ( feedback->isCanceled() )
117 break;
118
119 const double rx = x_distribution( random_device );
120 const double ry = y_distribution( random_device );
121
122 QgsFeature f = QgsFeature( i );
123
124 f.setGeometry( QgsGeometry( new QgsPoint( rx, ry ) ) );
125 f.setAttributes( QgsAttributes() << i );
126 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
127 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
128 i++;
129 feedback->setProgress( static_cast<int>( static_cast<double>( i ) / static_cast<double>( mNumPoints ) * 100 ) );
130 }
131 }
132 else
133 {
135 int distCheckIterations = 0;
136
137 int i = 0;
138 while ( i < mNumPoints )
139 {
140 if ( feedback->isCanceled() )
141 break;
142
143 const double rx = x_distribution( random_device );
144 const double ry = y_distribution( random_device );
145
146 //check if new random point is inside searching distance to existing points
147 const QList<QgsFeatureId> neighbors = index.nearestNeighbor( QgsPointXY( rx, ry ), 1, mDistance );
148 if ( neighbors.empty() )
149 {
150 QgsFeature f = QgsFeature( i );
151 f.setAttributes( QgsAttributes() << i );
152 const QgsGeometry randomPointGeom = QgsGeometry( new QgsPoint( rx, ry ) );
153 f.setGeometry( randomPointGeom );
154 if ( !index.addFeature( f ) || !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
155 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
156 i++;
157 distCheckIterations = 0; //reset distCheckIterations if a point is added
158 feedback->setProgress( static_cast<int>( static_cast<double>( i ) / static_cast<double>( mNumPoints ) * 100 ) );
159 }
160 else
161 {
162 if ( distCheckIterations == mMaxAttempts )
163 {
164 throw QgsProcessingException( QObject::tr( "%1 of %2 points have been successfully created, but no more random points could be found "
165 "due to the given minimum distance between points. Either choose a larger extent, "
166 "lower the minimum distance between points or try increasing the number "
167 "of attempts for searching new points." )
168 .arg( i )
169 .arg( mNumPoints ) );
170 }
171 else
172 {
173 distCheckIterations++;
174 continue; //retry with new point
175 }
176 }
177 }
178 }
179
180 sink->finalize();
181
182 QVariantMap outputs;
183 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
184
185 return outputs;
186}
187
@ VectorPoint
Vector point layers.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
A vector of attributes.
@ 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
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
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
A geometry is the spatial representation of a feature.
A class to represent a 2D point.
Definition qgspointxy.h:60
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
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.
A coordinate reference system parameter for processing algorithms.
A double numeric parameter for distance values.
A rectangular map extent parameter for processing algorithms.
A feature sink output for processing algorithms.
A numeric parameter for processing algorithms.
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.