QGIS API Documentation  3.6.0-Noosa (5873452)
qgsgeometryoverlapcheck.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsgeometryoverlapcheck.cpp
3  ---------------------
4  begin : September 2015
5  copyright : (C) 2014 by Sandro Mani / Sourcepole AG
6  email : smani at sourcepole dot ch
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 
17 #include "qgsgeometryengine.h"
19 #include "qgsfeaturepool.h"
20 #include "qgsvectorlayer.h"
21 #include "qgsfeedback.h"
22 
23 QgsGeometryOverlapCheck::QgsGeometryOverlapCheck( const QgsGeometryCheckContext *context, const QVariantMap &configuration )
24  : QgsGeometryCheck( context, configuration )
25  , mOverlapThresholdMapUnits( configurationValue<double>( QStringLiteral( "maxOverlapArea" ) ) )
26 
27 {
28 
29 }
30 
31 void QgsGeometryOverlapCheck::collectErrors( const QMap<QString, QgsFeaturePool *> &featurePools, QList<QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids ) const
32 {
33  QMap<QString, QgsFeatureIds> featureIds = ids.isEmpty() ? allLayerFeatureIds( featurePools ) : ids.toMap();
34  const QgsGeometryCheckerUtils::LayerFeatures layerFeaturesA( featurePools, featureIds, compatibleGeometryTypes(), feedback, mContext, true );
35  QList<QString> layerIds = featureIds.keys();
36  for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeatureA : layerFeaturesA )
37  {
38  if ( feedback && feedback->isCanceled() )
39  break;
40 
41  // Ensure each pair of layers only gets compared once: remove the current layer from the layerIds, but add it to the layerList for layerFeaturesB
42  layerIds.removeOne( layerFeatureA.layer()->id() );
43 
44  QgsRectangle bboxA = layerFeatureA.geometry().constGet()->boundingBox();
45  std::unique_ptr< QgsGeometryEngine > geomEngineA = QgsGeometryCheckerUtils::createGeomEngine( layerFeatureA.geometry().constGet(), mContext->tolerance );
46  if ( !geomEngineA->isValid() )
47  {
48  messages.append( tr( "Overlap check failed for (%1): the geometry is invalid" ).arg( layerFeatureA.id() ) );
49  continue;
50  }
51 
52  const QgsGeometryCheckerUtils::LayerFeatures layerFeaturesB( featurePools, QList<QString>() << layerFeatureA.layer()->id() << layerIds, bboxA, compatibleGeometryTypes(), mContext );
53  for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeatureB : layerFeaturesB )
54  {
55  if ( feedback && feedback->isCanceled() )
56  break;
57 
58  // > : only report overlaps within same layer once
59  if ( layerFeatureA.layer()->id() == layerFeatureB.layer()->id() && layerFeatureB.feature().id() >= layerFeatureA.feature().id() )
60  {
61  continue;
62  }
63  QString errMsg;
64  if ( geomEngineA->overlaps( layerFeatureB.geometry().constGet(), &errMsg ) )
65  {
66  std::unique_ptr<QgsAbstractGeometry> interGeom( geomEngineA->intersection( layerFeatureB.geometry().constGet() ) );
67  if ( interGeom && !interGeom->isEmpty() )
68  {
69  QgsGeometryCheckerUtils::filter1DTypes( interGeom.get() );
70  for ( int iPart = 0, nParts = interGeom->partCount(); iPart < nParts; ++iPart )
71  {
72  QgsAbstractGeometry *interPart = QgsGeometryCheckerUtils::getGeomPart( interGeom.get(), iPart );
73  double area = interPart->area();
74  if ( area > mContext->reducedTolerance && ( area < mOverlapThresholdMapUnits || mOverlapThresholdMapUnits == 0.0 ) )
75  {
76  errors.append( new QgsGeometryOverlapCheckError( this, layerFeatureA, QgsGeometry( interPart->clone() ), interPart->centroid(), area, layerFeatureB ) );
77  }
78  }
79  }
80  else if ( !errMsg.isEmpty() )
81  {
82  messages.append( tr( "Overlap check between features %1 and %2 %3" ).arg( layerFeatureA.id(), layerFeatureB.id(), errMsg ) );
83  }
84  }
85  }
86  }
87 }
88 
89 void QgsGeometryOverlapCheck::fixError( const QMap<QString, QgsFeaturePool *> &featurePools, QgsGeometryCheckError *error, int method, const QMap<QString, int> & /*mergeAttributeIndices*/, Changes &changes ) const
90 {
91  QString errMsg;
92  QgsGeometryOverlapCheckError *overlapError = static_cast<QgsGeometryOverlapCheckError *>( error );
93 
94  QgsFeaturePool *featurePoolA = featurePools[ overlapError->layerId() ];
95  QgsFeaturePool *featurePoolB = featurePools[ overlapError->overlappedFeature().layerId() ];
96  QgsFeature featureA;
97  QgsFeature featureB;
98  if ( !featurePoolA->getFeature( overlapError->featureId(), featureA ) ||
99  !featurePoolB->getFeature( overlapError->overlappedFeature().featureId(), featureB ) )
100  {
101  error->setObsolete();
102  return;
103  }
104 
105  // Check if error still applies
106  QgsGeometryCheckerUtils::LayerFeature layerFeatureA( featurePoolA, featureA, mContext, true );
107  QgsGeometryCheckerUtils::LayerFeature layerFeatureB( featurePoolB, featureB, mContext, true );
108  std::unique_ptr< QgsGeometryEngine > geomEngineA = QgsGeometryCheckerUtils::createGeomEngine( layerFeatureA.geometry().constGet(), mContext->reducedTolerance );
109 
110  if ( !geomEngineA->overlaps( layerFeatureB.geometry().constGet() ) )
111  {
112  error->setObsolete();
113  return;
114  }
115  std::unique_ptr< QgsAbstractGeometry > interGeom( geomEngineA->intersection( layerFeatureB.geometry().constGet(), &errMsg ) );
116  if ( !interGeom )
117  {
118  error->setFixFailed( tr( "Failed to compute intersection between overlapping features: %1" ).arg( errMsg ) );
119  return;
120  }
121 
122  // Search which overlap part this error parametrizes (using fuzzy-matching of the area and centroid...)
123  QgsAbstractGeometry *interPart = nullptr;
124  for ( int iPart = 0, nParts = interGeom->partCount(); iPart < nParts; ++iPart )
125  {
126  QgsAbstractGeometry *part = QgsGeometryCheckerUtils::getGeomPart( interGeom.get(), iPart );
127  if ( std::fabs( part->area() - overlapError->value().toDouble() ) < mContext->reducedTolerance &&
129  {
130  interPart = part;
131  break;
132  }
133  }
134  if ( !interPart || interPart->isEmpty() )
135  {
136  error->setObsolete();
137  return;
138  }
139 
140  // Fix error
141  if ( method == NoChange )
142  {
143  error->setFixed( method );
144  }
145  else if ( method == Subtract )
146  {
147  std::unique_ptr< QgsAbstractGeometry > diff1( geomEngineA->difference( interPart, &errMsg ) );
148  if ( !diff1 || diff1->isEmpty() )
149  {
150  diff1.reset();
151  }
152  else
153  {
155  }
156  std::unique_ptr< QgsGeometryEngine > geomEngineB = QgsGeometryCheckerUtils::createGeomEngine( layerFeatureB.geometry().constGet(), mContext->reducedTolerance );
157  std::unique_ptr< QgsAbstractGeometry > diff2( geomEngineB->difference( interPart, &errMsg ) );
158  if ( !diff2 || diff2->isEmpty() )
159  {
160  diff2.reset();
161  }
162  else
163  {
165  }
166  double shared1 = diff1 ? QgsGeometryCheckerUtils::sharedEdgeLength( diff1.get(), interPart, mContext->reducedTolerance ) : 0;
167  double shared2 = diff2 ? QgsGeometryCheckerUtils::sharedEdgeLength( diff2.get(), interPart, mContext->reducedTolerance ) : 0;
168  if ( !diff1 || !diff2 || shared1 == 0. || shared2 == 0. )
169  {
170  error->setFixFailed( tr( "Could not find shared edges between intersection and overlapping features" ) );
171  }
172  else
173  {
174  if ( shared1 < shared2 )
175  {
178  featureA.setGeometry( QgsGeometry( std::move( diff1 ) ) );
179 
180  changes[error->layerId()][featureA.id()].append( Change( ChangeFeature, ChangeChanged ) );
181  featurePoolA->updateFeature( featureA );
182  }
183  else
184  {
187  featureB.setGeometry( QgsGeometry( std::move( diff2 ) ) );
188 
189  changes[overlapError->overlappedFeature().layerId()][featureB.id()].append( Change( ChangeFeature, ChangeChanged ) );
190  featurePoolB->updateFeature( featureB );
191  }
192 
193  error->setFixed( method );
194  }
195  }
196  else
197  {
198  error->setFixFailed( tr( "Unknown method" ) );
199  }
200 }
201 
203 {
204  static QStringList methods = QStringList()
205  << tr( "Remove overlapping area from neighboring polygon with shortest shared edge" )
206  << tr( "No action" );
207  return methods;
208 }
209 
211 {
212  return factoryDescription();
213 }
214 
216 {
217  return factoryId();
218 }
219 
220 QgsGeometryCheck::Flags QgsGeometryOverlapCheck::flags() const
221 {
222  return factoryFlags();
223 }
224 
226 QString QgsGeometryOverlapCheck::factoryDescription()
227 {
228  return tr( "Overlap" );
229 }
230 
231 QgsGeometryCheck::CheckType QgsGeometryOverlapCheck::factoryCheckType()
232 {
234 }
235 
236 QString QgsGeometryOverlapCheck::factoryId()
237 {
238  return QStringLiteral( "QgsGeometryOverlapCheck" );
239 }
240 
241 QgsGeometryCheck::Flags QgsGeometryOverlapCheck::factoryFlags()
242 {
244 }
245 
246 QList<QgsWkbTypes::GeometryType> QgsGeometryOverlapCheck::factoryCompatibleGeometryTypes()
247 {
249 }
250 
251 bool QgsGeometryOverlapCheck::factoryIsCompatible( QgsVectorLayer *layer ) SIP_SKIP
252 {
253  return factoryCompatibleGeometryTypes().contains( layer->geometryType() );
254 }
255 
257 QgsGeometryOverlapCheckError::QgsGeometryOverlapCheckError( const QgsGeometryCheck *check, const QgsGeometryCheckerUtils::LayerFeature &layerFeature, const QgsGeometry &geometry, const QgsPointXY &errorLocation, const QVariant &value, const QgsGeometryCheckerUtils::LayerFeature &overlappedFeature )
258  : QgsGeometryCheckError( check, layerFeature.layer()->id(), layerFeature.feature().id(), geometry, errorLocation, QgsVertexId(), value, ValueArea )
259  , mOverlappedFeature( OverlappedFeature( overlappedFeature.layer(), overlappedFeature.feature().id() ) )
260 {
261 
262 }
263 
265 {
266  return QCoreApplication::translate( "QgsGeometryTypeCheckError", "Overlap with %1 at feature %2" ).arg( mOverlappedFeature.layerName(), QString::number( mOverlappedFeature.featureId() ) );
267 }
QgsFeatureId id
Definition: qgsfeature.h:64
A rectangle specified with double values.
Definition: qgsrectangle.h:41
Subtract the overlap region from the polygon.
static bool pointsFuzzyEqual(const QgsPointXY &p1, const QgsPointXY &p2, double tol)
Determine whether two points are equal up to the specified tolerance.
virtual bool isEmpty() const
Returns true if the geometry is empty.
bool getFeature(QgsFeatureId id, QgsFeature &feature, QgsFeedback *feedback=nullptr)
Retrieves the feature with the specified id into feature.
QgsGeometryOverlapCheck(const QgsGeometryCheckContext *context, const QVariantMap &configuration)
Checks for overlapping polygons.
static QgsAbstractGeometry * getGeomPart(QgsAbstractGeometry *geom, int partIdx)
const QgsCoordinateReferenceSystem mapCrs
The coordinate system in which calculations should be done.
QgsPointXY transform(const QgsPointXY &point, TransformDirection direction=ForwardTransform) const SIP_THROW(QgsCsException)
Transform the point from the source CRS to the destination CRS.
A class to represent a 2D point.
Definition: qgspointxy.h:43
const QgsPointXY & location() const
The location of the error in map units.
QMap< QString, QgsFeatureIds > toMap() const
Contains a set of layers and feature ids in those layers to pass to a geometry check.
CheckType
The type of a check.
QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:106
void fixError(const QMap< QString, QgsFeaturePool *> &featurePools, QgsGeometryCheckError *error, int method, const QMap< QString, int > &mergeAttributeIndices, Changes &changes) const override
Fix the error error with the specified method.
QList< QgsWkbTypes::GeometryType > compatibleGeometryTypes() const override
A list of geometry types for which this check can be performed.
void setObsolete()
Set the error status to obsolete.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:55
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
QStringList resolutionMethods() const override
Returns a list of descriptions for available resolutions for errors.
virtual void updateFeature(QgsFeature &feature)=0
Updates a feature in this pool.
void setFixFailed(const QString &reason)
Set the error status to failed and specify the reason for failure.
virtual QgsPoint centroid() const
Returns the centroid of the geometry.
Base class for feedback objects to be used for cancelation of something running in a worker thread...
Definition: qgsfeedback.h:44
Base configuration for geometry checks.
QgsGeometryCheck::Flags flags() const override
Flags for this geometry check.
static double sharedEdgeLength(const QgsAbstractGeometry *geom1, const QgsAbstractGeometry *geom2, double tol)
An error of a QgsGeometryOverlapCheck.
Utility class for identifying a unique vertex within a geometry.
#define SIP_SKIP
Definition: qgis_sip.h:119
const OverlappedFeature & overlappedFeature() const
Returns the overlapped feature.
QString description() const override
Returns a human readable description for this check.
A layer feature combination to uniquely identify and access a feature in a set of layers...
This class implements a geometry check.
virtual double area() const
Returns the area of the geometry.
Abstract base class for all geometries.
QMap< QString, QgsFeatureIds > allLayerFeatureIds(const QMap< QString, QgsFeaturePool *> &featurePools) const
Returns all layers and feature ids.
const QString & layerId() const
The id of the layer on which this error has been detected.
const double tolerance
The tolerance to allow for in geometry checks.
const QgsGeometryCheckContext * mContext
const double reducedTolerance
The tolerance to allow for in geometry checks.
A list of layers and feature ids for each of these layers.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static void filter1DTypes(QgsAbstractGeometry *geom)
void collectErrors(const QMap< QString, QgsFeaturePool *> &featurePools, QList< QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids=LayerFeatureIds()) const override
The main worker method.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
Transform from destination to source CRS.
A feature pool is based on a vector layer and caches features.
QString id() const override
Returns an id for this check.
Descripts a change to fix a geometry.
void setFixed(int method)
Set the status to fixed and specify the method that has been used to fix the error.
void setGeometry(const QgsGeometry &geometry)
Set the feature&#39;s geometry.
Definition: qgsfeature.cpp:137
Class for doing transforms between two map coordinate systems.
const QgsCoordinateTransformContext transformContext
The coordinate transform context with which transformations will be done.
QgsFeatureId featureId() const
The id of the feature on which this error has been detected.
QgsCoordinateReferenceSystem crs() const
The coordinate reference system of this layer.
This represents an error reported by a geometry check.
static std::unique_ptr< QgsGeometryEngine > createGeomEngine(const QgsAbstractGeometry *geometry, double tolerance)
QString description() const override
The error description.
QVariant value() const
An additional value for the error.
Represents a vector layer which manages a vector based data sets.
Something has been updated.
QgsGeometryOverlapCheckError(const QgsGeometryCheck *check, const QgsGeometryCheckerUtils::LayerFeature &layerFeature, const QgsGeometry &geometry, const QgsPointXY &errorLocation, const QVariant &value, const QgsGeometryCheckerUtils::LayerFeature &overlappedFeature)
Creates a new overlap check error for check and the layerFeature combination.
This change happens on feature level.
This geometry check should be available in layer validation on the vector layer peroperties.
The check controls a whole layer (topology checks)
const QgsGeometry & geometry() const
Returns the geometry of this feature.