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