QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
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 const QString outputFile = parameterAsFileOutput( parameters, u"OUTPUT_HTML_FILE"_s, context );
133 QString areaUnit = QgsUnitTypes::toAbbreviatedString( QgsUnitTypes::distanceToAreaUnit( mCrs.mapUnits() ) );
134
135 QString tableDest;
136 std::unique_ptr<QgsFeatureSink> sink;
137 if ( parameters.contains( u"OUTPUT_TABLE"_s ) && parameters.value( u"OUTPUT_TABLE"_s ).isValid() )
138 {
139 QgsFields outFields;
140 outFields.append( QgsField( u"volume"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
141 outFields.append( QgsField( areaUnit.replace( u"²"_s, "2"_L1 ), QMetaType::Type::Double, QString(), 20, 8 ) );
142 outFields.append( QgsField( u"pixel_count"_s, QMetaType::Type::LongLong ) );
143 sink.reset( parameterAsSink( parameters, u"OUTPUT_TABLE"_s, context, tableDest, outFields, Qgis::WkbType::NoGeometry, QgsCoordinateReferenceSystem() ) );
144 if ( !sink )
145 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_TABLE"_s ) );
146 }
147
148 double volume = 0;
149 long long count = 0;
150
151 QgsRasterIterator iter( mInterface.get() );
152 iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
153
154 int iterLeft = 0;
155 int iterTop = 0;
156 int iterCols = 0;
157 int iterRows = 0;
158 std::unique_ptr<QgsRasterBlock> rasterBlock;
159 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, rasterBlock, iterLeft, iterTop ) )
160 {
161 feedback->setProgress( 100 * iter.progress( mBand ) );
162 for ( int row = 0; row < iterRows; row++ )
163 {
164 if ( feedback->isCanceled() )
165 break;
166 for ( int column = 0; column < iterCols; column++ )
167 {
168 if ( mHasNoDataValue && rasterBlock->isNoData( row, column ) )
169 {
170 continue;
171 }
172
173 const double z = rasterBlock->value( row, column ) - mLevel;
174
175 switch ( mMethod )
176 {
177 case CountOnlyAboveBaseLevel:
178 if ( z > 0.0 )
179 {
180 volume += z;
181 count++;
182 }
183 continue;
184
185 case CountOnlyBelowBaseLevel:
186 if ( z < 0.0 )
187 {
188 volume += z;
189 count++;
190 }
191 continue;
192
193 case SubtractVolumesBelowBaseLevel:
194 volume += z;
195 count++;
196 continue;
197
198 case AddVolumesBelowBaseLevel:
199 volume += std::fabs( z );
200 count++;
201 continue;
202 }
203 }
204 }
205 }
206
207 QVariantMap outputs;
208 const double pixelArea = mRasterUnitsPerPixelX * mRasterUnitsPerPixelY;
209 const double area = count * pixelArea;
210 volume *= pixelArea;
211 if ( !outputFile.isEmpty() )
212 {
213 QFile file( outputFile );
214 if ( file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
215 {
216 const QString encodedAreaUnit = QgsStringUtils::ampersandEncode( areaUnit );
217
218 QTextStream out( &file );
219 out << u"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/></head><body>\n"_s;
220 out << u"<p>%1: %2 (%3 %4)</p>\n"_s.arg( QObject::tr( "Analyzed file" ), mSource, QObject::tr( "band" ) ).arg( mBand );
221 out << QObject::tr( "<p>%1: %2</p>\n" ).arg( QObject::tr( "Volume" ), QString::number( volume, 'g', 16 ) );
222 out << QObject::tr( "<p>%1: %2</p>\n" ).arg( QObject::tr( "Pixel count" ) ).arg( count );
223 out << QObject::tr( "<p>%1: %2 %3</p>\n" ).arg( QObject::tr( "Area" ), QString::number( area, 'g', 16 ), encodedAreaUnit );
224 out << u"</body></html>"_s;
225 outputs.insert( u"OUTPUT_HTML_FILE"_s, outputFile );
226 }
227 }
228
229 if ( sink )
230 {
231 QgsFeature f;
232 f.setAttributes( QgsAttributes() << volume << area << count );
233 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
234 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT_TABLE"_s ) );
235 sink->finalize();
236 outputs.insert( u"OUTPUT_TABLE"_s, tableDest );
237 }
238 outputs.insert( u"VOLUME"_s, volume );
239 outputs.insert( u"AREA"_s, area );
240 outputs.insert( u"PIXEL_COUNT"_s, count );
241 return outputs;
242}
243
244
@ 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
@ Double
Double/float values.
Definition qgis.h:3921
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 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.