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