QGIS API Documentation  3.16.0-Hannover (43b64b13f3)
qgsalgorithmzonalstatisticsfeaturebased.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsalgorithmzonalstatisticsfeaturebased.cpp
3  ---------------------
4  begin : September 2020
5  copyright : (C) 2020 by Matthias Kuhn
6  email : [email protected]
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 QgsZonalStatisticsFeatureBasedAlgorithm::name() const
39 {
40  return QStringLiteral( "zonalstatisticsfb" );
41 }
42 
43 QString QgsZonalStatisticsFeatureBasedAlgorithm::displayName() const
44 {
45  return QObject::tr( "Zonal statistics" );
46 }
47 
48 QStringList QgsZonalStatisticsFeatureBasedAlgorithm::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 QgsZonalStatisticsFeatureBasedAlgorithm::group() const
55 {
56  return QObject::tr( "Raster analysis" );
57 }
58 
59 QString QgsZonalStatisticsFeatureBasedAlgorithm::groupId() const
60 {
61  return QStringLiteral( "rasteranalysis" );
62 }
63 
64 QString QgsZonalStatisticsFeatureBasedAlgorithm::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 QList<int> QgsZonalStatisticsFeatureBasedAlgorithm::inputLayerTypes() const
71 {
72  return QList<int>() << QgsProcessing::TypeVectorPolygon;
73 }
74 
75 QgsZonalStatisticsFeatureBasedAlgorithm *QgsZonalStatisticsFeatureBasedAlgorithm::createInstance() const
76 {
77  return new QgsZonalStatisticsFeatureBasedAlgorithm();
78 }
79 
80 void QgsZonalStatisticsFeatureBasedAlgorithm::initParameters( const QVariantMap &configuration )
81 {
82  Q_UNUSED( configuration )
83  QStringList statChoices;
84  statChoices.reserve( STATS.size() );
85  for ( QgsZonalStatistics::Statistic stat : STATS )
86  {
87  statChoices << QgsZonalStatistics::displayName( stat );
88  }
89 
90  addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
91  addParameter( new QgsProcessingParameterBand( QStringLiteral( "RASTER_BAND" ),
92  QObject::tr( "Raster band" ), 1, QStringLiteral( "INPUT_RASTER" ) ) );
93 
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 
100 QString QgsZonalStatisticsFeatureBasedAlgorithm::outputName() const
101 {
102  return QObject::tr( "Zonal Statistics" );
103 }
104 
105 QgsFields QgsZonalStatisticsFeatureBasedAlgorithm::outputFields( const QgsFields &inputFields ) const
106 {
107  Q_UNUSED( inputFields )
108  return mOutputFields;
109 }
110 
111 bool QgsZonalStatisticsFeatureBasedAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
112 {
113  mPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
114 
115  const QList< int > stats = parameterAsEnums( parameters, QStringLiteral( "STATISTICS" ), context );
116  mStats = QgsZonalStatistics::Statistics();
117  for ( int s : stats )
118  {
119  mStats |= STATS.at( s );
120  }
121 
122  QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
123  if ( !rasterLayer )
124  throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
125 
126  mBand = parameterAsInt( parameters, QStringLiteral( "RASTER_BAND" ), context );
127  if ( mBand < 1 || mBand > rasterLayer->bandCount() )
128  throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand )
129  .arg( rasterLayer->bandCount() ) );
130 
131  if ( !rasterLayer->dataProvider() )
132  throw QgsProcessingException( QObject::tr( "Invalid raster layer. Layer %1 is invalid." ).arg( rasterLayer->id() ) );
133 
134  mRaster.reset( rasterLayer->dataProvider()->clone() );
135  mCrs = rasterLayer->crs();
136  mPixelSizeX = rasterLayer->rasterUnitsPerPixelX();
137  mPixelSizeY = rasterLayer->rasterUnitsPerPixelY();
138  std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, inputParameterName(), context ) );
139 
140  mOutputFields = source->fields();
141 
142  for ( QgsZonalStatistics::Statistic stat : STATS )
143  {
144  if ( mStats & stat )
145  {
146  QgsField field = QgsField( mPrefix + QgsZonalStatistics::shortName( stat ), QVariant::Double, QStringLiteral( "double precision" ) );
147  if ( mOutputFields.names().contains( field.name() ) )
148  {
149  throw QgsProcessingException( QObject::tr( "Field %1 already exists" ).arg( field.name() ) );
150  }
151  mOutputFields.append( field );
152  mStatFieldsMapping.insert( stat, mOutputFields.size() - 1 );
153  }
154  }
155 
156  return true;
157 }
158 
159 QgsFeatureList QgsZonalStatisticsFeatureBasedAlgorithm::processFeature( const QgsFeature &feature, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
160 {
161  Q_UNUSED( context )
162  Q_UNUSED( feedback )
163  QgsAttributes attributes = feature.attributes();
164  attributes.resize( mOutputFields.size() );
165 
166  QMap<QgsZonalStatistics::Statistic, QVariant> results = QgsZonalStatistics::calculateStatistics( mRaster.get(), feature.geometry(), mPixelSizeX, mPixelSizeY, mBand, mStats );
167  for ( auto result = results.constBegin(); result != results.constEnd(); ++result )
168  {
169  attributes.replace( mStatFieldsMapping.value( result.key() ), result.value() );
170  }
171 
172  QgsFeature resultFeature = feature;
173  resultFeature.setAttributes( attributes );
174 
175  return QgsFeatureList { resultFeature };
176 }
177 
178 bool QgsZonalStatisticsFeatureBasedAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
179 {
180  Q_UNUSED( layer )
181  return false;
182 }
183 
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:89
QgsRasterLayer::bandCount
int bandCount() const
Returns the number of bands in this layer.
Definition: qgsrasterlayer.cpp:217
QgsZonalStatistics::calculateStatistics
QgsZonalStatistics::Result calculateStatistics(QgsFeedback *feedback)
Runs the calculation.
Definition: qgszonalstatistics.cpp:58
QgsProcessingFeedback
Base class for providing feedback from a processing algorithm.
Definition: qgsprocessingfeedback.h:38
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:50
QgsFields
Container of fields for a vector layer.
Definition: qgsfields.h:45
QgsZonalStatistics::StDev
@ StDev
Standard deviation of pixel values.
Definition: qgszonalstatistics.h:57
QgsFeature::geometry
QgsGeometry geometry
Definition: qgsfeature.h:67
field
const QgsField & field
Definition: qgsfield.h:456
QgsZonalStatistics::Count
@ Count
Pixel count.
Definition: qgszonalstatistics.h:53
QgsZonalStatistics::Min
@ Min
Min of pixel values.
Definition: qgszonalstatistics.h:58
QgsField::name
QString name
Definition: qgsfield.h:59
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:44
QgsZonalStatistics::Max
@ Max
Max of pixel values.
Definition: qgszonalstatistics.h:59
QgsProcessingParameterString
A string parameter for processing algorithms.
Definition: qgsprocessingparameters.h:2324
QgsZonalStatistics::shortName
static QString shortName(QgsZonalStatistics::Statistic statistic)
Returns a short, friendly display name for a statistic, suitable for use in a field name.
Definition: qgszonalstatistics.cpp:256
QgsFeatureList
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:583
QgsRasterLayer::dataProvider
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
Definition: qgsrasterlayer.cpp:234
QgsProcessingParameterRasterLayer
A raster layer parameter for processing algorithms.
Definition: qgsprocessingparameters.h:2223
QgsMapLayer::id
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
Definition: qgsmaplayer.cpp:148
QgsZonalStatistics::Sum
@ Sum
Sum of pixel values.
Definition: qgszonalstatistics.h:54
QgsRasterLayer
Represents a raster layer.
Definition: qgsrasterlayer.h:71
QgsFeature::attributes
QgsAttributes attributes
Definition: qgsfeature.h:65
QgsRasterLayer::rasterUnitsPerPixelY
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
Definition: qgsrasterlayer.cpp:583
QgsZonalStatistics::Variance
@ Variance
Variance of pixel values.
Definition: qgszonalstatistics.h:64
QgsMapLayer
Base class for all map layer types.
Definition: qgsmaplayer.h:83
QgsZonalStatistics::Range
@ Range
Range of pixel values (max - min)
Definition: qgszonalstatistics.h:60
QgsProcessingParameterBand
A raster band parameter for Processing algorithms.
Definition: qgsprocessingparameters.h:3225
QgsAttributes
A vector of attributes.
Definition: qgsattributes.h:58
QgsFeature
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:56
QgsProcessingParameterEnum
An enum based parameter for processing algorithms, allowing for selection from predefined values.
Definition: qgsprocessingparameters.h:2256
QgsFeature::setAttributes
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:129
QgsZonalStatistics::Statistic
Statistic
Enumeration of flags that specify statistics to be calculated.
Definition: qgszonalstatistics.h:52
QgsProcessingException
Custom exception class for processing related exceptions.
Definition: qgsexception.h:83
QgsZonalStatistics::Variety
@ Variety
Variety (count of distinct) pixel values.
Definition: qgszonalstatistics.h:63
QgsZonalStatistics::Minority
@ Minority
Minority of pixel values.
Definition: qgszonalstatistics.h:61
qgsalgorithmzonalstatisticsfeaturebased.h
QgsRasterLayer::rasterUnitsPerPixelX
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
Definition: qgsrasterlayer.cpp:567
QgsField
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:50