QGIS API Documentation  3.12.1-București (121cc00ff0)
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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" );
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::shortHelpString() const
65 {
66  return QObject::tr( "This algorithm calculates statistics of a raster layer for each feature "
67  "of an overlapping polygon vector layer." );
68 }
69 
70 QgsProcessingAlgorithm::Flags QgsZonalStatisticsAlgorithm::flags() const
71 {
73 }
74 
75 QgsZonalStatisticsAlgorithm *QgsZonalStatisticsAlgorithm::createInstance() const
76 {
77  return new QgsZonalStatisticsAlgorithm();
78 }
79 
80 void QgsZonalStatisticsAlgorithm::initAlgorithm( const QVariantMap & )
81 {
82  QStringList statChoices;
83  statChoices.reserve( STATS.size() );
84  for ( QgsZonalStatistics::Statistic stat : STATS )
85  {
86  statChoices << QgsZonalStatistics::displayName( stat );
87  }
88 
89  addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
90  addParameter( new QgsProcessingParameterBand( QStringLiteral( "RASTER_BAND" ),
91  QObject::tr( "Raster band" ), 1, QStringLiteral( "INPUT_RASTER" ) ) );
92  addParameter( new QgsProcessingParameterVectorLayer( QStringLiteral( "INPUT_VECTOR" ), QObject::tr( "Vector layer containing zones" ),
93  QList< int >() << QgsProcessing::TypeVectorPolygon ) );
94  addParameter( new QgsProcessingParameterString( QStringLiteral( "COLUMN_PREFIX" ), QObject::tr( "Output column prefix" ), QStringLiteral( "_" ) ) );
95 
96  addParameter( new QgsProcessingParameterEnum( QStringLiteral( "STATISTICS" ), QObject::tr( "Statistics to calculate" ),
97  statChoices, true, QVariantList() << 0 << 1 << 2 ) );
98 
99  addOutput( new QgsProcessingOutputVectorLayer( QStringLiteral( "INPUT_VECTOR" ), QObject::tr( "Zonal statistics" ), QgsProcessing::TypeVectorPolygon ) );
100 }
101 
102 bool QgsZonalStatisticsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
103 {
104  QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
105  if ( !rasterLayer )
106  throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
107 
108  mBand = parameterAsInt( parameters, QStringLiteral( "RASTER_BAND" ), context );
109  if ( mBand < 1 || mBand > rasterLayer->bandCount() )
110  throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand )
111  .arg( rasterLayer->bandCount() ) );
112 
113  mInterface.reset( rasterLayer->dataProvider()->clone() );
114  mCrs = rasterLayer->crs();
115  mPixelSizeX = rasterLayer->rasterUnitsPerPixelX();
116  mPixelSizeY = rasterLayer->rasterUnitsPerPixelY();
117 
118  mPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
119 
120  const QList< int > stats = parameterAsEnums( parameters, QStringLiteral( "STATISTICS" ), context );
121  mStats = nullptr;
122  for ( int s : stats )
123  {
124  mStats |= STATS.at( s );
125  }
126 
127  return true;
128 }
129 
130 QVariantMap QgsZonalStatisticsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
131 {
132  QgsVectorLayer *layer = parameterAsVectorLayer( parameters, QStringLiteral( "INPUT_VECTOR" ), context );
133  if ( !layer )
134  throw QgsProcessingException( QObject::tr( "Invalid zones layer" ) );
135 
136  QgsZonalStatistics zs( layer,
137  mInterface.get(),
138  mCrs,
139  mPixelSizeX,
140  mPixelSizeY,
141  mPrefix,
142  mBand,
143  QgsZonalStatistics::Statistics( mStats )
144  );
145 
146  zs.calculateStatistics( feedback );
147 
148  QVariantMap outputs;
149  outputs.insert( QStringLiteral( "INPUT_VECTOR" ), layer->id() );
150  return outputs;
151 }
152 
Base class for providing feedback from a processing algorithm.
Statistic
Enumeration of flags that specify statistics to be calculated.
int bandCount() const
Returns the number of bands in this layer.
Represents a raster layer.
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
QgsRasterInterface * clone() const override=0
Clone itself, create deep copy.
virtual Flags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users...
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
A raster band parameter for Processing algorithms.
A vector layer output for processing algorithms.
Median of pixel values.
Minority of pixel values.
Variety (count of distinct) pixel values.
Variance of pixel values.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
A raster layer parameter for processing algorithms.
static QString displayName(QgsZonalStatistics::Statistic statistic)
Returns the friendly display name for a statistic.
QString id() const
Returns the layer&#39;s unique ID, which is used to access this layer from QgsProject.
An enum based parameter for processing algorithms, allowing for selection from predefined values...
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Sum of pixel values.
Majority of pixel values.
Custom exception class for processing related exceptions.
Definition: qgsexception.h:82
Vector polygon layers.
Definition: qgsprocessing.h:50
A vector layer (with or without geometry) parameter for processing algorithms.
int calculateStatistics(QgsFeedback *feedback)
Starts the calculation.
Max of pixel values.
Mean of pixel values.
Range of pixel values (max - min)
A class that calculates raster statistics (count, sum, mean) for a polygon or multipolygon layer and ...
Min of pixel values.
Represents a vector layer which manages a vector based data sets.
Contains information about the context in which a processing algorithm is executed.
A string parameter for processing algorithms.
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:86
Standard deviation of pixel values.