QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsgeometryareacheck.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsgeometryareacheck.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
18#include "qgsfeaturepool.h"
19#include "qgsfeedback.h"
23#include "qgsgeometryengine.h"
24
25QgsGeometryCheck::Result QgsGeometryAreaCheck::collectErrors( const QMap<QString, QgsFeaturePool *> &featurePools, QList<QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids ) const
26{
27 Q_UNUSED( messages )
28
29 QMap<QString, QSet<QVariant>> uniqueIds;
30 const QMap<QString, QgsFeatureIds> featureIds = ids.isEmpty() ? allLayerFeatureIds( featurePools ) : ids.toMap();
31 const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds, compatibleGeometryTypes(), feedback, mContext );
32 for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
33 {
34 if ( feedback && feedback->isCanceled() )
35 {
37 }
38
39 if ( context()->uniqueIdFieldIndex != -1 )
40 {
41 QgsGeometryCheck::Result result = checkUniqueId( layerFeature, uniqueIds );
43 {
44 return result;
45 }
46 }
47
48 const QgsAbstractGeometry *geom = layerFeature.geometry().constGet();
49 const double layerToMapUnits = scaleFactor( layerFeature.layer() );
50 for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart )
51 {
52 double value;
54 if ( checkThreshold( layerToMapUnits, part, value ) )
55 {
56 errors.append( new QgsGeometryCheckError( this, layerFeature, part->centroid(), QgsVertexId( iPart ), value * layerToMapUnits * layerToMapUnits, QgsGeometryCheckError::ValueArea ) );
57 }
58 }
59 }
61}
62
63void QgsGeometryAreaCheck::fixError( const QMap<QString, QgsFeaturePool *> &featurePools, QgsGeometryCheckError *error, int method, const QMap<QString, int> &mergeAttributeIndices, Changes &changes ) const
64{
65 QgsFeaturePool *featurePool = featurePools[error->layerId()];
66 QgsFeature feature;
67 if ( !featurePool->getFeature( error->featureId(), feature ) )
68 {
69 error->setObsolete();
70 return;
71 }
72
73 const QgsGeometry g = feature.geometry();
74 const QgsAbstractGeometry *geom = g.constGet();
75 const QgsVertexId vidx = error->vidx();
76
77 const double layerToMapUnits = scaleFactor( featurePool->layer() );
78
79 // Check if polygon still exists
80 if ( !vidx.isValid( geom ) )
81 {
82 error->setObsolete();
83 return;
84 }
85
86 // Check if error still applies
87 double value;
88 if ( !checkThreshold( layerToMapUnits, QgsGeometryCheckerUtils::getGeomPart( geom, vidx.part ), value ) )
89 {
90 error->setObsolete();
91 return;
92 }
93
94 // Fix with selected method
95 if ( method == NoChange )
96 {
97 error->setFixed( method );
98 }
99 else if ( method == Delete )
100 {
101 deleteFeatureGeometryPart( featurePools, error->layerId(), feature, vidx.part, changes );
102 error->setFixed( method );
103 }
104 else if ( method == MergeLongestEdge || method == MergeLargestArea || method == MergeIdenticalAttribute )
105 {
106 QString errMsg;
107 if ( mergeWithNeighbor( featurePools, error->layerId(), feature, vidx.part, method, mergeAttributeIndices[error->layerId()], changes, errMsg ) )
108 {
109 error->setFixed( method );
110 }
111 else
112 {
113 error->setFixFailed( tr( "Failed to merge with neighbor: %1" ).arg( errMsg ) );
114 }
115 }
116 else
117 {
118 error->setFixFailed( tr( "Unknown method" ) );
119 }
120}
121
122bool QgsGeometryAreaCheck::checkThreshold( double layerToMapUnits, const QgsAbstractGeometry *geom, double &value ) const
123{
124 value = geom->area();
125 const double threshold = mAreaThreshold / ( layerToMapUnits * layerToMapUnits );
126 return value < threshold;
127}
128
129bool QgsGeometryAreaCheck::mergeWithNeighbor( const QMap<QString, QgsFeaturePool *> &featurePools, const QString &layerId, QgsFeature &feature, int partIdx, int method, int mergeAttributeIndex, Changes &changes, QString &errMsg ) const
130{
131 QgsFeaturePool *featurePool = featurePools[layerId];
132
133 double maxVal = 0.;
134 QgsFeature mergeFeature;
135 int mergePartIdx = -1;
136 bool matchFound = false;
137 const QgsGeometry featureGeometry = feature.geometry();
138 const QgsAbstractGeometry *geom = featureGeometry.constGet();
139
140 // Search for touching neighboring geometries
141 const QgsFeatureIds intersects = featurePool->getIntersects( featureGeometry.boundingBox() );
142 for ( const QgsFeatureId testId : intersects )
143 {
144 QgsFeature testFeature;
145 if ( !featurePool->getFeature( testId, testFeature ) )
146 {
147 continue;
148 }
149 const QgsGeometry testFeatureGeom = testFeature.geometry();
150 const QgsAbstractGeometry *testGeom = testFeatureGeom.constGet();
151 for ( int testPartIdx = 0, nTestParts = testGeom->partCount(); testPartIdx < nTestParts; ++testPartIdx )
152 {
153 if ( testId == feature.id() && testPartIdx == partIdx )
154 {
155 continue;
156 }
157 const double len = QgsGeometryCheckerUtils::sharedEdgeLength( QgsGeometryCheckerUtils::getGeomPart( geom, partIdx ), QgsGeometryCheckerUtils::getGeomPart( testGeom, testPartIdx ), mContext->reducedTolerance );
158 if ( len > 0. )
159 {
160 if ( method == MergeLongestEdge || method == MergeLargestArea )
161 {
162 double val;
163 if ( method == MergeLongestEdge )
164 {
165 val = len;
166 }
167 else
168 {
169 if ( dynamic_cast<const QgsGeometryCollection *>( testGeom ) )
170 val = static_cast<const QgsGeometryCollection *>( testGeom )->geometryN( testPartIdx )->area();
171 else
172 val = testGeom->area();
173 }
174 if ( val > maxVal )
175 {
176 maxVal = val;
177 mergeFeature = testFeature;
178 mergePartIdx = testPartIdx;
179 }
180 }
181 else if ( method == MergeIdenticalAttribute )
182 {
183 if ( testFeature.attribute( mergeAttributeIndex ) == feature.attribute( mergeAttributeIndex ) )
184 {
185 mergeFeature = testFeature;
186 mergePartIdx = testPartIdx;
187 matchFound = true;
188 break;
189 }
190 }
191 }
192 }
193 if ( matchFound )
194 {
195 break;
196 }
197 }
198
199 if ( !matchFound && maxVal == 0. )
200 {
201 return method == MergeIdenticalAttribute;
202 }
203
204 // Merge geometries
205 const QgsGeometry mergeFeatureGeom = mergeFeature.geometry();
206 const QgsAbstractGeometry *mergeGeom = mergeFeatureGeom.constGet();
207 std::unique_ptr<QgsGeometryEngine> geomEngine( QgsGeometry::createGeometryEngine( QgsGeometryCheckerUtils::getGeomPart( mergeGeom, mergePartIdx ), mContext->reducedTolerance ) );
208 QgsAbstractGeometry *combinedGeom = geomEngine->combine( QgsGeometryCheckerUtils::getGeomPart( geom, partIdx ), &errMsg );
209 if ( !combinedGeom || combinedGeom->isEmpty() || !QgsWkbTypes::isSingleType( combinedGeom->wkbType() ) )
210 {
211 return false;
212 }
213
214 // Replace polygon in merge geometry
215 if ( mergeFeature.id() == feature.id() && mergePartIdx > partIdx )
216 {
217 --mergePartIdx;
218 }
219 replaceFeatureGeometryPart( featurePools, layerId, mergeFeature, mergePartIdx, combinedGeom, changes );
220 // Remove polygon from source geometry
221 deleteFeatureGeometryPart( featurePools, layerId, feature, partIdx, changes );
222
223 return true;
224}
225
227{
228 static const QStringList methods = QStringList()
229 << tr( "Merge with neighboring polygon with longest shared edge" )
230 << tr( "Merge with neighboring polygon with largest area" )
231 << tr( "Merge with neighboring polygon with identical attribute value, if any, or leave as is" )
232 << tr( "Delete feature" )
233 << tr( "No action" );
234 return methods;
235}
Abstract base class for all geometries.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
virtual bool isEmpty() const
Returns true if the geometry is empty.
virtual int partCount() const =0
Returns count of parts contained in the geometry.
virtual QgsPoint centroid() const
Returns the centroid of the geometry.
virtual double area() const
Returns the planar, 2-dimensional area of the geometry.
A feature pool is based on a vector layer and caches features.
QgsFeatureIds getIntersects(const QgsRectangle &rect) const
Gets all feature ids in the bounding box rect.
QgsVectorLayer * layer() const
Gets a pointer to the underlying 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
QgsGeometry geometry
Definition qgsfeature.h:69
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
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
Q_DECL_DEPRECATED QStringList resolutionMethods() const override
Returns a list of descriptions for available resolutions for errors.
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.
QList< Qgis::GeometryType > compatibleGeometryTypes() const override
A list of geometry types for which this check can be performed.
QgsGeometryCheck::Result collectErrors(const QMap< QString, QgsFeaturePool * > &featurePools, QList< QgsGeometryCheckError * > &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids=LayerFeatureIds()) const override
The main worker method.
This represents an error reported by a geometry check.
@ ValueArea
The value is an area.
const QgsVertexId & vidx() const
The id of the affected vertex.
QgsFeatureId featureId() const
The id of the feature on which this error has been detected.
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.
void setObsolete()
Set the error status to obsolete.
const QString & layerId() const
The id of the layer on which this error has been detected.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
void deleteFeatureGeometryPart(const QMap< QString, QgsFeaturePool * > &featurePools, const QString &layerId, QgsFeature &feature, int partIdx, Changes &changes) const
Deletes a part of a feature geometry.
void replaceFeatureGeometryPart(const QMap< QString, QgsFeaturePool * > &featurePools, const QString &layerId, QgsFeature &feature, int partIdx, QgsAbstractGeometry *newPartGeom, Changes &changes) const
Replaces a part in a feature geometry.
const QgsGeometryCheckContext * mContext
QMap< QString, QgsFeatureIds > allLayerFeatureIds(const QMap< QString, QgsFeaturePool * > &featurePools) const
Returns all layers and feature ids.
Result checkUniqueId(const QgsGeometryCheckerUtils::LayerFeature layerFeature, QMap< QString, QSet< QVariant > > &uniqueIds) const
Checks that there are no duplicated unique IDs.
Result
Result of the geometry checker operation.
@ Canceled
User canceled calculation.
@ Success
Operation completed successfully.
double scaleFactor(const QPointer< QgsVectorLayer > &layer) const
Determines the scale factor of a layer to the map coordinate reference system.
const QgsGeometryCheckContext * context() const
Returns the context.
A layer feature combination to uniquely identify and access a feature in a set of layers.
Contains a set of layers and feature ids in those layers to pass to a geometry check.
static QgsAbstractGeometry * getGeomPart(QgsAbstractGeometry *geom, int partIdx)
static double sharedEdgeLength(const QgsAbstractGeometry *geom1, const QgsAbstractGeometry *geom2, double tol)
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...
static Q_INVOKABLE bool isSingleType(Qgis::WkbType type)
Returns true if the WKB type is a single type.
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
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
bool isValid() const
Returns true if the vertex id is valid.
Definition qgsvertexid.h:45
int part
Part number.
Definition qgsvertexid.h:88