QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmfixgeometrygap.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmfixgeometrygap.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
20#include "qgsgeometrygapcheck.h"
23
25
26QString QgsFixGeometryGapAlgorithm::name() const
27{
28 return QStringLiteral( "fixgeometrygap" );
29}
30
31QString QgsFixGeometryGapAlgorithm::displayName() const
32{
33 return QObject::tr( "Fill gaps" );
34}
35
36QString QgsFixGeometryGapAlgorithm::shortDescription() const
37{
38 return QObject::tr( "Fills gaps detected with the \"Small gaps\" algorithm from the \"Check geometry\" section." );
39}
40
41QStringList QgsFixGeometryGapAlgorithm::tags() const
42{
43 return QObject::tr( "fix,fill,gap" ).split( ',' );
44}
45
46QString QgsFixGeometryGapAlgorithm::group() const
47{
48 return QObject::tr( "Fix geometry" );
49}
50
51QString QgsFixGeometryGapAlgorithm::groupId() const
52{
53 return QStringLiteral( "fixgeometry" );
54}
55
56QString QgsFixGeometryGapAlgorithm::shortHelpString() const
57{
58 return QObject::tr( "This algorithm fills the gaps based on a gap and neighbors layer from the \"Small gaps\" algorithm in the \"Check geometry\" section.\n\n"
59 "3 different fixing methods are available, which will give different results." );
60}
61
62QgsFixGeometryGapAlgorithm *QgsFixGeometryGapAlgorithm::createInstance() const
63{
64 return new QgsFixGeometryGapAlgorithm();
65}
66
67void QgsFixGeometryGapAlgorithm::initAlgorithm( const QVariantMap &configuration )
68{
69 Q_UNUSED( configuration )
70
71 // Inputs
73 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
74 ) );
76 QStringLiteral( "NEIGHBORS" ), QObject::tr( "Neighbors layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector )
77 ) );
79 QStringLiteral( "GAPS" ), QObject::tr( "Gaps layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
80 ) );
81
82 // Specific inputs for this check
83 QStringList methods;
84 {
85 QList<QgsGeometryCheckResolutionMethod> checkMethods = QgsGeometryGapCheck( nullptr, QVariantMap() ).availableResolutionMethods();
86 std::transform(
87 checkMethods.cbegin(), checkMethods.cend() - 1, std::inserter( methods, methods.begin() ),
88 []( const QgsGeometryCheckResolutionMethod &checkMethod ) { return checkMethod.name(); }
89 );
90 }
91 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Method" ), methods ) );
92
93 addParameter( new QgsProcessingParameterField(
94 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Field of original feature unique identifier" ),
95 QString(), QStringLiteral( "INPUT" )
96 ) );
97 addParameter( new QgsProcessingParameterField(
98 QStringLiteral( "ERROR_ID_IDX" ), QObject::tr( "Field of error id" ),
99 QStringLiteral( "gc_errorid" ), QStringLiteral( "GAPS" ),
101 ) );
102
103 // Outputs
104 addParameter( new QgsProcessingParameterFeatureSink(
105 QStringLiteral( "OUTPUT" ), QObject::tr( "Gaps-filled layer" ), Qgis::ProcessingSourceType::VectorPolygon
106 ) );
107 addParameter( new QgsProcessingParameterFeatureSink(
108 QStringLiteral( "REPORT" ), QObject::tr( "Report layer from fixing gaps" ), Qgis::ProcessingSourceType::VectorPoint
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
120QVariantMap QgsFixGeometryGapAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
121{
122 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
123 if ( !input )
124 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
125
126 const std::unique_ptr<QgsProcessingFeatureSource> neighbors( parameterAsSource( parameters, QStringLiteral( "NEIGHBORS" ), context ) );
127 if ( !neighbors )
128 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "NEIGHBORS" ) ) );
129
130 const std::unique_ptr<QgsProcessingFeatureSource> gaps( parameterAsSource( parameters, QStringLiteral( "GAPS" ), context ) );
131 if ( !gaps )
132 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "GAPS" ) ) );
133
134 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
135
136 const QString featIdFieldName = parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context );
137 const QString errorIdFieldName = parameterAsString( parameters, QStringLiteral( "ERROR_ID_IDX" ), context );
138
139 // Specific inputs for this check
140 int method = parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context );
141 switch ( method )
142 {
143 case 0:
145 break;
146 case 1:
148 break;
149 case 2:
151 break;
152 default:
153 throw QgsProcessingException( QObject::tr( "Unknown resolution method" ) );
154 }
155
156 // Verify that input fields exists
157 if ( gaps->fields().indexFromName( errorIdFieldName ) == -1 )
158 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the gaps layer." ).arg( errorIdFieldName ) );
159 if ( neighbors->fields().indexFromName( featIdFieldName ) == -1 )
160 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the neighbors layer." ).arg( featIdFieldName ) );
161 int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
162 if ( inputIdFieldIndex == -1 )
163 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in input layer." ).arg( featIdFieldName ) );
164
165 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
166 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
167 if ( inputFeatIdFieldType != neighbors->fields().at( neighbors->fields().indexFromName( featIdFieldName ) ).type() )
168 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as in the neighbors layer." ).arg( featIdFieldName ) );
169
170 QString dest_output;
171 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink(
172 parameters, QStringLiteral( "OUTPUT" ), context, dest_output, input->fields(), input->wkbType(), input->sourceCrs()
173 ) );
174 if ( !sink_output )
175 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
176
177 QString dest_report;
178 QgsFields reportFields = gaps->fields();
179 reportFields.append( QgsField( QStringLiteral( "report" ), QMetaType::QString ) );
180 reportFields.append( QgsField( QStringLiteral( "error_fixed" ), QMetaType::Bool ) );
181 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink(
182 parameters, QStringLiteral( "REPORT" ), context, dest_report, reportFields, Qgis::WkbType::Point, gaps->sourceCrs()
183 ) );
184 if ( !sink_report )
185 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "REPORT" ) ) );
186
187 QgsProject *project = QgsProject::instance();
189 mTolerance, input->sourceCrs(), project->transformContext(), project
190 );
191 QStringList messages;
192
193 const QgsGeometryGapCheck check( &checkContext, QVariantMap() );
194
195 multiStepFeedback.setCurrentStep( 1 );
196 multiStepFeedback.setProgressText( QObject::tr( "Preparing features..." ) );
197 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize( QgsFeatureRequest() ) );
198 QgsVectorDataProviderFeaturePool featurePool = QgsVectorDataProviderFeaturePool( fixedLayer.get(), false );
199 QMap<QString, QgsFeaturePool *> featurePools;
200 featurePools.insert( fixedLayer->id(), &featurePool );
201
202 // To add features into the layer, the geometry checker looks for the layer in the project
204 {
205 project->addMapLayer( fixedLayer.get(), false, false );
206 fixedLayer->startEditing();
207 }
208
209 QgsFeature gapFeature;
210 QgsFeatureIterator gapsFeaturesIt = gaps->getFeatures();
211 QgsFeature reportFeature;
212 reportFeature.setFields( reportFields );
213 long long progression = 0;
214 long long totalProgression = gaps->featureCount();
215 multiStepFeedback.setCurrentStep( 2 );
216 multiStepFeedback.setProgressText( QObject::tr( "Fixing errors..." ) );
217 while ( gapsFeaturesIt.nextFeature( gapFeature ) )
218 {
219 if ( feedback->isCanceled() )
220 break;
221
222 progression++;
223 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
224 reportFeature.setGeometry( gapFeature.geometry().centroid() );
225
226 QVariant gapId = gapFeature.attribute( errorIdFieldName );
227 if ( !gapId.isValid() || gapId.isNull() )
228 throw QgsProcessingException( QObject::tr( "NULL or invalid value found in field \"%1\"" ).arg( errorIdFieldName ) );
229
230 // Get the neighbor features of the current gap to fill the neighbors ids
231 QgsFeature f;
232 QgsFeatureIds neighborIds;
233 const QString errorIdValue = gapFeature.attribute( errorIdFieldName ).toString();
234 QgsFeatureIterator it = neighbors->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + errorIdFieldName + "\" = " + errorIdValue ) );
235 while ( it.nextFeature( f ) )
236 {
237 QString neighborIdValue = f.attribute( featIdFieldName ).toString();
238 if ( inputFeatIdFieldType == QMetaType::QString )
239 neighborIdValue = "'" + neighborIdValue + "'";
240 QgsFeature neighborFeature;
241 if ( fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + neighborIdValue ) ).nextFeature( neighborFeature ) )
242 neighborIds << neighborFeature.id();
243 }
244
245 QMap<QString, QgsFeatureIds> neighborsMap;
246 neighborsMap.insert( fixedLayer->id(), neighborIds );
248 &check,
249 fixedLayer->id(),
250 gapFeature.geometry(),
251 neighborsMap,
252 0,
253 QgsRectangle(),
255 );
256
258 check.fixError( featurePools, &gapError, method, QMap<QString, int>(), changes );
259
260 QString resolutionMessage = gapError.resolutionMessage();
262 resolutionMessage = QObject::tr( "Error is obsolete" );
263
264 reportFeature.setAttributes( gapFeature.attributes() << resolutionMessage << ( gapError.status() == QgsGeometryCheckError::StatusFixed ) );
265
266 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
267 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
268 }
269 multiStepFeedback.setProgress( 100 );
270
272 {
273 if ( !fixedLayer->commitChanges() )
274 throw QgsProcessingException( QObject::tr( "Unable to add gap features" ) );
275 project->removeMapLayer( fixedLayer.get() );
276 }
277
278 progression = 0;
279 totalProgression = fixedLayer->featureCount();
280 multiStepFeedback.setCurrentStep( 2 );
281 multiStepFeedback.setProgressText( QObject::tr( "Exporting fixed layer..." ) );
282 QgsFeature fixedFeature;
283 QgsFeatureIterator fixedFeaturesIt = fixedLayer->getFeatures();
284 while ( fixedFeaturesIt.nextFeature( fixedFeature ) )
285 {
286 if ( feedback->isCanceled() )
287 break;
288
289 progression++;
290 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
291 if ( !sink_output->addFeature( fixedFeature, QgsFeatureSink::FastInsert ) )
292 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
293 }
294 multiStepFeedback.setProgress( 100 );
295
296 QVariantMap outputs;
297 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
298 outputs.insert( QStringLiteral( "REPORT" ), dest_report );
299
300 return outputs;
301}
302
303bool QgsFixGeometryGapAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
304{
305 mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );
306
307 return true;
308}
309
310Qgis::ProcessingAlgorithmFlags QgsFixGeometryGapAlgorithm::flags() const
311{
313}
314
@ 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.
@ Numeric
Accepts numeric fields.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3476
@ 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.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
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
QgsFeatureId id
Definition qgsfeature.h:66
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
void setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
QgsGeometry geometry
Definition qgsfeature.h:69
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
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
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
QMetaType::Type type
Definition qgsfield.h:60
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.
@ StatusFixed
The error is fixed.
@ StatusObsolete
The error is obsolete because of other modifications.
Status status() const
The status of the error.
QString resolutionMessage() const
A message with details, how the error has been resolved.
Implements a resolution for problems detected in geometry checks.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
An error produced by a QgsGeometryGapCheck.
Checks for gaps between neighbouring polygons.
QList< QgsGeometryCheckResolutionMethod > availableResolutionMethods() const override
Returns a list of available resolution methods.
@ CreateNewFeature
Create a new feature with the gap geometry.
@ MergeLongestEdge
Merge the gap with the polygon with the longest shared edge.
@ MergeLargestArea
Merge with neighbouring polygon with largest area.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
Processing feedback object for multi-step operations.
An enum based parameter for processing algorithms, allowing for selection from predefined 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.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:107
void removeMapLayer(const QString &layerId)
Remove a layer from the registry by layer ID.
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsCoordinateTransformContext transformContext
Definition qgsproject.h:113
QgsMapLayer * addMapLayer(QgsMapLayer *mapLayer, bool addToLegend=true, bool takeOwnership=true)
Add a layer to the map of loaded layers.
A rectangle specified with double values.
A feature pool based on a vector data provider.
QSet< QgsFeatureId > QgsFeatureIds