QGIS API Documentation 3.99.0-Master (2fe06baccd8)
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
23
24QString QgsRasterSamplingAlgorithm::name() const
25{
26 return QStringLiteral( "rastersampling" );
27}
28
29QString QgsRasterSamplingAlgorithm::displayName() const
30{
31 return QObject::tr( "Sample raster values" );
32}
33
34QStringList QgsRasterSamplingAlgorithm::tags() const
35{
36 return QObject::tr( "extract,point,pixel,value" ).split( ',' );
37}
38
39QString QgsRasterSamplingAlgorithm::group() const
40{
41 return QObject::tr( "Raster analysis" );
42}
43
44QString QgsRasterSamplingAlgorithm::groupId() const
45{
46 return QStringLiteral( "rasteranalysis" );
47}
48
49QString QgsRasterSamplingAlgorithm::shortDescription() const
50{
51 return QObject::tr( "Samples raster values under a set of points." );
52}
53
54QString QgsRasterSamplingAlgorithm::shortHelpString() const
55{
56 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"
57 "If the raster layer has more than one band, all the band values are sampled." );
58}
59
60QgsRasterSamplingAlgorithm *QgsRasterSamplingAlgorithm::createInstance() const
61{
62 return new QgsRasterSamplingAlgorithm();
63}
64
65void QgsRasterSamplingAlgorithm::initAlgorithm( const QVariantMap & )
66{
67 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
68 addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "RASTERCOPY" ), QObject::tr( "Raster layer" ) ) );
69
70 addParameter( new QgsProcessingParameterString( QStringLiteral( "COLUMN_PREFIX" ), QObject::tr( "Output column prefix" ), QStringLiteral( "SAMPLE_" ), false, true ) );
71 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Sampled" ), Qgis::ProcessingSourceType::VectorPoint ) );
72}
73
74bool QgsRasterSamplingAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
75{
76 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, QStringLiteral( "RASTERCOPY" ), context );
77 if ( !layer )
78 throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "RASTERCOPY" ) ) );
79
80 mBandCount = layer->bandCount();
81 mCrs = layer->crs();
82 mDataProvider.reset( static_cast<QgsRasterDataProvider *>( layer->dataProvider()->clone() ) );
83
84 return true;
85}
86
87QVariantMap QgsRasterSamplingAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
88{
89 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
90 if ( !source )
91 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
92
93 const QString fieldPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
94 QgsFields newFields;
95 QgsAttributes emptySampleAttributes;
96 for ( int band = 1; band <= mBandCount; band++ )
97 {
98 const Qgis::DataType dataType = mDataProvider->dataType( band );
99 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 );
100
101 newFields.append( QgsField( QStringLiteral( "%1%2" ).arg( fieldPrefix, QString::number( band ) ), intSafe ? QMetaType::Type::Int : QMetaType::Type::Double ) );
102 emptySampleAttributes += QVariant();
103 }
104 const QgsFields fields = QgsProcessingUtils::combineFields( source->fields(), newFields );
105
106 QString dest;
107 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, source->wkbType(), source->sourceCrs() ) );
108 if ( !sink )
109 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
110
111 const long count = source->featureCount();
112 const double step = count > 0 ? 100.0 / count : 1;
113 long current = 0;
114
115 const QgsCoordinateTransform ct( source->sourceCrs(), mCrs, context.transformContext() );
116 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest() );
117 QgsFeature feature;
118 while ( it.nextFeature( feature ) )
119 {
120 if ( feedback->isCanceled() )
121 {
122 break;
123 }
124 feedback->setProgress( current * step );
125 current++;
126
127 QgsAttributes attributes = feature.attributes();
128 QgsFeature outputFeature( feature );
129 if ( !feature.hasGeometry() )
130 {
131 attributes += emptySampleAttributes;
132 outputFeature.setAttributes( attributes );
133 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
134 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
135 feedback->reportError( QObject::tr( "No geometry attached to feature %1." ).arg( feature.id() ) );
136 continue;
137 }
138
139 QgsGeometry geometry = feature.geometry();
140 if ( geometry.isMultipart() && geometry.get()->partCount() != 1 )
141 {
142 attributes += emptySampleAttributes;
143 outputFeature.setAttributes( attributes );
144 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
145 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
146 feedback->reportError( QObject::tr( "Impossible to sample data of multipart feature %1." ).arg( feature.id() ) );
147 continue;
148 }
150 try
151 {
152 point = ct.transform( point );
153 }
154 catch ( const QgsException & )
155 {
156 attributes += emptySampleAttributes;
157 outputFeature.setAttributes( attributes );
158 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
159 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
160 feedback->reportError( QObject::tr( "Could not reproject feature %1 to raster CRS." ).arg( feature.id() ) );
161 continue;
162 }
163
164 for ( int band = 1; band <= mBandCount; band++ )
165 {
166 bool ok = false;
167 const double value = mDataProvider->sample( point, band, &ok );
168 attributes += ok ? value : QVariant();
169 }
170 outputFeature.setAttributes( attributes );
171 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
172 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
173 }
174
175 sink->finalize();
176
177 QVariantMap outputs;
178 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
179 return outputs;
180}
181
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
DataType
Raster data types.
Definition qgis.h:372
@ CInt32
Complex Int32.
Definition qgis.h:383
@ Int16
Sixteen bit signed integer (qint16).
Definition qgis.h:377
@ UInt16
Sixteen bit unsigned integer (quint16).
Definition qgis.h:376
@ Byte
Eight bit unsigned integer (quint8).
Definition qgis.h:374
@ Int32
Thirty two bit signed integer (qint32).
Definition qgis.h:379
@ CInt16
Complex Int16.
Definition qgis.h:382
@ UInt32
Thirty two bit unsigned integer (quint32).
Definition qgis.h:378
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:58
QgsAttributes attributes
Definition qgsfeature.h:67
QgsFeatureId id
Definition qgsfeature.h:66
QgsGeometry geometry
Definition qgsfeature.h:69
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:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
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:73
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:87
Represents a 2D point.
Definition qgspointxy.h:60
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)