QGIS API Documentation 4.3.0-Master (0d5b841b09e)
Loading...
Searching...
No Matches
qgsalgorithmrasterzonalstats.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrasterzonalstats.cpp
3 ---------------------
4 begin : December 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
19
20#include "qgsrasterprojector.h"
22#include "qgsstringutils.h"
23#include "qgsunittypes.h"
24
25#include <QString>
26
27using namespace Qt::StringLiterals;
28
30
31QString QgsRasterLayerZonalStatsAlgorithm::name() const
32{
33 return u"rasterlayerzonalstats"_s;
34}
35
36QString QgsRasterLayerZonalStatsAlgorithm::displayName() const
37{
38 return QObject::tr( "Raster layer zonal statistics" );
39}
40
41QStringList QgsRasterLayerZonalStatsAlgorithm::tags() const
42{
43 return QObject::tr( "count,area,statistics,stats,zones,categories,minimum,maximum,mean,sum,total" ).split( ',' );
44}
45
46QString QgsRasterLayerZonalStatsAlgorithm::group() const
47{
48 return QObject::tr( "Raster analysis" );
49}
50
51QString QgsRasterLayerZonalStatsAlgorithm::groupId() const
52{
53 return u"rasteranalysis"_s;
54}
55
56void QgsRasterLayerZonalStatsAlgorithm::initAlgorithm( const QVariantMap & )
57{
58 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT"_s, QObject::tr( "Input layer" ) ) );
59 addParameter( new QgsProcessingParameterBand( u"BAND"_s, QObject::tr( "Band number" ), 1, u"INPUT"_s ) );
60 addParameter( new QgsProcessingParameterRasterLayer( u"ZONES"_s, QObject::tr( "Zones layer" ) ) );
61 addParameter( new QgsProcessingParameterBand( u"ZONES_BAND"_s, QObject::tr( "Zones band number" ), 1, u"ZONES"_s ) );
62
63 auto refParam = std::make_unique<QgsProcessingParameterEnum>( u"REF_LAYER"_s, QObject::tr( "Reference layer" ), QStringList() << QObject::tr( "Input layer" ) << QObject::tr( "Zones layer" ), false, 0 );
64 refParam->setFlags( refParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
65 addParameter( refParam.release() );
66
67 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT_TABLE"_s, QObject::tr( "Statistics" ), Qgis::ProcessingSourceType::Vector ) );
68
69 addOutput( new QgsProcessingOutputString( u"EXTENT"_s, QObject::tr( "Extent" ) ) );
70 addOutput( new QgsProcessingOutputString( u"CRS_AUTHID"_s, QObject::tr( "CRS authority identifier" ) ) );
71 addOutput( new QgsProcessingOutputNumber( u"WIDTH_IN_PIXELS"_s, QObject::tr( "Width in pixels" ) ) );
72 addOutput( new QgsProcessingOutputNumber( u"HEIGHT_IN_PIXELS"_s, QObject::tr( "Height in pixels" ) ) );
73 addOutput( new QgsProcessingOutputNumber( u"TOTAL_PIXEL_COUNT"_s, QObject::tr( "Total pixel count" ) ) );
74 addOutput( new QgsProcessingOutputNumber( u"NODATA_PIXEL_COUNT"_s, QObject::tr( "NoData pixel count" ) ) );
75}
76
77QString QgsRasterLayerZonalStatsAlgorithm::shortDescription() const
78{
79 return QObject::tr( "Calculates statistics for a raster layer's values, categorized by zones defined in another raster layer." );
80}
81
82QString QgsRasterLayerZonalStatsAlgorithm::shortHelpString() const
83{
84 return QObject::tr(
85 "This algorithm calculates statistics for a raster layer's values, categorized by zones defined in another raster layer.\n\n"
86 "If the reference layer parameter is set to \"Input layer\", then zones are determined by sampling the zone raster layer value at the centroid of each pixel from the source raster layer.\n\n"
87 "If the reference layer parameter is set to \"Zones layer\", then the input raster layer will be sampled at the centroid of each pixel from the zones raster layer.\n\n"
88 "If either the source raster layer or the zone raster layer value is NoData for a pixel, that pixel's value will be skipped and not included in the calculated statistics."
89 );
90}
91
92QgsRasterLayerZonalStatsAlgorithm *QgsRasterLayerZonalStatsAlgorithm::createInstance() const
93{
94 return new QgsRasterLayerZonalStatsAlgorithm();
95}
96
97bool QgsRasterLayerZonalStatsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
98{
99 mRefLayer = static_cast<RefLayer>( parameterAsEnum( parameters, u"REF_LAYER"_s, context ) );
100
101 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u"INPUT"_s, context );
102 const int band = parameterAsInt( parameters, u"BAND"_s, context );
103
104 if ( !layer )
105 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT"_s ) );
106
107 mBand = parameterAsInt( parameters, u"BAND"_s, context );
108 if ( mBand < 1 || mBand > layer->bandCount() )
109 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( layer->bandCount() ) );
110
111 mHasNoDataValue = layer->dataProvider()->sourceHasNoDataValue( band );
112
113 QgsRasterLayer *zonesLayer = parameterAsRasterLayer( parameters, u"ZONES"_s, context );
114
115 if ( !zonesLayer )
116 throw QgsProcessingException( invalidRasterError( parameters, u"ZONES"_s ) );
117
118 mZonesBand = parameterAsInt( parameters, u"ZONES_BAND"_s, context );
119 if ( mZonesBand < 1 || mZonesBand > zonesLayer->bandCount() )
120 throw QgsProcessingException( QObject::tr( "Invalid band number for ZONES_BAND (%1): Valid values for input raster are 1 to %2" ).arg( mZonesBand ).arg( zonesLayer->bandCount() ) );
121 mZonesHasNoDataValue = zonesLayer->dataProvider()->sourceHasNoDataValue( band );
122
123 mSourceDataProvider.reset( layer->dataProvider()->clone() );
124 mSourceInterface = mSourceDataProvider.get();
125 mZonesDataProvider.reset( zonesLayer->dataProvider()->clone() );
126 mZonesInterface = mZonesDataProvider.get();
127
128 switch ( mRefLayer )
129 {
130 case Source:
131 mCrs = layer->crs();
132 mRasterUnitsPerPixelX = layer->rasterUnitsPerPixelX();
133 mRasterUnitsPerPixelY = layer->rasterUnitsPerPixelY();
134 mLayerWidth = layer->width();
135 mLayerHeight = layer->height();
136 mExtent = layer->extent();
137
138 // add projector if necessary
139 if ( layer->crs() != zonesLayer->crs() )
140 {
141 mProjector = std::make_unique<QgsRasterProjector>();
142 mProjector->setInput( mZonesDataProvider.get() );
143 mProjector->setCrs( zonesLayer->crs(), layer->crs(), context.transformContext() );
144 mZonesInterface = mProjector.get();
145 }
146 break;
147
148 case Zones:
149 mCrs = zonesLayer->crs();
150 mRasterUnitsPerPixelX = zonesLayer->rasterUnitsPerPixelX();
151 mRasterUnitsPerPixelY = zonesLayer->rasterUnitsPerPixelY();
152 mLayerWidth = zonesLayer->width();
153 mLayerHeight = zonesLayer->height();
154 mExtent = zonesLayer->extent();
155
156 // add projector if necessary
157 if ( layer->crs() != zonesLayer->crs() )
158 {
159 mProjector = std::make_unique<QgsRasterProjector>();
160 mProjector->setInput( mSourceDataProvider.get() );
161 mProjector->setCrs( layer->crs(), zonesLayer->crs(), context.transformContext() );
162 mSourceInterface = mProjector.get();
163 }
164 break;
165 }
166
167 return true;
168}
169
170QVariantMap QgsRasterLayerZonalStatsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
171{
172 QGS_MARK_ALGORITHM_SOURCE
173
174 QString areaUnit = QgsUnitTypes::toAbbreviatedString( QgsUnitTypes::distanceToAreaUnit( mCrs.mapUnits() ) );
175
176 QString tableDest;
177 std::unique_ptr<QgsFeatureSink> sink;
178 if ( parameters.contains( u"OUTPUT_TABLE"_s ) && parameters.value( u"OUTPUT_TABLE"_s ).isValid() )
179 {
180 QgsFields outFields;
181 outFields.append( QgsField( u"zone"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
182 outFields.append( QgsField( areaUnit.isEmpty() ? "area" : areaUnit.replace( u"²"_s, "2"_L1 ), QMetaType::Type::Double, QString(), 20, 8 ) );
183 outFields.append( QgsField( u"sum"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
184 outFields.append( QgsField( u"count"_s, QMetaType::Type::LongLong, QString(), 20 ) );
185 outFields.append( QgsField( u"min"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
186 outFields.append( QgsField( u"max"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
187 outFields.append( QgsField( u"mean"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
188
189 sink.reset( parameterAsSink( parameters, u"OUTPUT_TABLE"_s, context, tableDest, outFields, Qgis::WkbType::NoGeometry, QgsCoordinateReferenceSystem() ) );
190 if ( !sink )
191 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_TABLE"_s ) );
192 }
193
194 struct StatCalculator
195 {
196 // only calculate cheap stats-- we cannot calculate stats which require holding values in memory -- because otherwise we'll end
197 // up trying to store EVERY pixel value from the input in memory
199 };
200 QHash<double, StatCalculator> zoneStats;
201 qgssize noDataCount = 0;
202
203 const qgssize layerSize = static_cast<qgssize>( mLayerWidth ) * static_cast<qgssize>( mLayerHeight );
204
205 QgsRasterIterator iter = mRefLayer == Source ? QgsRasterIterator( mSourceInterface ) : QgsRasterIterator( mZonesInterface );
206 iter.startRasterRead( mRefLayer == Source ? mBand : mZonesBand, mLayerWidth, mLayerHeight, mExtent );
207
208 int iterLeft = 0;
209 int iterTop = 0;
210 int iterCols = 0;
211 int iterRows = 0;
212 QgsRectangle blockExtent;
213 std::unique_ptr<QgsRasterBlock> rasterBlock;
214 std::unique_ptr<QgsRasterBlock> zonesRasterBlock;
215 bool isNoData = false;
216 while ( true )
217 {
218 int band;
219 if ( mRefLayer == Source )
220 {
221 band = mBand;
222 if ( !iter.readNextRasterPart( mBand, iterCols, iterRows, rasterBlock, iterLeft, iterTop, &blockExtent ) )
223 break;
224
225 zonesRasterBlock.reset( mZonesInterface->block( mZonesBand, blockExtent, iterCols, iterRows ) );
226 }
227 else
228 {
229 band = mZonesBand;
230 if ( !iter.readNextRasterPart( mZonesBand, iterCols, iterRows, zonesRasterBlock, iterLeft, iterTop, &blockExtent ) )
231 break;
232
233 rasterBlock.reset( mSourceInterface->block( mBand, blockExtent, iterCols, iterRows ) );
234 }
235 if ( !zonesRasterBlock || !rasterBlock )
236 continue;
237
238 feedback->setProgress( 100 * iter.progress( band ) );
239 if ( !rasterBlock->isValid() || rasterBlock->isEmpty() || !zonesRasterBlock->isValid() || zonesRasterBlock->isEmpty() )
240 continue;
241
242 for ( int row = 0; row < iterRows; row++ )
243 {
244 if ( feedback->isCanceled() )
245 break;
246
247 for ( int column = 0; column < iterCols; column++ )
248 {
249 const double value = rasterBlock->valueAndNoData( row, column, isNoData );
250 if ( mHasNoDataValue && isNoData )
251 {
252 noDataCount += 1;
253 continue;
254 }
255 const double zone = zonesRasterBlock->valueAndNoData( row, column, isNoData );
256 if ( mZonesHasNoDataValue && isNoData )
257 {
258 noDataCount += 1;
259 continue;
260 }
261 zoneStats[zone].s.addValue( value );
262 }
263 }
264 }
265
266 QVariantMap outputs;
267 outputs.insert( u"EXTENT"_s, mExtent.toString() );
268 outputs.insert( u"CRS_AUTHID"_s, mCrs.authid() );
269 outputs.insert( u"WIDTH_IN_PIXELS"_s, mLayerWidth );
270 outputs.insert( u"HEIGHT_IN_PIXELS"_s, mLayerHeight );
271 outputs.insert( u"TOTAL_PIXEL_COUNT"_s, layerSize );
272 outputs.insert( u"NODATA_PIXEL_COUNT"_s, noDataCount );
273
274 const double pixelArea = mRasterUnitsPerPixelX * mRasterUnitsPerPixelY;
275
276 for ( auto it = zoneStats.begin(); it != zoneStats.end(); ++it )
277 {
278 QgsFeature f;
279 it->s.finalize();
280 f.setAttributes( QgsAttributes() << it.key() << it->s.count() * pixelArea << it->s.sum() << it->s.count() << it->s.min() << it->s.max() << it->s.mean() );
281 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
282 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT_TABLE"_s ) );
283 else
284 feedback->featureAddedToSink( u"OUTPUT_TABLE"_s );
285 }
286
287 sink->finalize();
288 feedback->featureSinkFinalized( u"OUTPUT_TABLE"_s );
289
290 outputs.insert( u"OUTPUT_TABLE"_s, tableDest );
291
292 return outputs;
293}
294
295
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3757
@ Mean
Mean of values.
Definition qgis.h:6574
@ Max
Max of values.
Definition qgis.h:6579
@ Min
Min of values.
Definition qgis.h:6578
@ Sum
Sum of values.
Definition qgis.h:6573
@ Count
Count.
Definition qgis.h:6571
@ NoGeometry
No geometry.
Definition qgis.h:312
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3984
Represents a coordinate reference system (CRS).
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
virtual Q_INVOKABLE 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.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
A numeric output for processing algorithms.
A string output for processing algorithms.
A raster band parameter for Processing algorithms.
A feature sink output for processing algorithms.
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.
Iterator for sequentially processing raster cells.
bool readNextRasterPart(int bandNumber, int &nCols, int &nRows, QgsRasterBlock **block, int &topLeftCol, int &topLeftRow)
Fetches next part of raster data, caller takes ownership of the block and caller should delete the bl...
double progress(int bandNumber, double currentBlockProgress=-1) const
Returns the raster iteration progress as a fraction from 0 to 1.0, for the specified bandNumber.
void startRasterRead(int bandNumber, qgssize nCols, qgssize nRows, const QgsRectangle &extent, QgsRasterBlockFeedback *feedback=nullptr)
Start reading of raster band.
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.
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.
static Q_INVOKABLE QString toAbbreviatedString(Qgis::DistanceUnit unit)
Returns a translated abbreviation representing a distance unit.
static Q_INVOKABLE Qgis::AreaUnit distanceToAreaUnit(Qgis::DistanceUnit distanceUnit)
Converts a distance unit to its corresponding area unit, e.g., meters to square meters.
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:8241