QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmconstantraster.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmconstantraster.cpp
3 ---------------------
4 begin : November 2019
5 copyright : (C) 2019 by Alexander Bruy
6 email : alexander dot bruy 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
18#include <limits>
19#include "math.h"
21#include "qgsrasterfilewriter.h"
22
24
25QString QgsConstantRasterAlgorithm::name() const
26{
27 return QStringLiteral( "createconstantrasterlayer" );
28}
29
30QString QgsConstantRasterAlgorithm::displayName() const
31{
32 return QObject::tr( "Create constant raster layer" );
33}
34
35QStringList QgsConstantRasterAlgorithm::tags() const
36{
37 return QObject::tr( "raster,create,constant" ).split( ',' );
38}
39
40QString QgsConstantRasterAlgorithm::group() const
41{
42 return QObject::tr( "Raster creation" );
43}
44
45QString QgsConstantRasterAlgorithm::groupId() const
46{
47 return QStringLiteral( "rastercreation" );
48}
49
50QString QgsConstantRasterAlgorithm::shortHelpString() const
51{
52 return QObject::tr( "This algorithm generates a raster layer for a given extent and cell "
53 "size filled with a single constant value.\n"
54 "Additionally an output data type can be specified. "
55 "The algorithm will abort if a value has been entered that "
56 "cannot be represented by the selected output raster data type." );
57}
58
59QString QgsConstantRasterAlgorithm::shortDescription() const
60{
61 return QObject::tr( "Generates a raster layer for a given extent and cell size filled with a single constant value." );
62}
63
64QgsConstantRasterAlgorithm *QgsConstantRasterAlgorithm::createInstance() const
65{
66 return new QgsConstantRasterAlgorithm();
67}
68
69void QgsConstantRasterAlgorithm::initAlgorithm( const QVariantMap & )
70{
71 addParameter( new QgsProcessingParameterExtent( QStringLiteral( "EXTENT" ), QObject::tr( "Desired extent" ) ) );
72 addParameter( new QgsProcessingParameterCrs( QStringLiteral( "TARGET_CRS" ), QObject::tr( "Target CRS" ), QStringLiteral( "ProjectCrs" ) ) );
73 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "PIXEL_SIZE" ), QObject::tr( "Pixel size" ), Qgis::ProcessingNumberParameterType::Double, 1, false, 0 ) );
74 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "NUMBER" ), QObject::tr( "Constant value" ), Qgis::ProcessingNumberParameterType::Double, 1, false ) );
75
76 QStringList rasterDataTypes; //currently supported raster data types that can be handled QgsRasterBlock::writeValue()
77 rasterDataTypes << QStringLiteral( "Byte" )
78 << QStringLiteral( "Integer16" )
79 << QStringLiteral( "Unsigned Integer16" )
80 << QStringLiteral( "Integer32" )
81 << QStringLiteral( "Unsigned Integer32" )
82 << QStringLiteral( "Float32" )
83 << QStringLiteral( "Float64" );
84
85 //QGIS3: parameter set to Float32 by default so that existing models/scripts don't break
86 std::unique_ptr<QgsProcessingParameterDefinition> rasterTypeParameter = std::make_unique<QgsProcessingParameterEnum>( QStringLiteral( "OUTPUT_TYPE" ), QObject::tr( "Output raster data type" ), rasterDataTypes, false, 5, false );
87 rasterTypeParameter->setFlags( Qgis::ProcessingParameterFlag::Advanced );
88 addParameter( rasterTypeParameter.release() );
89
90 // backwards compatibility parameter
91 // TODO QGIS 4: remove parameter and related logic
92 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATE_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
93 createOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
94 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
95 addParameter( createOptsParam.release() );
96
97 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATION_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
98 creationOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
99 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
100 addParameter( creationOptsParam.release() );
101
102 addParameter( new QgsProcessingParameterRasterDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Constant" ) ) );
103}
104
105QVariantMap QgsConstantRasterAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
106{
107 const QgsCoordinateReferenceSystem crs = parameterAsCrs( parameters, QStringLiteral( "TARGET_CRS" ), context );
108 const QgsRectangle extent = parameterAsExtent( parameters, QStringLiteral( "EXTENT" ), context, crs );
109 const double pixelSize = parameterAsDouble( parameters, QStringLiteral( "PIXEL_SIZE" ), context );
110 const double value = parameterAsDouble( parameters, QStringLiteral( "NUMBER" ), context );
111 const int typeId = parameterAsInt( parameters, QStringLiteral( "OUTPUT_TYPE" ), context );
112
113 if ( pixelSize <= 0 )
114 {
115 throw QgsProcessingException( QObject::tr( "Pixel size must be greater than 0." ) );
116 }
117
118 //implement warning if input float has decimal places but is written to integer raster
119 double fractpart;
120 double intpart;
121 fractpart = abs( std::modf( value, &intpart ) ); //@abs: negative values may be entered
122
123 Qgis::DataType rasterDataType = Qgis::DataType::Float32; //standard output type
124 switch ( typeId )
125 {
126 case 0:
127 rasterDataType = Qgis::DataType::Byte;
128 if ( value < std::numeric_limits<quint8>::min() || value > std::numeric_limits<quint8>::max() )
129 throw QgsProcessingException( QObject::tr( "Raster datasets of type %3 only accept positive values between %1 and %2" ).arg( std::numeric_limits<quint8>::min() ).arg( std::numeric_limits<quint8>::max() ).arg( QLatin1String( "Byte" ) ) );
130 if ( fractpart > 0 )
131 feedback->reportError( QObject::tr( "The entered constant value has decimals but will be written to a raster dataset of type %1. The decimals of the constant value will be omitted." ).arg( QLatin1String( "Byte" ) ) );
132 break;
133 case 1:
134 rasterDataType = Qgis::DataType::Int16;
135 if ( value < std::numeric_limits<qint16>::min() || value > std::numeric_limits<qint16>::max() )
136 throw QgsProcessingException( QObject::tr( "Raster datasets of type %3 only accept values between %1 and %2" ).arg( std::numeric_limits<qint16>::min() ).arg( std::numeric_limits<qint16>::max() ).arg( QLatin1String( "Integer16" ) ) );
137 if ( fractpart > 0 )
138 feedback->reportError( QObject::tr( "The entered constant value has decimals but will be written to a raster dataset of type %1. The decimals of the constant value will be omitted." ).arg( QLatin1String( "Integer16" ) ) );
139 break;
140 case 2:
141 rasterDataType = Qgis::DataType::UInt16;
142 if ( value < std::numeric_limits<quint16>::min() || value > std::numeric_limits<quint16>::max() )
143 throw QgsProcessingException( QObject::tr( "Raster datasets of type %3 only accept positive values between %1 and %2" ).arg( std::numeric_limits<quint16>::min() ).arg( std::numeric_limits<quint16>::max() ).arg( "Unsigned Integer16" ) );
144 if ( fractpart > 0 )
145 feedback->reportError( QObject::tr( "The entered constant value has decimals but will be written to a raster dataset of type %1. The decimals of the constant value will be omitted." ).arg( QLatin1String( "Unsigned Integer16" ) ) );
146 break;
147 case 3:
148 rasterDataType = Qgis::DataType::Int32;
149 if ( value < std::numeric_limits<qint32>::min() || value > std::numeric_limits<qint32>::max() )
150 throw QgsProcessingException( QObject::tr( "Raster datasets of type %3 only accept values between %1 and %2" ).arg( std::numeric_limits<qint32>::min() ).arg( std::numeric_limits<qint32>::max() ).arg( QLatin1String( "Integer32" ) ) );
151 if ( fractpart > 0 )
152 feedback->reportError( QObject::tr( "The entered constant value has decimals but will be written to a raster dataset of type %1. The decimals of the constant value will be omitted." ).arg( QLatin1String( "Integer32" ) ) );
153 break;
154 case 4:
155 rasterDataType = Qgis::DataType::UInt32;
156 if ( value < std::numeric_limits<quint32>::min() || value > std::numeric_limits<quint32>::max() )
157 throw QgsProcessingException( QObject::tr( "Raster datasets of type %3 only accept positive values between %1 and %2" ).arg( std::numeric_limits<quint32>::min() ).arg( std::numeric_limits<quint32>::max() ).arg( QLatin1String( "Unsigned Integer32" ) ) );
158 if ( fractpart > 0 )
159 feedback->reportError( QObject::tr( "The entered constant value has decimals but will be written to a raster dataset of type %1. The decimals of the constant value will be omitted." ).arg( QLatin1String( "Unsigned Integer32" ) ) );
160 break;
161 case 5:
162 rasterDataType = Qgis::DataType::Float32;
163 break;
164 case 6:
165 rasterDataType = Qgis::DataType::Float64;
166 break;
167 default:
168 break;
169 }
170
171 QString creationOptions = parameterAsString( parameters, QStringLiteral( "CREATION_OPTIONS" ), context ).trimmed();
172 // handle backwards compatibility parameter CREATE_OPTIONS
173 const QString optionsString = parameterAsString( parameters, QStringLiteral( "CREATE_OPTIONS" ), context );
174 if ( !optionsString.isEmpty() )
175 creationOptions = optionsString;
176
177 const QString outputFile = parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context );
178 const QFileInfo fi( outputFile );
179 const QString outputFormat = QgsRasterFileWriter::driverForExtension( fi.suffix() );
180
181 // round up width and height to the nearest integer as GDAL does (e.g. in gdal_rasterize)
182 // see https://github.com/qgis/QGIS/issues/43547
183 const int rows = static_cast<int>( 0.5 + extent.height() / pixelSize );
184 const int cols = static_cast<int>( 0.5 + extent.width() / pixelSize );
185
186 //build new raster extent based on number of columns and cellsize
187 //this prevents output cellsize being calculated too small
188 const QgsRectangle rasterExtent = QgsRectangle( extent.xMinimum(), extent.yMaximum() - ( rows * pixelSize ), extent.xMinimum() + ( cols * pixelSize ), extent.yMaximum() );
189
190 auto writer = std::make_unique<QgsRasterFileWriter>( outputFile );
191 writer->setOutputProviderKey( QStringLiteral( "gdal" ) );
192 if ( !creationOptions.isEmpty() )
193 {
194 writer->setCreationOptions( creationOptions.split( '|' ) );
195 }
196 writer->setOutputFormat( outputFormat );
197 std::unique_ptr<QgsRasterDataProvider> provider( writer->createOneBandRaster( rasterDataType, cols, rows, rasterExtent, crs ) );
198 if ( !provider )
199 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
200 if ( !provider->isValid() )
201 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
202
203 //Thoughts on noData:
204 //Setting a noData value is disabled so that the user is protected from accidentally creating an empty raster (eg. when value is set to -9999)
205 //We could also allow creating empty rasters by exposing a noData value parameter (usecases?).
206
207 //prepare raw data depending on raster data type
208 QgsRasterBlock block( rasterDataType, cols, 1 );
209 block.fill( value );
210
211 const double step = rows > 0 ? 100.0 / rows : 1;
212
213 for ( int i = 0; i < rows; i++ )
214 {
215 if ( feedback->isCanceled() )
216 {
217 break;
218 }
219
220 if ( !provider->writeBlock( &block, 1, 0, i ) )
221 {
222 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( provider->error().summary() ) );
223 }
224 feedback->setProgress( i * step );
225 }
226
227 QVariantMap outputs;
228 outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
229 return outputs;
230}
231
DataType
Raster data types.
Definition qgis.h:351
@ Float32
Thirty two bit floating point (float)
@ Int16
Sixteen bit signed integer (qint16)
@ UInt16
Sixteen bit unsigned integer (quint16)
@ Byte
Eight bit unsigned integer (quint8)
@ Int32
Thirty two bit signed integer (qint32)
@ Float64
Sixty four bit floating point (double)
@ UInt32
Thirty two bit unsigned integer (quint32)
@ Hidden
Parameter is hidden and should not be shown to users.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Represents a coordinate reference system (CRS).
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
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.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A coordinate reference system parameter for processing algorithms.
A rectangular map extent parameter for processing algorithms.
A numeric parameter for processing algorithms.
A raster layer destination parameter, for specifying the destination path for a raster layer created ...
Raster data container.
static QString driverForExtension(const QString &extension)
Returns the GDAL driver name for a specified file extension.
A rectangle specified with double values.
double xMinimum
double yMaximum
const QgsCoordinateReferenceSystem & crs