QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
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#include "qgszonalstatistics.h"
20
22
23const std::vector< Qgis::ZonalStatistic > STATS
24{
37};
38
39QString QgsZonalStatisticsFeatureBasedAlgorithm::name() const
40{
41 return QStringLiteral( "zonalstatisticsfb" );
42}
43
44QString QgsZonalStatisticsFeatureBasedAlgorithm::displayName() const
45{
46 return QObject::tr( "Zonal statistics" );
47}
48
49QStringList QgsZonalStatisticsFeatureBasedAlgorithm::tags() const
50{
51 return QObject::tr( "stats,statistics,zones,layer,sum,maximum,minimum,mean,count,standard,deviation,"
52 "median,range,majority,minority,variety,variance,summary,raster" ).split( ',' );
53}
54
55QString QgsZonalStatisticsFeatureBasedAlgorithm::group() const
56{
57 return QObject::tr( "Raster analysis" );
58}
59
60QString QgsZonalStatisticsFeatureBasedAlgorithm::groupId() const
61{
62 return QStringLiteral( "rasteranalysis" );
63}
64
65QString QgsZonalStatisticsFeatureBasedAlgorithm::shortHelpString() const
66{
67 return QObject::tr( "This algorithm calculates statistics of a raster layer for each feature "
68 "of an overlapping polygon vector layer." );
69}
70
71QList<int> QgsZonalStatisticsFeatureBasedAlgorithm::inputLayerTypes() const
72{
73 return QList<int>() << static_cast< int >( Qgis::ProcessingSourceType::VectorPolygon );
74}
75
76QgsZonalStatisticsFeatureBasedAlgorithm *QgsZonalStatisticsFeatureBasedAlgorithm::createInstance() const
77{
78 return new QgsZonalStatisticsFeatureBasedAlgorithm();
79}
80
81void QgsZonalStatisticsFeatureBasedAlgorithm::initParameters( const QVariantMap &configuration )
82{
83 Q_UNUSED( configuration )
84 QStringList statChoices;
85 statChoices.reserve( STATS.size() );
86 for ( const Qgis::ZonalStatistic stat : STATS )
87 {
88 statChoices << QgsZonalStatistics::displayName( stat );
89 }
90
91 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
92 addParameter( new QgsProcessingParameterBand( QStringLiteral( "RASTER_BAND" ),
93 QObject::tr( "Raster band" ), 1, QStringLiteral( "INPUT_RASTER" ) ) );
94
95 addParameter( new QgsProcessingParameterString( QStringLiteral( "COLUMN_PREFIX" ), QObject::tr( "Output column prefix" ), QStringLiteral( "_" ) ) );
96
97 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "STATISTICS" ), QObject::tr( "Statistics to calculate" ),
98 statChoices, true, QVariantList() << 0 << 1 << 2 ) );
99}
100
101QString QgsZonalStatisticsFeatureBasedAlgorithm::outputName() const
102{
103 return QObject::tr( "Zonal Statistics" );
104}
105
106QgsFields QgsZonalStatisticsFeatureBasedAlgorithm::outputFields( const QgsFields &inputFields ) const
107{
108 Q_UNUSED( inputFields )
109 return mOutputFields;
110}
111
112bool QgsZonalStatisticsFeatureBasedAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
113{
114 mPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
115
116 const QList< int > stats = parameterAsEnums( parameters, QStringLiteral( "STATISTICS" ), context );
117 mStats = Qgis::ZonalStatistics();
118 for ( const int s : stats )
119 {
120 mStats |= STATS.at( s );
121 }
122
123 QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
124 if ( !rasterLayer )
125 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
126
127 mBand = parameterAsInt( parameters, QStringLiteral( "RASTER_BAND" ), context );
128 if ( mBand < 1 || mBand > rasterLayer->bandCount() )
129 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand )
130 .arg( rasterLayer->bandCount() ) );
131
132 if ( !rasterLayer->dataProvider() )
133 throw QgsProcessingException( QObject::tr( "Invalid raster layer. Layer %1 is invalid." ).arg( rasterLayer->id() ) );
134
135 mRaster.reset( rasterLayer->dataProvider()->clone() );
136 mCrs = rasterLayer->crs();
137 mPixelSizeX = rasterLayer->rasterUnitsPerPixelX();
138 mPixelSizeY = rasterLayer->rasterUnitsPerPixelY();
139 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, inputParameterName(), context ) );
140
141 mOutputFields = source->fields();
142
143 for ( const Qgis::ZonalStatistic stat : STATS )
144 {
145 if ( mStats & stat )
146 {
147 const QgsField field = QgsField( mPrefix + QgsZonalStatistics::shortName( stat ), QVariant::Double, QStringLiteral( "double precision" ) );
148 if ( mOutputFields.names().contains( field.name() ) )
149 {
150 throw QgsProcessingException( QObject::tr( "Field %1 already exists" ).arg( field.name() ) );
151 }
152 mOutputFields.append( field );
153 mStatFieldsMapping.insert( stat, mOutputFields.size() - 1 );
154 }
155 }
156
157 return true;
158}
159
160QgsFeatureList QgsZonalStatisticsFeatureBasedAlgorithm::processFeature( const QgsFeature &feature, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
161{
162 if ( !mCreatedTransform )
163 {
164 mCreatedTransform = true;
165 mFeatureToRasterTransform = QgsCoordinateTransform( sourceCrs(), mCrs, context.transformContext() );
166 }
167
168 Q_UNUSED( feedback )
169 QgsAttributes attributes = feature.attributes();
170 attributes.resize( mOutputFields.size() );
171
172 QgsGeometry geometry = feature.geometry();
173 try
174 {
175 geometry.transform( mFeatureToRasterTransform );
176 }
177 catch ( QgsCsException & )
178 {
179 if ( feedback )
180 feedback->reportError( QObject::tr( "Encountered a transform error when reprojecting feature with id %1." ).arg( feature.id() ) );
181 }
182
183 const QMap<Qgis::ZonalStatistic, QVariant> results = QgsZonalStatistics::calculateStatistics( mRaster.get(), geometry, mPixelSizeX, mPixelSizeY, mBand, mStats );
184 for ( auto result = results.constBegin(); result != results.constEnd(); ++result )
185 {
186 attributes.replace( mStatFieldsMapping.value( result.key() ), result.value() );
187 }
188
189 QgsFeature resultFeature = feature;
190 resultFeature.setAttributes( attributes );
191
192 return QgsFeatureList { resultFeature };
193}
194
195bool QgsZonalStatisticsFeatureBasedAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
196{
197 Q_UNUSED( layer )
198 return false;
199}
200
@ VectorPolygon
Vector polygon layers.
ZonalStatistic
Statistics to be calculated during a zonal statistics operation.
Definition: qgis.h:4665
@ StDev
Standard deviation of pixel values.
@ Mean
Mean of pixel values.
@ Median
Median of pixel values.
@ Max
Max of pixel values.
@ Variance
Variance of pixel values.
@ Min
Min of pixel values.
@ Range
Range of pixel values (max - min)
@ Sum
Sum of pixel values.
@ Minority
Minority of pixel values.
@ Majority
Majority of pixel values.
@ Variety
Variety (count of distinct) pixel values.
@ Count
Pixel count.
QFlags< ZonalStatistic > ZonalStatistics
Statistics to be calculated during a zonal statistics operation.
Definition: qgis.h:4688
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:67
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:53
QString name
Definition: qgsfield.h:62
Container of fields for a vector layer.
Definition: qgsfields.h:45
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:162
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
Base class for all map layer types.
Definition: qgsmaplayer.h:75
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:81
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.
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.
Qgis::ZonalStatisticResult calculateStatistics(QgsFeedback *feedback)
Runs the calculation.
static QString displayName(Qgis::ZonalStatistic statistic)
Returns the friendly display name for a statistic.
static QString shortName(Qgis::ZonalStatistic statistic)
Returns a short, friendly display name for a statistic, suitable for use in a field name.
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:917