QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
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
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29QString QgsZonalStatisticsFeatureBasedAlgorithm::name() const
30{
31 return u"zonalstatisticsfb"_s;
32}
33
34QString QgsZonalStatisticsFeatureBasedAlgorithm::displayName() const
35{
36 return QObject::tr( "Zonal statistics" );
37}
38
39QStringList QgsZonalStatisticsFeatureBasedAlgorithm::tags() const
40{
41 return QObject::tr(
42 "stats,statistics,zones,layer,sum,maximum,minimum,mean,count,standard,deviation,"
43 "median,range,majority,minority,variety,variance,summary,raster"
44 )
45 .split( ',' );
46}
47
48QString QgsZonalStatisticsFeatureBasedAlgorithm::group() const
49{
50 return QObject::tr( "Raster analysis" );
51}
52
53QString QgsZonalStatisticsFeatureBasedAlgorithm::groupId() const
54{
55 return u"rasteranalysis"_s;
56}
57
58QString QgsZonalStatisticsFeatureBasedAlgorithm::shortHelpString() const
59{
60 return QObject::tr(
61 "This algorithm calculates statistics of a raster layer for each feature "
62 "of an overlapping polygon vector layer."
63 );
64}
65
66QString QgsZonalStatisticsFeatureBasedAlgorithm::shortDescription() const
67{
68 return QObject::tr(
69 "Calculates statistics of a raster layer for each feature "
70 "of an overlapping polygon vector layer."
71 );
72}
73
74QList<int> QgsZonalStatisticsFeatureBasedAlgorithm::inputLayerTypes() const
75{
76 return QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon );
77}
78
79QgsZonalStatisticsFeatureBasedAlgorithm *QgsZonalStatisticsFeatureBasedAlgorithm::createInstance() const
80{
81 return new QgsZonalStatisticsFeatureBasedAlgorithm();
82}
83
84void QgsZonalStatisticsFeatureBasedAlgorithm::initParameters( const QVariantMap &configuration )
85{
86 Q_UNUSED( configuration )
87 QStringList statChoices;
88 statChoices.reserve( STATS.size() );
89 for ( const Qgis::ZonalStatistic stat : STATS )
90 {
91 statChoices << QgsZonalStatistics::displayName( stat );
92 }
93
94 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT_RASTER"_s, QObject::tr( "Raster layer" ) ) );
95 addParameter( new QgsProcessingParameterBand( u"RASTER_BAND"_s, QObject::tr( "Raster band" ), 1, u"INPUT_RASTER"_s ) );
96
97 addParameter( new QgsProcessingParameterString( u"COLUMN_PREFIX"_s, QObject::tr( "Output column prefix" ), u"_"_s ) );
98
99 addParameter( new QgsProcessingParameterEnum( u"STATISTICS"_s, QObject::tr( "Statistics to calculate" ), statChoices, true, QVariantList() << 0 << 1 << 2 ) );
100}
101
102QString QgsZonalStatisticsFeatureBasedAlgorithm::outputName() const
103{
104 return QObject::tr( "Zonal Statistics" );
105}
106
107QgsFields QgsZonalStatisticsFeatureBasedAlgorithm::outputFields( const QgsFields &inputFields ) const
108{
109 Q_UNUSED( inputFields )
110 return mOutputFields;
111}
112
113bool QgsZonalStatisticsFeatureBasedAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
114{
115 mPrefix = parameterAsString( parameters, u"COLUMN_PREFIX"_s, context );
116
117 const QList<int> stats = parameterAsEnums( parameters, u"STATISTICS"_s, context );
118 mStats = Qgis::ZonalStatistics();
119 for ( const int s : stats )
120 {
121 mStats |= STATS.at( s );
122 }
123
124 QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, u"INPUT_RASTER"_s, context );
125 if ( !rasterLayer )
126 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT_RASTER"_s ) );
127
128 mBand = parameterAsInt( parameters, u"RASTER_BAND"_s, context );
129 if ( mBand < 1 || mBand > rasterLayer->bandCount() )
130 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).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 ), QMetaType::Type::Double, u"double precision"_s );
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.
Definition qgis.h:3650
ZonalStatistic
Statistics to be calculated during a zonal statistics operation.
Definition qgis.h:6119
QFlags< ZonalStatistic > ZonalStatistics
Statistics to be calculated during a zonal statistics operation.
Definition qgis.h:6147
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:60
QgsAttributes attributes
Definition qgsfeature.h:69
QgsFeatureId id
Definition qgsfeature.h:68
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
QString name
Definition qgsfield.h:65
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:83
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
QString id
Definition qgsmaplayer.h:86
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