QGIS API Documentation 3.41.0-Master (af5edcb665c)
Loading...
Searching...
No Matches
qgsalgorithmrasterstackposition.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsrasterstackposition.cpp
3 ---------------------
4 begin : July 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#include "qgsrasterprojector.h"
20#include "qgsrasterfilewriter.h"
22
24
25//
26//QgsRasterFrequencyByComparisonOperatorBase
27//
28
29QString QgsRasterStackPositionAlgorithmBase::group() const
30{
31 return QObject::tr( "Raster analysis" );
32}
33
34QString QgsRasterStackPositionAlgorithmBase::groupId() const
35{
36 return QStringLiteral( "rasteranalysis" );
37}
38
39void QgsRasterStackPositionAlgorithmBase::initAlgorithm( const QVariantMap & )
40{
41 addParameter( new QgsProcessingParameterMultipleLayers( QStringLiteral( "INPUT_RASTERS" ), QObject::tr( "Input raster layers" ), Qgis::ProcessingSourceType::Raster ) );
42
43 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "REFERENCE_LAYER" ), QObject::tr( "Reference layer" ) ) );
44
45 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "IGNORE_NODATA" ), QObject::tr( "Ignore NoData values" ), false ) );
46
47 std::unique_ptr<QgsProcessingParameterNumber> output_nodata_parameter = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "OUTPUT_NODATA_VALUE" ), QObject::tr( "Output NoData value" ), Qgis::ProcessingNumberParameterType::Double, -9999, true );
48 output_nodata_parameter->setFlags( output_nodata_parameter->flags() | Qgis::ProcessingParameterFlag::Advanced );
49 addParameter( output_nodata_parameter.release() );
50
51 std::unique_ptr<QgsProcessingParameterString> createOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATE_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
52 createOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
53 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
54 addParameter( createOptsParam.release() );
55
56 addParameter( new QgsProcessingParameterRasterDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Output layer" ) ) );
57 addOutput( new QgsProcessingOutputString( QStringLiteral( "EXTENT" ), QObject::tr( "Extent" ) ) );
58 addOutput( new QgsProcessingOutputString( QStringLiteral( "CRS_AUTHID" ), QObject::tr( "CRS authority identifier" ) ) );
59 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "WIDTH_IN_PIXELS" ), QObject::tr( "Width in pixels" ) ) );
60 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "HEIGHT_IN_PIXELS" ), QObject::tr( "Height in pixels" ) ) );
61 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "TOTAL_PIXEL_COUNT" ), QObject::tr( "Total pixel count" ) ) );
62}
63
64bool QgsRasterStackPositionAlgorithmBase::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
65{
66 QgsRasterLayer *referenceLayer = parameterAsRasterLayer( parameters, QStringLiteral( "REFERENCE_LAYER" ), context );
67 if ( !referenceLayer )
68 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "REFERENCE_LAYER" ) ) );
69
70 mIgnoreNoData = parameterAsBool( parameters, QStringLiteral( "IGNORE_NODATA" ), context );
71 mNoDataValue = parameterAsDouble( parameters, QStringLiteral( "OUTPUT_NODATA_VALUE" ), context );
72
73 mCrs = referenceLayer->crs();
74 mRasterUnitsPerPixelX = referenceLayer->rasterUnitsPerPixelX();
75 mRasterUnitsPerPixelY = referenceLayer->rasterUnitsPerPixelY();
76 mLayerWidth = referenceLayer->width();
77 mLayerHeight = referenceLayer->height();
78 mExtent = referenceLayer->extent();
79
80 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, QStringLiteral( "INPUT_RASTERS" ), context );
81 QList<QgsRasterLayer *> rasterLayers;
82 rasterLayers.reserve( layers.count() );
83 for ( QgsMapLayer *l : layers )
84 {
85 if ( feedback->isCanceled() )
86 break; //in case some slow data sources are loaded
87
88 if ( l->type() == Qgis::LayerType::Raster )
89 {
90 QgsRasterLayer *layer = qobject_cast<QgsRasterLayer *>( l );
91 QgsRasterAnalysisUtils::RasterLogicInput input;
92 const int band = 1; //could be made dynamic
93 input.hasNoDataValue = layer->dataProvider()->sourceHasNoDataValue( band );
94 input.sourceDataProvider.reset( layer->dataProvider()->clone() );
95 input.interface = input.sourceDataProvider.get();
96 // add projector if necessary
97 if ( layer->crs() != mCrs )
98 {
99 input.projector = std::make_unique<QgsRasterProjector>();
100 input.projector->setInput( input.sourceDataProvider.get() );
101 input.projector->setCrs( layer->crs(), mCrs, context.transformContext() );
102 input.interface = input.projector.get();
103 }
104 mInputs.emplace_back( std::move( input ) );
105 }
106 }
107
108 return true;
109}
110
111QVariantMap QgsRasterStackPositionAlgorithmBase::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
112{
113 const QString createOptions = parameterAsString( parameters, QStringLiteral( "CREATE_OPTIONS" ), context ).trimmed();
114 const QString outputFile = parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context );
115 const QFileInfo fi( outputFile );
116 const QString outputFormat = QgsRasterFileWriter::driverForExtension( fi.suffix() );
117
118 std::unique_ptr<QgsRasterFileWriter> writer = std::make_unique<QgsRasterFileWriter>( outputFile );
119 writer->setOutputProviderKey( QStringLiteral( "gdal" ) );
120 if ( !createOptions.isEmpty() )
121 {
122 writer->setCreateOptions( createOptions.split( '|' ) );
123 }
124 writer->setOutputFormat( outputFormat );
125 std::unique_ptr<QgsRasterDataProvider> provider( writer->createOneBandRaster( Qgis::DataType::Int32, mLayerWidth, mLayerHeight, mExtent, mCrs ) );
126 if ( !provider )
127 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
128 if ( !provider->isValid() )
129 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
130
131 provider->setNoDataValue( 1, mNoDataValue );
132 const qgssize layerSize = static_cast<qgssize>( mLayerWidth ) * static_cast<qgssize>( mLayerHeight );
133
136 const int nbBlocksWidth = static_cast<int>( std::ceil( 1.0 * mLayerWidth / maxWidth ) );
137 const int nbBlocksHeight = static_cast<int>( std::ceil( 1.0 * mLayerHeight / maxHeight ) );
138 const int nbBlocks = nbBlocksWidth * nbBlocksHeight;
139 provider->setEditable( true );
140
141 QgsRasterIterator iter( provider.get() );
142 iter.startRasterRead( 1, mLayerWidth, mLayerHeight, mExtent );
143 int iterLeft = 0;
144 int iterTop = 0;
145 int iterCols = 0;
146 int iterRows = 0;
147 QgsRectangle blockExtent;
148
149 std::unique_ptr<QgsRasterBlock> outputBlock;
150 while ( iter.readNextRasterPart( 1, iterCols, iterRows, outputBlock, iterLeft, iterTop, &blockExtent ) )
151 {
152 std::vector<std::unique_ptr<QgsRasterBlock>> inputBlocks;
153 for ( const QgsRasterAnalysisUtils::RasterLogicInput &i : mInputs )
154 {
155 if ( feedback->isCanceled() )
156 break; //in case some slow data sources are loaded
157 for ( const int band : i.bands )
158 {
159 if ( feedback->isCanceled() )
160 break; //in case some slow data sources are loaded
161 std::unique_ptr<QgsRasterBlock> b( i.interface->block( band, blockExtent, iterCols, iterRows ) );
162 inputBlocks.emplace_back( std::move( b ) );
163 }
164 }
165
166 feedback->setProgress( 100 * ( ( iterTop / maxHeight * nbBlocksWidth ) + iterLeft / maxWidth ) / nbBlocks );
167 for ( int row = 0; row < iterRows; row++ )
168 {
169 if ( feedback->isCanceled() )
170 break;
171
172 for ( int col = 0; col < iterCols; col++ )
173 {
174 bool noDataInStack = false;
175
176 if ( !inputBlocks.empty() )
177 {
178 const int position = findPosition( inputBlocks, row, col, noDataInStack );
179
180 if ( position == -1 || ( noDataInStack && !mIgnoreNoData ) )
181 {
182 //output cell will always be NoData if NoData occurs the current raster cell
183 //of the input blocks and NoData is not ignored
184 //this saves unnecessary iterations on the cellValueStack
185 outputBlock->setValue( row, col, mNoDataValue );
186 }
187 else
188 {
189 outputBlock->setValue( row, col, position );
190 }
191 }
192 else
193 {
194 outputBlock->setValue( row, col, mNoDataValue );
195 }
196 }
197 }
198 provider->writeBlock( outputBlock.get(), 1, iterLeft, iterTop );
199 }
200 provider->setEditable( false );
201
202 QVariantMap outputs;
203 outputs.insert( QStringLiteral( "EXTENT" ), mExtent.toString() );
204 outputs.insert( QStringLiteral( "CRS_AUTHID" ), mCrs.authid() );
205 outputs.insert( QStringLiteral( "WIDTH_IN_PIXELS" ), mLayerWidth );
206 outputs.insert( QStringLiteral( "HEIGHT_IN_PIXELS" ), mLayerHeight );
207 outputs.insert( QStringLiteral( "TOTAL_PIXEL_COUNT" ), layerSize );
208 outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
209
210 return outputs;
211}
212
213//
214// QgsRasterStackLowestPositionAlgorithm
215//
216QString QgsRasterStackLowestPositionAlgorithm::displayName() const
217{
218 return QObject::tr( "Lowest position in raster stack" );
219}
220
221QString QgsRasterStackLowestPositionAlgorithm::name() const
222{
223 return QStringLiteral( "lowestpositioninrasterstack" );
224}
225
226QStringList QgsRasterStackLowestPositionAlgorithm::tags() const
227{
228 return QObject::tr( "cell,lowest,position,pixel,stack" ).split( ',' );
229}
230
231QString QgsRasterStackLowestPositionAlgorithm::shortHelpString() const
232{
233 return QObject::tr( "The lowest position algorithm evaluates on a cell-by-cell basis the position "
234 "of the raster with the lowest value in a stack of rasters. Position counts start "
235 "with 1 and range to the total number of input rasters. The order of the input "
236 "rasters is relevant for the algorithm. If multiple rasters feature the lowest value, "
237 "the first raster will be used for the position value.\n "
238 "If multiband rasters are used in the data raster stack, the algorithm will always "
239 "perform the analysis on the first band of the rasters - use GDAL to use other bands in the analysis. "
240 "Any NoData cells in the raster layer stack will result in a NoData cell "
241 "in the output raster unless the \"ignore NoData\" parameter is checked. "
242 "The output NoData value can be set manually. The output rasters extent and resolution "
243 "is defined by a reference raster layer and is always of int32 type." );
244}
245
246QgsRasterStackLowestPositionAlgorithm *QgsRasterStackLowestPositionAlgorithm::createInstance() const
247{
248 return new QgsRasterStackLowestPositionAlgorithm();
249}
250
251int QgsRasterStackLowestPositionAlgorithm::findPosition( std::vector<std::unique_ptr<QgsRasterBlock>> &inputBlocks, int &row, int &col, bool &noDataInRasterBlockStack )
252{
253 int lowestPosition = 0;
254
255 //auxiliary variables
256 const int inputBlocksCount = inputBlocks.size();
257 int currentPosition = 0;
258 int noDataCount = 0;
259 double firstValue = mNoDataValue;
260 bool firstValueIsNoData = true;
261
262 while ( firstValueIsNoData && ( currentPosition < inputBlocksCount ) )
263 {
264 //check if all blocks are nodata/invalid
265 std::unique_ptr<QgsRasterBlock> &firstBlock = inputBlocks.at( currentPosition );
266 firstValue = firstBlock->valueAndNoData( row, col, firstValueIsNoData );
267
268 if ( !firstBlock->isValid() || firstValueIsNoData )
269 {
270 noDataInRasterBlockStack = true;
271 noDataCount++;
272 }
273 else
274 {
275 lowestPosition = currentPosition;
276 }
277 currentPosition++;
278 }
279
280 if ( noDataCount == inputBlocksCount )
281 {
282 noDataInRasterBlockStack = true;
283 return -1; //all blocks are NoData
284 }
285 else
286 {
287 //scan for the lowest value
288 while ( currentPosition < inputBlocksCount )
289 {
290 std::unique_ptr<QgsRasterBlock> &currentBlock = inputBlocks.at( currentPosition );
291
292 bool currentValueIsNoData = false;
293 const double currentValue = currentBlock->valueAndNoData( row, col, currentValueIsNoData );
294
295 if ( !currentBlock->isValid() || currentValueIsNoData )
296 {
297 noDataInRasterBlockStack = true;
298 noDataCount++;
299 }
300 else
301 {
302 if ( currentValue < firstValue )
303 {
304 firstValue = currentValue;
305 lowestPosition = currentPosition;
306 }
307 }
308 currentPosition++;
309 }
310 }
311 //the ArcGIS implementation uses 1 for first position value instead of 0 as in standard c++
312 return ++lowestPosition; //therefore ++
313}
314
315//
316// QgsRasterStackHighestPositionAlgorithmAlgorithm
317//
318
319QString QgsRasterStackHighestPositionAlgorithm::displayName() const
320{
321 return QObject::tr( "Highest position in raster stack" );
322}
323
324QString QgsRasterStackHighestPositionAlgorithm::name() const
325{
326 return QStringLiteral( "highestpositioninrasterstack" );
327}
328
329QStringList QgsRasterStackHighestPositionAlgorithm::tags() const
330{
331 return QObject::tr( "cell,highest,position,pixel,stack" ).split( ',' );
332}
333
334QString QgsRasterStackHighestPositionAlgorithm::shortHelpString() const
335{
336 return QObject::tr( "The highest position algorithm evaluates on a cell-by-cell basis the position "
337 "of the raster with the highest value in a stack of rasters. Position counts start "
338 "with 1 and range to the total number of input rasters. The order of the input "
339 "rasters is relevant for the algorithm. If multiple rasters feature the highest value, "
340 "the first raster will be used for the position value.\n "
341 "If multiband rasters are used in the data raster stack, the algorithm will always "
342 "perform the analysis on the first band of the rasters - use GDAL to use other bands in the analysis. "
343 "Any NoData cells in the raster layer stack will result in a NoData cell "
344 "in the output raster unless the \"ignore NoData\" parameter is checked. "
345 "The output NoData value can be set manually. The output rasters extent and resolution "
346 "is defined by a reference raster layer and is always of int32 type." );
347}
348
349QgsRasterStackHighestPositionAlgorithm *QgsRasterStackHighestPositionAlgorithm::createInstance() const
350{
351 return new QgsRasterStackHighestPositionAlgorithm();
352}
353
354int QgsRasterStackHighestPositionAlgorithm::findPosition( std::vector<std::unique_ptr<QgsRasterBlock>> &inputBlocks, int &row, int &col, bool &noDataInRasterBlockStack )
355{
356 int highestPosition = 0;
357
358 //auxiliary variables
359 const int inputBlocksCount = inputBlocks.size();
360 int currentPosition = 0;
361 int noDataCount = 0;
362 double firstValue = mNoDataValue;
363 bool firstValueIsNoData = true;
364
365 while ( firstValueIsNoData && ( currentPosition < inputBlocksCount ) )
366 {
367 //check if all blocks are nodata/invalid
368 std::unique_ptr<QgsRasterBlock> &firstBlock = inputBlocks.at( currentPosition );
369 firstValue = firstBlock->valueAndNoData( row, col, firstValueIsNoData );
370
371 if ( !firstBlock->isValid() || firstValueIsNoData )
372 {
373 noDataInRasterBlockStack = true;
374 noDataCount++;
375 }
376 else
377 {
378 highestPosition = currentPosition;
379 }
380
381 currentPosition++;
382 }
383
384 if ( noDataCount == inputBlocksCount )
385 {
386 noDataInRasterBlockStack = true;
387 return -1; //all blocks are NoData
388 }
389 else
390 {
391 //scan for the lowest value
392 while ( currentPosition < inputBlocksCount )
393 {
394 std::unique_ptr<QgsRasterBlock> &currentBlock = inputBlocks.at( currentPosition );
395
396 bool currentValueIsNoData = false;
397 const double currentValue = currentBlock->valueAndNoData( row, col, currentValueIsNoData );
398
399 if ( !currentBlock->isValid() || currentValueIsNoData )
400 {
401 noDataInRasterBlockStack = true;
402 noDataCount++;
403 }
404 else
405 {
406 if ( currentValue > firstValue )
407 {
408 firstValue = currentValue;
409 highestPosition = currentPosition;
410 }
411 }
412 currentPosition++;
413 }
414 }
415 //the ArcGIS implementation uses 1 for first position value instead of 0 as in standard c++
416 return ++highestPosition; //therefore ++
417}
418
@ Int32
Thirty two bit signed integer (qint32)
@ Raster
Raster layer.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
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
Base class for all map layer types.
Definition qgsmaplayer.h:76
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.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
A numeric output for processing algorithms.
A string output for processing algorithms.
A boolean parameter for processing algorithms.
A parameter for processing algorithms which accepts multiple map layers.
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.
virtual bool sourceHasNoDataValue(int bandNo) const
Returns true if source band has no data value.
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.
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.
int width() const
Returns the width of the (unclipped) raster.
A rectangle specified with double values.
unsigned long long qgssize
Qgssize is used instead of size_t, because size_t is stdlib type, unknown by SIP, and it would be har...
Definition qgis.h:6614