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