QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
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
21#include "qgsgeometrygapcheck.h"
22#include "qgspoint.h"
23#include "qgsvectorlayer.h"
25
27
28QString QgsGeometryCheckGapAlgorithm::name() const
29{
30 return QStringLiteral( "checkgeometrygap" );
31}
32
33QString QgsGeometryCheckGapAlgorithm::displayName() const
34{
35 return QObject::tr( "Small gaps" );
36}
37
38QString QgsGeometryCheckGapAlgorithm::shortDescription() const
39{
40 return QObject::tr( "Detects gaps between polygons smaller than a given area." );
41}
42
43QStringList QgsGeometryCheckGapAlgorithm::tags() const
44{
45 return QObject::tr( "check,geometry,gap" ).split( ',' );
46}
47
48QString QgsGeometryCheckGapAlgorithm::group() const
49{
50 return QObject::tr( "Check geometry" );
51}
52
53QString QgsGeometryCheckGapAlgorithm::groupId() const
54{
55 return QStringLiteral( "checkgeometry" );
56}
57
58QString QgsGeometryCheckGapAlgorithm::shortHelpString() const
59{
60 return QObject::tr( "This algorithm checks the gaps between polygons.\n"
61 "Gaps with an area smaller than the gap threshold are errors.\n\n"
62 "If an allowed gaps layer is given, the gaps contained in polygons from this layer will be ignored.\n"
63 "An optional buffer can be applied to the allowed gaps.\n\n"
64 "The neighbors output layer is needed for the fix geometry (gaps) algorithm. It is a 1-N "
65 "relational table for correspondance between a gap and the unique id of its neighbor features." );
66}
67
68Qgis::ProcessingAlgorithmFlags QgsGeometryCheckGapAlgorithm::flags() const
69{
71}
72
73QgsGeometryCheckGapAlgorithm *QgsGeometryCheckGapAlgorithm::createInstance() const
74{
75 return new QgsGeometryCheckGapAlgorithm();
76}
77
78void QgsGeometryCheckGapAlgorithm::initAlgorithm( const QVariantMap &configuration )
79{
80 Q_UNUSED( configuration )
81
83 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
84 ) );
85 addParameter( new QgsProcessingParameterField(
86 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Unique feature identifier" ), QString(), QStringLiteral( "INPUT" )
87 ) );
88 addParameter( new QgsProcessingParameterNumber(
89 QStringLiteral( "GAP_THRESHOLD" ), QObject::tr( "Gap threshold" ), Qgis::ProcessingNumberParameterType::Double, 0, false, 0.0
90 ) );
91
92 // Optional allowed gaps layer and buffer value
93 addParameter( new QgsProcessingParameterVectorLayer(
94 QStringLiteral( "ALLOWED_GAPS_LAYER" ), QObject::tr( "Allowed gaps layer" ),
95 QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ), QVariant(), true
96 ) );
97 addParameter( new QgsProcessingParameterDistance(
98 QStringLiteral( "ALLOWED_GAPS_BUFFER" ), QObject::tr( "Allowed gaps buffer" ), QVariant(), QStringLiteral( "ALLOWED_GAPS_LAYER" ), true, 0.0
99 ) );
100
101 addParameter( new QgsProcessingParameterFeatureSink(
102 QStringLiteral( "NEIGHBORS" ), QObject::tr( "Neighbors layer" ), Qgis::ProcessingSourceType::Vector
103 ) );
104 addParameter( new QgsProcessingParameterFeatureSink(
105 QStringLiteral( "ERRORS" ), QObject::tr( "Gap errors" ), Qgis::ProcessingSourceType::VectorPoint, QVariant(), true, false
106 ) );
107 addParameter( new QgsProcessingParameterFeatureSink(
108 QStringLiteral( "OUTPUT" ), QObject::tr( "Gap features" ), Qgis::ProcessingSourceType::VectorPolygon
109 ) );
110
111 std::unique_ptr<QgsProcessingParameterNumber> tolerance = std::make_unique<QgsProcessingParameterNumber>(
112 QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
113 );
114 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
115 tolerance->setHelp( QObject::tr( "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
116 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
117 addParameter( tolerance.release() );
118}
119
120bool QgsGeometryCheckGapAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
121{
122 mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );
123
124 return true;
125}
126
127QgsFields QgsGeometryCheckGapAlgorithm::outputFields()
128{
129 QgsFields fields;
130 fields.append( QgsField( QStringLiteral( "gc_layerid" ), QMetaType::QString ) );
131 fields.append( QgsField( QStringLiteral( "gc_layername" ), QMetaType::QString ) );
132 fields.append( QgsField( QStringLiteral( "gc_partidx" ), QMetaType::Int ) );
133 fields.append( QgsField( QStringLiteral( "gc_ringidx" ), QMetaType::Int ) );
134 fields.append( QgsField( QStringLiteral( "gc_vertidx" ), QMetaType::Int ) );
135 fields.append( QgsField( QStringLiteral( "gc_errorx" ), QMetaType::Double ) );
136 fields.append( QgsField( QStringLiteral( "gc_errory" ), QMetaType::Double ) );
137 fields.append( QgsField( QStringLiteral( "gc_error" ), QMetaType::QString ) );
138 fields.append( QgsField( QStringLiteral( "gc_errorid" ), QMetaType::LongLong ) );
139 return fields;
140}
141
142
143QVariantMap QgsGeometryCheckGapAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
144{
145 QString dest_output;
146 QString dest_errors;
147 QString dest_neighbors;
148 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
149 if ( !input )
150 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
151
152 QgsVectorLayer *allowedGapsLayer = parameterAsVectorLayer( parameters, QStringLiteral( "ALLOWED_GAPS_LAYER" ), context );
153
154 const double allowedGapsBuffer = parameterAsDouble( parameters, QStringLiteral( "ALLOWED_GAPS_BUFFER" ), context );
155 const double gapThreshold = parameterAsDouble( parameters, QStringLiteral( "GAP_THRESHOLD" ), context );
156
157 const QgsFields fields = outputFields();
158
159 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink(
160 parameters, QStringLiteral( "OUTPUT" ), context, dest_output, fields, input->wkbType(), input->sourceCrs()
161 ) );
162
163 const std::unique_ptr<QgsFeatureSink> sink_errors( parameterAsSink(
164 parameters, QStringLiteral( "ERRORS" ), context, dest_errors, fields, Qgis::WkbType::Point, input->sourceCrs()
165 ) );
166 if ( !sink_errors )
167 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "ERRORS" ) ) );
168
169 QString uniqueIdFieldName( parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context ) );
170 int uniqueIdFieldIdx = input->fields().indexFromName( uniqueIdFieldName );
171 if ( uniqueIdFieldIdx == -1 )
172 throw QgsProcessingException( QObject::tr( "Missing field %1 in input layer" ).arg( uniqueIdFieldName ) );
173
174 QgsFields neighborsFields = QgsFields();
175 neighborsFields.append( QgsField( "gc_errorid", QMetaType::LongLong ) );
176 neighborsFields.append( input->fields().at( uniqueIdFieldIdx ) );
177 const std::unique_ptr<QgsFeatureSink> sink_neighbors( parameterAsSink(
178 parameters, QStringLiteral( "NEIGHBORS" ), context, dest_neighbors, neighborsFields, Qgis::WkbType::NoGeometry
179 ) );
180 if ( !sink_neighbors )
181 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "NEIGHBORS" ) ) );
182
183 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
184
185 const QgsProject *project = QgsProject::instance();
186
187 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), project->transformContext(), project );
188
189 // Test detection
190 QList<QgsGeometryCheckError *> checkErrors;
191 QStringList messages;
192
193 QVariantMap configurationCheck;
194 configurationCheck.insert( "gapThreshold", gapThreshold );
195 configurationCheck.insert( "allowedGapsEnabled", allowedGapsLayer != nullptr );
196 if ( allowedGapsLayer )
197 {
198 configurationCheck.insert( "allowedGapsLayer", allowedGapsLayer->id() );
199 configurationCheck.insert( "allowedGapsBuffer", allowedGapsBuffer );
200 }
201 QgsGeometryGapCheck check( &checkContext, configurationCheck );
202 check.prepare( &checkContext, configurationCheck );
203
204 multiStepFeedback.setCurrentStep( 1 );
205 feedback->setProgressText( QObject::tr( "Preparing features…" ) );
206 QMap<QString, QgsFeaturePool *> checkerFeaturePools;
207
208 std::unique_ptr<QgsVectorLayer> inputLayer( input->materialize( QgsFeatureRequest() ) );
210 checkerFeaturePools.insert( inputLayer->id(), &featurePool );
211
212 multiStepFeedback.setCurrentStep( 2 );
213 feedback->setProgressText( QObject::tr( "Collecting errors…" ) );
214 check.collectErrors( checkerFeaturePools, checkErrors, messages, feedback );
215
216 multiStepFeedback.setCurrentStep( 3 );
217 feedback->setProgressText( QObject::tr( "Exporting errors…" ) );
218 double step { checkErrors.size() > 0 ? 100.0 / checkErrors.size() : 1 };
219 long long i = 0;
220 feedback->setProgress( 0.0 );
221
222 for ( const QgsGeometryCheckError *error : checkErrors )
223 {
224 if ( feedback->isCanceled() )
225 break;
226
227 const QgsGeometryGapCheckError *gapError = dynamic_cast<const QgsGeometryGapCheckError *>( error );
228 if ( !gapError )
229 break;
230
231 const QgsFeatureIds neighborIds = gapError->neighbors()[inputLayer->id()];
232 for ( QgsFeatureId neighborId : neighborIds )
233 {
234 QgsFeature neighborFeature;
235 neighborFeature.setAttributes(
236 QgsAttributes() << i
237 << inputLayer->getFeature( neighborId ).attribute( uniqueIdFieldIdx )
238 );
239 if ( !sink_neighbors->addFeature( neighborFeature, QgsFeatureSink::FastInsert ) )
240 throw QgsProcessingException( writeFeatureError( sink_neighbors.get(), parameters, QStringLiteral( "NEIGHBORS" ) ) );
241 }
242
243 QgsFeature f;
244 QgsAttributes attrs = f.attributes();
245 attrs
246 << inputLayer->id()
247 << inputLayer->name()
248 << error->vidx().part
249 << error->vidx().ring
250 << error->vidx().vertex
251 << error->location().x()
252 << error->location().y()
253 << error->value().toString()
254 << i;
255 f.setAttributes( attrs );
256
257 f.setGeometry( error->geometry() );
258 if ( sink_output && !sink_output->addFeature( f, QgsFeatureSink::FastInsert ) )
259 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
260
261 f.setGeometry( QgsGeometry::fromPoint( QgsPoint( error->location().x(), error->location().y() ) ) );
262 if ( !sink_errors->addFeature( f, QgsFeatureSink::FastInsert ) )
263 throw QgsProcessingException( writeFeatureError( sink_errors.get(), parameters, QStringLiteral( "ERRORS" ) ) );
264
265 i++;
266 feedback->setProgress( 100.0 * step * static_cast<double>( i ) );
267 }
268
269 // Place the point layer above the polygon layer
270 if ( context.willLoadLayerOnCompletion( dest_output ) && context.willLoadLayerOnCompletion( dest_errors ) )
271 {
272 context.layerToLoadOnCompletionDetails( dest_errors ).layerSortKey = 0;
273 context.layerToLoadOnCompletionDetails( dest_output ).layerSortKey = 1;
274 }
275
276 // cleanup memory of the pointed data
277 for ( const QgsGeometryCheckError *error : checkErrors )
278 {
279 delete error;
280 }
281
282 QVariantMap outputs;
283 outputs.insert( QStringLiteral( "NEIGHBORS" ), dest_neighbors );
284 if ( sink_output )
285 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
286 outputs.insert( QStringLiteral( "ERRORS" ), dest_errors );
287
288 return outputs;
289}
290
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3476
@ NoGeometry
No geometry.
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
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:58
QgsAttributes attributes
Definition qgsfeature.h:67
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:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
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:70
Base configuration for geometry checks.
This represents an error reported by a geometry check.
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:80
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
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...
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 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.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:107
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsCoordinateTransformContext transformContext
Definition qgsproject.h:113
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