QGIS API Documentation 3.28.0-Firenze (ed3ad0430f)
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
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
22const std::vector< QgsZonalStatistics::Statistic > STATS
23{
36};
37
38QString QgsZonalStatisticsFeatureBasedAlgorithm::name() const
39{
40 return QStringLiteral( "zonalstatisticsfb" );
41}
42
43QString QgsZonalStatisticsFeatureBasedAlgorithm::displayName() const
44{
45 return QObject::tr( "Zonal statistics" );
46}
47
48QStringList 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
54QString QgsZonalStatisticsFeatureBasedAlgorithm::group() const
55{
56 return QObject::tr( "Raster analysis" );
57}
58
59QString QgsZonalStatisticsFeatureBasedAlgorithm::groupId() const
60{
61 return QStringLiteral( "rasteranalysis" );
62}
63
64QString 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
70QList<int> QgsZonalStatisticsFeatureBasedAlgorithm::inputLayerTypes() const
71{
72 return QList<int>() << QgsProcessing::TypeVectorPolygon;
73}
74
75QgsZonalStatisticsFeatureBasedAlgorithm *QgsZonalStatisticsFeatureBasedAlgorithm::createInstance() const
76{
77 return new QgsZonalStatisticsFeatureBasedAlgorithm();
78}
79
80void 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
100QString QgsZonalStatisticsFeatureBasedAlgorithm::outputName() const
101{
102 return QObject::tr( "Zonal Statistics" );
103}
104
105QgsFields QgsZonalStatisticsFeatureBasedAlgorithm::outputFields( const QgsFields &inputFields ) const
106{
107 Q_UNUSED( inputFields )
108 return mOutputFields;
109}
110
111bool 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
159QgsFeatureList 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
194bool QgsZonalStatisticsFeatureBasedAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
195{
196 Q_UNUSED( layer )
197 return false;
198}
199
A vector of attributes.
Definition: qgsattributes.h:59
Class for doing transforms between two map coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:66
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QgsAttributes attributes
Definition: qgsfeature.h:65
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:160
QgsGeometry geometry
Definition: qgsfeature.h:67
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:51
QString name
Definition: qgsfield.h:60
Container of fields for a vector layer.
Definition: qgsfields.h:45
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:164
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.
Base class for all map layer types.
Definition: qgsmaplayer.h:73
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:79
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
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.
Definition: qgsexception.h:83
Base class for providing feedback from a processing algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A raster band parameter for Processing algorithms.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A raster layer parameter for processing algorithms.
A string parameter for processing algorithms.
@ TypeVectorPolygon
Vector polygon layers.
Definition: qgsprocessing.h:51
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
Represents a raster layer.
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.
static QString shortName(QgsZonalStatistics::Statistic statistic)
Returns a short, friendly display name for a statistic, suitable for use in a field name.
Statistic
Enumeration of flags that specify statistics to be calculated.
@ Minority
Minority of pixel values.
@ Variety
Variety (count of distinct) pixel values.
@ Variance
Variance of pixel values.
@ Mean
Mean of pixel values.
@ Majority
Majority of pixel values.
@ Range
Range of pixel values (max - min)
@ Min
Min of pixel values.
@ Sum
Sum of pixel values.
@ StDev
Standard deviation of pixel values.
@ Max
Max of pixel values.
@ Median
Median of pixel values.
QgsZonalStatistics::Result calculateStatistics(QgsFeedback *feedback)
Runs the calculation.
static QString displayName(QgsZonalStatistics::Statistic statistic)
Returns the friendly display name for a statistic.
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:922
const QgsField & field
Definition: qgsfield.h:463