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