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