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