QGIS API Documentation 3.99.0-Master (2fe06baccd8)
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
23
24QString QgsRoundRasterValuesAlgorithm::name() const
25{
26 return QStringLiteral( "roundrastervalues" );
27}
28
29QString QgsRoundRasterValuesAlgorithm::displayName() const
30{
31 return QObject::tr( "Round raster" );
32}
33
34QStringList QgsRoundRasterValuesAlgorithm::tags() const
35{
36 return QObject::tr( "data,cells,round,truncate" ).split( ',' );
37}
38
39QString QgsRoundRasterValuesAlgorithm::group() const
40{
41 return QObject::tr( "Raster analysis" );
42}
43
44QString QgsRoundRasterValuesAlgorithm::groupId() const
45{
46 return QStringLiteral( "rasteranalysis" );
47}
48
49void QgsRoundRasterValuesAlgorithm::initAlgorithm( const QVariantMap & )
50{
51 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT" ), QStringLiteral( "Input raster" ) ) );
52 addParameter( new QgsProcessingParameterBand( QStringLiteral( "BAND" ), QObject::tr( "Band number" ), 1, QStringLiteral( "INPUT" ) ) );
53 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "ROUNDING_DIRECTION" ), QObject::tr( "Rounding direction" ), QStringList() << QObject::tr( "Round up" ) << QObject::tr( "Round to nearest" ) << QObject::tr( "Round down" ), false, 1 ) );
54 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "DECIMAL_PLACES" ), QObject::tr( "Number of decimals places" ), Qgis::ProcessingNumberParameterType::Integer, 2 ) );
55 std::unique_ptr<QgsProcessingParameterDefinition> baseParameter = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "BASE_N" ), QObject::tr( "Base n for rounding to multiples of n" ), Qgis::ProcessingNumberParameterType::Integer, 10, true, 1 );
56 baseParameter->setFlags( Qgis::ProcessingParameterFlag::Advanced );
57 addParameter( baseParameter.release() );
58
59 // backwards compatibility parameter
60 // TODO QGIS 4: remove parameter and related logic
61 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATE_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
62 createOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
63 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
64 addParameter( createOptsParam.release() );
65
66 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATION_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
67 creationOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
68 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
69 addParameter( creationOptsParam.release() );
70
71 addParameter( new QgsProcessingParameterRasterDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Output raster" ) ) );
72}
73
74QString QgsRoundRasterValuesAlgorithm::shortHelpString() const
75{
76 return QObject::tr( "This algorithm rounds the cell values of a raster dataset to the specified number of decimals.\n "
77 "Alternatively, a negative number of decimal places may be used to round values to powers of a base n "
78 "(specified in the advanced parameter Base n). For example, with a Base value n of 10 and Decimal places of -1 "
79 "the algorithm rounds cell values to multiples of 10, -2 rounds to multiples of 100, and so on. Arbitrary base values "
80 "may be chosen, the algorithm applies the same multiplicative principle. Rounding cell values to multiples of "
81 "a base n may be used to generalize raster layers.\n"
82 "The algorithm preserves the data type of the input raster. Therefore byte/integer rasters can only be rounded "
83 "to multiples of a base n, otherwise a warning is raised and the raster gets copied as byte/integer raster." );
84}
85
86QString QgsRoundRasterValuesAlgorithm::shortDescription() const
87{
88 return QObject::tr( "Rounds the cell values of a raster dataset to a specified number of decimals." );
89}
90
91QgsRoundRasterValuesAlgorithm *QgsRoundRasterValuesAlgorithm::createInstance() const
92{
93 return new QgsRoundRasterValuesAlgorithm();
94}
95
96bool QgsRoundRasterValuesAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
97{
98 Q_UNUSED( feedback );
99 QgsRasterLayer *inputRaster = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT" ), context );
100 mDecimalPrecision = parameterAsInt( parameters, QStringLiteral( "DECIMAL_PLACES" ), context );
101 mBaseN = parameterAsInt( parameters, QStringLiteral( "BASE_N" ), context );
102 mMultipleOfBaseN = pow( mBaseN, abs( mDecimalPrecision ) );
103 mScaleFactor = std::pow( 10.0, mDecimalPrecision );
104
105 if ( !inputRaster )
106 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT" ) ) );
107
108 mBand = parameterAsInt( parameters, QStringLiteral( "BAND" ), context );
109 if ( mBand < 1 || mBand > inputRaster->bandCount() )
110 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( inputRaster->bandCount() ) );
111
112 mRoundingDirection = parameterAsEnum( parameters, QStringLiteral( "ROUNDING_DIRECTION" ), context );
113
114 mInterface.reset( inputRaster->dataProvider()->clone() );
115 mDataType = mInterface->dataType( mBand );
116
117 switch ( mDataType )
118 {
124 mIsInteger = true;
125 if ( mDecimalPrecision > -1 )
126 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 );
127 break;
128 default:
129 mIsInteger = false;
130 break;
131 }
132
133 mInputNoDataValue = inputRaster->dataProvider()->sourceNoDataValue( mBand );
134 mExtent = inputRaster->extent();
135 mLayerWidth = inputRaster->width();
136 mLayerHeight = inputRaster->height();
137 mCrs = inputRaster->crs();
138 mNbCellsXProvider = mInterface->xSize();
139 mNbCellsYProvider = mInterface->ySize();
140 return true;
141}
142
143QVariantMap QgsRoundRasterValuesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
144{
145 //prepare output dataset
146 QString creationOptions = parameterAsString( parameters, QStringLiteral( "CREATION_OPTIONS" ), context ).trimmed();
147 // handle backwards compatibility parameter CREATE_OPTIONS
148 const QString optionsString = parameterAsString( parameters, QStringLiteral( "CREATE_OPTIONS" ), context );
149 if ( !optionsString.isEmpty() )
150 creationOptions = optionsString;
151
152 const QString outputFile = parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context );
153 const QFileInfo fi( outputFile );
154 const QString outputFormat = QgsRasterFileWriter::driverForExtension( fi.suffix() );
155 auto writer = std::make_unique<QgsRasterFileWriter>( outputFile );
156 writer->setOutputProviderKey( QStringLiteral( "gdal" ) );
157 if ( !creationOptions.isEmpty() )
158 {
159 writer->setCreationOptions( creationOptions.split( '|' ) );
160 }
161 writer->setOutputFormat( outputFormat );
162 std::unique_ptr<QgsRasterDataProvider> provider( writer->createOneBandRaster( mInterface->dataType( mBand ), mNbCellsXProvider, mNbCellsYProvider, mExtent, mCrs ) );
163 if ( !provider )
164 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
165 if ( !provider->isValid() )
166 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
167
168 //prepare output provider
169 QgsRasterDataProvider *destinationRasterProvider;
170 destinationRasterProvider = provider.get();
171 destinationRasterProvider->setEditable( true );
172 destinationRasterProvider->setNoDataValue( 1, mInputNoDataValue );
173
176 const int nbBlocksWidth = static_cast<int>( std::ceil( 1.0 * mLayerWidth / maxWidth ) );
177 const int nbBlocksHeight = static_cast<int>( std::ceil( 1.0 * mLayerHeight / maxHeight ) );
178 const int nbBlocks = nbBlocksWidth * nbBlocksHeight;
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( 100 * ( ( iterTop / maxHeight * nbBlocksWidth ) + iterLeft / maxWidth ) / nbBlocks );
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 QVariantMap outputs;
258 outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
259 return outputs;
260}
261
262double QgsRoundRasterValuesAlgorithm::roundNearest( double value, double m )
263{
264 return ( std::round( value * m * mScaleFactor ) / mScaleFactor ) * m;
265}
266
267double QgsRoundRasterValuesAlgorithm::roundUp( double value, double m )
268{
269 return ( std::ceil( value * m * mScaleFactor ) / mScaleFactor ) * m;
270}
271
272double QgsRoundRasterValuesAlgorithm::roundDown( double value, double m )
273{
274 return ( std::floor( value * m * mScaleFactor ) / mScaleFactor ) * m;
275}
276
277double QgsRoundRasterValuesAlgorithm::roundNearestBaseN( double value )
278{
279 return static_cast<double>( mMultipleOfBaseN * round( value / mMultipleOfBaseN ) );
280}
281
282double QgsRoundRasterValuesAlgorithm::roundUpBaseN( double value )
283{
284 return static_cast<double>( mMultipleOfBaseN * ceil( value / mMultipleOfBaseN ) );
285}
286
287double QgsRoundRasterValuesAlgorithm::roundDownBaseN( double value )
288{
289 return static_cast<double>( mMultipleOfBaseN * floor( value / mMultipleOfBaseN ) );
290}
291
@ Int16
Sixteen bit signed integer (qint16).
Definition qgis.h:377
@ UInt16
Sixteen bit unsigned integer (quint16).
Definition qgis.h:376
@ Byte
Eight bit unsigned integer (quint8).
Definition qgis.h:374
@ Int32
Thirty two bit signed integer (qint32).
Definition qgis.h:379
@ UInt32
Thirty two bit unsigned integer (quint32).
Definition qgis.h:378
@ Hidden
Parameter is hidden and should not be shown to users.
Definition qgis.h:3764
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
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:130
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:87
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.
static QString driverForExtension(const QString &extension)
Returns the GDAL driver name for a specified file extension.
Iterator for sequentially processing raster cells.
static const int DEFAULT_MAXIMUM_TILE_WIDTH
Default maximum tile width.
static const int DEFAULT_MAXIMUM_TILE_HEIGHT
Default maximum tile height.
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.