QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
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
19
22#include "qgsgeometrygapcheck.h"
24
26
27QString QgsFixGeometryGapAlgorithm::name() const
28{
29 return QStringLiteral( "fixgeometrygap" );
30}
31
32QString QgsFixGeometryGapAlgorithm::displayName() const
33{
34 return QObject::tr( "Fill gaps" );
35}
36
37QString QgsFixGeometryGapAlgorithm::shortDescription() const
38{
39 return QObject::tr( "Fills gaps detected with the \"Small gaps\" algorithm from the \"Check geometry\" section." );
40}
41
42QStringList QgsFixGeometryGapAlgorithm::tags() const
43{
44 return QObject::tr( "fix,fill,gap" ).split( ',' );
45}
46
47QString QgsFixGeometryGapAlgorithm::group() const
48{
49 return QObject::tr( "Fix geometry" );
50}
51
52QString QgsFixGeometryGapAlgorithm::groupId() const
53{
54 return QStringLiteral( "fixgeometry" );
55}
56
57QString QgsFixGeometryGapAlgorithm::shortHelpString() const
58{
59 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"
60 "3 different fixing methods are available, which will give different results." );
61}
62
63QgsFixGeometryGapAlgorithm *QgsFixGeometryGapAlgorithm::createInstance() const
64{
65 return new QgsFixGeometryGapAlgorithm();
66}
67
68void QgsFixGeometryGapAlgorithm::initAlgorithm( const QVariantMap &configuration )
69{
70 Q_UNUSED( configuration )
71
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 QStringList methods;
83 {
84 QList<QgsGeometryCheckResolutionMethod> checkMethods = QgsGeometryGapCheck( nullptr, QVariantMap() ).availableResolutionMethods();
85 std::transform(
86 checkMethods.cbegin(), checkMethods.cend() - 1, std::inserter( methods, methods.begin() ),
87 []( const QgsGeometryCheckResolutionMethod &checkMethod ) { return checkMethod.name(); }
88 );
89 }
90 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Method" ), methods ) );
91
92 addParameter( new QgsProcessingParameterField(
93 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Field of original feature unique identifier" ),
94 QString(), QStringLiteral( "INPUT" )
95 ) );
96 addParameter( new QgsProcessingParameterField(
97 QStringLiteral( "ERROR_ID_IDX" ), QObject::tr( "Field of error id" ),
98 QStringLiteral( "gc_errorid" ), QStringLiteral( "GAPS" ),
100 ) );
101
102 addParameter( new QgsProcessingParameterFeatureSink(
103 QStringLiteral( "OUTPUT" ), QObject::tr( "Gaps-filled layer" ), Qgis::ProcessingSourceType::VectorPolygon
104 ) );
105 addParameter( new QgsProcessingParameterFeatureSink(
106 QStringLiteral( "REPORT" ), QObject::tr( "Report layer from fixing gaps" ), Qgis::ProcessingSourceType::VectorPoint
107 ) );
108
109 auto tolerance = std::make_unique<QgsProcessingParameterNumber>(
110 QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
111 );
112 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
113 tolerance->setHelp( QObject::tr( "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
114 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
115 addParameter( tolerance.release() );
116}
117
118QVariantMap QgsFixGeometryGapAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
119{
120 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
121 if ( !input )
122 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
123
124 const std::unique_ptr<QgsProcessingFeatureSource> neighbors( parameterAsSource( parameters, QStringLiteral( "NEIGHBORS" ), context ) );
125 if ( !neighbors )
126 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "NEIGHBORS" ) ) );
127
128 const std::unique_ptr<QgsProcessingFeatureSource> gaps( parameterAsSource( parameters, QStringLiteral( "GAPS" ), context ) );
129 if ( !gaps )
130 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "GAPS" ) ) );
131
132 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
133
134 const QString featIdFieldName = parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context );
135 const QString errorIdFieldName = parameterAsString( parameters, QStringLiteral( "ERROR_ID_IDX" ), context );
136
137 // Specific inputs for this check
138 int method = parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context );
139 switch ( method )
140 {
141 case 0:
143 break;
144 case 1:
146 break;
147 case 2:
149 break;
150 default:
151 throw QgsProcessingException( QObject::tr( "Unknown resolution method" ) );
152 }
153
154 // Verify that input fields exists
155 if ( gaps->fields().indexFromName( errorIdFieldName ) == -1 )
156 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the gaps layer." ).arg( errorIdFieldName ) );
157 if ( neighbors->fields().indexFromName( featIdFieldName ) == -1 )
158 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the neighbors layer." ).arg( featIdFieldName ) );
159 const int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
160 if ( inputIdFieldIndex == -1 )
161 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in input layer." ).arg( featIdFieldName ) );
162
163 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
164 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
165 if ( inputFeatIdFieldType != neighbors->fields().at( neighbors->fields().indexFromName( featIdFieldName ) ).type() )
166 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as in the neighbors layer." ).arg( featIdFieldName ) );
167
168 QString dest_output;
169 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink(
170 parameters, QStringLiteral( "OUTPUT" ), context, dest_output, input->fields(), input->wkbType(), input->sourceCrs()
171 ) );
172 if ( !sink_output )
173 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
174
175 QString dest_report;
176 QgsFields reportFields = gaps->fields();
177 reportFields.append( QgsField( QStringLiteral( "report" ), QMetaType::QString ) );
178 reportFields.append( QgsField( QStringLiteral( "error_fixed" ), QMetaType::Bool ) );
179 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink(
180 parameters, QStringLiteral( "REPORT" ), context, dest_report, reportFields, Qgis::WkbType::Point, gaps->sourceCrs()
181 ) );
182 if ( !sink_report )
183 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "REPORT" ) ) );
184
185 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), context.transformContext(), context.project() );
186
187 const QgsGeometryGapCheck check( &checkContext, QVariantMap() );
188
189 multiStepFeedback.setCurrentStep( 1 );
190 multiStepFeedback.setProgressText( QObject::tr( "Preparing features..." ) );
191 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize( QgsFeatureRequest() ) );
192 QgsVectorDataProviderFeaturePool featurePool = QgsVectorDataProviderFeaturePool( fixedLayer.get(), false );
193 QMap<QString, QgsFeaturePool *> featurePools;
194 featurePools.insert( fixedLayer->id(), &featurePool );
195
196 // To add features into the layer, the geometry checker looks for the layer in the project
198 {
199 context.project()->addMapLayer( fixedLayer.get(), false, false );
200 fixedLayer->startEditing();
201 }
202
203 QgsFeature gapFeature;
204 QgsFeatureIterator gapsFeaturesIt = gaps->getFeatures();
205 QgsFeature reportFeature;
206 reportFeature.setFields( reportFields );
207 long long progression = 0;
208 long long totalProgression = gaps->featureCount();
209 multiStepFeedback.setCurrentStep( 2 );
210 multiStepFeedback.setProgressText( QObject::tr( "Fixing errors..." ) );
211 while ( gapsFeaturesIt.nextFeature( gapFeature ) )
212 {
213 if ( feedback->isCanceled() )
214 break;
215
216 progression++;
217 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
218 reportFeature.setGeometry( gapFeature.geometry().centroid() );
219
220 QVariant gapId = gapFeature.attribute( errorIdFieldName );
221 if ( !gapId.isValid() || gapId.isNull() )
222 throw QgsProcessingException( QObject::tr( "NULL or invalid value found in field \"%1\"" ).arg( errorIdFieldName ) );
223
224 // Get the neighbor features of the current gap to fill the neighbors ids
225 QgsFeature f;
226 QgsFeatureIds neighborIds;
227 const QString errorIdValue = gapFeature.attribute( errorIdFieldName ).toString();
228 QgsFeatureIterator it = neighbors->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + errorIdFieldName + "\" = " + errorIdValue ) );
229 while ( it.nextFeature( f ) )
230 {
231 QString neighborIdValue = f.attribute( featIdFieldName ).toString();
232 if ( inputFeatIdFieldType == QMetaType::QString )
233 neighborIdValue = "'" + neighborIdValue + "'";
234 QgsFeature neighborFeature;
235 if ( fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + neighborIdValue ) ).nextFeature( neighborFeature ) )
236 neighborIds << neighborFeature.id();
237 }
238
239 QMap<QString, QgsFeatureIds> neighborsMap;
240 neighborsMap.insert( fixedLayer->id(), neighborIds );
242 &check,
243 fixedLayer->id(),
244 gapFeature.geometry(),
245 neighborsMap,
246 0,
247 QgsRectangle(),
249 );
250
252 check.fixError( featurePools, &gapError, method, QMap<QString, int>(), changes );
253
254 QString resolutionMessage = gapError.resolutionMessage();
256 resolutionMessage = QObject::tr( "Error is obsolete" );
257
258 reportFeature.setAttributes( gapFeature.attributes() << resolutionMessage << ( gapError.status() == QgsGeometryCheckError::StatusFixed ) );
259
260 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
261 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
262 }
263 multiStepFeedback.setProgress( 100 );
264
266 {
267 if ( !fixedLayer->commitChanges() )
268 throw QgsProcessingException( QObject::tr( "Unable to add gap features" ) );
269 context.project()->removeMapLayer( fixedLayer.get() );
270 }
271
272 progression = 0;
273 totalProgression = fixedLayer->featureCount();
274 multiStepFeedback.setCurrentStep( 2 );
275 multiStepFeedback.setProgressText( QObject::tr( "Exporting fixed layer..." ) );
276 QgsFeature fixedFeature;
277 QgsFeatureIterator fixedFeaturesIt = fixedLayer->getFeatures();
278 while ( fixedFeaturesIt.nextFeature( fixedFeature ) )
279 {
280 if ( feedback->isCanceled() )
281 break;
282
283 progression++;
284 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
285 if ( !sink_output->addFeature( fixedFeature, QgsFeatureSink::FastInsert ) )
286 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
287 }
288 multiStepFeedback.setProgress( 100 );
289
290 QVariantMap outputs;
291 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
292 outputs.insert( QStringLiteral( "REPORT" ), dest_report );
293
294 return outputs;
295}
296
297bool QgsFixGeometryGapAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
298{
299 mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );
300
301 return true;
302}
303
304Qgis::ProcessingAlgorithmFlags QgsFixGeometryGapAlgorithm::flags() const
305{
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:3539
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
@ Numeric
Accepts numeric fields.
Definition qgis.h:3818
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3609
@ Point
Point.
Definition qgis.h:279
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3588
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3596
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
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:54
QMetaType::Type type
Definition qgsfield.h:61
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:73
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.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProject * project() const
Returns the project in which the algorithm is being 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.
void removeMapLayer(const QString &layerId)
Remove a layer from the registry by layer ID.
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