QGIS API Documentation  3.26.3-Buenos Aires (65e4edfdad)
qgsalgorithmzonalstatistics.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsalgorithmzonalstatistics.cpp
3  ---------------------
4  begin : December 2019
5  copyright : (C) 2019 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 
21 
22 const std::vector< QgsZonalStatistics::Statistic > STATS
23 {
36 };
37 
38 QString QgsZonalStatisticsAlgorithm::name() const
39 {
40  return QStringLiteral( "zonalstatistics" );
41 }
42 
43 QString QgsZonalStatisticsAlgorithm::displayName() const
44 {
45  return QObject::tr( "Zonal statistics (in place)" );
46 }
47 
48 QStringList QgsZonalStatisticsAlgorithm::tags() const
49 {
50  return QObject::tr( "stats,statistics,zones,layer,sum,maximum,minimum,mean,count,standard,deviation,"
51  "median,range,majority,minority,variety,variance,summary,raster" ).split( ',' );
52 }
53 
54 QString QgsZonalStatisticsAlgorithm::group() const
55 {
56  return QObject::tr( "Raster analysis" );
57 }
58 
59 QString QgsZonalStatisticsAlgorithm::groupId() const
60 {
61  return QStringLiteral( "rasteranalysis" );
62 }
63 
64 QString QgsZonalStatisticsAlgorithm::shortDescription() const
65 {
66  return QObject::tr( "Calculates statistics for a raster layer's values for each feature of an overlapping polygon vector layer." );
67 }
68 
69 QString QgsZonalStatisticsAlgorithm::shortHelpString() const
70 {
71  return QObject::tr( "This algorithm calculates statistics of a raster layer for each feature "
72  "of an overlapping polygon vector layer. The results will be written in place." );
73 }
74 
75 QgsProcessingAlgorithm::Flags QgsZonalStatisticsAlgorithm::flags() const
76 {
78 }
79 
80 QgsZonalStatisticsAlgorithm *QgsZonalStatisticsAlgorithm::createInstance() const
81 {
82  return new QgsZonalStatisticsAlgorithm();
83 }
84 
85 void QgsZonalStatisticsAlgorithm::initAlgorithm( const QVariantMap & )
86 {
87  QStringList statChoices;
88  statChoices.reserve( STATS.size() );
89  for ( const QgsZonalStatistics::Statistic stat : STATS )
90  {
91  statChoices << QgsZonalStatistics::displayName( stat );
92  }
93 
94  addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
95  addParameter( new QgsProcessingParameterBand( QStringLiteral( "RASTER_BAND" ),
96  QObject::tr( "Raster band" ), 1, QStringLiteral( "INPUT_RASTER" ) ) );
97  addParameter( new QgsProcessingParameterVectorLayer( QStringLiteral( "INPUT_VECTOR" ), QObject::tr( "Vector layer containing zones" ),
98  QList< int >() << QgsProcessing::TypeVectorPolygon ) );
99  addParameter( new QgsProcessingParameterString( QStringLiteral( "COLUMN_PREFIX" ), QObject::tr( "Output column prefix" ), QStringLiteral( "_" ) ) );
100 
101  addParameter( new QgsProcessingParameterEnum( QStringLiteral( "STATISTICS" ), QObject::tr( "Statistics to calculate" ),
102  statChoices, true, QVariantList() << 0 << 1 << 2 ) );
103 
104  addOutput( new QgsProcessingOutputVectorLayer( QStringLiteral( "INPUT_VECTOR" ), QObject::tr( "Zonal statistics" ), QgsProcessing::TypeVectorPolygon ) );
105 }
106 
107 bool QgsZonalStatisticsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
108 {
109  QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
110  if ( !rasterLayer )
111  throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
112 
113  mBand = parameterAsInt( parameters, QStringLiteral( "RASTER_BAND" ), context );
114  if ( mBand < 1 || mBand > rasterLayer->bandCount() )
115  throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand )
116  .arg( rasterLayer->bandCount() ) );
117 
118  mInterface.reset( rasterLayer->dataProvider()->clone() );
119  mCrs = rasterLayer->crs();
120  mPixelSizeX = rasterLayer->rasterUnitsPerPixelX();
121  mPixelSizeY = rasterLayer->rasterUnitsPerPixelY();
122 
123  mPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
124 
125  const QList< int > stats = parameterAsEnums( parameters, QStringLiteral( "STATISTICS" ), context );
126  mStats = QgsZonalStatistics::Statistics();
127  for ( const int s : stats )
128  {
129  mStats |= STATS.at( s );
130  }
131 
132  return true;
133 }
134 
135 QVariantMap QgsZonalStatisticsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
136 {
137  QgsVectorLayer *layer = parameterAsVectorLayer( parameters, QStringLiteral( "INPUT_VECTOR" ), context );
138  if ( !layer )
139  throw QgsProcessingException( QObject::tr( "Invalid zones layer" ) );
140 
141  QgsZonalStatistics zs( layer,
142  mInterface.get(),
143  mCrs,
144  mPixelSizeX,
145  mPixelSizeY,
146  mPrefix,
147  mBand,
148  QgsZonalStatistics::Statistics( mStats )
149  );
150 
151  zs.calculateStatistics( feedback );
152 
153  QVariantMap outputs;
154  outputs.insert( QStringLiteral( "INPUT_VECTOR" ), layer->id() );
155  return outputs;
156 }
157 
QgsZonalStatistics::displayName
static QString displayName(QgsZonalStatistics::Statistic statistic)
Returns the friendly display name for a statistic.
Definition: qgszonalstatistics.cpp:222
QgsMapLayer::crs
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:79
QgsRasterLayer::bandCount
int bandCount() const
Returns the number of bands in this layer.
Definition: qgsrasterlayer.cpp:240
QgsProcessingFeedback
Base class for providing feedback from a processing algorithm.
Definition: qgsprocessingfeedback.h:37
QgsZonalStatistics
A class that calculates raster statistics (count, sum, mean) for a polygon or multipolygon layer and ...
Definition: qgszonalstatistics.h:46
QgsZonalStatistics::Mean
@ Mean
Mean of pixel values.
Definition: qgszonalstatistics.h:55
QgsZonalStatistics::Majority
@ Majority
Majority of pixel values.
Definition: qgszonalstatistics.h:62
QgsProcessing::TypeVectorPolygon
@ TypeVectorPolygon
Vector polygon layers.
Definition: qgsprocessing.h:51
QgsProcessingOutputVectorLayer
A vector layer output for processing algorithms.
Definition: qgsprocessingoutputs.h:179
QgsZonalStatistics::StDev
@ StDev
Standard deviation of pixel values.
Definition: qgszonalstatistics.h:57
QgsZonalStatistics::Count
@ Count
Pixel count.
Definition: qgszonalstatistics.h:53
QgsZonalStatistics::Min
@ Min
Min of pixel values.
Definition: qgszonalstatistics.h:58
QgsRasterDataProvider::clone
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
QgsZonalStatistics::Median
@ Median
Median of pixel values.
Definition: qgszonalstatistics.h:56
QgsProcessingContext
Contains information about the context in which a processing algorithm is executed.
Definition: qgsprocessingcontext.h:46
QgsZonalStatistics::Max
@ Max
Max of pixel values.
Definition: qgszonalstatistics.h:59
qgsalgorithmzonalstatistics.h
QgsProcessingParameterString
A string parameter for processing algorithms.
Definition: qgsprocessingparameters.h:2647
QgsProcessingParameterRasterLayer
A raster layer parameter for processing algorithms.
Definition: qgsprocessingparameters.h:2495
QgsMapLayer::id
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
Definition: qgsmaplayer.cpp:169
QgsZonalStatistics::Sum
@ Sum
Sum of pixel values.
Definition: qgszonalstatistics.h:54
QgsProcessingParameterVectorLayer
A vector layer (with or without geometry) parameter for processing algorithms. Consider using the mor...
Definition: qgsprocessingparameters.h:2827
QgsRasterLayer
Represents a raster layer.
Definition: qgsrasterlayer.h:76
QgsRasterLayer::rasterUnitsPerPixelY
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
Definition: qgsrasterlayer.cpp:582
QgsProcessingAlgorithm::FlagNoThreading
@ FlagNoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition: qgsprocessingalgorithm.h:76
QgsZonalStatistics::Variance
@ Variance
Variance of pixel values.
Definition: qgszonalstatistics.h:64
QgsVectorLayer
Represents a vector layer which manages a vector based data sets.
Definition: qgsvectorlayer.h:391
QgsZonalStatistics::Range
@ Range
Range of pixel values (max - min)
Definition: qgszonalstatistics.h:60
QgsProcessingParameterBand
A raster band parameter for Processing algorithms.
Definition: qgsprocessingparameters.h:3548
QgsProcessingParameterEnum
An enum based parameter for processing algorithms, allowing for selection from predefined values.
Definition: qgsprocessingparameters.h:2540
QgsProcessingAlgorithm::flags
virtual Flags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Definition: qgsprocessingalgorithm.cpp:90
QgsProcessingAlgorithm::FlagDeprecated
@ FlagDeprecated
Algorithm is deprecated.
Definition: qgsprocessingalgorithm.h:85
QgsZonalStatistics::Statistic
Statistic
Enumeration of flags that specify statistics to be calculated.
Definition: qgszonalstatistics.h:51
QgsProcessingException
Custom exception class for processing related exceptions.
Definition: qgsexception.h:82
QgsRasterLayer::dataProvider
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
Definition: qgsrasterlayer.cpp:257
QgsZonalStatistics::Variety
@ Variety
Variety (count of distinct) pixel values.
Definition: qgszonalstatistics.h:63
QgsZonalStatistics::Minority
@ Minority
Minority of pixel values.
Definition: qgszonalstatistics.h:61
QgsRasterLayer::rasterUnitsPerPixelX
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
Definition: qgsrasterlayer.cpp:566