QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsalgorithmrasterlayeruniquevalues.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrasterlayeruniquevalues.cpp
3 ---------------------
4 begin : April 2017
5 copyright : (C) 2017 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 "qgsstringutils.h"
21#include "qgsunittypes.h"
22
23#include <QString>
24#include <QTextStream>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsRasterLayerUniqueValuesReportAlgorithm::name() const
31{
32 return u"rasterlayeruniquevaluesreport"_s;
33}
34
35QString QgsRasterLayerUniqueValuesReportAlgorithm::displayName() const
36{
37 return QObject::tr( "Raster layer unique values report" );
38}
39
40QStringList QgsRasterLayerUniqueValuesReportAlgorithm::tags() const
41{
42 return QObject::tr( "count,area,statistics" ).split( ',' );
43}
44
45QString QgsRasterLayerUniqueValuesReportAlgorithm::group() const
46{
47 return QObject::tr( "Raster analysis" );
48}
49
50QString QgsRasterLayerUniqueValuesReportAlgorithm::groupId() const
51{
52 return u"rasteranalysis"_s;
53}
54
55void QgsRasterLayerUniqueValuesReportAlgorithm::initAlgorithm( const QVariantMap & )
56{
57 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT"_s, QObject::tr( "Input layer" ) ) );
58 addParameter( new QgsProcessingParameterBand( u"BAND"_s, QObject::tr( "Band number" ), 1, u"INPUT"_s ) );
59 addParameter( new QgsProcessingParameterFileDestination( u"OUTPUT_HTML_FILE"_s, QObject::tr( "Unique values report" ), QObject::tr( "HTML files (*.html)" ), QVariant(), true ) );
60 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT_TABLE"_s, QObject::tr( "Unique values table" ), Qgis::ProcessingSourceType::Vector, QVariant(), true, false ) );
61
62 addOutput( new QgsProcessingOutputString( u"EXTENT"_s, QObject::tr( "Extent" ) ) );
63 addOutput( new QgsProcessingOutputString( u"CRS_AUTHID"_s, QObject::tr( "CRS authority identifier" ) ) );
64 addOutput( new QgsProcessingOutputNumber( u"WIDTH_IN_PIXELS"_s, QObject::tr( "Width in pixels" ) ) );
65 addOutput( new QgsProcessingOutputNumber( u"HEIGHT_IN_PIXELS"_s, QObject::tr( "Height in pixels" ) ) );
66 addOutput( new QgsProcessingOutputNumber( u"TOTAL_PIXEL_COUNT"_s, QObject::tr( "Total pixel count" ) ) );
67 addOutput( new QgsProcessingOutputNumber( u"NODATA_PIXEL_COUNT"_s, QObject::tr( "NoData pixel count" ) ) );
68}
69
70QString QgsRasterLayerUniqueValuesReportAlgorithm::shortHelpString() const
71{
72 return QObject::tr(
73 "This algorithm returns the count and area of each unique value in a given raster layer. "
74 "The area calculation is done in the area unit of the layer's CRS."
75 );
76}
77
78QString QgsRasterLayerUniqueValuesReportAlgorithm::shortDescription() const
79{
80 return QObject::tr( "Returns the count and area of each unique value in a given raster layer." );
81}
82
83QgsRasterLayerUniqueValuesReportAlgorithm *QgsRasterLayerUniqueValuesReportAlgorithm::createInstance() const
84{
85 return new QgsRasterLayerUniqueValuesReportAlgorithm();
86}
87
88bool QgsRasterLayerUniqueValuesReportAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
89{
90 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u"INPUT"_s, context );
91 const int band = parameterAsInt( parameters, u"BAND"_s, context );
92
93 if ( !layer )
94 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT"_s ) );
95
96 mBand = parameterAsInt( parameters, u"BAND"_s, context );
97 if ( mBand < 1 || mBand > layer->bandCount() )
98 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( layer->bandCount() ) );
99
100 mInterface.reset( layer->dataProvider()->clone() );
101 mHasNoDataValue = layer->dataProvider()->sourceHasNoDataValue( band );
102 mLayerWidth = layer->width();
103 mLayerHeight = layer->height();
104 mExtent = layer->extent();
105 mCrs = layer->crs();
106 mRasterUnitsPerPixelX = layer->rasterUnitsPerPixelX();
107 mRasterUnitsPerPixelY = layer->rasterUnitsPerPixelY();
108 mSource = layer->source();
109
110 return true;
111}
112
113QVariantMap QgsRasterLayerUniqueValuesReportAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
114{
115 const QString outputFile = parameterAsFileOutput( parameters, u"OUTPUT_HTML_FILE"_s, context );
116
117 QString areaUnit = QgsUnitTypes::toAbbreviatedString( QgsUnitTypes::distanceToAreaUnit( mCrs.mapUnits() ) );
118
119 QString tableDest;
120 std::unique_ptr<QgsFeatureSink> sink;
121 if ( parameters.contains( u"OUTPUT_TABLE"_s ) && parameters.value( u"OUTPUT_TABLE"_s ).isValid() )
122 {
123 QgsFields outFields;
124 outFields.append( QgsField( u"value"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
125 outFields.append( QgsField( u"count"_s, QMetaType::Type::LongLong, QString(), 20 ) );
126 outFields.append( QgsField( areaUnit.replace( u"²"_s, "2"_L1 ), QMetaType::Type::Double, QString(), 20, 8 ) );
127 sink.reset( parameterAsSink( parameters, u"OUTPUT_TABLE"_s, context, tableDest, outFields, Qgis::WkbType::NoGeometry, QgsCoordinateReferenceSystem() ) );
128 if ( !sink )
129 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_TABLE"_s ) );
130 }
131
132 QHash<double, qgssize> uniqueValues;
133 qgssize noDataCount = 0;
134
135 const qgssize layerSize = static_cast<qgssize>( mLayerWidth ) * static_cast<qgssize>( mLayerHeight );
136
137 QgsRasterIterator iter( mInterface.get() );
138 iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
139
140 int iterLeft = 0;
141 int iterTop = 0;
142 int iterCols = 0;
143 int iterRows = 0;
144 bool isNoData = false;
145 std::unique_ptr<QgsRasterBlock> rasterBlock;
146 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, rasterBlock, iterLeft, iterTop ) )
147 {
148 feedback->setProgress( 100 * iter.progress( mBand ) );
149 for ( int row = 0; row < iterRows; row++ )
150 {
151 if ( feedback->isCanceled() )
152 break;
153 for ( int column = 0; column < iterCols; column++ )
154 {
155 const double value = rasterBlock->valueAndNoData( row, column, isNoData );
156 if ( mHasNoDataValue && isNoData )
157 {
158 noDataCount++;
159 }
160 else
161 {
162 uniqueValues[value]++;
163 }
164 }
165 }
166 if ( feedback->isCanceled() )
167 break;
168 }
169
170 QMap<double, qgssize> sortedUniqueValues;
171 for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
172 {
173 sortedUniqueValues.insert( it.key(), it.value() );
174 }
175
176 QVariantMap outputs;
177 outputs.insert( u"EXTENT"_s, mExtent.toString() );
178 outputs.insert( u"CRS_AUTHID"_s, mCrs.authid() );
179 outputs.insert( u"WIDTH_IN_PIXELS"_s, mLayerWidth );
180 outputs.insert( u"HEIGHT_IN_PIXELS"_s, mLayerHeight );
181 outputs.insert( u"TOTAL_PIXEL_COUNT"_s, layerSize );
182 outputs.insert( u"NODATA_PIXEL_COUNT"_s, noDataCount );
183
184 const double pixelArea = mRasterUnitsPerPixelX * mRasterUnitsPerPixelY;
185
186 if ( !outputFile.isEmpty() )
187 {
188 QFile file( outputFile );
189 if ( file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
190 {
191 const QString encodedAreaUnit = QgsStringUtils::ampersandEncode( areaUnit );
192
193 QTextStream out( &file );
194 out << u"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/></head><body>\n"_s;
195 out << u"<p>%1: %2 (%3 %4)</p>\n"_s.arg( QObject::tr( "Analyzed file" ), mSource, QObject::tr( "band" ) ).arg( mBand );
196 out << QObject::tr( "<p>%1: %2</p>\n" ).arg( QObject::tr( "Extent" ), mExtent.toString() );
197 out << QObject::tr( "<p>%1: %2</p>\n" ).arg( QObject::tr( "Projection" ), mCrs.userFriendlyIdentifier() );
198 out << QObject::tr( "<p>%1: %2 (%3 %4)</p>\n" ).arg( QObject::tr( "Width in pixels" ) ).arg( mLayerWidth ).arg( QObject::tr( "units per pixel" ) ).arg( mRasterUnitsPerPixelX );
199 out << QObject::tr( "<p>%1: %2 (%3 %4)</p>\n" ).arg( QObject::tr( "Height in pixels" ) ).arg( mLayerHeight ).arg( QObject::tr( "units per pixel" ) ).arg( mRasterUnitsPerPixelY );
200 out << QObject::tr( "<p>%1: %2</p>\n" ).arg( QObject::tr( "Total pixel count" ) ).arg( layerSize );
201 if ( mHasNoDataValue )
202 out << QObject::tr( "<p>%1: %2</p>\n" ).arg( QObject::tr( "NoData pixel count" ) ).arg( noDataCount );
203 out << u"<table><tr><td>%1</td><td>%2</td><td>%3 (%4)</td></tr>\n"_s.arg( QObject::tr( "Value" ), QObject::tr( "Pixel count" ), QObject::tr( "Area" ), encodedAreaUnit );
204
205 for ( auto it = sortedUniqueValues.constBegin(); it != sortedUniqueValues.constEnd(); ++it )
206 {
207 const double area = it.value() * pixelArea;
208 out << u"<tr><td>%1</td><td>%2</td><td>%3</td></tr>\n"_s.arg( it.key() ).arg( it.value() ).arg( QString::number( area, 'g', 16 ) );
209 }
210 out << u"</table>\n</body></html>"_s;
211 outputs.insert( u"OUTPUT_HTML_FILE"_s, outputFile );
212 }
213 }
214
215 if ( sink )
216 {
217 for ( auto it = sortedUniqueValues.constBegin(); it != sortedUniqueValues.constEnd(); ++it )
218 {
219 QgsFeature f;
220 const double area = it.value() * pixelArea;
221 f.setAttributes( QgsAttributes() << it.key() << it.value() << area );
222 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
223 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT_TABLE"_s ) );
224 }
225 sink->finalize();
226 outputs.insert( u"OUTPUT_TABLE"_s, tableDest );
227 }
228
229 return outputs;
230}
231
232
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3653
@ NoGeometry
No geometry.
Definition qgis.h:312
A vector of attributes.
Represents a coordinate reference system (CRS).
@ 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
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
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:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
virtual QgsRectangle extent() const
Returns the extent of the layer.
QString source() const
Returns the source for the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
A numeric output for processing algorithms.
A string output for processing algorithms.
A raster band parameter for Processing algorithms.
A feature sink output for processing algorithms.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
A raster layer parameter for processing algorithms.
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.
Iterator for sequentially processing raster cells.
Represents a raster layer.
int height() const
Returns the height of the (unclipped) raster.
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.
int width() const
Returns the width of the (unclipped) raster.
static QString ampersandEncode(const QString &string)
Makes a raw string safe for inclusion as a HTML/XML string literal.
static Q_INVOKABLE QString toAbbreviatedString(Qgis::DistanceUnit unit)
Returns a translated abbreviation representing a distance unit.
static Q_INVOKABLE Qgis::AreaUnit distanceToAreaUnit(Qgis::DistanceUnit distanceUnit)
Converts a distance unit to its corresponding area unit, e.g., meters to square meters.
unsigned long long qgssize
Qgssize is used instead of size_t, because size_t is stdlib type, unknown by SIP, and it would be har...
Definition qgis.h:7485