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