QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmroundrastervalues.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmroundrastervalues.cpp
3 ---------------------
4 begin : April 2020
5 copyright : (C) 2020 by Clemens Raffler
6 email : clemens dot raffler 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 "qgsrasterfilewriter.h"
21
22#include <QString>
23
24using namespace Qt::StringLiterals;
25
27
28QString QgsRoundRasterValuesAlgorithm::name() const
29{
30 return u"roundrastervalues"_s;
31}
32
33QString QgsRoundRasterValuesAlgorithm::displayName() const
34{
35 return QObject::tr( "Round raster" );
36}
37
38QStringList QgsRoundRasterValuesAlgorithm::tags() const
39{
40 return QObject::tr( "data,cells,round,truncate" ).split( ',' );
41}
42
43QString QgsRoundRasterValuesAlgorithm::group() const
44{
45 return QObject::tr( "Raster analysis" );
46}
47
48QString QgsRoundRasterValuesAlgorithm::groupId() const
49{
50 return u"rasteranalysis"_s;
51}
52
53void QgsRoundRasterValuesAlgorithm::initAlgorithm( const QVariantMap & )
54{
55 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT"_s, u"Input raster"_s ) );
56 addParameter( new QgsProcessingParameterBand( u"BAND"_s, QObject::tr( "Band number" ), 1, u"INPUT"_s ) );
57 addParameter( new QgsProcessingParameterEnum( u"ROUNDING_DIRECTION"_s, QObject::tr( "Rounding direction" ), QStringList() << QObject::tr( "Round up" ) << QObject::tr( "Round to nearest" ) << QObject::tr( "Round down" ), false, 1 ) );
58 addParameter( new QgsProcessingParameterNumber( u"DECIMAL_PLACES"_s, QObject::tr( "Number of decimals places" ), Qgis::ProcessingNumberParameterType::Integer, 2 ) );
59 std::unique_ptr<QgsProcessingParameterDefinition> baseParameter = std::make_unique<QgsProcessingParameterNumber>( u"BASE_N"_s, QObject::tr( "Base n for rounding to multiples of n" ), Qgis::ProcessingNumberParameterType::Integer, 10, true, 1 );
60 baseParameter->setFlags( Qgis::ProcessingParameterFlag::Advanced );
61 addParameter( baseParameter.release() );
62
63 // backwards compatibility parameter
64 // TODO QGIS 5: remove parameter and related logic
65 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( u"CREATE_OPTIONS"_s, QObject::tr( "Creation options" ), QVariant(), false, true );
66 createOptsParam->setMetadata( QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"widget_type"_s, u"rasteroptions"_s } } ) } } ) );
67 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
68 addParameter( createOptsParam.release() );
69
70 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( u"CREATION_OPTIONS"_s, QObject::tr( "Creation options" ), QVariant(), false, true );
71 creationOptsParam->setMetadata( QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"widget_type"_s, u"rasteroptions"_s } } ) } } ) );
72 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
73 addParameter( creationOptsParam.release() );
74
75 addParameter( new QgsProcessingParameterRasterDestination( u"OUTPUT"_s, QObject::tr( "Output raster" ) ) );
76}
77
78QString QgsRoundRasterValuesAlgorithm::shortHelpString() const
79{
80 return QObject::tr( "This algorithm rounds the cell values of a raster dataset to the specified number of decimals.\n "
81 "Alternatively, a negative number of decimal places may be used to round values to powers of a base n "
82 "(specified in the advanced parameter Base n). For example, with a Base value n of 10 and Decimal places of -1 "
83 "the algorithm rounds cell values to multiples of 10, -2 rounds to multiples of 100, and so on. Arbitrary base values "
84 "may be chosen, the algorithm applies the same multiplicative principle. Rounding cell values to multiples of "
85 "a base n may be used to generalize raster layers.\n"
86 "The algorithm preserves the data type of the input raster. Therefore byte/integer rasters can only be rounded "
87 "to multiples of a base n, otherwise a warning is raised and the raster gets copied as byte/integer raster." );
88}
89
90QString QgsRoundRasterValuesAlgorithm::shortDescription() const
91{
92 return QObject::tr( "Rounds the cell values of a raster dataset to a specified number of decimals." );
93}
94
95QgsRoundRasterValuesAlgorithm *QgsRoundRasterValuesAlgorithm::createInstance() const
96{
97 return new QgsRoundRasterValuesAlgorithm();
98}
99
100bool QgsRoundRasterValuesAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
101{
102 Q_UNUSED( feedback );
103 QgsRasterLayer *inputRaster = parameterAsRasterLayer( parameters, u"INPUT"_s, context );
104 mDecimalPrecision = parameterAsInt( parameters, u"DECIMAL_PLACES"_s, context );
105 mBaseN = parameterAsInt( parameters, u"BASE_N"_s, context );
106 mMultipleOfBaseN = pow( mBaseN, abs( mDecimalPrecision ) );
107 mScaleFactor = std::pow( 10.0, mDecimalPrecision );
108
109 if ( !inputRaster )
110 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT"_s ) );
111
112 mBand = parameterAsInt( parameters, u"BAND"_s, context );
113 if ( mBand < 1 || mBand > inputRaster->bandCount() )
114 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( inputRaster->bandCount() ) );
115
116 mRoundingDirection = parameterAsEnum( parameters, u"ROUNDING_DIRECTION"_s, context );
117
118 mInterface.reset( inputRaster->dataProvider()->clone() );
119 mDataType = mInterface->dataType( mBand );
120
121 switch ( mDataType )
122 {
128 mIsInteger = true;
129 if ( mDecimalPrecision > -1 )
130 feedback->reportError( QObject::tr( "Input raster is of byte or integer type. The cell values cannot be rounded and will be output using the same data type." ), false );
131 break;
132 default:
133 mIsInteger = false;
134 break;
135 }
136
137 mInputNoDataValue = inputRaster->dataProvider()->sourceNoDataValue( mBand );
138 mExtent = inputRaster->extent();
139 mLayerWidth = inputRaster->width();
140 mLayerHeight = inputRaster->height();
141 mCrs = inputRaster->crs();
142 mNbCellsXProvider = mInterface->xSize();
143 mNbCellsYProvider = mInterface->ySize();
144 return true;
145}
146
147QVariantMap QgsRoundRasterValuesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
148{
149 //prepare output dataset
150 QString creationOptions = parameterAsString( parameters, u"CREATION_OPTIONS"_s, context ).trimmed();
151 // handle backwards compatibility parameter CREATE_OPTIONS
152 const QString optionsString = parameterAsString( parameters, u"CREATE_OPTIONS"_s, context );
153 if ( !optionsString.isEmpty() )
154 creationOptions = optionsString;
155
156 const QString outputFile = parameterAsOutputLayer( parameters, u"OUTPUT"_s, context );
157 const QString outputFormat = parameterAsOutputRasterFormat( parameters, u"OUTPUT"_s, context );
158 auto writer = std::make_unique<QgsRasterFileWriter>( outputFile );
159 writer->setOutputProviderKey( u"gdal"_s );
160 if ( !creationOptions.isEmpty() )
161 {
162 writer->setCreationOptions( creationOptions.split( '|' ) );
163 }
164 writer->setOutputFormat( outputFormat );
165 std::unique_ptr<QgsRasterDataProvider> provider( writer->createOneBandRaster( mInterface->dataType( mBand ), mNbCellsXProvider, mNbCellsYProvider, mExtent, mCrs ) );
166 if ( !provider )
167 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
168 if ( !provider->isValid() )
169 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
170
171 //prepare output provider
172 QgsRasterDataProvider *destinationRasterProvider;
173 destinationRasterProvider = provider.get();
174 destinationRasterProvider->setEditable( true );
175 destinationRasterProvider->setNoDataValue( 1, mInputNoDataValue );
176
177 const bool hasReportsDuringClose = provider->hasReportsDuringClose();
178 const double maxProgressDuringBlockWriting = hasReportsDuringClose ? 50.0 : 100.0;
179
180 QgsRasterIterator iter( mInterface.get() );
181 iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
182 int iterLeft = 0;
183 int iterTop = 0;
184 int iterCols = 0;
185 int iterRows = 0;
186 std::unique_ptr<QgsRasterBlock> analysisRasterBlock;
187 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, analysisRasterBlock, iterLeft, iterTop ) )
188 {
189 if ( feedback )
190 feedback->setProgress( maxProgressDuringBlockWriting * iter.progress( mBand ) );
191 if ( mIsInteger && mDecimalPrecision > -1 )
192 {
193 //nothing to round, just write raster block
194 analysisRasterBlock->setNoDataValue( mInputNoDataValue );
195 if ( !destinationRasterProvider->writeBlock( analysisRasterBlock.get(), mBand, iterLeft, iterTop ) )
196 {
197 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( destinationRasterProvider->error().summary() ) );
198 }
199 }
200 else
201 {
202 for ( int row = 0; row < iterRows; row++ )
203 {
204 if ( feedback && feedback->isCanceled() )
205 break;
206 for ( int column = 0; column < iterCols; column++ )
207 {
208 bool isNoData = false;
209 const double val = analysisRasterBlock->valueAndNoData( row, column, isNoData );
210 if ( isNoData )
211 {
212 analysisRasterBlock->setValue( row, column, mInputNoDataValue );
213 }
214 else
215 {
216 double roundedVal = mInputNoDataValue;
217 if ( mRoundingDirection == 0 && mDecimalPrecision < 0 )
218 {
219 roundedVal = roundUpBaseN( val );
220 }
221 else if ( mRoundingDirection == 0 && mDecimalPrecision > -1 )
222 {
223 const double m = ( val < 0.0 ) ? -1.0 : 1.0;
224 roundedVal = roundUp( val, m );
225 }
226 else if ( mRoundingDirection == 1 && mDecimalPrecision < 0 )
227 {
228 roundedVal = roundNearestBaseN( val );
229 }
230 else if ( mRoundingDirection == 1 && mDecimalPrecision > -1 )
231 {
232 const double m = ( val < 0.0 ) ? -1.0 : 1.0;
233 roundedVal = roundNearest( val, m );
234 }
235 else if ( mRoundingDirection == 2 && mDecimalPrecision < 0 )
236 {
237 roundedVal = roundDownBaseN( val );
238 }
239 else
240 {
241 const double m = ( val < 0.0 ) ? -1.0 : 1.0;
242 roundedVal = roundDown( val, m );
243 }
244 //integer values get automatically cast to double when reading and back to int when writing
245 analysisRasterBlock->setValue( row, column, roundedVal );
246 }
247 }
248 }
249 if ( !destinationRasterProvider->writeBlock( analysisRasterBlock.get(), mBand, iterLeft, iterTop ) )
250 {
251 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( destinationRasterProvider->error().summary() ) );
252 }
253 }
254 }
255 destinationRasterProvider->setEditable( false );
256
257 if ( feedback && hasReportsDuringClose )
258 {
259 std::unique_ptr<QgsFeedback> scaledFeedback( QgsFeedback::createScaledFeedback( feedback, maxProgressDuringBlockWriting, 100.0 ) );
260 if ( !provider->closeWithProgress( scaledFeedback.get() ) )
261 {
262 if ( feedback->isCanceled() )
263 return {};
264 throw QgsProcessingException( QObject::tr( "Could not write raster dataset" ) );
265 }
266 }
267
268 QVariantMap outputs;
269 outputs.insert( u"OUTPUT"_s, outputFile );
270 return outputs;
271}
272
273double QgsRoundRasterValuesAlgorithm::roundNearest( double value, double m )
274{
275 return ( std::round( value * m * mScaleFactor ) / mScaleFactor ) * m;
276}
277
278double QgsRoundRasterValuesAlgorithm::roundUp( double value, double m )
279{
280 return ( std::ceil( value * m * mScaleFactor ) / mScaleFactor ) * m;
281}
282
283double QgsRoundRasterValuesAlgorithm::roundDown( double value, double m )
284{
285 return ( std::floor( value * m * mScaleFactor ) / mScaleFactor ) * m;
286}
287
288double QgsRoundRasterValuesAlgorithm::roundNearestBaseN( double value )
289{
290 return static_cast<double>( mMultipleOfBaseN * round( value / mMultipleOfBaseN ) );
291}
292
293double QgsRoundRasterValuesAlgorithm::roundUpBaseN( double value )
294{
295 return static_cast<double>( mMultipleOfBaseN * ceil( value / mMultipleOfBaseN ) );
296}
297
298double QgsRoundRasterValuesAlgorithm::roundDownBaseN( double value )
299{
300 return static_cast<double>( mMultipleOfBaseN * floor( value / mMultipleOfBaseN ) );
301}
302
@ Int16
Sixteen bit signed integer (qint16).
Definition qgis.h:384
@ UInt16
Sixteen bit unsigned integer (quint16).
Definition qgis.h:383
@ Byte
Eight bit unsigned integer (quint8).
Definition qgis.h:381
@ Int32
Thirty two bit signed integer (qint32).
Definition qgis.h:386
@ UInt32
Thirty two bit unsigned integer (quint32).
Definition qgis.h:385
@ 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
virtual QgsError error() const
Gets current status error.
QString summary() const
Short error description, usually the first error in chain, the real error.
Definition qgserror.cpp:133
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
static std::unique_ptr< QgsFeedback > createScaledFeedback(QgsFeedback *parentFeedback, double startPercentage, double endPercentage)
Returns a feedback object whose [0, 100] progression range will be mapped to parentFeedback [startPer...
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.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A raster band parameter for Processing algorithms.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A numeric 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.
Base class for raster data providers.
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
virtual bool setNoDataValue(int bandNo, double noDataValue)
Set no data value on created dataset.
virtual double sourceNoDataValue(int bandNo) const
Value representing no data value.
bool writeBlock(QgsRasterBlock *block, int band, int xOffset=0, int yOffset=0)
Writes pixel data from a raster block into the provider data source.
virtual bool setEditable(bool enabled)
Turns on/off editing mode of the provider.
Iterator for sequentially processing raster cells.
Represents a raster layer.
int height() const
Returns the height of the (unclipped) raster.
int bandCount() const
Returns the number of bands in this layer.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
int width() const
Returns the width of the (unclipped) raster.