QGIS API Documentation 3.41.0-Master (af5edcb665c)
Loading...
Searching...
No Matches
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#include "qgsapplication.h"
23
24QgsGeometryOverlapCheck::QgsGeometryOverlapCheck( const QgsGeometryCheckContext *context, const QVariantMap &configuration )
25 : QgsGeometryCheck( context, configuration )
26 , mOverlapThresholdMapUnits( configurationValue<double>( QStringLiteral( "maxOverlapArea" ) ) )
27
28{
29}
30
31void QgsGeometryOverlapCheck::collectErrors( const QMap<QString, QgsFeaturePool *> &featurePools, QList<QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids ) const
32{
33 const 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 const QgsGeometry geomA = layerFeatureA.geometry();
45 const QgsRectangle bboxA = geomA.boundingBox();
46 std::unique_ptr<QgsGeometryEngine> geomEngineA( QgsGeometry::createGeometryEngine( geomA.constGet(), mContext->tolerance ) );
47 geomEngineA->prepareGeometry();
48 if ( !geomEngineA->isValid() )
49 {
50 messages.append( tr( "Overlap check failed for (%1): the geometry is invalid" ).arg( layerFeatureA.id() ) );
51 continue;
52 }
53
54 const QgsGeometryCheckerUtils::LayerFeatures layerFeaturesB( featurePools, QList<QString>() << layerFeatureA.layer()->id() << layerIds, bboxA, compatibleGeometryTypes(), mContext );
55 for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeatureB : layerFeaturesB )
56 {
57 if ( feedback && feedback->isCanceled() )
58 break;
59
60 // > : only report overlaps within same layer once
61 if ( layerFeatureA.layerId() == layerFeatureB.layerId() && layerFeatureB.feature().id() >= layerFeatureA.feature().id() )
62 {
63 continue;
64 }
65
66 QString errMsg;
67 const QgsGeometry geometryB = layerFeatureB.geometry();
68 const QgsAbstractGeometry *geomB = geometryB.constGet();
69 if ( geomEngineA->overlaps( geomB, &errMsg ) )
70 {
71 std::unique_ptr<QgsAbstractGeometry> interGeom( geomEngineA->intersection( geomB ) );
72 if ( interGeom && !interGeom->isEmpty() )
73 {
75 for ( int iPart = 0, nParts = interGeom->partCount(); iPart < nParts; ++iPart )
76 {
77 QgsAbstractGeometry *interPart = QgsGeometryCheckerUtils::getGeomPart( interGeom.get(), iPart );
78 const double area = interPart->area();
79 if ( area > mContext->reducedTolerance && ( area < mOverlapThresholdMapUnits || mOverlapThresholdMapUnits == 0.0 ) )
80 {
81 errors.append( new QgsGeometryOverlapCheckError( this, layerFeatureA, QgsGeometry( interPart->clone() ), interPart->centroid(), area, layerFeatureB ) );
82 }
83 }
84 }
85 else if ( !errMsg.isEmpty() )
86 {
87 messages.append( tr( "Overlap check between features %1 and %2 %3" ).arg( layerFeatureA.id(), layerFeatureB.id(), errMsg ) );
88 }
89 }
90 }
91 }
92}
93
94void QgsGeometryOverlapCheck::fixError( const QMap<QString, QgsFeaturePool *> &featurePools, QgsGeometryCheckError *error, int method, const QMap<QString, int> & /*mergeAttributeIndices*/, Changes &changes ) const
95{
96 QString errMsg;
97 QgsGeometryOverlapCheckError *overlapError = static_cast<QgsGeometryOverlapCheckError *>( error );
98
99 QgsFeaturePool *featurePoolA = featurePools[overlapError->layerId()];
100 QgsFeaturePool *featurePoolB = featurePools[overlapError->overlappedFeature().layerId()];
101 QgsFeature featureA;
102 QgsFeature featureB;
103 if ( !featurePoolA->getFeature( overlapError->featureId(), featureA ) || !featurePoolB->getFeature( overlapError->overlappedFeature().featureId(), featureB ) )
104 {
105 error->setObsolete();
106 return;
107 }
108
109 // Check if error still applies
110 const QgsGeometryCheckerUtils::LayerFeature layerFeatureA( featurePoolA, featureA, mContext, true );
111 const QgsGeometryCheckerUtils::LayerFeature layerFeatureB( featurePoolB, featureB, mContext, true );
112 const QgsGeometry geometryA = layerFeatureA.geometry();
113 std::unique_ptr<QgsGeometryEngine> geomEngineA( QgsGeometry::createGeometryEngine( geometryA.constGet(), mContext->tolerance ) );
114 geomEngineA->prepareGeometry();
115
116 const QgsGeometry geometryB = layerFeatureB.geometry();
117 if ( !geomEngineA->overlaps( geometryB.constGet() ) )
118 {
119 error->setObsolete();
120 return;
121 }
122 std::unique_ptr<QgsAbstractGeometry> interGeom( geomEngineA->intersection( geometryB.constGet(), &errMsg ) );
123 if ( !interGeom )
124 {
125 error->setFixFailed( tr( "Failed to compute intersection between overlapping features: %1" ).arg( errMsg ) );
126 return;
127 }
128
129 // Search which overlap part this error parametrizes (using fuzzy-matching of the area and centroid...)
130 QgsAbstractGeometry *interPart = nullptr;
131 for ( int iPart = 0, nParts = interGeom->partCount(); iPart < nParts; ++iPart )
132 {
133 QgsAbstractGeometry *part = QgsGeometryCheckerUtils::getGeomPart( interGeom.get(), iPart );
134 if ( std::fabs( part->area() - overlapError->value().toDouble() ) < mContext->reducedTolerance && QgsGeometryUtilsBase::fuzzyDistanceEqual( mContext->reducedTolerance, part->centroid().x(), part->centroid().y(), overlapError->location().x(), overlapError->location().y() ) ) // TODO: add fuzzyDistanceEqual in QgsAbstractGeometry classes
135 {
136 interPart = part;
137 break;
138 }
139 }
140 if ( !interPart || interPart->isEmpty() )
141 {
142 error->setObsolete();
143 return;
144 }
145
146 // Fix error
147 if ( method == NoChange )
148 {
149 error->setFixed( method );
150 }
151 else if ( method == Subtract )
152 {
153 std::unique_ptr<QgsGeometryEngine> geomEngineDiffA( QgsGeometry::createGeometryEngine( geometryA.constGet(), 0 ) );
154 std::unique_ptr<QgsAbstractGeometry> diff1( geomEngineDiffA->difference( interPart, &errMsg ) );
155 if ( !diff1 || diff1->isEmpty() )
156 {
157 diff1.reset();
158 }
159 else
160 {
162 }
163 std::unique_ptr<QgsGeometryEngine> geomEngineDiffB( QgsGeometry::createGeometryEngine( geometryB.constGet(), 0 ) );
164 std::unique_ptr<QgsAbstractGeometry> diff2( geomEngineDiffB->difference( interPart, &errMsg ) );
165 if ( !diff2 || diff2->isEmpty() )
166 {
167 diff2.reset();
168 }
169 else
170 {
172 }
173 const double shared1 = diff1 ? QgsGeometryCheckerUtils::sharedEdgeLength( diff1.get(), interPart, mContext->reducedTolerance ) : 0;
174 const double shared2 = diff2 ? QgsGeometryCheckerUtils::sharedEdgeLength( diff2.get(), interPart, mContext->reducedTolerance ) : 0;
175 if ( !diff1 || !diff2 || shared1 == 0. || shared2 == 0. )
176 {
177 error->setFixFailed( tr( "Could not find shared edges between intersection and overlapping features" ) );
178 }
179 else
180 {
181 if ( shared1 < shared2 )
182 {
183 const QgsCoordinateTransform ct( featurePoolA->crs(), mContext->mapCrs, mContext->transformContext );
184 diff1->transform( ct, Qgis::TransformDirection::Reverse );
185 featureA.setGeometry( QgsGeometry( std::move( diff1 ) ) );
186
187 changes[error->layerId()][featureA.id()].append( Change( ChangeFeature, ChangeChanged ) );
188 featurePoolA->updateFeature( featureA );
189 }
190 else
191 {
192 const QgsCoordinateTransform ct( featurePoolB->crs(), mContext->mapCrs, mContext->transformContext );
193 diff2->transform( ct, Qgis::TransformDirection::Reverse );
194 featureB.setGeometry( QgsGeometry( std::move( diff2 ) ) );
195
196 changes[overlapError->overlappedFeature().layerId()][featureB.id()].append( Change( ChangeFeature, ChangeChanged ) );
197 featurePoolB->updateFeature( featureB );
198 }
199
200 error->setFixed( method );
201 }
202 }
203 else
204 {
205 error->setFixFailed( tr( "Unknown method" ) );
206 }
207}
208
210{
211 static const QStringList methods = QStringList()
212 << tr( "Remove overlapping area from neighboring polygon with shortest shared edge" )
213 << tr( "No action" );
214 return methods;
215}
216
218{
219 return factoryDescription();
220}
221
223{
224 return factoryId();
225}
226
228{
229 return factoryFlags();
230}
231
233QString QgsGeometryOverlapCheck::factoryDescription()
234{
235 return tr( "Overlap" );
236}
237
238QgsGeometryCheck::CheckType QgsGeometryOverlapCheck::factoryCheckType()
239{
241}
242
243QString QgsGeometryOverlapCheck::factoryId()
244{
245 return QStringLiteral( "QgsGeometryOverlapCheck" );
246}
247
248QgsGeometryCheck::Flags QgsGeometryOverlapCheck::factoryFlags()
249{
251}
252
253QList<Qgis::GeometryType> QgsGeometryOverlapCheck::factoryCompatibleGeometryTypes()
254{
256}
257
258bool QgsGeometryOverlapCheck::factoryIsCompatible( QgsVectorLayer *layer ) SIP_SKIP
259{
260 return factoryCompatibleGeometryTypes().contains( layer->geometryType() );
261}
262
264QgsGeometryOverlapCheckError::QgsGeometryOverlapCheckError( const QgsGeometryCheck *check, const QgsGeometryCheckerUtils::LayerFeature &layerFeature, const QgsGeometry &geometry, const QgsPointXY &errorLocation, const QVariant &value, const QgsGeometryCheckerUtils::LayerFeature &overlappedFeature )
265 : QgsGeometryCheckError( check, layerFeature.layer()->id(), layerFeature.feature().id(), geometry, errorLocation, QgsVertexId(), value, ValueArea )
266 , mOverlappedFeature( OverlappedFeature( overlappedFeature.layer(), overlappedFeature.feature().id() ) )
267{
268}
269
271{
272 QgsGeometryOverlapCheckError *err = dynamic_cast<QgsGeometryOverlapCheckError *>( other );
273 return err && other->layerId() == layerId() && other->featureId() == featureId() && err->overlappedFeature() == overlappedFeature() && location().distanceCompare( other->location(), mCheck->context()->reducedTolerance ) && std::fabs( value().toDouble() - other->value().toDouble() ) < mCheck->context()->reducedTolerance;
274}
275
277{
278 QgsGeometryOverlapCheckError *err = dynamic_cast<QgsGeometryOverlapCheckError *>( other );
279 return err && other->layerId() == layerId() && other->featureId() == featureId() && err->overlappedFeature() == overlappedFeature();
280}
281
283{
284 if ( !QgsGeometryCheckError::handleChanges( changes ) )
285 {
286 return false;
287 }
288 if ( changes.value( mOverlappedFeature.layerId() ).contains( mOverlappedFeature.featureId() ) )
289 {
290 return false;
291 }
292 return true;
293}
294
296{
297 return QCoreApplication::translate( "QgsGeometryTypeCheckError", "Overlap with %1 at feature %2" ).arg( mOverlappedFeature.layerName(), QString::number( mOverlappedFeature.featureId() ) );
298}
299
300QMap<QString, QgsFeatureIds> QgsGeometryOverlapCheckError::involvedFeatures() const
301{
302 QMap<QString, QgsFeatureIds> features;
303 features[layerId()].insert( featureId() );
304 features[mOverlappedFeature.layerId()].insert( mOverlappedFeature.featureId() );
305 return features;
306}
307
309{
311 return QgsApplication::getThemeIcon( QStringLiteral( "/algorithms/mAlgorithmCheckGeometry.svg" ) );
312 else
313 return QgsApplication::getThemeIcon( QStringLiteral( "/checks/Overlap.svg" ) );
314}
@ Polygon
Polygons.
@ Reverse
Reverse/inverse transform (from destination to source)
Abstract base class for all geometries.
virtual bool isEmpty() const
Returns true if the geometry is empty.
virtual QgsPoint centroid() const
Returns the centroid of the geometry.
virtual double area() const
Returns the planar, 2-dimensional area of the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
Class for doing transforms between two map coordinate systems.
A feature pool is based on a vector layer and caches features.
virtual void updateFeature(QgsFeature &feature)=0
Updates a feature in this pool.
QgsCoordinateReferenceSystem crs() const
The coordinate reference system of this layer.
bool getFeature(QgsFeatureId id, QgsFeature &feature)
Retrieves the feature with the specified id into feature.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsFeatureId id
Definition qgsfeature.h:66
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
Base configuration for geometry checks.
const double reducedTolerance
The tolerance to allow for in geometry checks.
const QgsCoordinateTransformContext transformContext
The coordinate transform context with which transformations will be done.
const QgsCoordinateReferenceSystem mapCrs
The coordinate system in which calculations should be done.
const double tolerance
The tolerance to allow for in geometry checks.
This represents an error reported by a geometry check.
@ StatusFixed
The error is fixed.
Status status() const
The status of the error.
QgsFeatureId featureId() const
The id of the feature on which this error has been detected.
const QgsGeometryCheck * mCheck
void setFixed(int method)
Set the status to fixed and specify the method that has been used to fix the error.
void setFixFailed(const QString &reason)
Set the error status to failed and specify the reason for failure.
QVariant value() const
An additional value for the error.
void setObsolete()
Set the error status to obsolete.
const QString & layerId() const
The id of the layer on which this error has been detected.
virtual bool handleChanges(const QgsGeometryCheck::Changes &changes)
Apply a list of changes.
const QgsPointXY & location() const
The location of the error in map units.
This class implements a geometry check.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
QFlags< Flag > Flags
const QgsGeometryCheckContext * mContext
@ ChangeFeature
This change happens on feature level.
@ AvailableInValidation
This geometry check should be available in layer validation on the vector layer peroperties.
CheckType
The type of a check.
@ LayerCheck
The check controls a whole layer (topology checks)
QMap< QString, QgsFeatureIds > allLayerFeatureIds(const QMap< QString, QgsFeaturePool * > &featurePools) const
Returns all layers and feature ids.
@ ChangeChanged
Something has been updated.
const QgsGeometryCheckContext * context() const
Returns the context.
A layer feature combination to uniquely identify and access a feature in a set of layers.
QgsGeometry geometry() const
Returns the geometry of this feature.
Contains a set of layers and feature ids in those layers to pass to a geometry check.
static void filter1DTypes(QgsAbstractGeometry *geom)
static QgsAbstractGeometry * getGeomPart(QgsAbstractGeometry *geom, int partIdx)
static double sharedEdgeLength(const QgsAbstractGeometry *geom1, const QgsAbstractGeometry *geom2, double tol)
An error of a QgsGeometryOverlapCheck.
QMap< QString, QgsFeatureIds > involvedFeatures() const override
Returns a list of involved features.
QString description() const override
The error description.
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.
const OverlappedFeature & overlappedFeature() const
Returns the overlapped feature.
QIcon icon() const override
Returns an icon that should be shown for this kind of error.
bool closeMatch(QgsGeometryCheckError *other) const override
Check if this error is almost equal to other.
bool isEqual(QgsGeometryCheckError *other) const override
Check if this error is equal to other.
bool handleChanges(const QgsGeometryCheck::Changes &changes) override
Apply a list of changes.
void collectErrors(const QMap< QString, QgsFeaturePool * > &featurePools, QList< QgsGeometryCheckError * > &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids=LayerFeatureIds()) const override
The main worker method.
void fixError(const QMap< QString, QgsFeaturePool * > &featurePools, QgsGeometryCheckError *error, int method, const QMap< QString, int > &mergeAttributeIndices, Changes &changes) const override
Fixes the error error with the specified method.
Q_DECL_DEPRECATED QStringList resolutionMethods() const override
Returns a list of descriptions for available resolutions for errors.
QgsGeometryCheck::Flags flags() const override
Flags for this geometry check.
@ Subtract
Subtract the overlap region from the polygon.
@ NoChange
Do not change anything.
QList< Qgis::GeometryType > compatibleGeometryTypes() const override
A list of geometry types for which this check can be performed.
QgsGeometryOverlapCheck(const QgsGeometryCheckContext *context, const QVariantMap &configuration)
Checks for overlapping polygons.
QString id() const override
Returns an id for this check.
QString description() const override
Returns a human readable description for this check.
static bool fuzzyDistanceEqual(T epsilon, const Args &... args) noexcept
Compare equality between multiple pairs of values with a specified epsilon.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsRectangle boundingBox() const
Returns the bounding box of 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...
A class to represent a 2D point.
Definition qgspointxy.h:60
double y
Definition qgspointxy.h:64
double x
Definition qgspointxy.h:63
bool distanceCompare(const QgsPointXY &other, double epsilon=4 *std::numeric_limits< double >::epsilon()) const
Compares this point with another point with a fuzzy tolerance using distance comparison.
Definition qgspointxy.h:268
double x
Definition qgspoint.h:52
double y
Definition qgspoint.h:53
A rectangle specified with double values.
Represents a vector layer which manages a vector based data sets.
#define SIP_SKIP
Definition qgis_sip.h:126
Descripts a change to fix a geometry.
A list of layers and feature ids for each of these layers.
QMap< QString, QgsFeatureIds > toMap() const
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30