QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
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
20#include "qgsgeometryengine.h"
21#include "qgsmultipoint.h"
22#include "qgsspatialindex.h"
23
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsVoronoiPolygonsAlgorithm::name() const
31{
32 return u"voronoipolygons"_s;
33}
34
35QString QgsVoronoiPolygonsAlgorithm::displayName() const
36{
37 return QObject::tr( "Voronoi polygons" );
38}
39
40QStringList QgsVoronoiPolygonsAlgorithm::tags() const
41{
42 return QObject::tr( "voronoi,polygons,tessellation,diagram" ).split( ',' );
43}
44
45QString QgsVoronoiPolygonsAlgorithm::group() const
46{
47 return QObject::tr( "Vector geometry" );
48}
49
50QString QgsVoronoiPolygonsAlgorithm::groupId() const
51{
52 return u"vectorgeometry"_s;
53}
54
55QString QgsVoronoiPolygonsAlgorithm::shortHelpString() const
56{
57 return QObject::tr( "This algorithm generates a polygon layer containing the Voronoi diagram corresponding to input points." );
58}
59
60QString QgsVoronoiPolygonsAlgorithm::shortDescription() const
61{
62 return QObject::tr( "Generates a polygon layer containing the Voronoi diagram corresponding to input points." );
63}
64
65QgsVoronoiPolygonsAlgorithm *QgsVoronoiPolygonsAlgorithm::createInstance() const
66{
67 return new QgsVoronoiPolygonsAlgorithm();
68}
69
70void QgsVoronoiPolygonsAlgorithm::initAlgorithm( const QVariantMap & )
71{
72 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
73 addParameter( new QgsProcessingParameterNumber( u"BUFFER"_s, QObject::tr( "Buffer region (% of extent)" ), Qgis::ProcessingNumberParameterType::Double, 0, false, 0 ) );
74 addParameter( new QgsProcessingParameterNumber( u"TOLERANCE"_s, QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Double, 0, true, 0 ) );
75 addParameter( new QgsProcessingParameterBoolean( u"COPY_ATTRIBUTES"_s, QObject::tr( "Copy attributes from input features" ), true ) );
76 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Voronoi polygons" ), Qgis::ProcessingSourceType::VectorPolygon ) );
77}
78
79bool QgsVoronoiPolygonsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
80{
81 Q_UNUSED( feedback );
82
83 mSource.reset( parameterAsSource( parameters, u"INPUT"_s, context ) );
84 if ( !mSource )
85 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
86
87 if ( mSource->featureCount() < 3 )
88 throw QgsProcessingException( QObject::tr( "Input layer should contain at least 3 points." ) );
89
90 mBuffer = parameterAsDouble( parameters, u"BUFFER"_s, context );
91 mTolerance = parameterAsDouble( parameters, u"TOLERANCE"_s, context );
92 mCopyAttributes = parameterAsBool( parameters, u"COPY_ATTRIBUTES"_s, context );
93
94 return true;
95}
96
97QVariantMap QgsVoronoiPolygonsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
98{
99 QString dest;
100 if ( mCopyAttributes )
101 {
102 dest = voronoiWithAttributes( parameters, context, feedback );
103 }
104 else
105 {
106 dest = voronoiWithoutAttributes( parameters, context, feedback );
107 }
108
109 QVariantMap outputs;
110 outputs.insert( u"OUTPUT"_s, dest );
111 return outputs;
112}
113
114QString QgsVoronoiPolygonsAlgorithm::voronoiWithAttributes( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
115{
116 const QgsFields fields = mSource->fields();
117
118 QString dest;
119 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Polygon, mSource->sourceCrs() ) );
120 if ( !sink )
121 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
122
123 QgsFeatureRequest request;
125
126 QgsGeometry allPoints;
127 QHash<QgsFeatureId, QgsAttributes> attributeCache;
128
129 long long i = 0;
130 const double step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
131
132 const QgsSpatialIndex index( it, [&]( const QgsFeature &f ) -> bool {
133 i++;
134 if ( feedback->isCanceled() )
135 return false;
136
137 feedback->setProgress( i * step );
138
139 if ( !f.hasGeometry() )
140 return true;
141
142 const QgsAbstractGeometry *geom = f.geometry().constGet();
143 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
144 {
146 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
147 {
149 }
150 }
151 else
152 {
154 }
155
156 attributeCache.insert( f.id(), f.attributes() );
157
159
160 QgsRectangle extent = mSource->sourceExtent();
161 double delta = extent.width() * mBuffer / 100.0;
162 extent.setXMinimum( extent.xMinimum() - delta );
163 extent.setXMaximum( extent.xMaximum() + delta );
164 delta = extent.height() * mBuffer / 100.0;
165 extent.setYMinimum( extent.yMinimum() - delta );
166 extent.setYMaximum( extent.yMaximum() + delta );
167 const QgsGeometry clippingGeom = QgsGeometry::fromRect( extent );
168
169 const QgsGeometry voronoiDiagram = allPoints.voronoiDiagram( clippingGeom, mTolerance );
170
171 if ( !voronoiDiagram.isEmpty() )
172 {
173 std::unique_ptr<QgsGeometryEngine> engine;
174 std::unique_ptr<QgsGeometryEngine> extentEngine( QgsGeometry::createGeometryEngine( clippingGeom.constGet() ) );
175 const QVector<QgsGeometry> collection = voronoiDiagram.asGeometryCollection();
176 int i = 0;
177 for ( const QgsGeometry &collectionPart : collection )
178 {
179 if ( feedback->isCanceled() )
180 {
181 break;
182 }
183 QgsFeature f;
184 f.setFields( fields );
185
186 QgsGeometry voronoiClippedToExtent = QgsGeometry( extentEngine->intersection( collectionPart.constGet() ) );
188 if ( !voronoiClippedToExtent.isEmpty() )
189 {
190 f.setGeometry( QgsGeometry( voronoiClippedToExtent.constGet()->simplifiedTypeRef()->clone() ) );
191 const QList<QgsFeatureId> intersected = index.intersects( collectionPart.boundingBox() );
192 engine.reset( QgsGeometry::createGeometryEngine( collectionPart.constGet() ) );
193 engine->prepareGeometry();
194 for ( const QgsFeatureId id : intersected )
195 {
196 if ( engine->intersects( index.geometry( id ).constGet() ) )
197 {
198 f.setAttributes( attributeCache.value( id ) );
199 break;
200 }
201 }
202 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
203 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
204 }
205 feedback->setProgress( 50 + i * step );
206 i++;
207 }
208 }
209
210 sink->finalize();
211
212 return dest;
213}
214
215QString QgsVoronoiPolygonsAlgorithm::voronoiWithoutAttributes( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
216{
217 QgsFields fields;
218 fields.append( QgsField( u"id"_s, QMetaType::Type::LongLong ) );
219
220 QString dest;
221 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Polygon, mSource->sourceCrs() ) );
222 if ( !sink )
223 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
224
225 auto points = std::make_unique<QgsMultiPoint>();
226
227 long long i = 0;
228 const double step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
230 QgsFeature f;
231 while ( it.nextFeature( f ) )
232 {
233 i++;
234
235 if ( feedback->isCanceled() )
236 break;
237
238 feedback->setProgress( i * step );
239
240 if ( !f.hasGeometry() )
241 continue;
242
243 const QgsAbstractGeometry *geom = f.geometry().constGet();
244 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
245 {
247 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
248 {
249 points->addGeometry( qgsgeometry_cast<const QgsPoint *>( *pit )->clone() );
250 }
251 }
252 else
253 {
254 points->addGeometry( qgsgeometry_cast<const QgsPoint *>( geom )->clone() );
255 }
256 }
257
258 QgsRectangle extent = mSource->sourceExtent();
259 double delta = extent.width() * mBuffer / 100.0;
260 extent.setXMinimum( extent.xMinimum() - delta );
261 extent.setXMaximum( extent.xMaximum() + delta );
262 delta = extent.height() * mBuffer / 100.0;
263 extent.setYMinimum( extent.yMinimum() - delta );
264 extent.setYMaximum( extent.yMaximum() + delta );
265 const QgsGeometry clippingGeom = QgsGeometry::fromRect( extent );
266
267 QgsGeometry allPoints = QgsGeometry( std::move( points ) );
268 const QgsGeometry voronoiDiagram = allPoints.voronoiDiagram( clippingGeom, mTolerance );
269
270 if ( !voronoiDiagram.isEmpty() )
271 {
272 std::unique_ptr<QgsGeometryEngine> engine;
273 std::unique_ptr<QgsGeometryEngine> extentEngine( QgsGeometry::createGeometryEngine( clippingGeom.constGet() ) );
274 const QVector<QgsGeometry> collection = voronoiDiagram.asGeometryCollection();
275 for ( int i = 0; i < collection.length(); i++ )
276 {
277 if ( feedback->isCanceled() )
278 {
279 break;
280 }
281 QgsFeature f;
282 f.setFields( fields );
283 f.setGeometry( QgsGeometry( extentEngine->intersection( collection[i].constGet() ) ) );
284 f.setAttributes( QgsAttributes() << i );
285 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
286 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
287 feedback->setProgress( i * step );
288 }
289 }
290
291 sink->finalize();
292
293 return dest;
294}
295
@ VectorPoint
Vector point layers.
Definition qgis.h:3605
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3607
@ Polygon
Polygons.
Definition qgis.h:368
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3782
@ Point
Point.
Definition qgis.h:282
@ Polygon
Polygon.
Definition qgis.h:284
@ Double
Double/float values.
Definition qgis.h:3875
Abstract base class for all geometries.
virtual const QgsAbstractGeometry * simplifiedTypeRef() const
Returns a reference to the simplest lossless representation of this geometry, e.g.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
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:60
QgsAttributes attributes
Definition qgsfeature.h:69
QgsFeatureId id
Definition qgsfeature.h:68
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:71
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:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
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:76
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...
bool convertGeometryCollectionToSubclass(Qgis::GeometryType geomType)
Converts geometry collection to a the desired geometry type subclass (multi-point,...
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 Q_INVOKABLE bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.
T qgsgeometry_cast(QgsAbstractGeometry *geom)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features