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