26using namespace Qt::StringLiterals;
30QString QgsRasterSurfaceVolumeAlgorithm::name()
const
32 return u
"rastersurfacevolume"_s;
35QString QgsRasterSurfaceVolumeAlgorithm::displayName()
const
37 return QObject::tr(
"Raster surface volume" );
40QStringList QgsRasterSurfaceVolumeAlgorithm::tags()
const
42 return QObject::tr(
"sum,volume,area,height,terrain,dem,elevation" ).split(
',' );
45QString QgsRasterSurfaceVolumeAlgorithm::group()
const
47 return QObject::tr(
"Raster analysis" );
50QString QgsRasterSurfaceVolumeAlgorithm::groupId()
const
52 return u
"rasteranalysis"_s;
55void QgsRasterSurfaceVolumeAlgorithm::initAlgorithm(
const QVariantMap & )
60 addParameter(
new QgsProcessingParameterEnum( u
"METHOD"_s, QObject::tr(
"Method" ), 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" ) ) );
70QString QgsRasterSurfaceVolumeAlgorithm::shortHelpString()
const
72 return QObject::tr(
"This algorithm calculates the volume under a raster grid's surface.\n\n"
73 "Several methods of volume calculation are available, which control whether "
74 "only values above or below the specified base level are considered, or "
75 "whether volumes below the base level should be added or subtracted from the total volume.\n\n"
76 "The algorithm outputs the calculated volume, the total area, and the total number of pixels analysed. "
77 "If the 'Count Only Above Base Level' or 'Count Only Below Base Level' methods are used, "
78 "then the calculated area and pixel count only includes pixels which are above or below the "
79 "specified base level respectively.\n\n"
80 "Units of the calculated volume are dependent on the coordinate reference system of "
81 "the input raster file. For a CRS in meters, with a DEM height in meters, the calculated "
82 "value will be in meters³. If instead the input raster is in a geographic coordinate system "
83 "(e.g. latitude/longitude values), then the result will be in degrees² × meters, and an "
84 "appropriate scaling factor will need to be applied in order to convert to meters³." );
87QString QgsRasterSurfaceVolumeAlgorithm::shortDescription()
const
89 return QObject::tr(
"Calculates the volume under a raster grid's surface." );
92QgsRasterSurfaceVolumeAlgorithm *QgsRasterSurfaceVolumeAlgorithm::createInstance()
const
94 return new QgsRasterSurfaceVolumeAlgorithm();
99 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u
"INPUT"_s, context );
100 const int band = parameterAsInt( parameters, u
"BAND"_s, context );
105 mBand = parameterAsInt( parameters, u
"BAND"_s, context );
106 if ( mBand < 1 || mBand > layer->
bandCount() )
107 throw QgsProcessingException( QObject::tr(
"Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" ).arg( mBand ).arg( layer->
bandCount() ) );
111 mLayerWidth = layer->
width();
112 mLayerHeight = layer->
height();
113 mExtent = layer->
extent();
117 mSource = layer->
source();
119 mLevel = parameterAsDouble( parameters, u
"LEVEL"_s, context );
120 mMethod =
static_cast<Method
>( parameterAsEnum( parameters, u
"METHOD"_s, context ) );
126 const QString outputFile = parameterAsFileOutput( parameters, u
"OUTPUT_HTML_FILE"_s, context );
130 std::unique_ptr<QgsFeatureSink> sink;
131 if ( parameters.contains( u
"OUTPUT_TABLE"_s ) && parameters.value( u
"OUTPUT_TABLE"_s ).isValid() )
134 outFields.
append(
QgsField( u
"volume"_s, QMetaType::Type::Double, QString(), 20, 8 ) );
135 outFields.
append(
QgsField( areaUnit.replace( u
"²"_s,
"2"_L1 ), QMetaType::Type::Double, QString(), 20, 8 ) );
136 outFields.
append(
QgsField( u
"pixel_count"_s, QMetaType::Type::LongLong ) );
146 iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
152 std::unique_ptr<QgsRasterBlock> rasterBlock;
153 while ( iter.readNextRasterPart( mBand, iterCols, iterRows, rasterBlock, iterLeft, iterTop ) )
155 feedback->
setProgress( 100 * iter.progress( mBand ) );
156 for (
int row = 0; row < iterRows; row++ )
160 for (
int column = 0; column < iterCols; column++ )
162 if ( mHasNoDataValue && rasterBlock->isNoData( row, column ) )
167 const double z = rasterBlock->value( row, column ) - mLevel;
171 case CountOnlyAboveBaseLevel:
179 case CountOnlyBelowBaseLevel:
187 case SubtractVolumesBelowBaseLevel:
192 case AddVolumesBelowBaseLevel:
193 volume += std::fabs( z );
202 const double pixelArea = mRasterUnitsPerPixelX * mRasterUnitsPerPixelY;
203 const double area = count * pixelArea;
205 if ( !outputFile.isEmpty() )
207 QFile file( outputFile );
208 if ( file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
212 QTextStream out( &file );
213 out << u
"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/></head><body>\n"_s;
214 out << u
"<p>%1: %2 (%3 %4)</p>\n"_s.arg( QObject::tr(
"Analyzed file" ), mSource, QObject::tr(
"band" ) ).arg( mBand );
215 out << QObject::tr(
"<p>%1: %2</p>\n" ).arg( QObject::tr(
"Volume" ), QString::number( volume,
'g', 16 ) );
216 out << QObject::tr(
"<p>%1: %2</p>\n" ).arg( QObject::tr(
"Pixel count" ) ).arg( count );
217 out << QObject::tr(
"<p>%1: %2 %3</p>\n" ).arg( QObject::tr(
"Area" ), QString::number( area,
'g', 16 ), encodedAreaUnit );
218 out << u
"</body></html>"_s;
219 outputs.insert( u
"OUTPUT_HTML_FILE"_s, outputFile );
230 outputs.insert( u
"OUTPUT_TABLE"_s, tableDest );
232 outputs.insert( u
"VOLUME"_s, volume );
233 outputs.insert( u
"AREA"_s, area );
234 outputs.insert( u
"PIXEL_COUNT"_s, count );
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ Double
Double/float values.
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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
virtual QgsRectangle extent() const
Returns the extent of the layer.
QString source() const
Returns the source for the layer.
QgsCoordinateReferenceSystem crs
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.