QGIS API Documentation 3.41.0-Master (3440c17df1d)
Loading...
Searching...
No Matches
qgsalgorithmdissolve.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmdissolve.cpp
3 ---------------------
4 begin : April 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson 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
21
22//
23// QgsCollectorAlgorithm
24//
25
26QVariantMap QgsCollectorAlgorithm::processCollection( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback,
27 const std::function<QgsGeometry( const QVector< QgsGeometry >& )> &collector, int maxQueueLength, Qgis::ProcessingFeatureSourceFlags sourceFlags, bool separateDisjoint )
28{
29 std::unique_ptr< QgsProcessingFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
30 if ( !source )
31 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
32
33 QString dest;
34 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(), QgsWkbTypes::multiType( source->wkbType() ), source->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
35
36 if ( !sink )
37 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
38
39 QVariantMap outputs;
40 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
41
42 const QStringList fields = parameterAsStrings( parameters, QStringLiteral( "FIELD" ), context );
43
44 const long count = source->featureCount();
45
46 if ( !( count > 0 ) )
47 return outputs;
48
49 QgsFeature f;
50 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest(), sourceFlags );
51
52 const double step = count > 0 ? 100.0 / count : 1;
53 int current = 0;
54
55 if ( fields.isEmpty() )
56 {
57 // dissolve all - not using fields
58 bool firstFeature = true;
59 // we dissolve geometries in blocks using unaryUnion
60 QVector< QgsGeometry > geomQueue;
61 QgsFeature outputFeature;
62
63 while ( it.nextFeature( f ) )
64 {
65 if ( feedback->isCanceled() )
66 {
67 break;
68 }
69
70 if ( firstFeature )
71 {
72 outputFeature = f;
73 firstFeature = false;
74 }
75
76 if ( f.hasGeometry() && !f.geometry().isEmpty() )
77 {
78 geomQueue.append( f.geometry() );
79 if ( maxQueueLength > 0 && geomQueue.length() > maxQueueLength )
80 {
81 // queue too long, combine it
82 const QgsGeometry tempOutputGeometry = collector( geomQueue );
83 geomQueue.clear();
84 geomQueue << tempOutputGeometry;
85 }
86 }
87
88 feedback->setProgress( current * step );
89 current++;
90 }
91
92 if ( geomQueue.isEmpty() )
93 {
94 outputFeature.clearGeometry();
95 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
96 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
97 }
98 else if ( !separateDisjoint )
99 {
100 outputFeature.setGeometry( collector( geomQueue ) );
101 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
102 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
103 }
104 else
105 {
106 const QgsGeometry combinedGeometry = collector( geomQueue );
107 for ( auto it = combinedGeometry.const_parts_begin(); it != combinedGeometry.const_parts_end(); ++it )
108 {
109 QgsGeometry partGeom( ( ( *it )->clone() ) );
110 partGeom.convertToMultiType();
111 outputFeature.setGeometry( partGeom );
112 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
113 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
114 }
115 }
116 }
117 else
118 {
119 QList< int > fieldIndexes;
120 fieldIndexes.reserve( fields.size() );
121 for ( const QString &field : fields )
122 {
123 const int index = source->fields().lookupField( field );
124 if ( index >= 0 )
125 fieldIndexes << index;
126 }
127
128 QHash< QVariant, QgsAttributes > attributeHash;
129 QHash< QVariant, QVector< QgsGeometry > > geometryHash;
130
131 while ( it.nextFeature( f ) )
132 {
133 if ( feedback->isCanceled() )
134 {
135 break;
136 }
137
138 QVariantList indexAttributes;
139 indexAttributes.reserve( fieldIndexes.size() );
140 for ( const int index : std::as_const( fieldIndexes ) )
141 {
142 indexAttributes << f.attribute( index );
143 }
144
145 if ( !attributeHash.contains( indexAttributes ) )
146 {
147 // keep attributes of first feature
148 attributeHash.insert( indexAttributes, f.attributes() );
149 }
150
151 if ( f.hasGeometry() && !f.geometry().isEmpty() )
152 {
153 geometryHash[ indexAttributes ].append( f.geometry() );
154 }
155 }
156
157 const int numberFeatures = attributeHash.count();
158 QHash< QVariant, QgsAttributes >::const_iterator attrIt = attributeHash.constBegin();
159 for ( ; attrIt != attributeHash.constEnd(); ++attrIt )
160 {
161 if ( feedback->isCanceled() )
162 {
163 break;
164 }
165
166 QgsFeature outputFeature;
167 outputFeature.setAttributes( attrIt.value() );
168 auto geometryHashIt = geometryHash.find( attrIt.key() );
169 if ( geometryHashIt != geometryHash.end() )
170 {
171 QgsGeometry geom = collector( geometryHashIt.value() );
172 if ( !geom.isMultipart() )
173 {
174 geom.convertToMultiType();
175 }
176 if ( !separateDisjoint )
177 {
178 outputFeature.setGeometry( geom );
179 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
180 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
181 }
182 else
183 {
184 for ( auto it = geom.const_parts_begin(); it != geom.const_parts_end(); ++it )
185 {
186 QgsGeometry partGeom( ( ( *it )->clone() ) );
187 partGeom.convertToMultiType();
188 outputFeature.setGeometry( partGeom );
189 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
190 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
191 }
192 }
193 }
194 else
195 {
196 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
197 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
198 }
199
200 feedback->setProgress( current * 100.0 / numberFeatures );
201 current++;
202 }
203 }
204
205 sink->finalize();
206
207 return outputs;
208}
209
210
211//
212// QgsDissolveAlgorithm
213//
214
215QString QgsDissolveAlgorithm::name() const
216{
217 return QStringLiteral( "dissolve" );
218}
219
220QString QgsDissolveAlgorithm::displayName() const
221{
222 return QObject::tr( "Dissolve" );
223}
224
225QStringList QgsDissolveAlgorithm::tags() const
226{
227 return QObject::tr( "dissolve,union,combine,collect" ).split( ',' );
228}
229
230QString QgsDissolveAlgorithm::group() const
231{
232 return QObject::tr( "Vector geometry" );
233}
234
235QString QgsDissolveAlgorithm::groupId() const
236{
237 return QStringLiteral( "vectorgeometry" );
238}
239
240
241void QgsDissolveAlgorithm::initAlgorithm( const QVariantMap & )
242{
243 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ) ) );
244 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD" ), QObject::tr( "Dissolve field(s)" ), QVariant(),
245 QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Any, true, true ) );
246
247 std::unique_ptr< QgsProcessingParameterBoolean > disjointParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "SEPARATE_DISJOINT" ),
248 QObject::tr( "Keep disjoint features separate" ), false );
249 disjointParam->setFlags( disjointParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
250 addParameter( disjointParam.release() );
251
252 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Dissolved" ) ) );
253}
254
255QString QgsDissolveAlgorithm::shortHelpString() const
256{
257 return QObject::tr( "This algorithm takes a vector layer and combines their features into new features. One or more attributes can "
258 "be specified to dissolve features belonging to the same class (having the same value for the specified attributes), alternatively "
259 "all features can be dissolved in a single one.\n\n"
260 "All output geometries will be converted to multi geometries. "
261 "In case the input is a polygon layer, common boundaries of adjacent polygons being dissolved will get erased.\n\n"
262 "If enabled, the optional \"Keep disjoint features separate\" setting will cause features and parts that do not overlap or touch to be exported "
263 "as separate features (instead of parts of a single multipart feature)." );
264}
265
266Qgis::ProcessingAlgorithmDocumentationFlags QgsDissolveAlgorithm::documentationFlags() const
267{
269}
270
271QgsDissolveAlgorithm *QgsDissolveAlgorithm::createInstance() const
272{
273 return new QgsDissolveAlgorithm();
274}
275
276QVariantMap QgsDissolveAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
277{
278 const bool separateDisjoint = parameterAsBool( parameters, QStringLiteral( "SEPARATE_DISJOINT" ), context );
279
280 return processCollection( parameters, context, feedback, [ & ]( const QVector< QgsGeometry > &parts )->QgsGeometry
281 {
282 QgsGeometry result( QgsGeometry::unaryUnion( parts ) );
283 if ( QgsWkbTypes::geometryType( result.wkbType() ) == Qgis::GeometryType::Line )
284 result = result.mergeLines();
285 // Geos may fail in some cases, let's try a slower but safer approach
286 // See: https://github.com/qgis/QGIS/issues/28411 - Dissolve tool failing to produce outputs
287 if ( ! result.lastError().isEmpty() && parts.count() > 2 )
288 {
289 if ( feedback->isCanceled() )
290 return result;
291
292 feedback->pushDebugInfo( QObject::tr( "GEOS exception: taking the slower route ..." ) );
293 result = QgsGeometry();
294 for ( const auto &p : parts )
295 {
296 result = QgsGeometry::unaryUnion( QVector< QgsGeometry >() << result << p );
297 if ( QgsWkbTypes::geometryType( result.wkbType() ) == Qgis::GeometryType::Line )
298 result = result.mergeLines();
299 if ( feedback->isCanceled() )
300 return result;
301 }
302 }
303 if ( ! result.lastError().isEmpty() )
304 {
305 feedback->reportError( result.lastError(), true );
306 if ( result.isEmpty() )
307 throw QgsProcessingException( QObject::tr( "The algorithm returned no output." ) );
308 }
309 return result;
310 }, 10000, Qgis::ProcessingFeatureSourceFlags(), separateDisjoint );
311}
312
313//
314// QgsCollectAlgorithm
315//
316
317QString QgsCollectAlgorithm::name() const
318{
319 return QStringLiteral( "collect" );
320}
321
322QString QgsCollectAlgorithm::displayName() const
323{
324 return QObject::tr( "Collect geometries" );
325}
326
327QStringList QgsCollectAlgorithm::tags() const
328{
329 return QObject::tr( "union,combine,collect,multipart,parts,single" ).split( ',' );
330}
331
332QString QgsCollectAlgorithm::group() const
333{
334 return QObject::tr( "Vector geometry" );
335}
336
337QString QgsCollectAlgorithm::groupId() const
338{
339 return QStringLiteral( "vectorgeometry" );
340}
341
342QVariantMap QgsCollectAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
343{
344 return processCollection( parameters, context, feedback, []( const QVector< QgsGeometry > &parts )->QgsGeometry
345 {
346 return QgsGeometry::collectGeometry( parts );
348}
349
350
351void QgsCollectAlgorithm::initAlgorithm( const QVariantMap & )
352{
353 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ) ) );
354 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD" ), QObject::tr( "Unique ID fields" ), QVariant(),
355 QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Any, true, true ) );
356
357 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Collected" ) ) );
358}
359
360QString QgsCollectAlgorithm::shortHelpString() const
361{
362 return QObject::tr( "This algorithm takes a vector layer and collects its geometries into new multipart geometries. One or more attributes can "
363 "be specified to collect only geometries belonging to the same class (having the same value for the specified attributes), alternatively "
364 "all geometries can be collected." ) +
365 QStringLiteral( "\n\n" ) +
366 QObject::tr( "All output geometries will be converted to multi geometries, even those with just a single part. "
367 "This algorithm does not dissolve overlapping geometries - they will be collected together without modifying the shape of each geometry part." ) +
368 QStringLiteral( "\n\n" ) +
369 QObject::tr( "See the 'Promote to multipart' or 'Aggregate' algorithms for alternative options." );
370}
371
372Qgis::ProcessingAlgorithmDocumentationFlags QgsCollectAlgorithm::documentationFlags() const
373{
375}
376
377QgsCollectAlgorithm *QgsCollectAlgorithm::createInstance() const
378{
379 return new QgsCollectAlgorithm();
380}
381
382
383
384
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3367
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
QFlags< ProcessingFeatureSourceFlag > ProcessingFeatureSourceFlags
Flags which control how QgsProcessingFeatureSource fetches features.
Definition qgis.h:3444
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...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
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
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
void clearGeometry()
Removes any geometry associated with the feature.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
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
A geometry is the spatial representation of a feature.
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
static QgsGeometry collectGeometry(const QVector< QgsGeometry > &geometries)
Creates a new multipart geometry from a list of QgsGeometry objects.
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
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.
virtual void pushDebugInfo(const QString &info)
Pushes an informational message containing debugging helpers from the algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Qgis::WkbType multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.