QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
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
19
20#include "qgslogger.h"
22
24
25QString QgsZonalHistogramAlgorithm::name() const
26{
27 return QStringLiteral( "zonalhistogram" );
28}
29
30QString QgsZonalHistogramAlgorithm::displayName() const
31{
32 return QObject::tr( "Zonal histogram" );
33}
34
35QStringList QgsZonalHistogramAlgorithm::tags() const
36{
37 return QObject::tr( "raster,unique,values,count,area,statistics" ).split( ',' );
38}
39
40QString QgsZonalHistogramAlgorithm::group() const
41{
42 return QObject::tr( "Raster analysis" );
43}
44
45QString QgsZonalHistogramAlgorithm::groupId() const
46{
47 return QStringLiteral( "rasteranalysis" );
48}
49
50void QgsZonalHistogramAlgorithm::initAlgorithm( const QVariantMap & )
51{
52 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT_RASTER" ), QObject::tr( "Raster layer" ) ) );
53 addParameter( new QgsProcessingParameterBand( QStringLiteral( "RASTER_BAND" ), QObject::tr( "Band number" ), 1, QStringLiteral( "INPUT_RASTER" ) ) );
54
55 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT_VECTOR" ), QObject::tr( "Vector layer containing zones" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
56
57 addParameter( new QgsProcessingParameterString( QStringLiteral( "COLUMN_PREFIX" ), QObject::tr( "Output column prefix" ), QStringLiteral( "HISTO_" ), false, true ) );
58
59 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Output zones" ), Qgis::ProcessingSourceType::VectorPolygon ) );
60}
61
62QString QgsZonalHistogramAlgorithm::shortHelpString() const
63{
64 return QObject::tr( "This algorithm appends fields representing counts of each unique value from a raster layer contained within zones defined as polygons." );
65}
66
67QString QgsZonalHistogramAlgorithm::shortDescription() const
68{
69 return QObject::tr( "Appends fields representing counts of each unique value from a raster layer contained within zones defined as polygons." );
70}
71
72QgsZonalHistogramAlgorithm *QgsZonalHistogramAlgorithm::createInstance() const
73{
74 return new QgsZonalHistogramAlgorithm();
75}
76
77bool QgsZonalHistogramAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
78{
79 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT_RASTER" ), context );
80 if ( !layer )
81 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT_RASTER" ) ) );
82
83 mRasterBand = parameterAsInt( parameters, QStringLiteral( "RASTER_BAND" ), context );
84 mHasNoDataValue = layer->dataProvider()->sourceHasNoDataValue( mRasterBand );
85 mNodataValue = layer->dataProvider()->sourceNoDataValue( mRasterBand );
86 mRasterInterface.reset( layer->dataProvider()->clone() );
87 mRasterExtent = layer->extent();
88 mCrs = layer->crs();
89 mCellSizeX = std::abs( layer->rasterUnitsPerPixelX() );
90 mCellSizeY = std::abs( layer->rasterUnitsPerPixelX() );
91 mNbCellsXProvider = mRasterInterface->xSize();
92 mNbCellsYProvider = mRasterInterface->ySize();
93 Qgis::DataType dataType = mRasterInterface->dataType( mRasterBand );
94
95 switch ( dataType )
96 {
102 break;
103 default:
104 feedback->pushWarning( QObject::tr( "The input raster is a floating-point raster. Such rasters are not suitable for use with zonal histogram algorithm.\n"
105 "Please use Round raster or Reclassify by table tools to reduce number of decimal places or define histogram bins." ) );
106 break;
107 }
108
109 return true;
110}
111
112QVariantMap QgsZonalHistogramAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
113{
114 std::unique_ptr<QgsFeatureSource> zones( parameterAsSource( parameters, QStringLiteral( "INPUT_VECTOR" ), context ) );
115 if ( !zones )
116 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT_VECTOR" ) ) );
117
118 const long count = zones->featureCount();
119 const double step = count > 0 ? 100.0 / count : 1;
120 long current = 0;
121
122 QList<double> uniqueValues;
123 QMap<QgsFeatureId, QHash<double, qgssize>> featuresUniqueValues;
124
125 // First loop through the zones to build up a list of unique values across all zones to determine sink fields list
126 QgsFeatureRequest request;
127 request.setNoAttributes();
128 if ( zones->sourceCrs() != mCrs )
129 {
130 request.setDestinationCrs( mCrs, context.transformContext() );
131 }
132 QgsFeatureIterator it = zones->getFeatures( request );
133 QgsFeature f;
134 while ( it.nextFeature( f ) )
135 {
136 if ( feedback->isCanceled() )
137 {
138 break;
139 }
140 feedback->setProgress( current * step );
141
142 if ( !f.hasGeometry() )
143 {
144 current++;
145 continue;
146 }
147
148 const QgsGeometry featureGeometry = f.geometry();
149 const QgsRectangle featureRect = featureGeometry.boundingBox().intersect( mRasterExtent );
150 if ( featureRect.isEmpty() )
151 {
152 current++;
153 continue;
154 }
155
156 int nCellsX, nCellsY;
157 QgsRectangle rasterBlockExtent;
158 QgsRasterAnalysisUtils::cellInfoForBBox( mRasterExtent, featureRect, mCellSizeX, mCellSizeY, nCellsX, nCellsY, mNbCellsXProvider, mNbCellsYProvider, rasterBlockExtent );
159
160 QHash<double, qgssize> fUniqueValues;
161 QgsRasterAnalysisUtils::statisticsFromMiddlePointTest( mRasterInterface.get(), mRasterBand, featureGeometry, nCellsX, nCellsY, mCellSizeX, mCellSizeY, rasterBlockExtent, [&fUniqueValues]( double value, const QgsPointXY & ) { fUniqueValues[value]++; }, false );
162
163 if ( fUniqueValues.count() < 1 )
164 {
165 // The cell resolution is probably larger than the polygon area. We switch to slower precise pixel - polygon intersection in this case
166 // TODO: eventually deal with weight if needed
167 QgsRasterAnalysisUtils::statisticsFromPreciseIntersection( mRasterInterface.get(), mRasterBand, featureGeometry, nCellsX, nCellsY, mCellSizeX, mCellSizeY, rasterBlockExtent, [&fUniqueValues]( double value, double, const QgsPointXY & ) { fUniqueValues[value]++; }, false );
168 }
169
170 for ( auto it = fUniqueValues.constBegin(); it != fUniqueValues.constEnd(); ++it )
171 {
172 if ( uniqueValues.indexOf( it.key() ) == -1 )
173 {
174 uniqueValues << it.key();
175 }
176 featuresUniqueValues[f.id()][it.key()] += it.value();
177 }
178
179 current++;
180 }
181
182 std::sort( uniqueValues.begin(), uniqueValues.end() );
183
184 const QString fieldPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
185 QgsFields newFields;
186 for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
187 {
188 newFields.append( QgsField( QStringLiteral( "%1%2" ).arg( fieldPrefix, mHasNoDataValue && *it == mNodataValue ? QStringLiteral( "NODATA" ) : QString::number( *it ) ), QMetaType::Type::LongLong, QString(), -1, 0 ) );
189 }
190 const QgsFields fields = QgsProcessingUtils::combineFields( zones->fields(), newFields );
191
192 QString dest;
193 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, zones->wkbType(), zones->sourceCrs() ) );
194 if ( !sink )
195 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
196
197 it = zones->getFeatures( QgsFeatureRequest() );
198 while ( it.nextFeature( f ) )
199 {
200 QgsAttributes attributes = f.attributes();
201 const QHash<double, qgssize> fUniqueValues = featuresUniqueValues.value( f.id() );
202 for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
203 {
204 attributes += fUniqueValues.value( *it, 0 );
205 }
206
207 QgsFeature outputFeature;
208 outputFeature.setGeometry( f.geometry() );
209 outputFeature.setAttributes( attributes );
210
211 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
212 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
213 }
214
215 sink->finalize();
216
217 QVariantMap outputs;
218 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
219 return outputs;
220}
221
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
DataType
Raster data types.
Definition qgis.h:372
@ Int16
Sixteen bit signed integer (qint16).
Definition qgis.h:377
@ UInt16
Sixteen bit unsigned integer (quint16).
Definition qgis.h:376
@ Byte
Eight bit unsigned integer (quint8).
Definition qgis.h:374
@ Int32
Thirty two bit signed integer (qint32).
Definition qgis.h:379
@ UInt32
Thirty two bit unsigned integer (quint32).
Definition qgis.h:378
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:54
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:73
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:87
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.