QGIS API Documentation 4.3.0-Master (2b7e6c9893e)
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 QGS_MARK_ALGORITHM_SOURCE
100
101 QString dest;
102 if ( mCopyAttributes )
103 {
104 dest = voronoiWithAttributes( parameters, context, feedback );
105 }
106 else
107 {
108 dest = voronoiWithoutAttributes( parameters, context, feedback );
109 }
110
111 QVariantMap outputs;
112 outputs.insert( u"OUTPUT"_s, dest );
113 return outputs;
114}
115
116QString QgsVoronoiPolygonsAlgorithm::voronoiWithAttributes( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
117{
118 const QgsFields fields = mSource->fields();
119
120 QString dest;
121 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Polygon, mSource->sourceCrs() ) );
122 if ( !sink )
123 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
124
125 QgsFeatureRequest request;
127
128 QgsGeometry allPoints;
129 QHash<QgsFeatureId, QgsAttributes> attributeCache;
130
131 long long i = 0;
132 const double step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
133
134 const QgsSpatialIndex index(
135 it,
136 [&]( const QgsFeature &f ) -> bool {
137 i++;
138 if ( feedback->isCanceled() )
139 return false;
140
141 feedback->setProgress( i * step );
142
143 if ( !f.hasGeometry() )
144 return true;
145
146 const QgsAbstractGeometry *geom = f.geometry().constGet();
147 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
148 {
150 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
151 {
153 }
154 }
155 else
156 {
158 }
159
160 attributeCache.insert( f.id(), f.attributes() );
161
162 return true;
163 },
165 );
166
167 QgsRectangle extent = mSource->sourceExtent();
168 double delta = extent.width() * mBuffer / 100.0;
169 extent.setXMinimum( extent.xMinimum() - delta );
170 extent.setXMaximum( extent.xMaximum() + delta );
171 delta = extent.height() * mBuffer / 100.0;
172 extent.setYMinimum( extent.yMinimum() - delta );
173 extent.setYMaximum( extent.yMaximum() + delta );
174 const QgsGeometry clippingGeom = QgsGeometry::fromRect( extent );
175
176 const QgsGeometry voronoiDiagram = allPoints.voronoiDiagram( clippingGeom, mTolerance );
177
178 if ( !voronoiDiagram.isEmpty() )
179 {
180 std::unique_ptr<QgsGeometryEngine> engine;
181 std::unique_ptr<QgsGeometryEngine> extentEngine( QgsGeometry::createGeometryEngine( clippingGeom.constGet() ) );
182 const QVector<QgsGeometry> collection = voronoiDiagram.asGeometryCollection();
183 int i = 0;
184 for ( const QgsGeometry &collectionPart : collection )
185 {
186 if ( feedback->isCanceled() )
187 {
188 break;
189 }
190 QgsFeature f;
191 f.setFields( fields );
192
193 QgsGeometry voronoiClippedToExtent = QgsGeometry( extentEngine->intersection( collectionPart.constGet(), nullptr, QgsGeometryParameters(), feedback ) );
195 if ( !voronoiClippedToExtent.isEmpty() )
196 {
197 f.setGeometry( QgsGeometry( voronoiClippedToExtent.constGet()->simplifiedTypeRef()->clone() ) );
198 const QList<QgsFeatureId> intersected = index.intersects( collectionPart.boundingBox() );
199 engine.reset( QgsGeometry::createGeometryEngine( collectionPart.constGet() ) );
200 engine->prepareGeometry();
201 for ( const QgsFeatureId id : intersected )
202 {
203 if ( engine->intersects( index.geometry( id ).constGet() ) )
204 {
205 f.setAttributes( attributeCache.value( id ) );
206 break;
207 }
208 }
209 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
210 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
211 else
212 feedback->featureAddedToSink( u"OUTPUT"_s );
213 }
214 feedback->setProgress( 50 + i * step );
215 i++;
216 }
217 }
218
219 sink->finalize();
220 feedback->featureSinkFinalized( u"OUTPUT"_s );
221
222 return dest;
223}
224
225QString QgsVoronoiPolygonsAlgorithm::voronoiWithoutAttributes( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
226{
227 QgsFields fields;
228 fields.append( QgsField( u"id"_s, QMetaType::Type::LongLong ) );
229
230 QString dest;
231 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Polygon, mSource->sourceCrs() ) );
232 if ( !sink )
233 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
234
235 auto points = std::make_unique<QgsMultiPoint>();
236
237 long long i = 0;
238 const double step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
240 QgsFeature f;
241 while ( it.nextFeature( f ) )
242 {
243 i++;
244
245 if ( feedback->isCanceled() )
246 break;
247
248 feedback->setProgress( i * step );
249
250 if ( !f.hasGeometry() )
251 continue;
252
253 const QgsAbstractGeometry *geom = f.geometry().constGet();
254 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
255 {
257 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
258 {
259 points->addGeometry( qgsgeometry_cast<const QgsPoint *>( *pit )->clone() );
260 }
261 }
262 else
263 {
264 points->addGeometry( qgsgeometry_cast<const QgsPoint *>( geom )->clone() );
265 }
266 }
267
268 QgsRectangle extent = mSource->sourceExtent();
269 double delta = extent.width() * mBuffer / 100.0;
270 extent.setXMinimum( extent.xMinimum() - delta );
271 extent.setXMaximum( extent.xMaximum() + delta );
272 delta = extent.height() * mBuffer / 100.0;
273 extent.setYMinimum( extent.yMinimum() - delta );
274 extent.setYMaximum( extent.yMaximum() + delta );
275 const QgsGeometry clippingGeom = QgsGeometry::fromRect( extent );
276
277 QgsGeometry allPoints = QgsGeometry( std::move( points ) );
278 const QgsGeometry voronoiDiagram = allPoints.voronoiDiagram( clippingGeom, mTolerance );
279
280 if ( !voronoiDiagram.isEmpty() )
281 {
282 std::unique_ptr<QgsGeometryEngine> engine;
283 std::unique_ptr<QgsGeometryEngine> extentEngine( QgsGeometry::createGeometryEngine( clippingGeom.constGet() ) );
284 const QVector<QgsGeometry> collection = voronoiDiagram.asGeometryCollection();
285 for ( int i = 0; i < collection.length(); i++ )
286 {
287 if ( feedback->isCanceled() )
288 {
289 break;
290 }
291 QgsFeature f;
292 f.setFields( fields );
293 f.setGeometry( QgsGeometry( extentEngine->intersection( collection[i].constGet(), nullptr, QgsGeometryParameters(), feedback ) ) );
294 f.setAttributes( QgsAttributes() << i );
295 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
296 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
297 else
298 feedback->featureAddedToSink( u"OUTPUT"_s );
299 feedback->setProgress( i * step );
300 }
301 }
302
303 sink->finalize();
304 feedback->featureSinkFinalized( u"OUTPUT"_s );
305
306 return dest;
307}
308
@ VectorPoint
Vector point layers.
Definition qgis.h:3752
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3754
@ Polygon
Polygons.
Definition qgis.h:382
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3932
@ Point
Point.
Definition qgis.h:296
@ Polygon
Polygon.
Definition qgis.h:298
@ Double
Double/float values.
Definition qgis.h:4025
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:64
QgsFeatureId id
Definition qgsfeature.h:63
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
Encapsulates parameters under which a geometry operation is performed.
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.
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 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