QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
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(
133 it,
134 [&]( const QgsFeature &f ) -> bool {
135 i++;
136 if ( feedback->isCanceled() )
137 return false;
138
139 feedback->setProgress( i * step );
140
141 if ( !f.hasGeometry() )
142 return true;
143
144 const QgsAbstractGeometry *geom = f.geometry().constGet();
145 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
146 {
148 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
149 {
151 }
152 }
153 else
154 {
156 }
157
158 attributeCache.insert( f.id(), f.attributes() );
159
160 return true;
161 },
163 );
164
165 QgsRectangle extent = mSource->sourceExtent();
166 double delta = extent.width() * mBuffer / 100.0;
167 extent.setXMinimum( extent.xMinimum() - delta );
168 extent.setXMaximum( extent.xMaximum() + delta );
169 delta = extent.height() * mBuffer / 100.0;
170 extent.setYMinimum( extent.yMinimum() - delta );
171 extent.setYMaximum( extent.yMaximum() + delta );
172 const QgsGeometry clippingGeom = QgsGeometry::fromRect( extent );
173
174 const QgsGeometry voronoiDiagram = allPoints.voronoiDiagram( clippingGeom, mTolerance );
175
176 if ( !voronoiDiagram.isEmpty() )
177 {
178 std::unique_ptr<QgsGeometryEngine> engine;
179 std::unique_ptr<QgsGeometryEngine> extentEngine( QgsGeometry::createGeometryEngine( clippingGeom.constGet() ) );
180 const QVector<QgsGeometry> collection = voronoiDiagram.asGeometryCollection();
181 int i = 0;
182 for ( const QgsGeometry &collectionPart : collection )
183 {
184 if ( feedback->isCanceled() )
185 {
186 break;
187 }
188 QgsFeature f;
189 f.setFields( fields );
190
191 QgsGeometry voronoiClippedToExtent = QgsGeometry( extentEngine->intersection( collectionPart.constGet() ) );
193 if ( !voronoiClippedToExtent.isEmpty() )
194 {
195 f.setGeometry( QgsGeometry( voronoiClippedToExtent.constGet()->simplifiedTypeRef()->clone() ) );
196 const QList<QgsFeatureId> intersected = index.intersects( collectionPart.boundingBox() );
197 engine.reset( QgsGeometry::createGeometryEngine( collectionPart.constGet() ) );
198 engine->prepareGeometry();
199 for ( const QgsFeatureId id : intersected )
200 {
201 if ( engine->intersects( index.geometry( id ).constGet() ) )
202 {
203 f.setAttributes( attributeCache.value( id ) );
204 break;
205 }
206 }
207 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
208 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
209 }
210 feedback->setProgress( 50 + i * step );
211 i++;
212 }
213 }
214
215 sink->finalize();
216
217 return dest;
218}
219
220QString QgsVoronoiPolygonsAlgorithm::voronoiWithoutAttributes( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
221{
222 QgsFields fields;
223 fields.append( QgsField( u"id"_s, QMetaType::Type::LongLong ) );
224
225 QString dest;
226 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Polygon, mSource->sourceCrs() ) );
227 if ( !sink )
228 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
229
230 auto points = std::make_unique<QgsMultiPoint>();
231
232 long long i = 0;
233 const double step = mSource->featureCount() > 0 ? 50.0 / mSource->featureCount() : 1;
235 QgsFeature f;
236 while ( it.nextFeature( f ) )
237 {
238 i++;
239
240 if ( feedback->isCanceled() )
241 break;
242
243 feedback->setProgress( i * step );
244
245 if ( !f.hasGeometry() )
246 continue;
247
248 const QgsAbstractGeometry *geom = f.geometry().constGet();
249 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
250 {
252 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
253 {
254 points->addGeometry( qgsgeometry_cast<const QgsPoint *>( *pit )->clone() );
255 }
256 }
257 else
258 {
259 points->addGeometry( qgsgeometry_cast<const QgsPoint *>( geom )->clone() );
260 }
261 }
262
263 QgsRectangle extent = mSource->sourceExtent();
264 double delta = extent.width() * mBuffer / 100.0;
265 extent.setXMinimum( extent.xMinimum() - delta );
266 extent.setXMaximum( extent.xMaximum() + delta );
267 delta = extent.height() * mBuffer / 100.0;
268 extent.setYMinimum( extent.yMinimum() - delta );
269 extent.setYMaximum( extent.yMaximum() + delta );
270 const QgsGeometry clippingGeom = QgsGeometry::fromRect( extent );
271
272 QgsGeometry allPoints = QgsGeometry( std::move( points ) );
273 const QgsGeometry voronoiDiagram = allPoints.voronoiDiagram( clippingGeom, mTolerance );
274
275 if ( !voronoiDiagram.isEmpty() )
276 {
277 std::unique_ptr<QgsGeometryEngine> engine;
278 std::unique_ptr<QgsGeometryEngine> extentEngine( QgsGeometry::createGeometryEngine( clippingGeom.constGet() ) );
279 const QVector<QgsGeometry> collection = voronoiDiagram.asGeometryCollection();
280 for ( int i = 0; i < collection.length(); i++ )
281 {
282 if ( feedback->isCanceled() )
283 {
284 break;
285 }
286 QgsFeature f;
287 f.setFields( fields );
288 f.setGeometry( QgsGeometry( extentEngine->intersection( collection[i].constGet() ) ) );
289 f.setAttributes( QgsAttributes() << i );
290 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
291 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
292 feedback->setProgress( i * step );
293 }
294 }
295
296 sink->finalize();
297
298 return dest;
299}
300
@ VectorPoint
Vector point layers.
Definition qgis.h:3648
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3650
@ 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:3828
@ Point
Point.
Definition qgis.h:296
@ Polygon
Polygon.
Definition qgis.h:298
@ Double
Double/float values.
Definition qgis.h:3921
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: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:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
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