QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmrastersampling.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmrastersampling.cpp
3 --------------------------
4 begin : August 2020
5 copyright : (C) 2020 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 "qgsmultipoint.h"
21
22#include <QString>
23
24using namespace Qt::StringLiterals;
25
27
28QString QgsRasterSamplingAlgorithm::name() const
29{
30 return u"rastersampling"_s;
31}
32
33QString QgsRasterSamplingAlgorithm::displayName() const
34{
35 return QObject::tr( "Sample raster values" );
36}
37
38QStringList QgsRasterSamplingAlgorithm::tags() const
39{
40 return QObject::tr( "extract,point,pixel,value" ).split( ',' );
41}
42
43QString QgsRasterSamplingAlgorithm::group() const
44{
45 return QObject::tr( "Raster analysis" );
46}
47
48QString QgsRasterSamplingAlgorithm::groupId() const
49{
50 return u"rasteranalysis"_s;
51}
52
53QString QgsRasterSamplingAlgorithm::shortDescription() const
54{
55 return QObject::tr( "Samples raster values under a set of points." );
56}
57
58QString QgsRasterSamplingAlgorithm::shortHelpString() const
59{
60 return QObject::tr( "This algorithm creates a new vector layer with the same attributes of the input layer and the raster values corresponding on the point location.\n\n"
61 "If the raster layer has more than one band, all the band values are sampled." );
62}
63
64QgsRasterSamplingAlgorithm *QgsRasterSamplingAlgorithm::createInstance() const
65{
66 return new QgsRasterSamplingAlgorithm();
67}
68
69void QgsRasterSamplingAlgorithm::initAlgorithm( const QVariantMap & )
70{
71 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
72 addParameter( new QgsProcessingParameterRasterLayer( u"RASTERCOPY"_s, QObject::tr( "Raster layer" ) ) );
73
74 addParameter( new QgsProcessingParameterString( u"COLUMN_PREFIX"_s, QObject::tr( "Output column prefix" ), u"SAMPLE_"_s, false, true ) );
75 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Sampled" ), Qgis::ProcessingSourceType::VectorPoint ) );
76}
77
78bool QgsRasterSamplingAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
79{
80 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u"RASTERCOPY"_s, context );
81 if ( !layer )
82 throw QgsProcessingException( invalidRasterError( parameters, u"RASTERCOPY"_s ) );
83
84 mBandCount = layer->bandCount();
85 mCrs = layer->crs();
86 mDataProvider.reset( static_cast<QgsRasterDataProvider *>( layer->dataProvider()->clone() ) );
87
88 return true;
89}
90
91QVariantMap QgsRasterSamplingAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
92{
93 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
94 if ( !source )
95 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
96
97 const QString fieldPrefix = parameterAsString( parameters, u"COLUMN_PREFIX"_s, context );
98 QgsFields newFields;
99 QgsAttributes emptySampleAttributes;
100 for ( int band = 1; band <= mBandCount; band++ )
101 {
102 const Qgis::DataType dataType = mDataProvider->dataType( band );
103 const bool intSafe = ( dataType == Qgis::DataType::Byte || dataType == Qgis::DataType::UInt16 || dataType == Qgis::DataType::Int16 || dataType == Qgis::DataType::UInt32 || dataType == Qgis::DataType::Int32 || dataType == Qgis::DataType::CInt16 || dataType == Qgis::DataType::CInt32 );
104
105 newFields.append( QgsField( u"%1%2"_s.arg( fieldPrefix, QString::number( band ) ), intSafe ? QMetaType::Type::Int : QMetaType::Type::Double ) );
106 emptySampleAttributes += QVariant();
107 }
108 const QgsFields fields = QgsProcessingUtils::combineFields( source->fields(), newFields );
109
110 QString dest;
111 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, source->wkbType(), source->sourceCrs() ) );
112 if ( !sink )
113 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
114
115 const long count = source->featureCount();
116 const double step = count > 0 ? 100.0 / count : 1;
117 long current = 0;
118
119 const QgsCoordinateTransform ct( source->sourceCrs(), mCrs, context.transformContext() );
120 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest() );
121 QgsFeature feature;
122 while ( it.nextFeature( feature ) )
123 {
124 if ( feedback->isCanceled() )
125 {
126 break;
127 }
128 feedback->setProgress( current * step );
129 current++;
130
131 QgsAttributes attributes = feature.attributes();
132 QgsFeature outputFeature( feature );
133 if ( !feature.hasGeometry() )
134 {
135 attributes += emptySampleAttributes;
136 outputFeature.setAttributes( attributes );
137 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
138 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
139 feedback->reportError( QObject::tr( "No geometry attached to feature %1." ).arg( feature.id() ) );
140 continue;
141 }
142
143 QgsGeometry geometry = feature.geometry();
144 if ( geometry.isMultipart() && geometry.get()->partCount() != 1 )
145 {
146 attributes += emptySampleAttributes;
147 outputFeature.setAttributes( attributes );
148 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
149 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
150 feedback->reportError( QObject::tr( "Impossible to sample data of multipart feature %1." ).arg( feature.id() ) );
151 continue;
152 }
154 try
155 {
156 point = ct.transform( point );
157 }
158 catch ( const QgsException & )
159 {
160 attributes += emptySampleAttributes;
161 outputFeature.setAttributes( attributes );
162 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
163 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
164 feedback->reportError( QObject::tr( "Could not reproject feature %1 to raster CRS." ).arg( feature.id() ) );
165 continue;
166 }
167
168 for ( int band = 1; band <= mBandCount; band++ )
169 {
170 bool ok = false;
171 const double value = mDataProvider->sample( point, band, &ok );
172 attributes += ok ? value : QVariant();
173 }
174 outputFeature.setAttributes( attributes );
175 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
176 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
177 }
178
179 sink->finalize();
180
181 QVariantMap outputs;
182 outputs.insert( u"OUTPUT"_s, dest );
183 return outputs;
184}
185
@ VectorPoint
Vector point layers.
Definition qgis.h:3605
DataType
Raster data types.
Definition qgis.h:379
@ CInt32
Complex Int32.
Definition qgis.h:390
@ Int16
Sixteen bit signed integer (qint16).
Definition qgis.h:384
@ UInt16
Sixteen bit unsigned integer (quint16).
Definition qgis.h:383
@ Byte
Eight bit unsigned integer (quint8).
Definition qgis.h:381
@ Int32
Thirty two bit signed integer (qint32).
Definition qgis.h:386
@ CInt16
Complex Int16.
Definition qgis.h:389
@ UInt32
Thirty two bit unsigned integer (quint32).
Definition qgis.h:385
virtual int partCount() const =0
Returns count of parts contained in the geometry.
A vector of attributes.
Handles coordinate transforms between two coordinate systems.
Defines a QGIS exception class.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
@ 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
QgsAttributes attributes
Definition qgsfeature.h:69
QgsFeatureId id
Definition qgsfeature.h:68
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
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:76
A geometry is the spatial representation of a feature.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
Represents a 2D point.
Definition qgspointxy.h:62
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
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 feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A raster layer parameter for processing algorithms.
A string parameter for processing algorithms.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
Base class for raster data providers.
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
Represents a raster layer.
int bandCount() const
Returns the number of bands in this layer.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
T qgsgeometry_cast(QgsAbstractGeometry *geom)