QGIS API Documentation 4.3.0-Master (0d5b841b09e)
Loading...
Searching...
No Matches
qgsalgorithmpixelcentroidsfrompolygons.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmpixelcentroidsfrompolygons.cpp
3 ---------------------
4 begin : December 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
19
20#include "qgsgeos.h"
22
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29QString QgsPixelCentroidsFromPolygonsAlgorithm::name() const
30{
31 return u"generatepointspixelcentroidsinsidepolygons"_s;
32}
33
34QString QgsPixelCentroidsFromPolygonsAlgorithm::displayName() const
35{
36 return QObject::tr( "Generate points (pixel centroids) inside polygons" );
37}
38
39QStringList QgsPixelCentroidsFromPolygonsAlgorithm::tags() const
40{
41 return QObject::tr( "raster,polygon,centroid,pixel,create" ).split( ',' );
42}
43
44QString QgsPixelCentroidsFromPolygonsAlgorithm::group() const
45{
46 return QObject::tr( "Vector creation" );
47}
48
49QString QgsPixelCentroidsFromPolygonsAlgorithm::groupId() const
50{
51 return u"vectorcreation"_s;
52}
53
54QString QgsPixelCentroidsFromPolygonsAlgorithm::shortHelpString() const
55{
56 return QObject::tr(
57 "This algorithm generates pixel centroids for the raster area falling inside polygons. Used to generate points "
58 "for further raster sampling."
59 );
60}
61
62QString QgsPixelCentroidsFromPolygonsAlgorithm::shortDescription() const
63{
64 return QObject::tr( "Generates pixel centroids for the raster area falling inside polygons." );
65}
66
67Qgis::ProcessingAlgorithmDocumentationFlags QgsPixelCentroidsFromPolygonsAlgorithm::documentationFlags() const
68{
70}
71
72QgsPixelCentroidsFromPolygonsAlgorithm *QgsPixelCentroidsFromPolygonsAlgorithm::createInstance() const
73{
74 return new QgsPixelCentroidsFromPolygonsAlgorithm();
75}
76
77void QgsPixelCentroidsFromPolygonsAlgorithm::initAlgorithm( const QVariantMap & )
78{
79 addParameter( new QgsProcessingParameterRasterLayer( u"INPUT_RASTER"_s, QObject::tr( "Raster layer" ) ) );
80 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT_VECTOR"_s, QObject::tr( "Vector layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
81
82 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Pixel centroids" ), Qgis::ProcessingSourceType::VectorPoint ) );
83}
84
85bool QgsPixelCentroidsFromPolygonsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
86{
87 QgsRasterLayer *rasterLayer = parameterAsRasterLayer( parameters, u"INPUT_RASTER"_s, context );
88
89 if ( !rasterLayer )
90 throw QgsProcessingException( invalidRasterError( parameters, u"INPUT_RASTER"_s ) );
91
92 mCrs = rasterLayer->crs();
93 mRasterUnitsPerPixelX = rasterLayer->rasterUnitsPerPixelX();
94 mRasterUnitsPerPixelY = rasterLayer->rasterUnitsPerPixelY();
95 mExtent = rasterLayer->extent();
96 return true;
97}
98
99QVariantMap QgsPixelCentroidsFromPolygonsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
100{
101 QGS_MARK_ALGORITHM_SOURCE
102
103 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT_VECTOR"_s, context ) );
104 if ( !source )
105 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT_VECTOR"_s ) );
106
107 QgsFields fields;
108 fields.append( QgsField( u"id"_s, QMetaType::Type::LongLong ) );
109 fields.append( QgsField( u"poly_id"_s, QMetaType::Type::Int ) );
110 fields.append( QgsField( u"point_id"_s, QMetaType::Type::Int ) );
111
112 QString dest;
113 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Point, mCrs, QgsFeatureSink::RegeneratePrimaryKey ) );
114 if ( !sink )
115 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
116
117 const double step = source->featureCount() ? 100.0 / source->featureCount() : 1;
118 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest().setDestinationCrs( mCrs, context.transformContext() ).setSubsetOfAttributes( QList<int>() ) );
119
120 QgsFeature feature;
121 feature.setFields( fields );
122
123 int fid = 0;
124 int pointId = 0;
125
126 int i = 0;
127 QgsFeature f;
128 while ( it.nextFeature( f ) )
129 {
130 if ( feedback->isCanceled() )
131 {
132 break;
133 }
134
135 if ( !f.hasGeometry() )
136 {
137 continue;
138 }
139
140 const QgsRectangle bbox = f.geometry().boundingBox();
141 const double xMin = bbox.xMinimum();
142 const double xMax = bbox.xMaximum();
143 const double yMin = bbox.yMinimum();
144 const double yMax = bbox.yMaximum();
145
146 double x, y;
147 int startRow, startColumn;
148 int endRow, endColumn;
149 QgsRasterAnalysisUtils::mapToPixel( xMin, yMax, mExtent, mRasterUnitsPerPixelX, mRasterUnitsPerPixelY, startColumn, startRow );
150 QgsRasterAnalysisUtils::mapToPixel( xMax, yMin, mExtent, mRasterUnitsPerPixelX, mRasterUnitsPerPixelY, endColumn, endRow );
151
152 auto engine = std::make_unique<QgsGeos>( f.geometry().constGet() );
153 engine->prepareGeometry();
154
155 for ( int row = startRow; row <= endRow; row++ )
156 {
157 for ( int col = startColumn; col <= endColumn; col++ )
158 {
159 if ( feedback->isCanceled() )
160 {
161 break;
162 }
163
164 QgsRasterAnalysisUtils::pixelToMap( col, row, mExtent, mRasterUnitsPerPixelX, mRasterUnitsPerPixelY, x, y );
165 if ( engine->contains( x, y ) )
166 {
167 feature.setGeometry( std::make_unique<QgsPoint>( x, y ) );
168 feature.setAttributes( QgsAttributes() << fid << i << pointId );
169 if ( !sink->addFeature( feature, QgsFeatureSink::FastInsert ) )
170 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
171 else
172 feedback->featureAddedToSink( u"OUTPUT"_s );
173
174 fid++;
175 pointId++;
176 }
177 }
178 }
179
180 pointId = 0;
181
182 feedback->setProgress( i * step );
183 i++;
184 }
185
186 sink->finalize();
187 feedback->featureSinkFinalized( u"OUTPUT"_s );
188
189 QVariantMap outputs;
190 outputs.insert( u"OUTPUT"_s, dest );
191 return outputs;
192}
193
@ VectorPoint
Vector point layers.
Definition qgis.h:3752
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3754
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3838
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3849
@ Point
Point.
Definition qgis.h:296
A vector of attributes.
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).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
void setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
QgsGeometry geometry
Definition qgsfeature.h:66
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's 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
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
virtual Q_INVOKABLE QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
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.
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.
Represents a raster layer.
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
double rasterUnitsPerPixelY() const
Returns the number of raster units per each raster pixel in Y axis.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
double yMaximum