QGIS API Documentation 4.3.0-Master (45633be667c)
Loading...
Searching...
No Matches
qgsalgorithmrastersurfacevolume.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrasterlayeruniquevalues.cpp
3 ---------------------
4 begin : January 2019
5 copyright : (C) 2019 by Nyall Dawson
6 email : nyall dot dawson 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 QgsRasterSurfaceVolumeAlgorithm::name() const
31{
32 return u"rastersurfacevolume"_s;
33}
34
35QString QgsRasterSurfaceVolumeAlgorithm::displayName() const
36{
37 return QObject::tr( "Raster surface volume" );
38}
39
40QStringList QgsRasterSurfaceVolumeAlgorithm::tags() const
41{
42 return QObject::tr( "sum,volume,area,height,terrain,dem,elevation" ).split( ',' );
43}
44
45QString QgsRasterSurfaceVolumeAlgorithm::group() const
46{
47 return QObject::tr( "Raster analysis" );
48}
49
50QString QgsRasterSurfaceVolumeAlgorithm::groupId() const
51{
52 return u"rasteranalysis"_s;
53}
54
55void QgsRasterSurfaceVolumeAlgorithm::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 QgsProcessingParameterNumber( u"LEVEL"_s, QObject::tr( "Base level" ), Qgis::ProcessingNumberParameterType::Double, 0 ) );
60 addParameter( new QgsProcessingParameterEnum(
61 u"METHOD"_s,
62 QObject::tr( "Method" ),
63 QStringList() << QObject::tr( "Count Only Above Base Level" ) << QObject::tr( "Count Only Below Base Level" ) << QObject::tr( "Subtract Volumes Below Base Level" ) << QObject::tr( "Add Volumes Below Base Level" )
64 ) );
65
66 addParameter( new QgsProcessingParameterFileDestination( u"OUTPUT_HTML_FILE"_s, QObject::tr( "Surface volume report" ), QObject::tr( "HTML files (*.html)" ), QVariant(), true ) );
67 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT_TABLE"_s, QObject::tr( "Surface volume table" ), Qgis::ProcessingSourceType::Vector, QVariant(), true, false ) );
68
69 addOutput( new QgsProcessingOutputNumber( u"VOLUME"_s, QObject::tr( "Volume" ) ) );
70 addOutput( new QgsProcessingOutputNumber( u"PIXEL_COUNT"_s, QObject::tr( "Pixel count" ) ) );
71 addOutput( new QgsProcessingOutputNumber( u"AREA"_s, QObject::tr( "Area" ) ) );
72}
73
74QString QgsRasterSurfaceVolumeAlgorithm::shortHelpString() const
75{
76 return QObject::tr(
77 "This algorithm calculates the volume under a raster grid's surface.\n\n"
78 "Several methods of volume calculation are available, which control whether "
79 "only values above or below the specified base level are considered, or "
80 "whether volumes below the base level should be added or subtracted from the total volume.\n\n"
81 "The algorithm outputs the calculated volume, the total area, and the total number of pixels analysed. "
82 "If the 'Count Only Above Base Level' or 'Count Only Below Base Level' methods are used, "
83 "then the calculated area and pixel count only includes pixels which are above or below the "
84 "specified base level respectively.\n\n"
85 "Units of the calculated volume are dependent on the coordinate reference system of "
86 "the input raster file. For a CRS in meters, with a DEM height in meters, the calculated "
87 "value will be in meters³. If instead the input raster is in a geographic coordinate system "
88 "(e.g. latitude/longitude values), then the result will be in degrees² × meters, and an "
89 "appropriate scaling factor will need to be applied in order to convert to meters³."
90 );
91}
92
93QString QgsRasterSurfaceVolumeAlgorithm::shortDescription() const
94{
95 return QObject::tr( "Calculates the volume under a raster grid's surface." );
96}
97
98QgsRasterSurfaceVolumeAlgorithm *QgsRasterSurfaceVolumeAlgorithm::createInstance() const
99{
100 return new QgsRasterSurfaceVolumeAlgorithm();
101}
102
103bool QgsRasterSurfaceVolumeAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
104{
105 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u"INPUT"_s, context );
106 const int band = parameterAsInt( parameters, u"BAND"_s, context );
107
108 if ( !layer )
109 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT"_s ) );
110
111 mBand = parameterAsInt( parameters, u"BAND"_s, context );
112 if ( mBand < 1 || mBand > layer->bandCount() )
113 throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( layer->bandCount() ) );
114
115 mInterface.reset( layer->dataProvider()->clone() );
116 mHasNoDataValue = layer->dataProvider()->sourceHasNoDataValue( band );
117 mLayerWidth = layer->width();
118 mLayerHeight = layer->height();
119 mExtent = layer->extent();
120 mCrs = layer->crs();
121 mRasterUnitsPerPixelX = layer->rasterUnitsPerPixelX();
122 mRasterUnitsPerPixelY = layer->rasterUnitsPerPixelY();
123 mSource = layer->source();
124
125 mLevel = parameterAsDouble( parameters, u"LEVEL"_s, context );
126 mMethod = static_cast<Method>( parameterAsEnum( parameters, u"METHOD"_s, context ) );
127 return true;
128}
129
130QVariantMap QgsRasterSurfaceVolumeAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
131{
132 QGS_MARK_ALGORITHM_SOURCE
133
134 const QString outputFile = parameterAsFileOutput( parameters, u"OUTPUT_HTML_FILE"_s, context );
135 QString areaUnit = QgsUnitTypes::toAbbreviatedString( QgsUnitTypes::distanceToAreaUnit( mCrs.mapUnits() ) );
136
137 QString tableDest;
138 std::unique_ptr<QgsFeatureSink> sink;
139 if ( parameters.contains( u"OUTPUT_TABLE"_s ) && parameters.value( u"OUTPUT_TABLE"_s ).isValid() )
140 {
141 QgsFields outFields;
142 outFields.append( QgsField( u"volume"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
143 outFields.append( QgsField( areaUnit.replace( u"²"_s, "2"_L1 ), QMetaType::Type::Double, QString(), 20, 8 ) );
144 outFields.append( QgsField( u"pixel_count"_s, QMetaType::Type::LongLong ) );
145 sink.reset( parameterAsSink( parameters, u"OUTPUT_TABLE"_s, context, tableDest, outFields, Qgis::WkbType::NoGeometry, QgsCoordinateReferenceSystem() ) );
146 if ( !sink )
147 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_TABLE"_s ) );
148 }
149
150 double volume = 0;
151 long long count = 0;
152
153 QgsRasterIterator iter( mInterface.get() );
154 iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
155
156 int iterLeft = 0;
157 int iterTop = 0;
158 int iterCols = 0;
159 int iterRows = 0;
160 std::unique_ptr<QgsRasterBlock> rasterBlock;
161 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, rasterBlock, iterLeft, iterTop ) )
162 {
163 feedback->setProgress( 100 * iter.progress( mBand ) );
164 for ( int row = 0; row < iterRows; row++ )
165 {
166 if ( feedback->isCanceled() )
167 break;
168 for ( int column = 0; column < iterCols; column++ )
169 {
170 if ( mHasNoDataValue && rasterBlock->isNoData( row, column ) )
171 {
172 continue;
173 }
174
175 const double z = rasterBlock->value( row, column ) - mLevel;
176
177 switch ( mMethod )
178 {
179 case CountOnlyAboveBaseLevel:
180 if ( z > 0.0 )
181 {
182 volume += z;
183 count++;
184 }
185 continue;
186
187 case CountOnlyBelowBaseLevel:
188 if ( z < 0.0 )
189 {
190 volume += z;
191 count++;
192 }
193 continue;
194
195 case SubtractVolumesBelowBaseLevel:
196 volume += z;
197 count++;
198 continue;
199
200 case AddVolumesBelowBaseLevel:
201 volume += std::fabs( z );
202 count++;
203 continue;
204 }
205 }
206 }
207 }
208
209 QVariantMap outputs;
210 const double pixelArea = mRasterUnitsPerPixelX * mRasterUnitsPerPixelY;
211 const double area = count * pixelArea;
212 volume *= pixelArea;
213 if ( !outputFile.isEmpty() )
214 {
215 QFile file( outputFile );
216 if ( file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
217 {
218 const QString encodedAreaUnit = QgsStringUtils::ampersandEncode( areaUnit );
219
220 QTextStream out( &file );
221 out << u"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/></head><body>\n"_s;
222 out << u"<p>%1: %2 (%3 %4)</p>\n"_s.arg( QObject::tr( "Analyzed file" ), mSource, QObject::tr( "band" ) ).arg( mBand );
223 out << QObject::tr( "<p>%1: %2</p>\n" ).arg( QObject::tr( "Volume" ), QString::number( volume, 'g', 16 ) );
224 out << QObject::tr( "<p>%1: %2</p>\n" ).arg( QObject::tr( "Pixel count" ) ).arg( count );
225 out << QObject::tr( "<p>%1: %2 %3</p>\n" ).arg( QObject::tr( "Area" ), QString::number( area, 'g', 16 ), encodedAreaUnit );
226 out << u"</body></html>"_s;
227 outputs.insert( u"OUTPUT_HTML_FILE"_s, outputFile );
228 }
229 }
230
231 if ( sink )
232 {
233 QgsFeature f;
234 f.setAttributes( QgsAttributes() << volume << area << count );
235 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
236 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT_TABLE"_s ) );
237 else
238 feedback->featureAddedToSink( u"OUTPUT_TABLE"_s );
239 sink->finalize();
240 feedback->featureSinkFinalized( u"OUTPUT_TABLE"_s );
241 outputs.insert( u"OUTPUT_TABLE"_s, tableDest );
242 }
243 outputs.insert( u"VOLUME"_s, volume );
244 outputs.insert( u"AREA"_s, area );
245 outputs.insert( u"PIXEL_COUNT"_s, count );
246 return outputs;
247}
248
249
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3757
@ NoGeometry
No geometry.
Definition qgis.h:312
@ Double
Double/float values.
Definition qgis.h:4047
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:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
virtual Q_INVOKABLE 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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
A numeric output for processing algorithms.
A raster band parameter for Processing algorithms.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
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 numeric parameter for processing algorithms.
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.