QGIS API Documentation  3.26.3-Buenos Aires (65e4edfdad)
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 ( const 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 ( const 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 ( const QgsZonalStatistics::Statistic stat : STATS )
143  {
144  if ( mStats & stat )
145  {
146  const 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  if ( !mCreatedTransform )
162  {
163  mCreatedTransform = true;
164  mFeatureToRasterTransform = QgsCoordinateTransform( sourceCrs(), mCrs, context.transformContext() );
165  }
166 
167  Q_UNUSED( feedback )
168  QgsAttributes attributes = feature.attributes();
169  attributes.resize( mOutputFields.size() );
170 
171  QgsGeometry geometry = feature.geometry();
172  try
173  {
174  geometry.transform( mFeatureToRasterTransform );
175  }
176  catch ( QgsCsException & )
177  {
178  if ( feedback )
179  feedback->reportError( QObject::tr( "Encountered a transform error when reprojecting feature with id %1." ).arg( feature.id() ) );
180  }
181 
182  const QMap<QgsZonalStatistics::Statistic, QVariant> results = QgsZonalStatistics::calculateStatistics( mRaster.get(), geometry, mPixelSizeX, mPixelSizeY, mBand, mStats );
183  for ( auto result = results.constBegin(); result != results.constEnd(); ++result )
184  {
185  attributes.replace( mStatFieldsMapping.value( result.key() ), result.value() );
186  }
187 
188  QgsFeature resultFeature = feature;
189  resultFeature.setAttributes( attributes );
190 
191  return QgsFeatureList { resultFeature };
192 }
193 
194 bool QgsZonalStatisticsFeatureBasedAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
195 {
196  Q_UNUSED( layer )
197  return false;
198 }
199 
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
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:37
QgsGeometry::transform
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
Definition: qgsgeometry.cpp:3128
QgsZonalStatistics::Mean
@ Mean
Mean of pixel values.
Definition: qgszonalstatistics.h:55
QgsZonalStatistics::Majority
@ Majority
Majority of pixel values.
Definition: qgszonalstatistics.h:62
QgsProcessingFeedback::reportError
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
Definition: qgsprocessingfeedback.cpp:59
QgsProcessing::TypeVectorPolygon
@ TypeVectorPolygon
Vector polygon layers.
Definition: qgsprocessing.h:51
QgsFields
Container of fields for a vector layer.
Definition: qgsfields.h:44
QgsZonalStatistics::StDev
@ StDev
Standard deviation of pixel values.
Definition: qgszonalstatistics.h:57
QgsFeature::geometry
QgsGeometry geometry
Definition: qgsfeature.h:71
field
const QgsField & field
Definition: qgsfield.h:463
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:60
QgsRasterDataProvider::clone
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
QgsFeature::id
QgsFeatureId id
Definition: qgsfeature.h:68
QgsZonalStatistics::Median
@ Median
Median of pixel values.
Definition: qgszonalstatistics.h:56
QgsCsException
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:65
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
QgsProcessingParameterString
A string parameter for processing algorithms.
Definition: qgsprocessingparameters.h:2647
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:882
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
QgsProcessingContext::transformContext
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Definition: qgsprocessingcontext.h:165
QgsZonalStatistics::Sum
@ Sum
Sum of pixel values.
Definition: qgszonalstatistics.h:54
QgsRasterLayer
Represents a raster layer.
Definition: qgsrasterlayer.h:76
QgsFeature::attributes
QgsAttributes attributes
Definition: qgsfeature.h:69
QgsRasterLayer::rasterUnitsPerPixelY
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
Definition: qgsrasterlayer.cpp:582
QgsZonalStatistics::Variance
@ Variance
Variance of pixel values.
Definition: qgszonalstatistics.h:64
QgsGeometry
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
QgsMapLayer
Base class for all map layer types. This is the base class for all map layer types (vector,...
Definition: qgsmaplayer.h:72
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
QgsAttributes
A vector of attributes. Mostly equal to QVector<QVariant>.
Definition: qgsattributes.h:57
QgsFeature
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:55
QgsProcessingParameterEnum
An enum based parameter for processing algorithms, allowing for selection from predefined values.
Definition: qgsprocessingparameters.h:2540
QgsFeature::setAttributes
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:160
QgsCoordinateTransform
Class for doing transforms between two map coordinate systems.
Definition: qgscoordinatetransform.h:57
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
qgsalgorithmzonalstatisticsfeaturebased.h
QgsRasterLayer::rasterUnitsPerPixelX
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
Definition: qgsrasterlayer.cpp:566
QgsField
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:50