QGIS API Documentation  3.10.0-A Coruña (6c816b4204)
qgsoverlayutils.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsoverlayutils.cpp
3  ---------------------
4  Date : April 2018
5  Copyright : (C) 2018 by Martin Dobias
6  Email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
16 #include "qgsoverlayutils.h"
17 
18 #include "qgsgeometryengine.h"
19 #include "qgsprocessingalgorithm.h"
20 
22 
23 bool QgsOverlayUtils::sanitizeIntersectionResult( QgsGeometry &geom, QgsWkbTypes::GeometryType geometryType )
24 {
25  if ( geom.isNull() )
26  {
27  // TODO: not sure if this ever happens - if it does, that means GEOS failed badly - would be good to have a test for such situation
28  throw QgsProcessingException( QStringLiteral( "%1\n\n%2" ).arg( QObject::tr( "GEOS geoprocessing error: intersection failed." ), geom.lastError() ) );
29  }
30 
31  // Intersection of geometries may give use also geometries we do not want in our results.
32  // For example, two square polygons touching at the corner have a point as the intersection, but no area.
33  // In other cases we may get a mixture of geometries in the output - we want to keep only the expected types.
35  {
36  // try to filter out irrelevant parts with different geometry type than what we want
37  geom.convertGeometryCollectionToSubclass( geometryType );
38  if ( geom.isEmpty() )
39  return false;
40  }
41 
42  if ( QgsWkbTypes::geometryType( geom.wkbType() ) != geometryType )
43  {
44  // we can't make use of this resulting geometry
45  return false;
46  }
47 
48  // some data providers are picky about the geometries we pass to them: we can't add single-part geometries
49  // when we promised multi-part geometries, so ensure we have the right type
50  geom.convertToMultiType();
51 
52  return true;
53 }
54 
55 
57 static bool sanitizeDifferenceResult( QgsGeometry &geom )
58 {
59  if ( geom.isNull() )
60  {
61  // TODO: not sure if this ever happens - if it does, that means GEOS failed badly - would be good to have a test for such situation
62  throw QgsProcessingException( QStringLiteral( "%1\n\n%2" ).arg( QObject::tr( "GEOS geoprocessing error: difference failed." ), geom.lastError() ) );
63  }
64 
65  // if geomB covers the whole source geometry, we get an empty geometry collection
66  if ( geom.isEmpty() )
67  return false;
68 
69  // some data providers are picky about the geometries we pass to them: we can't add single-part geometries
70  // when we promised multi-part geometries, so ensure we have the right type
71  geom.convertToMultiType();
72 
73  return true;
74 }
75 
76 
77 void QgsOverlayUtils::difference( const QgsFeatureSource &sourceA, const QgsFeatureSource &sourceB, QgsFeatureSink &sink, QgsProcessingContext &context, QgsProcessingFeedback *feedback, int &count, int totalCount, QgsOverlayUtils::DifferenceOutput outputAttrs )
78 {
79  QgsFeatureRequest requestB;
80  requestB.setNoAttributes();
81  if ( outputAttrs != OutputBA )
82  requestB.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() );
83  QgsSpatialIndex indexB( sourceB.getFeatures( requestB ), feedback );
84 
85  int fieldsCountA = sourceA.fields().count();
86  int fieldsCountB = sourceB.fields().count();
87  QgsAttributes attrs;
88  attrs.resize( outputAttrs == OutputA ? fieldsCountA : ( fieldsCountA + fieldsCountB ) );
89 
90  if ( totalCount == 0 )
91  totalCount = 1; // avoid division by zero
92 
93  QgsFeature featA;
94  QgsFeatureRequest requestA;
95  requestA.setInvalidGeometryCheck( context.invalidGeometryCheck() );
96  if ( outputAttrs == OutputBA )
97  requestA.setDestinationCrs( sourceB.sourceCrs(), context.transformContext() );
98  QgsFeatureIterator fitA = sourceA.getFeatures( requestA );
99  while ( fitA.nextFeature( featA ) )
100  {
101  if ( feedback->isCanceled() )
102  break;
103 
104  if ( featA.hasGeometry() )
105  {
106  QgsGeometry geom( featA.geometry() );
107  QgsFeatureIds intersects = indexB.intersects( geom.boundingBox() ).toSet();
108 
109  QgsFeatureRequest request;
110  request.setFilterFids( intersects );
111  request.setNoAttributes();
112  if ( outputAttrs != OutputBA )
113  request.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() );
114 
115  std::unique_ptr< QgsGeometryEngine > engine;
116  if ( !intersects.isEmpty() )
117  {
118  // use prepared geometries for faster intersection tests
119  engine.reset( QgsGeometry::createGeometryEngine( geom.constGet() ) );
120  engine->prepareGeometry();
121  }
122 
123  QVector<QgsGeometry> geometriesB;
124  QgsFeature featB;
125  QgsFeatureIterator fitB = sourceB.getFeatures( request );
126  while ( fitB.nextFeature( featB ) )
127  {
128  if ( feedback->isCanceled() )
129  break;
130 
131  if ( engine->intersects( featB.geometry().constGet() ) )
132  geometriesB << featB.geometry();
133  }
134 
135  if ( !geometriesB.isEmpty() )
136  {
137  QgsGeometry geomB = QgsGeometry::unaryUnion( geometriesB );
138  if ( !geomB.lastError().isEmpty() )
139  {
140  // This may happen if input geometries from a layer do not line up well (for example polygons
141  // that are nearly touching each other, but there is a very tiny overlap or gap at one of the edges).
142  // It is possible to get rid of this issue in two steps:
143  // 1. snap geometries with a small tolerance (e.g. 1cm) using QgsGeometrySnapperSingleSource
144  // 2. fix geometries (removes polygons collapsed to lines etc.) using MakeValid
145  throw QgsProcessingException( QStringLiteral( "%1\n\n%2" ).arg( QObject::tr( "GEOS geoprocessing error: unary union failed." ), geomB.lastError() ) );
146  }
147  geom = geom.difference( geomB );
148  }
149 
150  if ( !sanitizeDifferenceResult( geom ) )
151  continue;
152 
153  const QgsAttributes attrsA( featA.attributes() );
154  switch ( outputAttrs )
155  {
156  case OutputA:
157  attrs = attrsA;
158  break;
159  case OutputAB:
160  for ( int i = 0; i < fieldsCountA; ++i )
161  attrs[i] = attrsA[i];
162  break;
163  case OutputBA:
164  for ( int i = 0; i < fieldsCountA; ++i )
165  attrs[i + fieldsCountB] = attrsA[i];
166  break;
167  }
168 
169  QgsFeature outFeat;
170  outFeat.setGeometry( geom );
171  outFeat.setAttributes( attrs );
172  sink.addFeature( outFeat, QgsFeatureSink::FastInsert );
173  }
174  else
175  {
176  // TODO: should we write out features that do not have geometry?
177  sink.addFeature( featA, QgsFeatureSink::FastInsert );
178  }
179 
180  ++count;
181  feedback->setProgress( count / ( double ) totalCount * 100. );
182  }
183 }
184 
185 
186 void QgsOverlayUtils::intersection( const QgsFeatureSource &sourceA, const QgsFeatureSource &sourceB, QgsFeatureSink &sink, QgsProcessingContext &context, QgsProcessingFeedback *feedback, int &count, int totalCount, const QList<int> &fieldIndicesA, const QList<int> &fieldIndicesB )
187 {
189  int attrCount = fieldIndicesA.count() + fieldIndicesB.count();
190 
191  QgsFeatureRequest request;
192  request.setNoAttributes();
193  request.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() );
194 
195  QgsFeature outFeat;
196  QgsSpatialIndex indexB( sourceB.getFeatures( request ), feedback );
197 
198  if ( totalCount == 0 )
199  totalCount = 1; // avoid division by zero
200 
201  QgsFeature featA;
202  QgsFeatureIterator fitA = sourceA.getFeatures( QgsFeatureRequest().setSubsetOfAttributes( fieldIndicesA ) );
203  while ( fitA.nextFeature( featA ) )
204  {
205  if ( feedback->isCanceled() )
206  break;
207 
208  if ( !featA.hasGeometry() )
209  continue;
210 
211  QgsGeometry geom( featA.geometry() );
212  QgsFeatureIds intersects = indexB.intersects( geom.boundingBox() ).toSet();
213 
214  QgsFeatureRequest request;
215  request.setFilterFids( intersects );
216  request.setDestinationCrs( sourceA.sourceCrs(), context.transformContext() );
217  request.setSubsetOfAttributes( fieldIndicesB );
218 
219  std::unique_ptr< QgsGeometryEngine > engine;
220  if ( !intersects.isEmpty() )
221  {
222  // use prepared geometries for faster intersection tests
223  engine.reset( QgsGeometry::createGeometryEngine( geom.constGet() ) );
224  engine->prepareGeometry();
225  }
226 
227  QgsAttributes outAttributes( attrCount );
228  const QgsAttributes attrsA( featA.attributes() );
229  for ( int i = 0; i < fieldIndicesA.count(); ++i )
230  outAttributes[i] = attrsA[fieldIndicesA[i]];
231 
232  QgsFeature featB;
233  QgsFeatureIterator fitB = sourceB.getFeatures( request );
234  while ( fitB.nextFeature( featB ) )
235  {
236  if ( feedback->isCanceled() )
237  break;
238 
239  QgsGeometry tmpGeom( featB.geometry() );
240  if ( !engine->intersects( tmpGeom.constGet() ) )
241  continue;
242 
243  QgsGeometry intGeom = geom.intersection( tmpGeom );
244  if ( !sanitizeIntersectionResult( intGeom, geometryType ) )
245  continue;
246 
247  const QgsAttributes attrsB( featB.attributes() );
248  for ( int i = 0; i < fieldIndicesB.count(); ++i )
249  outAttributes[fieldIndicesA.count() + i] = attrsB[fieldIndicesB[i]];
250 
251  outFeat.setGeometry( intGeom );
252  outFeat.setAttributes( outAttributes );
253  sink.addFeature( outFeat, QgsFeatureSink::FastInsert );
254  }
255 
256  ++count;
257  feedback->setProgress( count / ( double ) totalCount * 100. );
258  }
259 }
260 
261 void QgsOverlayUtils::resolveOverlaps( const QgsFeatureSource &source, QgsFeatureSink &sink, QgsProcessingFeedback *feedback )
262 {
263  int count = 0;
264  int totalCount = source.featureCount();
265  if ( totalCount == 0 )
266  return; // nothing to do here
267 
268  QgsFeatureId newFid = -1;
269 
271 
272  QgsFeatureRequest requestOnlyGeoms;
273  requestOnlyGeoms.setNoAttributes();
274 
275  QgsFeatureRequest requestOnlyAttrs;
276  requestOnlyAttrs.setFlags( QgsFeatureRequest::NoGeometry );
277 
278  QgsFeatureRequest requestOnlyIds;
279  requestOnlyIds.setFlags( QgsFeatureRequest::NoGeometry );
280  requestOnlyIds.setNoAttributes();
281 
282  // make a set of used feature IDs so that we do not try to reuse them for newly added features
283  QgsFeature f;
284  QSet<QgsFeatureId> fids;
285  QgsFeatureIterator it = source.getFeatures( requestOnlyIds );
286  while ( it.nextFeature( f ) )
287  {
288  if ( feedback->isCanceled() )
289  return;
290 
291  fids.insert( f.id() );
292  }
293 
294  QHash<QgsFeatureId, QgsGeometry> geometries;
295  QgsSpatialIndex index;
296  QHash<QgsFeatureId, QList<QgsFeatureId> > intersectingIds; // which features overlap a particular area
297 
298  // resolve intersections
299 
300  it = source.getFeatures( requestOnlyGeoms );
301  while ( it.nextFeature( f ) )
302  {
303  if ( feedback->isCanceled() )
304  return;
305 
306  QgsFeatureId fid1 = f.id();
307  QgsGeometry g1 = f.geometry();
308  std::unique_ptr< QgsGeometryEngine > g1engine;
309 
310  geometries.insert( fid1, g1 );
311  index.addFeature( f );
312 
313  QgsRectangle bbox( f.geometry().boundingBox() );
314  const QList<QgsFeatureId> ids = index.intersects( bbox );
315  for ( QgsFeatureId fid2 : ids )
316  {
317  if ( fid1 == fid2 )
318  continue;
319 
320  if ( !g1engine )
321  {
322  // use prepared geometries for faster intersection tests
323  g1engine.reset( QgsGeometry::createGeometryEngine( g1.constGet() ) );
324  g1engine->prepareGeometry();
325  }
326 
327  QgsGeometry g2 = geometries.value( fid2 );
328  if ( !g1engine->intersects( g2.constGet() ) )
329  continue;
330 
331  QgsGeometry geomIntersection = g1.intersection( g2 );
332  if ( !sanitizeIntersectionResult( geomIntersection, geometryType ) )
333  continue;
334 
335  //
336  // add intersection geometry
337  //
338 
339  // figure out new fid
340  while ( fids.contains( newFid ) )
341  --newFid;
342  fids.insert( newFid );
343 
344  geometries.insert( newFid, geomIntersection );
345  QgsFeature fx( newFid );
346  fx.setGeometry( geomIntersection );
347 
348  index.addFeature( fx );
349 
350  // figure out which feature IDs belong to this intersection. Some of the IDs can be of the newly
351  // created geometries - in such case we need to retrieve original IDs
352  QList<QgsFeatureId> lst;
353  if ( intersectingIds.contains( fid1 ) )
354  lst << intersectingIds.value( fid1 );
355  else
356  lst << fid1;
357  if ( intersectingIds.contains( fid2 ) )
358  lst << intersectingIds.value( fid2 );
359  else
360  lst << fid2;
361  intersectingIds.insert( newFid, lst );
362 
363  //
364  // update f1
365  //
366 
367  QgsGeometry g12 = g1.difference( g2 );
368 
369  index.deleteFeature( f );
370  geometries.remove( fid1 );
371 
372  if ( sanitizeDifferenceResult( g12 ) )
373  {
374  geometries.insert( fid1, g12 );
375 
376  QgsFeature f1x( fid1 );
377  f1x.setGeometry( g12 );
378  index.addFeature( f1x );
379  }
380 
381  //
382  // update f2
383  //
384 
385  QgsGeometry g21 = g2.difference( g1 );
386 
387  QgsFeature f2old( fid2 );
388  f2old.setGeometry( g2 );
389  index.deleteFeature( f2old );
390 
391  geometries.remove( fid2 );
392 
393  if ( sanitizeDifferenceResult( g21 ) )
394  {
395  geometries.insert( fid2, g21 );
396 
397  QgsFeature f2x( fid2 );
398  f2x.setGeometry( g21 );
399  index.addFeature( f2x );
400  }
401 
402  // update our temporary copy of the geometry to what is left from it
403  g1 = g12;
404  g1engine.reset();
405  }
406 
407  ++count;
408  feedback->setProgress( count / ( double ) totalCount * 100. );
409  }
410 
411  // release some memory of structures we don't need anymore
412 
413  fids.clear();
414  index = QgsSpatialIndex();
415 
416  // load attributes
417 
418  QHash<QgsFeatureId, QgsAttributes> attributesHash;
419  it = source.getFeatures( requestOnlyAttrs );
420  while ( it.nextFeature( f ) )
421  {
422  if ( feedback->isCanceled() )
423  return;
424 
425  attributesHash.insert( f.id(), f.attributes() );
426  }
427 
428  // store stuff in the sink
429 
430  for ( auto i = geometries.constBegin(); i != geometries.constEnd(); ++i )
431  {
432  if ( feedback->isCanceled() )
433  return;
434 
435  QgsFeature outFeature( i.key() );
436  outFeature.setGeometry( i.value() );
437 
438  if ( intersectingIds.contains( i.key() ) )
439  {
440  const QList<QgsFeatureId> ids = intersectingIds.value( i.key() );
441  for ( QgsFeatureId id : ids )
442  {
443  outFeature.setAttributes( attributesHash.value( id ) );
444  sink.addFeature( outFeature, QgsFeatureSink::FastInsert );
445  }
446  }
447  else
448  {
449  outFeature.setAttributes( attributesHash.value( i.key() ) );
450  sink.addFeature( outFeature, QgsFeatureSink::FastInsert );
451  }
452  }
453 }
454 
bool convertGeometryCollectionToSubclass(QgsWkbTypes::GeometryType geomType)
Converts geometry collection to a the desired geometry type subclass (multi-point, multi-linestring or multi-polygon).
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature&#39;s geometries.
QgsFeatureId id
Definition: qgsfeature.h:64
Wrapper for iterator of features from vector data provider or vector layer.
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
A rectangle specified with double values.
Definition: qgsrectangle.h:41
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:34
static Type multiType(Type type)
Returns the multi type for a WKB type.
Definition: qgswkbtypes.h:301
Base class for providing feedback from a processing algorithm.
virtual QgsFields fields() const =0
Returns the fields associated with features in the source.
QgsFeatureRequest & setInvalidGeometryCheck(InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
virtual QgsWkbTypes::Type wkbType() const =0
Returns the geometry type for features returned by this source.
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:63
An interface for objects which accept features via addFeature(s) methods.
qint64 QgsFeatureId
Definition: qgsfeatureid.h:25
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:122
void setAttributes(const QgsAttributes &attrs)
Sets the feature&#39;s attributes.
Definition: qgsfeature.cpp:127
QgsGeometry intersection(const QgsGeometry &geometry) const
Returns a geometry representing the points shared by this geometry and other.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:55
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:197
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
bool intersects(const QgsRectangle &rectangle) const
Returns true if this geometry exactly intersects with a rectangle.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest::InvalidGeometryCheck invalidGeometryCheck() const
Returns the behavior used for checking invalid geometries in input layers.
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
Definition: qgswkbtypes.h:812
This class wraps a request for features to a vector layer (or directly its vector data provider)...
Custom exception class for processing related exceptions.
Definition: qgsexception.h:82
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
virtual bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=nullptr)
Adds a single feature to the sink.
virtual QgsCoordinateReferenceSystem sourceCrs() const =0
Returns the coordinate reference system for features in the source.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
Definition: qgswkbtypes.h:139
bool deleteFeature(const QgsFeature &feature)
Removes a feature from the index.
QString lastError() const
Returns an error string referring to the last error encountered either when this geometry was created...
A spatial index for QgsFeature objects.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets feature IDs that should be fetched.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
An interface for objects which provide features via a getFeatures method.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature&#39;s geometry.
Definition: qgsfeature.cpp:137
QgsGeometry geometry
Definition: qgsfeature.h:67
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=nullptr) override
Adds a feature to the index.
bool nextFeature(QgsFeature &f)
Geometry is not required. It may still be returned if e.g. required for a filter condition.
A vector of attributes.
Definition: qgsattributes.h:57
static Type flatType(Type type)
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:576
Contains information about the context in which a processing algorithm is executed.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries)
Compute the unary union on a list of geometries.
QList< QgsFeatureId > intersects(const QgsRectangle &rectangle) const
Returns a list of features with a bounding box which intersects the specified rectangle.
QgsAttributes attributes
Definition: qgsfeature.h:65
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
virtual long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown...
QgsGeometry difference(const QgsGeometry &geometry) const
Returns a geometry representing the points making up this geometry that do not make up other...