QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmrandomextract.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrandomextract.cpp
3 ---------------------
4 begin : December 2019
5 copyright : (C) 2019 by Alexander Bruy
6 email : alexander dot bruy 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
19
20#include <random>
21
22#include "qgsvectorlayer.h"
23
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30void QgsRandomExtractSelectAlgorithmBase::sampleFeatureIds( QgsFeatureSource *source, const long long count, QgsProcessingFeedback *feedback )
31{
32 // Build a list of all feature ids
35 .setNoAttributes() );
36 std::vector<QgsFeatureId> allFeats;
37 allFeats.reserve( count );
38 QgsFeature f;
39 feedback->pushInfo( QObject::tr( "Building list of all features..." ) );
40 while ( fit.nextFeature( f ) )
41 {
42 if ( feedback->isCanceled() )
43 return;
44 allFeats.push_back( f.id() );
45 }
46 feedback->pushInfo( QObject::tr( "Done." ) );
47
48 // initialize random engine
49 std::random_device randomDevice;
50 std::mt19937 mersenneTwister( randomDevice() );
51 std::uniform_int_distribution<size_t> fidsDistribution;
52
53 // If the number of features to select is greater than half the total number of features
54 // we will instead randomly select features to *exclude* from the output layer
55 const std::size_t actualFeatureCount = allFeats.size();
56 std::size_t shuffledFeatureCount = count;
57 bool invertSelection = static_cast<std::size_t>( count ) > actualFeatureCount / 2;
58 if ( invertSelection )
59 shuffledFeatureCount = actualFeatureCount - count;
60
61 std::size_t nb = actualFeatureCount;
62
63 // Shuffle <number> features at the start of the iterator
64 feedback->pushInfo( QObject::tr( "Randomly selecting %1 features" ).arg( count ) );
65 auto cursor = allFeats.begin();
66 using difference_type = std::vector<QgsFeatureId>::difference_type;
67 while ( shuffledFeatureCount-- )
68 {
69 if ( feedback->isCanceled() )
70 return;
71
72 // Update the distribution to match the number of unshuffled features
73 fidsDistribution.param( std::uniform_int_distribution<size_t>::param_type( 0, nb - 1 ) );
74 // Swap the current feature with a random one
75 std::swap( *cursor, *( cursor + static_cast<difference_type>( fidsDistribution( mersenneTwister ) ) ) );
76 // Move the cursor to the next feature
77 ++cursor;
78
79 // Decrement the number of unshuffled features
80 --nb;
81 }
82
83 // Insert the selected features into a QgsFeatureIds set
84 if ( invertSelection )
85 for ( auto it = cursor; it != allFeats.end(); ++it )
86 mSelectedFeatureIds.insert( *it );
87 else
88 for ( auto it = allFeats.begin(); it != cursor; ++it )
89 mSelectedFeatureIds.insert( *it );
90}
91
92QString QgsRandomExtractSelectAlgorithmBase::group() const
93{
94 return QObject::tr( "Vector selection" );
95}
96
97QString QgsRandomExtractSelectAlgorithmBase::groupId() const
98{
99 return u"vectorselection"_s;
100}
101
102// Random extract algorithm
103
104QString QgsRandomExtractAlgorithm::name() const
105{
106 return u"randomextract"_s;
107}
108
109QString QgsRandomExtractAlgorithm::displayName() const
110{
111 return QObject::tr( "Random extract" );
112}
113
114QStringList QgsRandomExtractAlgorithm::tags() const
115{
116 return QObject::tr( "extract,filter,random,number,percentage" ).split( ',' );
117}
118
119QString QgsRandomExtractAlgorithm::shortDescription() const
120{
121 return QObject::tr( "Generates a vector layer that contains only a random subset of the features in an input layer." );
122}
123
124QString QgsRandomExtractAlgorithm::shortHelpString() const
125{
126 return QObject::tr( "This algorithm takes a vector layer and generates a new one that contains only a subset "
127 "of the features in the input layer.\n\n"
128 "The subset is defined randomly, using a percentage or count value to define the total number "
129 "of features in the subset." );
130}
131
132Qgis::ProcessingAlgorithmDocumentationFlags QgsRandomExtractAlgorithm::documentationFlags() const
133{
135}
136
137QgsRandomExtractAlgorithm *QgsRandomExtractAlgorithm::createInstance() const
138{
139 return new QgsRandomExtractAlgorithm();
140}
141
142void QgsRandomExtractAlgorithm::initAlgorithm( const QVariantMap & )
143{
144 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
145 addParameter( new QgsProcessingParameterEnum( u"METHOD"_s, QObject::tr( "Method" ), QStringList() << QObject::tr( "Number of features" ) << QObject::tr( "Percentage of features" ), false, 0 ) );
146 addParameter( new QgsProcessingParameterNumber( u"NUMBER"_s, QObject::tr( "Number/percentage of features" ), Qgis::ProcessingNumberParameterType::Integer, 10, false, 0 ) );
147
148 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Extracted (random)" ) ) );
149}
150
151QVariantMap QgsRandomExtractAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
152{
153 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
154 if ( !source )
155 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
156
157 QString dest;
158 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, source->fields(), source->wkbType(), source->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
159 if ( !sink )
160 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
161
162 const int method = parameterAsEnum( parameters, u"METHOD"_s, context );
163 long long number = parameterAsInt( parameters, u"NUMBER"_s, context );
164 const long long count = source->featureCount();
165
166 if ( method == 0 )
167 {
168 // number of features
169 if ( number > count )
170 throw QgsProcessingException( QObject::tr( "Selected number is greater than feature count. Choose a lower value and try again." ) );
171 }
172 else
173 {
174 // percentage of features
175 if ( number > 100 )
176 throw QgsProcessingException( QObject::tr( "Percentage can't be greater than 100. Choose a lower value and try again." ) );
177
178 number = static_cast<long long>( std::ceil( number * count / 100 ) );
179 }
180
181 sampleFeatureIds( source.get(), number, feedback );
182
183 feedback->pushInfo( QObject::tr( "Adding selected features" ) );
184 QgsFeature f;
186 while ( fit.nextFeature( f ) )
187 {
188 if ( feedback->isCanceled() )
189 return QVariantMap();
190
191 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
192 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
193 }
194
195 sink->finalize();
196
197 QVariantMap outputs;
198 outputs.insert( u"OUTPUT"_s, dest );
199 return outputs;
200}
201
202// Random selection algorithm
203
204QString QgsRandomSelectionAlgorithm::name() const
205{
206 return u"randomselection"_s;
207}
208
209QString QgsRandomSelectionAlgorithm::displayName() const
210{
211 return QObject::tr( "Random selection" );
212}
213
214QStringList QgsRandomSelectionAlgorithm::tags() const
215{
216 return QObject::tr( "select,random,number,percentage" ).split( ',' );
217}
218
219QString QgsRandomSelectionAlgorithm::shortDescription() const
220{
221 return QObject::tr( "Randomly selects features from a vector layer." );
222}
223
224QString QgsRandomSelectionAlgorithm::shortHelpString() const
225{
226 return QObject::tr( "This algorithm takes a vector layer and selects a subset of its features. "
227 "No new layer is generated by this algorithm.\n\n"
228 "The subset is defined randomly, using a percentage or count value to define "
229 "the total number of features in the subset." );
230}
231
232QgsRandomSelectionAlgorithm *QgsRandomSelectionAlgorithm::createInstance() const
233{
234 return new QgsRandomSelectionAlgorithm();
235}
236
237void QgsRandomSelectionAlgorithm::initAlgorithm( const QVariantMap & )
238{
239 addParameter( new QgsProcessingParameterVectorLayer( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
240 addParameter( new QgsProcessingParameterEnum( u"METHOD"_s, QObject::tr( "Method" ), QStringList() << QObject::tr( "Number of features" ) << QObject::tr( "Percentage of features" ), false, 0 ) );
241 addParameter( new QgsProcessingParameterNumber( u"NUMBER"_s, QObject::tr( "Number/percentage of features" ), Qgis::ProcessingNumberParameterType::Integer, 10, false, 0 ) );
242
243 addOutput( new QgsProcessingOutputVectorLayer( u"OUTPUT"_s, QObject::tr( "Selected (random)" ) ) );
244}
245
246QVariantMap QgsRandomSelectionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
247{
248 mInput = parameters.value( u"INPUT"_s );
249 mTargetLayer = parameterAsVectorLayer( parameters, u"INPUT"_s, context );
250
251 if ( !mTargetLayer )
252 throw QgsProcessingException( QObject::tr( "Could not load source layer for INPUT." ) );
253
254 const int method = parameterAsEnum( parameters, u"METHOD"_s, context );
255 long long number = parameterAsInt( parameters, u"NUMBER"_s, context );
256 const long long count = mTargetLayer->featureCount();
257
258 if ( method == 0 )
259 {
260 // number of features
261 if ( number > count )
262 throw QgsProcessingException( QObject::tr( "Selected number is greater than feature count. Choose a lower value and try again." ) );
263 }
264 else
265 {
266 // percentage of features
267 if ( number > 100 )
268 throw QgsProcessingException( QObject::tr( "Percentage can't be greater than 100. Choose a lower value and try again." ) );
269
270 number = static_cast<long long>( std::ceil( number * count / 100 ) );
271 }
272
273 // Insert the selected features into a QgsFeatureIds set
274 sampleFeatureIds( mTargetLayer, number, feedback );
275
276 return QVariantMap();
277}
278
279QVariantMap QgsRandomSelectionAlgorithm::postProcessAlgorithm( QgsProcessingContext &, QgsProcessingFeedback * )
280{
281 mTargetLayer->selectByIds( mSelectedFeatureIds );
282
283 QVariantMap outputs;
284 outputs.insert( u"OUTPUT"_s, mInput );
285 return outputs;
286}
287
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3610
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
Definition qgis.h:2254
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3690
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3701
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3782
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...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
An interface for objects which provide features via a getFeatures method.
virtual QgsFields fields() const =0
Returns the fields associated with features in the source.
virtual QgsCoordinateReferenceSystem sourceCrs() const =0
Returns the coordinate reference system for features in the source.
virtual Qgis::WkbType wkbType() const =0
Returns the geometry type for features returned by this source.
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
virtual long long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsFeatureId id
Definition qgsfeature.h:68
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
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 vector layer output for processing algorithms.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A numeric parameter for processing algorithms.
A vector layer (with or without geometry) parameter for processing algorithms.