QGIS API Documentation 4.3.0-Master (0d5b841b09e)
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,sample,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(
61 "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"
62 "If the raster layer has more than one band, all the band values are sampled."
63 );
64}
65
66QgsRasterSamplingAlgorithm *QgsRasterSamplingAlgorithm::createInstance() const
67{
68 return new QgsRasterSamplingAlgorithm();
69}
70
71void QgsRasterSamplingAlgorithm::initAlgorithm( const QVariantMap & )
72{
73 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
74 addParameter( new QgsProcessingParameterRasterLayer( u"RASTERCOPY"_s, QObject::tr( "Raster layer" ) ) );
75
76 addParameter( new QgsProcessingParameterString( u"COLUMN_PREFIX"_s, QObject::tr( "Output column prefix" ), u"SAMPLE_"_s, false, true ) );
77 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Sampled" ), Qgis::ProcessingSourceType::VectorPoint ) );
78}
79
80bool QgsRasterSamplingAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
81{
82 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u"RASTERCOPY"_s, context );
83 if ( !layer )
84 throw QgsProcessingException( invalidRasterError( parameters, u"RASTERCOPY"_s ) );
85
86 mBandCount = layer->bandCount();
87 mCrs = layer->crs();
88 mDataProvider.reset( static_cast<QgsRasterDataProvider *>( layer->dataProvider()->clone() ) );
89
90 return true;
91}
92
93QVariantMap QgsRasterSamplingAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
94{
95 QGS_MARK_ALGORITHM_SOURCE
96
97 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
98 if ( !source )
99 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
100
101 const QString fieldPrefix = parameterAsString( parameters, u"COLUMN_PREFIX"_s, context );
102 QgsFields newFields;
103 QgsAttributes emptySampleAttributes;
104 for ( int band = 1; band <= mBandCount; band++ )
105 {
106 const Qgis::DataType dataType = mDataProvider->dataType( band );
107 const bool intSafe
108 = ( 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 );
109
110 newFields.append( QgsField( u"%1%2"_s.arg( fieldPrefix, QString::number( band ) ), intSafe ? QMetaType::Type::Int : QMetaType::Type::Double ) );
111 emptySampleAttributes += QVariant();
112 }
113 const QgsFields fields = QgsProcessingUtils::combineFields( source->fields(), newFields );
114
115 QString dest;
116 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, source->wkbType(), source->sourceCrs() ) );
117 if ( !sink )
118 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
119
120 const long count = source->featureCount();
121 const double step = count > 0 ? 100.0 / count : 1;
122 long current = 0;
123
124 const QgsCoordinateTransform ct( source->sourceCrs(), mCrs, context.transformContext() );
125 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest() );
126 QgsFeature feature;
127 while ( it.nextFeature( feature ) )
128 {
129 if ( feedback->isCanceled() )
130 {
131 break;
132 }
133 feedback->setProgress( current * step );
134 current++;
135
136 QgsAttributes attributes = feature.attributes();
137 QgsFeature outputFeature( feature );
138 if ( !feature.hasGeometry() )
139 {
140 attributes += emptySampleAttributes;
141 outputFeature.setAttributes( attributes );
142 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
143 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
144 else
145 feedback->featureAddedToSink( u"OUTPUT"_s );
146 feedback->reportError( QObject::tr( "No geometry attached to feature %1." ).arg( feature.id() ) );
147 continue;
148 }
149
150 QgsGeometry geometry = feature.geometry();
151 if ( geometry.isMultipart() && geometry.get()->partCount() != 1 )
152 {
153 attributes += emptySampleAttributes;
154 outputFeature.setAttributes( attributes );
155 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
156 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
157 else
158 feedback->featureAddedToSink( u"OUTPUT"_s );
159 feedback->reportError( QObject::tr( "Impossible to sample data of multipart feature %1." ).arg( feature.id() ) );
160 continue;
161 }
162 QgsPointXY point(
165 );
166 try
167 {
168 point = ct.transform( point );
169 }
170 catch ( const QgsException & )
171 {
172 attributes += emptySampleAttributes;
173 outputFeature.setAttributes( attributes );
174 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
175 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
176 else
177 feedback->featureAddedToSink( u"OUTPUT"_s );
178 feedback->reportError( QObject::tr( "Could not reproject feature %1 to raster CRS." ).arg( feature.id() ) );
179 continue;
180 }
181
182 for ( int band = 1; band <= mBandCount; band++ )
183 {
184 bool ok = false;
185 const double value = mDataProvider->sample( point, band, &ok );
186 attributes += ok ? value : QVariant();
187 }
188 outputFeature.setAttributes( attributes );
189 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
190 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
191 else
192 feedback->featureAddedToSink( u"OUTPUT"_s );
193 }
194
195 sink->finalize();
196 feedback->featureSinkFinalized( u"OUTPUT"_s );
197
198 QVariantMap outputs;
199 outputs.insert( u"OUTPUT"_s, dest );
200 return outputs;
201}
202
@ VectorPoint
Vector point layers.
Definition qgis.h:3752
DataType
Raster data types.
Definition qgis.h:393
@ CInt32
Complex Int32.
Definition qgis.h:404
@ Int16
Sixteen bit signed integer (qint16).
Definition qgis.h:398
@ UInt16
Sixteen bit unsigned integer (quint16).
Definition qgis.h:397
@ Byte
Eight bit unsigned integer (quint8).
Definition qgis.h:395
@ Int32
Thirty two bit signed integer (qint32).
Definition qgis.h:400
@ CInt16
Complex Int16.
Definition qgis.h:403
@ UInt32
Thirty two bit unsigned integer (quint32).
Definition qgis.h:399
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:64
QgsFeatureId id
Definition qgsfeature.h:63
QgsGeometry geometry
Definition qgsfeature.h:66
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: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
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.
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.
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)