QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmcheckgeometrygap.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmcheckgeometrygap.cpp
3 ---------------------
4 begin : April 2025
5 copyright : (C) 2025 by Jacky Volpes
6 email : jacky dot volpes at oslandia 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
22#include "qgsgeometrygapcheck.h"
23#include "qgspoint.h"
25#include "qgsvectorlayer.h"
26
27#include <QString>
28
29using namespace Qt::StringLiterals;
30
32
33QString QgsGeometryCheckGapAlgorithm::name() const
34{
35 return u"checkgeometrygap"_s;
36}
37
38QString QgsGeometryCheckGapAlgorithm::displayName() const
39{
40 return QObject::tr( "Small gaps" );
41}
42
43QString QgsGeometryCheckGapAlgorithm::shortDescription() const
44{
45 return QObject::tr( "Detects gaps between polygons smaller than a given area." );
46}
47
48QStringList QgsGeometryCheckGapAlgorithm::tags() const
49{
50 return QObject::tr( "check,geometry,gap" ).split( ',' );
51}
52
53QString QgsGeometryCheckGapAlgorithm::group() const
54{
55 return QObject::tr( "Check geometry" );
56}
57
58QString QgsGeometryCheckGapAlgorithm::groupId() const
59{
60 return u"checkgeometry"_s;
61}
62
63QString QgsGeometryCheckGapAlgorithm::shortHelpString() const
64{
65 return QObject::tr( "This algorithm checks the gaps between polygons.\n"
66 "Gaps with an area smaller than the gap threshold are errors.\n\n"
67 "If an allowed gaps layer is given, the gaps contained in polygons from this layer will be ignored.\n"
68 "An optional buffer can be applied to the allowed gaps.\n\n"
69 "The neighbors output layer is needed for the fix geometry (gaps) algorithm. It is a 1-N "
70 "relational table for correspondence between a gap and the unique id of its neighbor features." );
71}
72
73Qgis::ProcessingAlgorithmFlags QgsGeometryCheckGapAlgorithm::flags() const
74{
76}
77
78QgsGeometryCheckGapAlgorithm *QgsGeometryCheckGapAlgorithm::createInstance() const
79{
80 return new QgsGeometryCheckGapAlgorithm();
81}
82
83void QgsGeometryCheckGapAlgorithm::initAlgorithm( const QVariantMap &configuration )
84{
85 Q_UNUSED( configuration )
86
88 u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
89 ) );
90 addParameter( new QgsProcessingParameterField(
91 u"UNIQUE_ID"_s, QObject::tr( "Unique feature identifier" ), QString(), u"INPUT"_s
92 ) );
93 addParameter( new QgsProcessingParameterNumber(
94 u"GAP_THRESHOLD"_s, QObject::tr( "Gap threshold" ), Qgis::ProcessingNumberParameterType::Double, 0, false, 0.0
95 ) );
96
97 // Optional allowed gaps layer and buffer value
98 addParameter( new QgsProcessingParameterVectorLayer(
99 u"ALLOWED_GAPS_LAYER"_s, QObject::tr( "Allowed gaps layer" ),
100 QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ), QVariant(), true
101 ) );
102 addParameter( new QgsProcessingParameterDistance(
103 u"ALLOWED_GAPS_BUFFER"_s, QObject::tr( "Allowed gaps buffer" ), QVariant(), u"ALLOWED_GAPS_LAYER"_s, true, 0.0
104 ) );
105
106 addParameter( new QgsProcessingParameterFeatureSink(
107 u"NEIGHBORS"_s, QObject::tr( "Neighbors layer" ), Qgis::ProcessingSourceType::Vector
108 ) );
109 addParameter( new QgsProcessingParameterFeatureSink(
110 u"ERRORS"_s, QObject::tr( "Gap errors" ), Qgis::ProcessingSourceType::VectorPoint, QVariant(), true, false
111 ) );
112 addParameter( new QgsProcessingParameterFeatureSink(
113 u"OUTPUT"_s, QObject::tr( "Gap features" ), Qgis::ProcessingSourceType::VectorPolygon
114 ) );
115
116 auto tolerance = std::make_unique<QgsProcessingParameterNumber>(
117 u"TOLERANCE"_s, QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
118 );
119 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
120 tolerance->setHelp( QObject::tr( "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
121 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
122 addParameter( tolerance.release() );
123}
124
125bool QgsGeometryCheckGapAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
126{
127 mTolerance = parameterAsInt( parameters, u"TOLERANCE"_s, context );
128
129 return true;
130}
131
132QgsFields QgsGeometryCheckGapAlgorithm::outputFields()
133{
134 QgsFields fields;
135 fields.append( QgsField( u"gc_layerid"_s, QMetaType::QString ) );
136 fields.append( QgsField( u"gc_layername"_s, QMetaType::QString ) );
137 fields.append( QgsField( u"gc_partidx"_s, QMetaType::Int ) );
138 fields.append( QgsField( u"gc_ringidx"_s, QMetaType::Int ) );
139 fields.append( QgsField( u"gc_vertidx"_s, QMetaType::Int ) );
140 fields.append( QgsField( u"gc_errorx"_s, QMetaType::Double ) );
141 fields.append( QgsField( u"gc_errory"_s, QMetaType::Double ) );
142 fields.append( QgsField( u"gc_error"_s, QMetaType::QString ) );
143 fields.append( QgsField( u"gc_errorid"_s, QMetaType::LongLong ) );
144 return fields;
145}
146
147QVariantMap QgsGeometryCheckGapAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
148{
149 QString dest_output;
150 QString dest_errors;
151 QString dest_neighbors;
152 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
153 if ( !input )
154 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
155
156 QgsVectorLayer *allowedGapsLayer = parameterAsVectorLayer( parameters, u"ALLOWED_GAPS_LAYER"_s, context );
157
158 const double allowedGapsBuffer = parameterAsDouble( parameters, u"ALLOWED_GAPS_BUFFER"_s, context );
159 const double gapThreshold = parameterAsDouble( parameters, u"GAP_THRESHOLD"_s, context );
160
161 const QgsFields fields = outputFields();
162
163 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink(
164 parameters, u"OUTPUT"_s, context, dest_output, fields, input->wkbType(), input->sourceCrs()
165 ) );
166 if ( !sink_output )
167 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
168
169 const std::unique_ptr<QgsFeatureSink> sink_errors( parameterAsSink(
170 parameters, u"ERRORS"_s, context, dest_errors, fields, Qgis::WkbType::Point, input->sourceCrs()
171 ) );
172
173 const QString uniqueIdFieldName( parameterAsString( parameters, u"UNIQUE_ID"_s, context ) );
174 const int uniqueIdFieldIdx = input->fields().indexFromName( uniqueIdFieldName );
175 if ( uniqueIdFieldIdx == -1 )
176 throw QgsProcessingException( QObject::tr( "Missing field %1 in input layer" ).arg( uniqueIdFieldName ) );
177
178 QgsFields neighborsFields = QgsFields();
179 neighborsFields.append( QgsField( "gc_errorid", QMetaType::LongLong ) );
180 neighborsFields.append( input->fields().at( uniqueIdFieldIdx ) );
181 const std::unique_ptr<QgsFeatureSink> sink_neighbors( parameterAsSink(
182 parameters, u"NEIGHBORS"_s, context, dest_neighbors, neighborsFields, Qgis::WkbType::NoGeometry
183 ) );
184 if ( !sink_neighbors )
185 throw QgsProcessingException( invalidSinkError( parameters, u"NEIGHBORS"_s ) );
186
187 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
188
189 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), context.transformContext(), context.project(), uniqueIdFieldIdx );
190
191 // Test detection
192 QList<QgsGeometryCheckError *> checkErrors;
193 QStringList messages;
194
195 QVariantMap configurationCheck;
196 configurationCheck.insert( "gapThreshold", gapThreshold );
197 configurationCheck.insert( "allowedGapsEnabled", allowedGapsLayer != nullptr );
198 if ( allowedGapsLayer )
199 {
200 configurationCheck.insert( "allowedGapsLayer", allowedGapsLayer->id() );
201 configurationCheck.insert( "allowedGapsBuffer", allowedGapsBuffer );
202 }
203 QgsGeometryGapCheck check( &checkContext, configurationCheck );
204 check.prepare( &checkContext, configurationCheck );
205
206 multiStepFeedback.setCurrentStep( 1 );
207 feedback->setProgressText( QObject::tr( "Preparing features…" ) );
208 QMap<QString, QgsFeaturePool *> checkerFeaturePools;
209
210 std::unique_ptr<QgsVectorLayer> inputLayer( input->materialize( QgsFeatureRequest() ) );
212 checkerFeaturePools.insert( inputLayer->id(), &featurePool );
213
214 multiStepFeedback.setCurrentStep( 2 );
215 feedback->setProgressText( QObject::tr( "Collecting errors…" ) );
216 QgsGeometryCheck::Result res = check.collectErrors( checkerFeaturePools, checkErrors, messages, feedback );
218 {
219 feedback->pushInfo( QObject::tr( "Errors collected successfully." ) );
220 }
221 else if ( res == QgsGeometryCheck::Result::Canceled )
222 {
223 throw QgsProcessingException( QObject::tr( "Operation was canceled." ) );
224 }
226 {
227 throw QgsProcessingException( QObject::tr( "Field '%1' contains non-unique values and can not be used as unique ID." ).arg( uniqueIdFieldName ) );
228 }
230 {
231 throw QgsProcessingException( QObject::tr( "Failed to perform geometry overlay operation." ) );
232 }
233
234 multiStepFeedback.setCurrentStep( 3 );
235 feedback->setProgressText( QObject::tr( "Exporting errors…" ) );
236 double step { checkErrors.size() > 0 ? 100.0 / checkErrors.size() : 1 };
237 long long i = 0;
238 feedback->setProgress( 0.0 );
239
240 for ( const QgsGeometryCheckError *error : checkErrors )
241 {
242 if ( feedback->isCanceled() )
243 break;
244
245 const QgsGeometryGapCheckError *gapError = dynamic_cast<const QgsGeometryGapCheckError *>( error );
246 if ( !gapError )
247 break;
248
249 const QgsFeatureIds neighborIds = gapError->neighbors()[inputLayer->id()];
250 for ( QgsFeatureId neighborId : neighborIds )
251 {
252 QgsFeature neighborFeature;
253 neighborFeature.setAttributes(
254 QgsAttributes() << i
255 << inputLayer->getFeature( neighborId ).attribute( uniqueIdFieldIdx )
256 );
257 if ( !sink_neighbors->addFeature( neighborFeature, QgsFeatureSink::FastInsert ) )
258 throw QgsProcessingException( writeFeatureError( sink_neighbors.get(), parameters, u"NEIGHBORS"_s ) );
259 }
260
261 QgsFeature f;
262 QgsAttributes attrs = f.attributes();
263 attrs
264 << inputLayer->id()
265 << inputLayer->name()
266 << error->vidx().part
267 << error->vidx().ring
268 << error->vidx().vertex
269 << error->location().x()
270 << error->location().y()
271 << error->value().toString()
272 << i;
273 f.setAttributes( attrs );
274
275 f.setGeometry( error->geometry() );
276 if ( !sink_output->addFeature( f, QgsFeatureSink::FastInsert ) )
277 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, u"OUTPUT"_s ) );
278
279 f.setGeometry( QgsGeometry::fromPoint( QgsPoint( error->location().x(), error->location().y() ) ) );
280 if ( sink_errors && !sink_errors->addFeature( f, QgsFeatureSink::FastInsert ) )
281 throw QgsProcessingException( writeFeatureError( sink_errors.get(), parameters, u"ERRORS"_s ) );
282
283 i++;
284 feedback->setProgress( 100.0 * step * static_cast<double>( i ) );
285 }
286
287 // Place the point layer above the polygon layer
288 if ( context.willLoadLayerOnCompletion( dest_output ) && context.willLoadLayerOnCompletion( dest_errors ) )
289 {
290 context.layerToLoadOnCompletionDetails( dest_errors ).layerSortKey = 1;
291 context.layerToLoadOnCompletionDetails( dest_output ).layerSortKey = 0;
292 }
293
294 // cleanup memory of the pointed data
295 for ( const QgsGeometryCheckError *error : checkErrors )
296 {
297 delete error;
298 }
299
300 QVariantMap outputs;
301 outputs.insert( u"NEIGHBORS"_s, dest_neighbors );
302 outputs.insert( u"OUTPUT"_s, dest_output );
303 if ( sink_errors )
304 outputs.insert( u"ERRORS"_s, dest_errors );
305
306 return outputs;
307}
308
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3610
@ VectorPoint
Vector point layers.
Definition qgis.h:3605
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3607
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3680
@ Point
Point.
Definition qgis.h:282
@ NoGeometry
No geometry.
Definition qgis.h:298
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3659
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3667
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
@ Double
Double/float values.
Definition qgis.h:3875
A vector of attributes.
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...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:69
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:76
Base configuration for geometry checks.
This represents an error reported by a geometry check.
Result
Result of the geometry checker operation.
@ Canceled
User canceled calculation.
@ DuplicatedUniqueId
Found duplicated unique ID value.
@ GeometryOverlayError
Error performing geometry overlay operation.
@ Success
Operation completed successfully.
An error produced by a QgsGeometryGapCheck.
const QMap< QString, QgsFeatureIds > & neighbors() const
A map of layers and feature ids of the neighbors of the gap.
Checks for gaps between neighbouring polygons.
static QgsGeometry fromPoint(const QgsPoint &point)
Creates a new geometry from a QgsPoint object.
QString id
Definition qgsmaplayer.h:86
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
int layerSortKey
Optional sorting key for sorting output layers when loading them into a project.
Contains information about the context in which a processing algorithm is executed.
QgsProcessingContext::LayerDetails & layerToLoadOnCompletionDetails(const QString &layer)
Returns a reference to the details for a given layer which is loaded on completion of the algorithm o...
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
bool willLoadLayerOnCompletion(const QString &layer) const
Returns true if the given layer (by ID or datasource) will be loaded into the current project upon co...
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void setProgressText(const QString &text)
Sets a progress report text string.
Processing feedback object for multi-step operations.
A double numeric parameter for distance values.
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.
A numeric parameter for processing algorithms.
A vector layer (with or without geometry) parameter for processing algorithms.
A feature pool based on a vector data provider.
Represents a vector layer which manages a vector based dataset.
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features