QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
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 : matthias@opengis.ch
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"
21
23
24QString QgsZonalStatisticsFeatureBasedAlgorithm::name() const
25{
26 return QStringLiteral( "zonalstatisticsfb" );
27}
28
29QString QgsZonalStatisticsFeatureBasedAlgorithm::displayName() const
30{
31 return QObject::tr( "Zonal statistics" );
32}
33
34QStringList QgsZonalStatisticsFeatureBasedAlgorithm::tags() const
35{
36 return QObject::tr( "stats,statistics,zones,layer,sum,maximum,minimum,mean,count,standard,deviation,"
37 "median,range,majority,minority,variety,variance,summary,raster" )
38 .split( ',' );
39}
40
41QString QgsZonalStatisticsFeatureBasedAlgorithm::group() const
42{
43 return QObject::tr( "Raster analysis" );
44}
45
46QString QgsZonalStatisticsFeatureBasedAlgorithm::groupId() const
47{
48 return QStringLiteral( "rasteranalysis" );
49}
50
51QString QgsZonalStatisticsFeatureBasedAlgorithm::shortHelpString() const
52{
53 return QObject::tr( "This algorithm calculates statistics of a raster layer for each feature "
54 "of an overlapping polygon vector layer." );
55}
56
57QString QgsZonalStatisticsFeatureBasedAlgorithm::shortDescription() const
58{
59 return QObject::tr( "Calculates statistics of a raster layer for each feature "
60 "of an overlapping polygon vector layer." );
61}
62
63QList<int> QgsZonalStatisticsFeatureBasedAlgorithm::inputLayerTypes() const
64{
65 return QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon );
66}
67
68QgsZonalStatisticsFeatureBasedAlgorithm *QgsZonalStatisticsFeatureBasedAlgorithm::createInstance() const
69{
70 return new QgsZonalStatisticsFeatureBasedAlgorithm();
71}
72
73void QgsZonalStatisticsFeatureBasedAlgorithm::initParameters( const QVariantMap &configuration )
74{
75 Q_UNUSED( configuration )
76 QStringList statChoices;
77 statChoices.reserve( STATS.size() );
78 for ( const Qgis::ZonalStatistic stat : STATS )
79 {
80 statChoices << QgsZonalStatistics::displayName( stat );
81 }
82
83 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
84 addParameter( new QgsProcessingParameterBand( QStringLiteral( "RASTER_BAND" ), QObject::tr( "Raster band" ), 1, QStringLiteral( "INPUT_RASTER" ) ) );
85
86 addParameter( new QgsProcessingParameterString( QStringLiteral( "COLUMN_PREFIX" ), QObject::tr( "Output column prefix" ), QStringLiteral( "_" ) ) );
87
88 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "STATISTICS" ), QObject::tr( "Statistics to calculate" ), statChoices, true, QVariantList() << 0 << 1 << 2 ) );
89}
90
91QString QgsZonalStatisticsFeatureBasedAlgorithm::outputName() const
92{
93 return QObject::tr( "Zonal Statistics" );
94}
95
96QgsFields QgsZonalStatisticsFeatureBasedAlgorithm::outputFields( const QgsFields &inputFields ) const
97{
98 Q_UNUSED( inputFields )
99 return mOutputFields;
100}
101
102bool QgsZonalStatisticsFeatureBasedAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
103{
104 mPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
105
106 const QList<int> stats = parameterAsEnums( parameters, QStringLiteral( "STATISTICS" ), context );
107 mStats = Qgis::ZonalStatistics();
108 for ( const int s : stats )
109 {
110 mStats |= STATS.at( s );
111 }
112
113 QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
114 if ( !rasterLayer )
115 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
116
117 mBand = parameterAsInt( parameters, QStringLiteral( "RASTER_BAND" ), context );
118 if ( mBand < 1 || mBand > rasterLayer->bandCount() )
119 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( rasterLayer->bandCount() ) );
120
121 if ( !rasterLayer->dataProvider() )
122 throw QgsProcessingException( QObject::tr( "Invalid raster layer. Layer %1 is invalid." ).arg( rasterLayer->id() ) );
123
124 mRaster.reset( rasterLayer->dataProvider()->clone() );
125 mCrs = rasterLayer->crs();
126 mPixelSizeX = rasterLayer->rasterUnitsPerPixelX();
127 mPixelSizeY = rasterLayer->rasterUnitsPerPixelY();
128 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, inputParameterName(), context ) );
129
130 mOutputFields = source->fields();
131
132 for ( const Qgis::ZonalStatistic stat : STATS )
133 {
134 if ( mStats & stat )
135 {
136 const QgsField field = QgsField( mPrefix + QgsZonalStatistics::shortName( stat ), QMetaType::Type::Double, QStringLiteral( "double precision" ) );
137 if ( mOutputFields.names().contains( field.name() ) )
138 {
139 throw QgsProcessingException( QObject::tr( "Field %1 already exists" ).arg( field.name() ) );
140 }
141 mOutputFields.append( field );
142 mStatFieldsMapping.insert( stat, mOutputFields.size() - 1 );
143 }
144 }
145
146 return true;
147}
148
149QgsFeatureList QgsZonalStatisticsFeatureBasedAlgorithm::processFeature( const QgsFeature &feature, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
150{
151 if ( !mCreatedTransform )
152 {
153 mCreatedTransform = true;
154 mFeatureToRasterTransform = QgsCoordinateTransform( sourceCrs(), mCrs, context.transformContext() );
155 }
156
157 Q_UNUSED( feedback )
158 QgsAttributes attributes = feature.attributes();
159 attributes.resize( mOutputFields.size() );
160
161 QgsGeometry geometry = feature.geometry();
162 try
163 {
164 geometry.transform( mFeatureToRasterTransform );
165 }
166 catch ( QgsCsException & )
167 {
168 if ( feedback )
169 feedback->reportError( QObject::tr( "Encountered a transform error when reprojecting feature with id %1." ).arg( feature.id() ) );
170 }
171
172 const QMap<Qgis::ZonalStatistic, QVariant> results = QgsZonalStatistics::calculateStatistics( mRaster.get(), geometry, mPixelSizeX, mPixelSizeY, mBand, mStats );
173 for ( auto result = results.constBegin(); result != results.constEnd(); ++result )
174 {
175 attributes.replace( mStatFieldsMapping.value( result.key() ), result.value() );
176 }
177
178 QgsFeature resultFeature = feature;
179 resultFeature.setAttributes( attributes );
180
181 return QgsFeatureList { resultFeature };
182}
183
184bool QgsZonalStatisticsFeatureBasedAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
185{
186 Q_UNUSED( layer )
187 return false;
188}
189
@ VectorPolygon
Vector polygon layers.
ZonalStatistic
Statistics to be calculated during a zonal statistics operation.
Definition qgis.h:5559
QFlags< ZonalStatistic > ZonalStatistics
Statistics to be calculated during a zonal statistics operation.
Definition qgis.h:5585
A vector of attributes.
Handles coordinate transforms between two coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsAttributes attributes
Definition qgsfeature.h:67
QgsFeatureId id
Definition qgsfeature.h:66
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
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:46
A geometry is the spatial representation of a feature.
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:77
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:84
QString id
Definition qgsmaplayer.h:80
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.
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