QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmreclassifybylayer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmreclassifybylayer.cpp
3 ---------------------
4 begin : June, 2018
5 copyright : (C) 2018 by Nyall Dawson
6 email : nyall dot dawson 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 <gdal.h>
21
22#include "qgis.h"
24#include "qgsrasterfilewriter.h"
25#include "qgsreclassifyutils.h"
26#include "qgsvariantutils.h"
27
28#include <QString>
29
30using namespace Qt::StringLiterals;
31
33
34//
35// QgsReclassifyAlgorithmBase
36//
37
38
39QString QgsReclassifyAlgorithmBase::group() const
40{
41 return QObject::tr( "Raster analysis" );
42}
43
44QString QgsReclassifyAlgorithmBase::groupId() const
45{
46 return u"rasteranalysis"_s;
47}
48
49void QgsReclassifyAlgorithmBase::initAlgorithm( const QVariantMap & )
50{
51 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT_RASTER"_s, QObject::tr( "Raster layer" ) ) );
52 addParameter( new QgsProcessingParameterBand( u"RASTER_BAND"_s, QObject::tr( "Band number" ), 1, u"INPUT_RASTER"_s ) );
53
54 addAlgorithmParams();
55
56 auto noDataValueParam = std::make_unique<QgsProcessingParameterNumber>( u"NO_DATA"_s, QObject::tr( "Output NoData value" ), Qgis::ProcessingNumberParameterType::Double, -9999 );
57 noDataValueParam->setFlags( Qgis::ProcessingParameterFlag::Advanced );
58 addParameter( noDataValueParam.release() );
59
60 auto boundsHandling = std::make_unique<QgsProcessingParameterEnum>( u"RANGE_BOUNDARIES"_s, QObject::tr( "Range boundaries" ), QStringList() << QObject::tr( "min < value <= max" ) << QObject::tr( "min <= value < max" ) << QObject::tr( "min <= value <= max" ) << QObject::tr( "min < value < max" ), false, 0 );
61 boundsHandling->setFlags( Qgis::ProcessingParameterFlag::Advanced );
62 addParameter( boundsHandling.release() );
63
64 auto missingValuesParam = std::make_unique<QgsProcessingParameterBoolean>( u"NODATA_FOR_MISSING"_s, QObject::tr( "Use NoData when no range matches value" ), false, false );
65 missingValuesParam->setFlags( Qgis::ProcessingParameterFlag::Advanced );
66 addParameter( missingValuesParam.release() );
67
68 std::unique_ptr<QgsProcessingParameterDefinition> typeChoice = QgsRasterAnalysisUtils::createRasterTypeParameter( u"DATA_TYPE"_s, QObject::tr( "Output data type" ), Qgis::DataType::Float32 );
69 typeChoice->setFlags( Qgis::ProcessingParameterFlag::Advanced );
70 addParameter( typeChoice.release() );
71
72 // backwards compatibility parameter
73 // TODO QGIS 5: remove parameter and related logic
74 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( u"CREATE_OPTIONS"_s, QObject::tr( "Creation options" ), QVariant(), false, true );
75 createOptsParam->setMetadata( QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"widget_type"_s, u"rasteroptions"_s } } ) } } ) );
76 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
77 addParameter( createOptsParam.release() );
78
79 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( u"CREATION_OPTIONS"_s, QObject::tr( "Creation options" ), QVariant(), false, true );
80 creationOptsParam->setMetadata( QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"widget_type"_s, u"rasteroptions"_s } } ) } } ) );
81 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
82 addParameter( creationOptsParam.release() );
83
84 addParameter( new QgsProcessingParameterRasterDestination( u"OUTPUT"_s, QObject::tr( "Reclassified raster" ) ) );
85}
86
87bool QgsReclassifyAlgorithmBase::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
88{
89 mDataType = QgsRasterAnalysisUtils::rasterTypeChoiceToDataType( parameterAsEnum( parameters, u"DATA_TYPE"_s, context ) );
90 if ( mDataType == Qgis::DataType::Int8 && atoi( GDALVersionInfo( "VERSION_NUM" ) ) < GDAL_COMPUTE_VERSION( 3, 7, 0 ) )
91 throw QgsProcessingException( QObject::tr( "Int8 data type requires GDAL version 3.7 or later" ) );
92
93 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u"INPUT_RASTER"_s, context );
94
95 if ( !layer )
96 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT_RASTER"_s ) );
97
98 mBand = parameterAsInt( parameters, u"RASTER_BAND"_s, context );
99 if ( mBand < 1 || mBand > layer->bandCount() )
100 throw QgsProcessingException( QObject::tr( "Invalid band number for RASTER_BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( layer->bandCount() ) );
101
102 mInterface.reset( layer->dataProvider()->clone() );
103 mExtent = layer->extent();
104 mCrs = layer->crs();
105 mRasterUnitsPerPixelX = std::abs( layer->rasterUnitsPerPixelX() );
106 mRasterUnitsPerPixelY = std::abs( layer->rasterUnitsPerPixelY() );
107 mNbCellsXProvider = mInterface->xSize();
108 mNbCellsYProvider = mInterface->ySize();
109
110 mNoDataValue = parameterAsDouble( parameters, u"NO_DATA"_s, context );
111 mUseNoDataForMissingValues = parameterAsBoolean( parameters, u"NODATA_FOR_MISSING"_s, context );
112
113 const int boundsType = parameterAsEnum( parameters, u"RANGE_BOUNDARIES"_s, context );
114 switch ( boundsType )
115 {
116 case 0:
117 mBoundsType = QgsReclassifyUtils::RasterClass::IncludeMax;
118 break;
119
120 case 1:
121 mBoundsType = QgsReclassifyUtils::RasterClass::IncludeMin;
122 break;
123
124 case 2:
125 mBoundsType = QgsReclassifyUtils::RasterClass::IncludeMinAndMax;
126 break;
127
128 case 3:
129 mBoundsType = QgsReclassifyUtils::RasterClass::Exclusive;
130 break;
131 }
132
133 return _prepareAlgorithm( parameters, context, feedback );
134}
135
136QVariantMap QgsReclassifyAlgorithmBase::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
137{
138 const QVector<QgsReclassifyUtils::RasterClass> classes = createClasses( mBoundsType, parameters, context, feedback );
139
140 QgsReclassifyUtils::reportClasses( classes, feedback );
141 QgsReclassifyUtils::checkForOverlaps( classes, feedback );
142
143 QString creationOptions = parameterAsString( parameters, u"CREATION_OPTIONS"_s, context ).trimmed();
144 // handle backwards compatibility parameter CREATE_OPTIONS
145 const QString optionsString = parameterAsString( parameters, u"CREATE_OPTIONS"_s, context );
146 if ( !optionsString.isEmpty() )
147 creationOptions = optionsString;
148
149 const QString outputFile = parameterAsOutputLayer( parameters, u"OUTPUT"_s, context );
150 const QString outputFormat = parameterAsOutputRasterFormat( parameters, u"OUTPUT"_s, context );
151
152 auto writer = std::make_unique<QgsRasterFileWriter>( outputFile );
153 writer->setOutputProviderKey( u"gdal"_s );
154 if ( !creationOptions.isEmpty() )
155 {
156 writer->setCreationOptions( creationOptions.split( '|' ) );
157 }
158
159 writer->setOutputFormat( outputFormat );
160 std::unique_ptr<QgsRasterDataProvider> provider( writer->createOneBandRaster( mDataType, mNbCellsXProvider, mNbCellsYProvider, mExtent, mCrs ) );
161 if ( !provider )
162 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
163 if ( !provider->isValid() )
164 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
165
166 provider->setNoDataValue( 1, mNoDataValue );
167
168 QgsReclassifyUtils::reclassify( classes, mInterface.get(), mBand, mExtent, mNbCellsXProvider, mNbCellsYProvider, std::move( provider ), mNoDataValue, mUseNoDataForMissingValues, feedback );
169
170 QVariantMap outputs;
171 outputs.insert( u"OUTPUT"_s, outputFile );
172 return outputs;
173}
174
175
176//
177// QgsReclassifyByLayerAlgorithm
178//
179
180QString QgsReclassifyByLayerAlgorithm::name() const
181{
182 return u"reclassifybylayer"_s;
183}
184
185QString QgsReclassifyByLayerAlgorithm::displayName() const
186{
187 return QObject::tr( "Reclassify by layer" );
188}
189
190QStringList QgsReclassifyByLayerAlgorithm::tags() const
191{
192 return QObject::tr( "raster,reclassify,classes,calculator" ).split( ',' );
193}
194
195QString QgsReclassifyByLayerAlgorithm::shortHelpString() const
196{
197 return QObject::tr( "This algorithm reclassifies a raster band by assigning new class values based on the ranges specified in a vector table." );
198}
199
200QString QgsReclassifyByLayerAlgorithm::shortDescription() const
201{
202 return QObject::tr( "Reclassifies a raster band by assigning new class values based on the ranges specified in a vector table." );
203}
204
205QgsReclassifyByLayerAlgorithm *QgsReclassifyByLayerAlgorithm::createInstance() const
206{
207 return new QgsReclassifyByLayerAlgorithm();
208}
209
210void QgsReclassifyByLayerAlgorithm::addAlgorithmParams()
211{
212 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT_TABLE"_s, QObject::tr( "Layer containing class breaks" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
213 addParameter( new QgsProcessingParameterField( u"MIN_FIELD"_s, QObject::tr( "Minimum class value field" ), QVariant(), u"INPUT_TABLE"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
214 addParameter( new QgsProcessingParameterField( u"MAX_FIELD"_s, QObject::tr( "Maximum class value field" ), QVariant(), u"INPUT_TABLE"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
215 addParameter( new QgsProcessingParameterField( u"VALUE_FIELD"_s, QObject::tr( "Output value field" ), QVariant(), u"INPUT_TABLE"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
216}
217
218bool QgsReclassifyByLayerAlgorithm::_prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
219{
220 std::unique_ptr<QgsFeatureSource> tableSource( parameterAsSource( parameters, u"INPUT_TABLE"_s, context ) );
221 if ( !tableSource )
222 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT_TABLE"_s ) );
223
224 const QString fieldMin = parameterAsString( parameters, u"MIN_FIELD"_s, context );
225 mMinFieldIdx = tableSource->fields().lookupField( fieldMin );
226 if ( mMinFieldIdx < 0 )
227 throw QgsProcessingException( QObject::tr( "Invalid field specified for MIN_FIELD: %1" ).arg( fieldMin ) );
228 const QString fieldMax = parameterAsString( parameters, u"MAX_FIELD"_s, context );
229 mMaxFieldIdx = tableSource->fields().lookupField( fieldMax );
230 if ( mMaxFieldIdx < 0 )
231 throw QgsProcessingException( QObject::tr( "Invalid field specified for MAX_FIELD: %1" ).arg( fieldMax ) );
232 const QString fieldValue = parameterAsString( parameters, u"VALUE_FIELD"_s, context );
233 mValueFieldIdx = tableSource->fields().lookupField( fieldValue );
234 if ( mValueFieldIdx < 0 )
235 throw QgsProcessingException( QObject::tr( "Invalid field specified for VALUE_FIELD: %1" ).arg( fieldValue ) );
236
237 QgsFeatureRequest request;
239 request.setSubsetOfAttributes( QgsAttributeList() << mMinFieldIdx << mMaxFieldIdx << mValueFieldIdx );
240 mTableIterator = tableSource->getFeatures( request );
241
242 return true;
243}
244
245QVector<QgsReclassifyUtils::RasterClass> QgsReclassifyByLayerAlgorithm::createClasses( QgsRasterRange::BoundsType boundsType, const QVariantMap &, QgsProcessingContext &, QgsProcessingFeedback * )
246{
247 QVector<QgsReclassifyUtils::RasterClass> classes;
248 QgsFeature f;
249 while ( mTableIterator.nextFeature( f ) )
250 {
251 bool ok = false;
252
253 // null values map to nan, which corresponds to a range extended to +/- infinity....
254 const QVariant minVariant = f.attribute( mMinFieldIdx );
255 double minValue;
256 if ( QgsVariantUtils::isNull( minVariant ) || minVariant.toString().isEmpty() )
257 {
258 minValue = std::numeric_limits<double>::quiet_NaN();
259 }
260 else
261 {
262 minValue = minVariant.toDouble( &ok );
263 if ( !ok )
264 throw QgsProcessingException( QObject::tr( "Invalid value for minimum: %1" ).arg( minVariant.toString() ) );
265 }
266 const QVariant maxVariant = f.attribute( mMaxFieldIdx );
267 double maxValue;
268 if ( QgsVariantUtils::isNull( maxVariant ) || maxVariant.toString().isEmpty() )
269 {
270 maxValue = std::numeric_limits<double>::quiet_NaN();
271 ok = true;
272 }
273 else
274 {
275 maxValue = maxVariant.toDouble( &ok );
276 if ( !ok )
277 throw QgsProcessingException( QObject::tr( "Invalid value for maximum: %1" ).arg( maxVariant.toString() ) );
278 }
279
280 const double value = f.attribute( mValueFieldIdx ).toDouble( &ok );
281 if ( !ok )
282 throw QgsProcessingException( QObject::tr( "Invalid output value: %1" ).arg( f.attribute( mValueFieldIdx ).toString() ) );
283
284 classes << QgsReclassifyUtils::RasterClass( minValue, maxValue, boundsType, value );
285 }
286 return classes;
287}
288
289
290//
291// QgsReclassifyByTableAlgorithm
292//
293
294QString QgsReclassifyByTableAlgorithm::name() const
295{
296 return u"reclassifybytable"_s;
297}
298
299QString QgsReclassifyByTableAlgorithm::displayName() const
300{
301 return QObject::tr( "Reclassify by table" );
302}
303
304QStringList QgsReclassifyByTableAlgorithm::tags() const
305{
306 return QObject::tr( "raster,reclassify,classes,calculator" ).split( ',' );
307}
308
309QString QgsReclassifyByTableAlgorithm::shortHelpString() const
310{
311 return QObject::tr( "This algorithm reclassifies a raster band by assigning new class values based on the ranges specified in a fixed table." );
312}
313
314QString QgsReclassifyByTableAlgorithm::shortDescription() const
315{
316 return QObject::tr( "Reclassifies a raster band by assigning new class values based on the ranges specified in a fixed table." );
317}
318
319QgsReclassifyByTableAlgorithm *QgsReclassifyByTableAlgorithm::createInstance() const
320{
321 return new QgsReclassifyByTableAlgorithm();
322}
323
324void QgsReclassifyByTableAlgorithm::addAlgorithmParams()
325{
326 addParameter( new QgsProcessingParameterMatrix( u"TABLE"_s, QObject::tr( "Reclassification table" ), 1, false, QStringList() << QObject::tr( "Minimum" ) << QObject::tr( "Maximum" ) << QObject::tr( "Value" ) ) );
327}
328
329bool QgsReclassifyByTableAlgorithm::_prepareAlgorithm( const QVariantMap &, QgsProcessingContext &, QgsProcessingFeedback * )
330{
331 return true;
332}
333
334QVector<QgsReclassifyUtils::RasterClass> QgsReclassifyByTableAlgorithm::createClasses( QgsReclassifyUtils::RasterClass::BoundsType boundsType, const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
335{
336 const QVariantList table = parameterAsMatrix( parameters, u"TABLE"_s, context );
337 if ( table.count() % 3 != 0 )
338 throw QgsProcessingException( QObject::tr( "Invalid value for TABLE: list must contain a multiple of 3 elements (found %1)" ).arg( table.count() ) );
339
340 const int rows = table.count() / 3;
341 QVector<QgsReclassifyUtils::RasterClass> classes;
342 classes.reserve( rows );
343 for ( int row = 0; row < rows; ++row )
344 {
345 bool ok = false;
346
347 // null values map to nan, which corresponds to a range extended to +/- infinity....
348 const QVariant minVariant = table.at( row * 3 );
349 double minValue;
350 if ( QgsVariantUtils::isNull( minVariant ) || minVariant.toString().isEmpty() )
351 {
352 minValue = std::numeric_limits<double>::quiet_NaN();
353 }
354 else
355 {
356 minValue = minVariant.toDouble( &ok );
357 if ( !ok )
358 throw QgsProcessingException( QObject::tr( "Invalid value for minimum: %1" ).arg( table.at( row * 3 ).toString() ) );
359 }
360 const QVariant maxVariant = table.at( row * 3 + 1 );
361 double maxValue;
362 if ( QgsVariantUtils::isNull( maxVariant ) || maxVariant.toString().isEmpty() )
363 {
364 maxValue = std::numeric_limits<double>::quiet_NaN();
365 ok = true;
366 }
367 else
368 {
369 maxValue = maxVariant.toDouble( &ok );
370 if ( !ok )
371 throw QgsProcessingException( QObject::tr( "Invalid value for maximum: %1" ).arg( table.at( row * 3 + 1 ).toString() ) );
372 }
373
374 const double value = table.at( row * 3 + 2 ).toDouble( &ok );
375 if ( !ok )
376 throw QgsProcessingException( QObject::tr( "Invalid output value: %1" ).arg( table.at( row * 3 + 2 ).toString() ) );
377
378 classes << QgsReclassifyUtils::RasterClass( minValue, maxValue, boundsType, value );
379 }
380 return classes;
381}
382
@ 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
@ Numeric
Accepts numeric fields.
Definition qgis.h:3889
@ Float32
Thirty two bit floating point (float).
Definition qgis.h:387
@ Int8
Eight bit signed integer (qint8) (added in QGIS 3.30).
Definition qgis.h:382
@ Hidden
Parameter is hidden and should not be shown to users.
Definition qgis.h:3835
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
@ Double
Double/float values.
Definition qgis.h:3875
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
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 raster band parameter for Processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A table (matrix) parameter for processing algorithms.
A raster layer destination parameter, for specifying the destination path for a raster layer created ...
A raster layer parameter for processing algorithms.
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
Represents a raster layer.
int bandCount() const
Returns the number of bands in this layer.
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
BoundsType
Handling for min and max bounds.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
QList< int > QgsAttributeList
Definition qgsfield.h:30