QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmzonalhistogram.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmzonalhistogram.cpp
3 ---------------------
4 begin : May, 2018
5 copyright : (C) 2018 by Mathieu Pellerin
6 email : nirvn dot asia at gmail dot com
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
20#include "qgslogger.h"
21
23
24QString QgsZonalHistogramAlgorithm::name() const
25{
26 return QStringLiteral( "zonalhistogram" );
27}
28
29QString QgsZonalHistogramAlgorithm::displayName() const
30{
31 return QObject::tr( "Zonal histogram" );
32}
33
34QStringList QgsZonalHistogramAlgorithm::tags() const
35{
36 return QObject::tr( "raster,unique,values,count,area,statistics" ).split( ',' );
37}
38
39QString QgsZonalHistogramAlgorithm::group() const
40{
41 return QObject::tr( "Raster analysis" );
42}
43
44QString QgsZonalHistogramAlgorithm::groupId() const
45{
46 return QStringLiteral( "rasteranalysis" );
47}
48
49void QgsZonalHistogramAlgorithm::initAlgorithm( const QVariantMap & )
50{
51 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
52 addParameter( new QgsProcessingParameterBand( QStringLiteral( "RASTER_BAND" ), QObject::tr( "Band number" ), 1, QStringLiteral( "INPUT_RASTER" ) ) );
53
54 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT_VECTOR" ), QObject::tr( "Vector layer containing zones" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
55
56 addParameter( new QgsProcessingParameterString( QStringLiteral( "COLUMN_PREFIX" ), QObject::tr( "Output column prefix" ), QStringLiteral( "HISTO_" ), false, true ) );
57
58 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Output zones" ), Qgis::ProcessingSourceType::VectorPolygon ) );
59}
60
61QString QgsZonalHistogramAlgorithm::shortHelpString() const
62{
63 return QObject::tr( "This algorithm appends fields representing counts of each unique value from a raster layer contained within zones defined as polygons." );
64}
65
66QString QgsZonalHistogramAlgorithm::shortDescription() const
67{
68 return QObject::tr( "Appends fields representing counts of each unique value from a raster layer contained within zones defined as polygons." );
69}
70
71QgsZonalHistogramAlgorithm *QgsZonalHistogramAlgorithm::createInstance() const
72{
73 return new QgsZonalHistogramAlgorithm();
74}
75
76bool QgsZonalHistogramAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
77{
78 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
79 if ( !layer )
80 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
81
82 mRasterBand = parameterAsInt( parameters, QStringLiteral( "RASTER_BAND" ), context );
83 mHasNoDataValue = layer->dataProvider()->sourceHasNoDataValue( mRasterBand );
84 mNodataValue = layer->dataProvider()->sourceNoDataValue( mRasterBand );
85 mRasterInterface.reset( layer->dataProvider()->clone() );
86 mRasterExtent = layer->extent();
87 mCrs = layer->crs();
88 mCellSizeX = std::abs( layer->rasterUnitsPerPixelX() );
89 mCellSizeY = std::abs( layer->rasterUnitsPerPixelX() );
90 mNbCellsXProvider = mRasterInterface->xSize();
91 mNbCellsYProvider = mRasterInterface->ySize();
92 Qgis::DataType dataType = mRasterInterface->dataType( mRasterBand );
93
94 switch ( dataType )
95 {
101 break;
102 default:
103 feedback->pushWarning( QObject::tr( "The input raster is a floating-point raster. Such rasters are not suitable for use with zonal histogram algorithm.\n"
104 "Please use Round raster or Reclassify by table tools to reduce number of decimal places or define histogram bins." ) );
105 break;
106 }
107
108 return true;
109}
110
111QVariantMap QgsZonalHistogramAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
112{
113 std::unique_ptr<QgsFeatureSource> zones( parameterAsSource( parameters, QStringLiteral( "INPUT_VECTOR" ), context ) );
114 if ( !zones )
115 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT_VECTOR" ) ) );
116
117 const long count = zones->featureCount();
118 const double step = count > 0 ? 100.0 / count : 1;
119 long current = 0;
120
121 QList<double> uniqueValues;
122 QMap<QgsFeatureId, QHash<double, qgssize>> featuresUniqueValues;
123
124 // First loop through the zones to build up a list of unique values across all zones to determine sink fields list
125 QgsFeatureRequest request;
126 request.setNoAttributes();
127 if ( zones->sourceCrs() != mCrs )
128 {
129 request.setDestinationCrs( mCrs, context.transformContext() );
130 }
131 QgsFeatureIterator it = zones->getFeatures( request );
132 QgsFeature f;
133 while ( it.nextFeature( f ) )
134 {
135 if ( feedback->isCanceled() )
136 {
137 break;
138 }
139 feedback->setProgress( current * step );
140
141 if ( !f.hasGeometry() )
142 {
143 current++;
144 continue;
145 }
146
147 const QgsGeometry featureGeometry = f.geometry();
148 const QgsRectangle featureRect = featureGeometry.boundingBox().intersect( mRasterExtent );
149 if ( featureRect.isEmpty() )
150 {
151 current++;
152 continue;
153 }
154
155 int nCellsX, nCellsY;
156 QgsRectangle rasterBlockExtent;
157 QgsRasterAnalysisUtils::cellInfoForBBox( mRasterExtent, featureRect, mCellSizeX, mCellSizeY, nCellsX, nCellsY, mNbCellsXProvider, mNbCellsYProvider, rasterBlockExtent );
158
159 QHash<double, qgssize> fUniqueValues;
160 QgsRasterAnalysisUtils::statisticsFromMiddlePointTest( mRasterInterface.get(), mRasterBand, featureGeometry, nCellsX, nCellsY, mCellSizeX, mCellSizeY, rasterBlockExtent, [&fUniqueValues]( double value, const QgsPointXY & ) { fUniqueValues[value]++; }, false );
161
162 if ( fUniqueValues.count() < 1 )
163 {
164 // The cell resolution is probably larger than the polygon area. We switch to slower precise pixel - polygon intersection in this case
165 // TODO: eventually deal with weight if needed
166 QgsRasterAnalysisUtils::statisticsFromPreciseIntersection( mRasterInterface.get(), mRasterBand, featureGeometry, nCellsX, nCellsY, mCellSizeX, mCellSizeY, rasterBlockExtent, [&fUniqueValues]( double value, double, const QgsPointXY & ) { fUniqueValues[value]++; }, false );
167 }
168
169 for ( auto it = fUniqueValues.constBegin(); it != fUniqueValues.constEnd(); ++it )
170 {
171 if ( uniqueValues.indexOf( it.key() ) == -1 )
172 {
173 uniqueValues << it.key();
174 }
175 featuresUniqueValues[f.id()][it.key()] += it.value();
176 }
177
178 current++;
179 }
180
181 std::sort( uniqueValues.begin(), uniqueValues.end() );
182
183 const QString fieldPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
184 QgsFields newFields;
185 for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
186 {
187 newFields.append( QgsField( QStringLiteral( "%1%2" ).arg( fieldPrefix, mHasNoDataValue && *it == mNodataValue ? QStringLiteral( "NODATA" ) : QString::number( *it ) ), QMetaType::Type::LongLong, QString(), -1, 0 ) );
188 }
189 const QgsFields fields = QgsProcessingUtils::combineFields( zones->fields(), newFields );
190
191 QString dest;
192 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, zones->wkbType(), zones->sourceCrs() ) );
193 if ( !sink )
194 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
195
196 it = zones->getFeatures( QgsFeatureRequest() );
197 while ( it.nextFeature( f ) )
198 {
199 QgsAttributes attributes = f.attributes();
200 const QHash<double, qgssize> fUniqueValues = featuresUniqueValues.value( f.id() );
201 for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
202 {
203 attributes += fUniqueValues.value( *it, 0 );
204 }
205
206 QgsFeature outputFeature;
207 outputFeature.setGeometry( f.geometry() );
208 outputFeature.setAttributes( attributes );
209
210 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
211 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
212 }
213
214 sink->finalize();
215
216 QVariantMap outputs;
217 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
218 return outputs;
219}
220
@ VectorPolygon
Vector polygon layers.
DataType
Raster data types.
Definition qgis.h:351
@ Int16
Sixteen bit signed integer (qint16)
@ UInt16
Sixteen bit unsigned integer (quint16)
@ Byte
Eight bit unsigned integer (quint8)
@ Int32
Thirty two bit signed integer (qint32)
@ UInt32
Thirty two bit unsigned integer (quint32)
A vector of attributes.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
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
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:70
A geometry is the spatial representation of a feature.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:84
Represents a 2D point.
Definition qgspointxy.h:60
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 pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
A raster band parameter for Processing algorithms.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A raster layer parameter for processing algorithms.
A string parameter for processing algorithms.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
virtual bool sourceHasNoDataValue(int bandNo) const
Returns true if source band has no data value.
virtual double sourceNoDataValue(int bandNo) const
Value representing no data value.
Represents a raster 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.
A rectangle specified with double values.
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.