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