QGIS API Documentation 4.1.0-Master (ca2ac17535b)
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(
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 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
96 if ( !source )
97 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
98
99 const QString fieldPrefix = parameterAsString( parameters, u"COLUMN_PREFIX"_s, context );
100 QgsFields newFields;
101 QgsAttributes emptySampleAttributes;
102 for ( int band = 1; band <= mBandCount; band++ )
103 {
104 const Qgis::DataType dataType = mDataProvider->dataType( band );
105 const bool intSafe
106 = ( 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 );
107
108 newFields.append( QgsField( u"%1%2"_s.arg( fieldPrefix, QString::number( band ) ), intSafe ? QMetaType::Type::Int : QMetaType::Type::Double ) );
109 emptySampleAttributes += QVariant();
110 }
111 const QgsFields fields = QgsProcessingUtils::combineFields( source->fields(), newFields );
112
113 QString dest;
114 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, source->wkbType(), source->sourceCrs() ) );
115 if ( !sink )
116 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
117
118 const long count = source->featureCount();
119 const double step = count > 0 ? 100.0 / count : 1;
120 long current = 0;
121
122 const QgsCoordinateTransform ct( source->sourceCrs(), mCrs, context.transformContext() );
123 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest() );
124 QgsFeature feature;
125 while ( it.nextFeature( feature ) )
126 {
127 if ( feedback->isCanceled() )
128 {
129 break;
130 }
131 feedback->setProgress( current * step );
132 current++;
133
134 QgsAttributes attributes = feature.attributes();
135 QgsFeature outputFeature( feature );
136 if ( !feature.hasGeometry() )
137 {
138 attributes += emptySampleAttributes;
139 outputFeature.setAttributes( attributes );
140 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
141 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
142 else
143 feedback->featureAddedToSink( u"OUTPUT"_s );
144 feedback->reportError( QObject::tr( "No geometry attached to feature %1." ).arg( feature.id() ) );
145 continue;
146 }
147
148 QgsGeometry geometry = feature.geometry();
149 if ( geometry.isMultipart() && geometry.get()->partCount() != 1 )
150 {
151 attributes += emptySampleAttributes;
152 outputFeature.setAttributes( attributes );
153 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
154 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
155 else
156 feedback->featureAddedToSink( u"OUTPUT"_s );
157 feedback->reportError( QObject::tr( "Impossible to sample data of multipart feature %1." ).arg( feature.id() ) );
158 continue;
159 }
160 QgsPointXY point(
163 );
164 try
165 {
166 point = ct.transform( point );
167 }
168 catch ( const QgsException & )
169 {
170 attributes += emptySampleAttributes;
171 outputFeature.setAttributes( attributes );
172 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
173 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
174 else
175 feedback->featureAddedToSink( u"OUTPUT"_s );
176 feedback->reportError( QObject::tr( "Could not reproject feature %1 to raster CRS." ).arg( feature.id() ) );
177 continue;
178 }
179
180 for ( int band = 1; band <= mBandCount; band++ )
181 {
182 bool ok = false;
183 const double value = mDataProvider->sample( point, band, &ok );
184 attributes += ok ? value : QVariant();
185 }
186 outputFeature.setAttributes( attributes );
187 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
188 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
189 else
190 feedback->featureAddedToSink( u"OUTPUT"_s );
191 }
192
193 sink->finalize();
194 feedback->featureSinkFinalized( u"OUTPUT"_s );
195
196 QVariantMap outputs;
197 outputs.insert( u"OUTPUT"_s, dest );
198 return outputs;
199}
200
@ VectorPoint
Vector point layers.
Definition qgis.h:3715
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:46
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)