QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
qgsalgorithmrastercalculator.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrastercalculator.cpp
3 ---------------------
4 begin : July 2023
5 copyright : (C) 2023 by Alexander Bruy
6 email : alexander dot bruy 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 "qgsrastercalculator.h"
21#include "qgsrasterfilewriter.h"
22
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29Qgis::ProcessingAlgorithmFlags QgsRasterCalculatorAlgorithm::flags() const
30{
32}
33
34QString QgsRasterCalculatorAlgorithm::name() const
35{
36 return u"rastercalc"_s;
37}
38
39QString QgsRasterCalculatorAlgorithm::displayName() const
40{
41 return QObject::tr( "Raster calculator" );
42}
43
44QStringList QgsRasterCalculatorAlgorithm::tags() const
45{
46 return QObject::tr( "raster,calculator" ).split( ',' );
47}
48
49QString QgsRasterCalculatorAlgorithm::group() const
50{
51 return QObject::tr( "Raster analysis" );
52}
53
54QString QgsRasterCalculatorAlgorithm::groupId() const
55{
56 return u"rasteranalysis"_s;
57}
58
59QString QgsRasterCalculatorAlgorithm::shortHelpString() const
60{
61 return QObject::tr( "This algorithm performs algebraic operations using raster layers." );
62}
63
64QString QgsRasterCalculatorAlgorithm::shortDescription() const
65{
66 return QObject::tr( "Performs algebraic operations using raster layers." );
67}
68
69QgsRasterCalculatorAlgorithm *QgsRasterCalculatorAlgorithm::createInstance() const
70{
71 return new QgsRasterCalculatorAlgorithm();
72}
73
74void QgsRasterCalculatorAlgorithm::initAlgorithm( const QVariantMap & )
75{
76 addParameter( new QgsProcessingParameterMultipleLayers( u"LAYERS"_s, QObject::tr( "Input layers" ), Qgis::ProcessingSourceType::Raster ) );
77 addParameter( new QgsProcessingParameterExpression( u"EXPRESSION"_s, QObject::tr( "Expression" ), QVariant(), u"LAYERS"_s, false, Qgis::ExpressionType::RasterCalculator ) );
78 auto extentParam = std::make_unique<QgsProcessingParameterExtent>( u"EXTENT"_s, QObject::tr( "Output extent" ), QVariant(), true );
79 extentParam->setHelp( QObject::tr( "Extent of the output layer. If not specified, the extent will be the overall extent of all input layers" ) );
80 addParameter( extentParam.release() );
81 auto cellSizeParam = std::make_unique<QgsProcessingParameterNumber>( u"CELL_SIZE"_s, QObject::tr( "Output cell size (leave empty to set automatically)" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0.0 );
82 cellSizeParam->setHelp( QObject::tr( "Cell size of the output layer. If not specified, the smallest cell size from the input layers will be used" ) );
83 addParameter( cellSizeParam.release() );
84 auto crsParam = std::make_unique<QgsProcessingParameterCrs>( u"CRS"_s, QObject::tr( "Output CRS" ), QVariant(), true );
85 crsParam->setHelp( QObject::tr( "CRS of the output layer. If not specified, the CRS of the first input layer will be used" ) );
86 addParameter( crsParam.release() );
87
88 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( u"CREATION_OPTIONS"_s, QObject::tr( "Creation options" ), QVariant(), false, true );
89 creationOptsParam->setMetadata( QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"widget_type"_s, u"rasteroptions"_s } } ) } } ) );
90 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
91 addParameter( creationOptsParam.release() );
92
93 addParameter( new QgsProcessingParameterRasterDestination( u"OUTPUT"_s, QObject::tr( "Calculated" ) ) );
94}
95
96bool QgsRasterCalculatorAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
97{
98 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
99
100 for ( const QgsMapLayer *layer : std::as_const( layers ) )
101 {
102 QgsMapLayer *clonedLayer { layer->clone() };
103 clonedLayer->moveToThread( nullptr );
104 mLayers << clonedLayer;
105 }
106
107 if ( mLayers.isEmpty() )
108 {
109 feedback->reportError( QObject::tr( "No layers selected" ), false );
110 return false;
111 }
112
113 return true;
114}
115
116QVariantMap QgsRasterCalculatorAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
117{
118 for ( QgsMapLayer *layer : std::as_const( mLayers ) )
119 {
120 layer->moveToThread( QThread::currentThread() );
121 }
122
124 if ( parameters.value( u"CRS"_s ).isValid() )
125 {
126 crs = parameterAsCrs( parameters, u"CRS"_s, context );
127 }
128 else
129 {
130 crs = mLayers.at( 0 )->crs();
131 }
132
133 QgsRectangle bbox;
134 if ( parameters.value( u"EXTENT"_s ).isValid() )
135 {
136 bbox = parameterAsExtent( parameters, u"EXTENT"_s, context, crs );
137 }
138 else
139 {
140 bbox = QgsProcessingUtils::combineLayerExtents( mLayers, crs, context );
141 }
142
143 double minCellSize = 1e9;
144
145 QVector<QgsRasterCalculatorEntry> entries;
146 for ( QgsMapLayer *layer : mLayers )
147 {
148 QgsRasterLayer *rLayer = qobject_cast<QgsRasterLayer *>( layer );
149 if ( !rLayer )
150 {
151 continue;
152 }
153
154 const int nBands = rLayer->dataProvider()->bandCount();
155 for ( int i = 0; i < nBands; ++i )
156 {
158 entry.ref = u"%1@%2"_s.arg( rLayer->name() ).arg( i + 1 );
159 entry.raster = rLayer;
160 entry.bandNumber = i + 1;
161 entries << entry;
162 }
163
164 QgsRectangle ext = rLayer->extent();
165 if ( rLayer->crs() != crs )
166 {
167 QgsCoordinateTransform ct( rLayer->crs(), crs, context.transformContext() );
168 ext = ct.transformBoundingBox( ext );
169 }
170
171 double cellSize = ( ext.xMaximum() - ext.xMinimum() ) / rLayer->width();
172 if ( cellSize < minCellSize )
173 {
174 minCellSize = cellSize;
175 }
176 }
177
178 double cellSize = parameterAsDouble( parameters, u"CELL_SIZE"_s, context );
179 if ( cellSize == 0 )
180 {
181 cellSize = minCellSize;
182 }
183
184 const QString creationOptions = parameterAsString( parameters, u"CREATION_OPTIONS"_s, context ).trimmed();
185 const QString expression = parameterAsExpression( parameters, u"EXPRESSION"_s, context );
186 const QString outputFile = parameterAsOutputLayer( parameters, u"OUTPUT"_s, context );
187 const QString outputFormat = parameterAsOutputRasterFormat( parameters, u"OUTPUT"_s, context );
188
189 double width = std::round( ( bbox.xMaximum() - bbox.xMinimum() ) / cellSize );
190 double height = std::round( ( bbox.yMaximum() - bbox.yMinimum() ) / cellSize );
191
192 QgsRasterCalculator calc( expression, outputFile, outputFormat, bbox, crs, width, height, entries, context.transformContext() );
193 calc.setCreationOptions( creationOptions.split( '|', Qt::SplitBehaviorFlags::SkipEmptyParts ) );
194 QgsRasterCalculator::Result result = calc.processCalculation( feedback );
195 qDeleteAll( mLayers );
196 mLayers.clear();
197 switch ( result )
198 {
200 throw QgsProcessingException( QObject::tr( "Error creating output file." ) );
202 throw QgsProcessingException( QObject::tr( "Error reading input layer." ) );
204 throw QgsProcessingException( QObject::tr( "Error parsing formula." ) );
206 throw QgsProcessingException( QObject::tr( "Error allocating memory for result." ) );
208 throw QgsProcessingException( QObject::tr( "Invalid band number for input." ) );
210 throw QgsProcessingException( QObject::tr( "Error occurred while performing calculation." ) );
211 default:
212 break;
213 }
214
215 QVariantMap outputs;
216 outputs.insert( u"OUTPUT"_s, outputFile );
217 return outputs;
218}
219
220Qgis::ProcessingAlgorithmFlags QgsRasterCalculatorModelerAlgorithm::flags() const
221{
223}
224
225QString QgsRasterCalculatorModelerAlgorithm::name() const
226{
227 return u"modelerrastercalc"_s;
228}
229
230QString QgsRasterCalculatorModelerAlgorithm::displayName() const
231{
232 return QObject::tr( "Raster calculator" );
233}
234
235QStringList QgsRasterCalculatorModelerAlgorithm::tags() const
236{
237 return QObject::tr( "raster,calculator" ).split( ',' );
238}
239
240QString QgsRasterCalculatorModelerAlgorithm::group() const
241{
242 return QObject::tr( "Raster analysis" );
243}
244
245QString QgsRasterCalculatorModelerAlgorithm::groupId() const
246{
247 return u"rasteranalysis"_s;
248}
249
250QgsRasterCalculatorModelerAlgorithm *QgsRasterCalculatorModelerAlgorithm::createInstance() const
251{
252 return new QgsRasterCalculatorModelerAlgorithm();
253}
254
255QVariantMap QgsRasterCalculatorModelerAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
256{
257 for ( QgsMapLayer *layer : std::as_const( mLayers ) )
258 {
259 layer->moveToThread( QThread::currentThread() );
260 }
261
263 if ( parameters.value( u"CRS"_s ).isValid() )
264 {
265 crs = parameterAsCrs( parameters, u"CRS"_s, context );
266 }
267 else
268 {
269 crs = mLayers.at( 0 )->crs();
270 }
271
272 QgsRectangle bbox;
273 if ( parameters.value( u"EXTENT"_s ).isValid() )
274 {
275 bbox = parameterAsExtent( parameters, u"EXTENT"_s, context, crs );
276 }
277 else
278 {
279 bbox = QgsProcessingUtils::combineLayerExtents( mLayers, crs, context );
280 }
281
282 double minCellSize = 1e9;
283
284 QVector<QgsRasterCalculatorEntry> entries;
285 int n = 0;
286 for ( QgsMapLayer *layer : mLayers )
287 {
288 QgsRasterLayer *rLayer = qobject_cast<QgsRasterLayer *>( layer );
289 if ( !rLayer )
290 {
291 continue;
292 }
293
294 n++;
295 const int nBands = rLayer->dataProvider()->bandCount();
296 for ( int i = 0; i < nBands; ++i )
297 {
299 entry.ref = u"%1@%2"_s.arg( indexToName( n ) ).arg( i + 1 );
300 entry.raster = rLayer;
301 entry.bandNumber = i + 1;
302 entries << entry;
303 }
304
305 QgsRectangle ext = rLayer->extent();
306 if ( rLayer->crs() != crs )
307 {
308 QgsCoordinateTransform ct( rLayer->crs(), crs, context.transformContext() );
309 ext = ct.transformBoundingBox( ext );
310 }
311
312 double cellSize = ( ext.xMaximum() - ext.xMinimum() ) / rLayer->width();
313 if ( cellSize < minCellSize )
314 {
315 minCellSize = cellSize;
316 }
317 }
318
319 double cellSize = parameterAsDouble( parameters, u"CELL_SIZE"_s, context );
320 if ( cellSize == 0 )
321 {
322 cellSize = minCellSize;
323 }
324
325 const QString expression = parameterAsExpression( parameters, u"EXPRESSION"_s, context );
326 const QString outputFile = parameterAsOutputLayer( parameters, u"OUTPUT"_s, context );
327 const QString outputFormat = parameterAsOutputRasterFormat( parameters, u"OUTPUT"_s, context );
328
329 double width = std::round( ( bbox.xMaximum() - bbox.xMinimum() ) / cellSize );
330 double height = std::round( ( bbox.yMaximum() - bbox.yMinimum() ) / cellSize );
331
332 QgsRasterCalculator calc( expression, outputFile, outputFormat, bbox, crs, width, height, entries, context.transformContext() );
333 QgsRasterCalculator::Result result = calc.processCalculation( feedback );
334 qDeleteAll( mLayers );
335 mLayers.clear();
336 switch ( result )
337 {
339 throw QgsProcessingException( QObject::tr( "Error creating output file." ) );
341 throw QgsProcessingException( QObject::tr( "Error reading input layer." ) );
343 throw QgsProcessingException( QObject::tr( "Error parsing formula." ) );
345 throw QgsProcessingException( QObject::tr( "Error allocating memory for result." ) );
347 throw QgsProcessingException( QObject::tr( "Invalid band number for input." ) );
349 throw QgsProcessingException( QObject::tr( "Error occurred while performing calculation." ) );
350 default:
351 break;
352 }
353
354 QVariantMap outputs;
355 outputs.insert( u"OUTPUT"_s, outputFile );
356 return outputs;
357}
358
359QString QgsRasterCalculatorModelerAlgorithm::indexToName( int index ) const
360{
361 QString name;
362 int div = index;
363 int mod = 0;
364
365 while ( div > 0 )
366 {
367 mod = ( div - 1 ) % 26;
368 name = static_cast<char>( 65 + mod ) + name;
369 div = ( int ) ( ( div - mod ) / 26 );
370 }
371 return name;
372}
373
@ Raster
Raster layers.
Definition qgis.h:3608
@ RasterCalculator
Raster calculator expression.
Definition qgis.h:5846
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3680
@ HideFromToolbox
Algorithm should be hidden from the toolbox.
Definition qgis.h:3654
@ HideFromModeler
Algorithm should be hidden from the modeler.
Definition qgis.h:3655
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
@ Double
Double/float values.
Definition qgis.h:3875
Represents a coordinate reference system (CRS).
Handles coordinate transforms between two coordinate systems.
Base class for all map layer types.
Definition qgsmaplayer.h:83
QString name
Definition qgsmaplayer.h:87
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
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.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
An expression 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 ...
static QgsRectangle combineLayerExtents(const QList< QgsMapLayer * > &layers, const QgsCoordinateReferenceSystem &crs, QgsProcessingContext &context)
Combines the extent of several map layers.
Represents an individual raster layer/band number entry within a raster calculation.
QgsRasterLayer * raster
Raster layer associated with entry.
int bandNumber
Band number for entry.
QString ref
Name of entry.
Performs raster layer calculations.
Result
Result of the calculation.
@ InputLayerError
Error reading input layer.
@ BandError
Invalid band number for input.
@ CreateOutputError
Error creating output data file.
@ ParserError
Error parsing formula.
@ CalculationError
Error occurred while performing calculation.
@ MemoryError
Error allocating memory for result.
virtual int bandCount() const =0
Gets number of bands.
Represents a raster layer.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
int width() const
Returns the width of the (unclipped) raster.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
double yMaximum