QGIS API Documentation 3.43.0-Master (0cdc48caa8d)
qgsalgorithmvoronoipolygons.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmvoronoipolygons.cpp
3 ---------------------
4 begin : July 2023
5 copyright : (C) 2023 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#include "qgsspatialindex.h"
20#include "qgsmultipoint.h"
21#include "qgsgeometryengine.h"
22
24
25QString QgsVoronoiPolygonsAlgorithm::name() const
26{
27 return QStringLiteral( "voronoipolygons" );
28}
29
30QString QgsVoronoiPolygonsAlgorithm::displayName() const
31{
32 return QObject::tr( "Voronoi polygons" );
33}
34
35QStringList QgsVoronoiPolygonsAlgorithm::tags() const
36{
37 return QObject::tr( "voronoi,polygons,tessellation,diagram" ).split( ',' );
38}
39
40QString QgsVoronoiPolygonsAlgorithm::group() const
41{
42 return QObject::tr( "Vector geometry" );
43}
44
45QString QgsVoronoiPolygonsAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorgeometry" );
48}
49
50QString QgsVoronoiPolygonsAlgorithm::shortHelpString() const
51{
52 return QObject::tr( "This algorithm generates a polygon layer containing the Voronoi diagram corresponding to input points." );
53}
54
55QString QgsVoronoiPolygonsAlgorithm::shortDescription() const
56{
57 return QObject::tr( "Generates a polygon layer containing the Voronoi diagram corresponding to input points." );
58}
59
60QgsVoronoiPolygonsAlgorithm *QgsVoronoiPolygonsAlgorithm::createInstance() const
61{
62 return new QgsVoronoiPolygonsAlgorithm();
63}
64
65void QgsVoronoiPolygonsAlgorithm::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 QgsProcessingParameterNumber( QStringLiteral( "BUFFER" ), QObject::tr( "Buffer region (% of extent)" ), Qgis::ProcessingNumberParameterType::Double, 0, false, 0 ) );
69 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Double, 0, true, 0 ) );
70 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "COPY_ATTRIBUTES" ), QObject::tr( "Copy attributes from input features" ), true ) );
71 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Voronoi polygons" ), Qgis::ProcessingSourceType::VectorPolygon ) );
72}
73
74bool QgsVoronoiPolygonsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
75{
76 Q_UNUSED( feedback );
77
78 mSource.reset( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
79 if ( !mSource )
80 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
81
82 if ( mSource->featureCount() < 3 )
83 throw QgsProcessingException( QObject::tr( "Input layer should contain at least 3 points." ) );
84
85 mBuffer = parameterAsDouble( parameters, QStringLiteral( "BUFFER" ), context );
86 mTolerance = parameterAsDouble( parameters, QStringLiteral( "TOLERANCE" ), context );
87 mCopyAttributes = parameterAsBool( parameters, QStringLiteral( "COPY_ATTRIBUTES" ), context );
88
89 return true;
90}
91
92QVariantMap QgsVoronoiPolygonsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
93{
94 QString dest;
95 if ( mCopyAttributes )
96 {
97 dest = voronoiWithAttributes( parameters, context, feedback );
98 }
99 else
100 {
101 dest = voronoiWithoutAttributes( parameters, context, feedback );
102 }
103
104 QVariantMap outputs;
105 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
106 return outputs;
107}
108
109QString QgsVoronoiPolygonsAlgorithm::voronoiWithAttributes( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
110{
111 const QgsFields fields = mSource->fields();
112
113 QString dest;
114 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::Polygon, mSource->sourceCrs() ) );
115 if ( !sink )
116 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
117
118 QgsFeatureRequest request;
120
121 QgsGeometry allPoints;
122 QHash<QgsFeatureId, QgsAttributes> attributeCache;
123
124 long long i = 0;
125 const double step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
126
127 const QgsSpatialIndex index( it, [&]( const QgsFeature &f ) -> bool {
128 i++;
129 if ( feedback->isCanceled() )
130 return false;
131
132 feedback->setProgress( i * step );
133
134 if ( !f.hasGeometry() )
135 return true;
136
137 const QgsAbstractGeometry *geom = f.geometry().constGet();
138 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
139 {
140 const QgsMultiPoint mp( *qgsgeometry_cast< const QgsMultiPoint * >( geom ) );
141 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
142 {
143 allPoints.addPartV2( qgsgeometry_cast< const QgsPoint * >( *pit )->clone(), Qgis::WkbType::Point );
144 }
145 }
146 else
147 {
148 allPoints.addPartV2( qgsgeometry_cast< const QgsPoint * >( geom )->clone(), Qgis::WkbType::Point );
149 }
150
151 attributeCache.insert( f.id(), f.attributes() );
152
154
155 QgsRectangle extent = mSource->sourceExtent();
156 double delta = extent.width() * mBuffer / 100.0;
157 extent.setXMinimum( extent.xMinimum() - delta );
158 extent.setXMaximum( extent.xMaximum() + delta );
159 delta = extent.height() * mBuffer / 100.0;
160 extent.setYMinimum( extent.yMinimum() - delta );
161 extent.setYMaximum( extent.yMaximum() + delta );
162 const QgsGeometry clippingGeom = QgsGeometry::fromRect( extent );
163
164 const QgsGeometry voronoiDiagram = allPoints.voronoiDiagram( clippingGeom, mTolerance );
165
166 if ( !voronoiDiagram.isEmpty() )
167 {
168 std::unique_ptr<QgsGeometryEngine> engine;
169 std::unique_ptr<QgsGeometryEngine> extentEngine( QgsGeometry::createGeometryEngine( clippingGeom.constGet() ) );
170 const QVector<QgsGeometry> collection = voronoiDiagram.asGeometryCollection();
171 for ( int i = 0; i < collection.length(); i++ )
172 {
173 if ( feedback->isCanceled() )
174 {
175 break;
176 }
177 QgsFeature f;
178 f.setFields( fields );
179 f.setGeometry( QgsGeometry( extentEngine->intersection( collection[i].constGet() ) ) );
180 const QList<QgsFeatureId> intersected = index.intersects( collection[i].boundingBox() );
181 engine.reset( QgsGeometry::createGeometryEngine( collection[i].constGet() ) );
182 engine->prepareGeometry();
183 for ( const QgsFeatureId id : intersected )
184 {
185 if ( engine->intersects( index.geometry( id ).constGet() ) )
186 {
187 f.setAttributes( attributeCache.value( id ) );
188 break;
189 }
190 }
191 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
192 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
193 feedback->setProgress( 50 + i * step );
194 }
195 }
196
197 sink->finalize();
198
199 return dest;
200}
201
202QString QgsVoronoiPolygonsAlgorithm::voronoiWithoutAttributes( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
203{
204 QgsFields fields;
205 fields.append( QgsField( QStringLiteral( "id" ), QMetaType::Type::LongLong ) );
206
207 QString dest;
208 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::Polygon, mSource->sourceCrs() ) );
209 if ( !sink )
210 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
211
212 auto points = std::make_unique<QgsMultiPoint>();
213
214 long long i = 0;
215 const double step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
217 QgsFeature f;
218 while ( it.nextFeature( f ) )
219 {
220 i++;
221
222 if ( feedback->isCanceled() )
223 break;
224
225 feedback->setProgress( i * step );
226
227 if ( !f.hasGeometry() )
228 continue;
229
230 const QgsAbstractGeometry *geom = f.geometry().constGet();
231 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
232 {
233 const QgsMultiPoint mp( *qgsgeometry_cast<const QgsMultiPoint *>( geom ) );
234 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
235 {
236 points->addGeometry( qgsgeometry_cast<const QgsPoint *>( *pit )->clone() );
237 }
238 }
239 else
240 {
241 points->addGeometry( qgsgeometry_cast<const QgsPoint *>( geom )->clone() );
242 }
243 }
244
245 QgsRectangle extent = mSource->sourceExtent();
246 double delta = extent.width() * mBuffer / 100.0;
247 extent.setXMinimum( extent.xMinimum() - delta );
248 extent.setXMaximum( extent.xMaximum() + delta );
249 delta = extent.height() * mBuffer / 100.0;
250 extent.setYMinimum( extent.yMinimum() - delta );
251 extent.setYMaximum( extent.yMaximum() + delta );
252 const QgsGeometry clippingGeom = QgsGeometry::fromRect( extent );
253
254 QgsGeometry allPoints = QgsGeometry( std::move( points ) );
255 const QgsGeometry voronoiDiagram = allPoints.voronoiDiagram( clippingGeom, mTolerance );
256
257 if ( !voronoiDiagram.isEmpty() )
258 {
259 std::unique_ptr<QgsGeometryEngine> engine;
260 std::unique_ptr<QgsGeometryEngine> extentEngine( QgsGeometry::createGeometryEngine( clippingGeom.constGet() ) );
261 const QVector<QgsGeometry> collection = voronoiDiagram.asGeometryCollection();
262 for ( int i = 0; i < collection.length(); i++ )
263 {
264 if ( feedback->isCanceled() )
265 {
266 break;
267 }
268 QgsFeature f;
269 f.setFields( fields );
270 f.setGeometry( QgsGeometry( extentEngine->intersection( collection[i].constGet() ) ) );
271 f.setAttributes( QgsAttributes() << i );
272 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
273 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
274 feedback->setProgress( i * step );
275 }
276 }
277
278 sink->finalize();
279
280 return dest;
281}
282
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
@ Polygon
Polygon.
Abstract base class for all geometries.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
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).
@ 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
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:69
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: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:53
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:70
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsGeometry voronoiDiagram(const QgsGeometry &extent=QgsGeometry(), double tolerance=0.0, bool edgesOnly=false) const
Creates a Voronoi diagram for the nodes contained within the geometry.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
Qgis::GeometryOperationResult addPartV2(const QVector< QgsPointXY > &points, Qgis::WkbType wkbType=Qgis::WkbType::Unknown)
Adds a new part to a the geometry.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Multi point geometry collection.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
A boolean parameter for processing algorithms.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A numeric parameter for processing algorithms.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
void setYMinimum(double y)
Set the minimum y value.
void setXMinimum(double x)
Set the minimum x value.
void setYMaximum(double y)
Set the maximum y value.
void setXMaximum(double x)
Set the maximum x value.
double yMaximum
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
static bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features