QGIS API Documentation 3.43.0-Master (c4a2e9c6d2f)
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( "Fix geometry (gap)" );
34}
35
36QStringList QgsFixGeometryGapAlgorithm::tags() const
37{
38 return QObject::tr( "fix,gap" ).split( ',' );
39}
40
41QString QgsFixGeometryGapAlgorithm::group() const
42{
43 return QObject::tr( "Fix geometry" );
44}
45
46QString QgsFixGeometryGapAlgorithm::groupId() const
47{
48 return QStringLiteral( "fixgeometry" );
49}
50
51QString QgsFixGeometryGapAlgorithm::shortHelpString() const
52{
53 return QObject::tr( "This algorithm fills the gaps based on a gap and neighbors layer from the check gap algorithm." );
54}
55
56QgsFixGeometryGapAlgorithm *QgsFixGeometryGapAlgorithm::createInstance() const
57{
58 return new QgsFixGeometryGapAlgorithm();
59}
60
61void QgsFixGeometryGapAlgorithm::initAlgorithm( const QVariantMap &configuration )
62{
63 Q_UNUSED( configuration )
64
65 // Inputs
67 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
68 ) );
70 QStringLiteral( "NEIGHBORS" ), QObject::tr( "Neighbors layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector )
71 ) );
73 QStringLiteral( "GAPS" ), QObject::tr( "Gaps layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
74 ) );
75
76 // Specific inputs for this check
77 QStringList methods;
78 {
79 QList<QgsGeometryCheckResolutionMethod> checkMethods = QgsGeometryGapCheck( nullptr, QVariantMap() ).availableResolutionMethods();
80 std::transform(
81 checkMethods.cbegin(), checkMethods.cend() - 1, std::inserter( methods, methods.begin() ),
82 []( const QgsGeometryCheckResolutionMethod &checkMethod ) { return checkMethod.name(); }
83 );
84 }
85 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Method" ), methods ) );
86
87 addParameter( new QgsProcessingParameterField(
88 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Field of original feature unique identifier" ),
89 QString(), QStringLiteral( "INPUT" )
90 ) );
91 addParameter( new QgsProcessingParameterField(
92 QStringLiteral( "ERROR_ID_IDX" ), QObject::tr( "Field of error id" ),
93 QStringLiteral( "gc_errorid" ), QStringLiteral( "GAPS" ),
95 ) );
96
97 // Outputs
98 addParameter( new QgsProcessingParameterFeatureSink(
99 QStringLiteral( "OUTPUT" ), QObject::tr( "Output layer" ), Qgis::ProcessingSourceType::VectorPolygon
100 ) );
101 addParameter( new QgsProcessingParameterFeatureSink(
102 QStringLiteral( "REPORT" ), QObject::tr( "Report layer" ), Qgis::ProcessingSourceType::VectorPoint
103 ) );
104
105 std::unique_ptr<QgsProcessingParameterNumber> tolerance = std::make_unique<QgsProcessingParameterNumber>(
106 QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
107 );
108 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
109 addParameter( tolerance.release() );
110}
111
112QVariantMap QgsFixGeometryGapAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
113{
114 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
115 if ( !input )
116 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
117
118 const std::unique_ptr<QgsProcessingFeatureSource> neighbors( parameterAsSource( parameters, QStringLiteral( "NEIGHBORS" ), context ) );
119 if ( !neighbors )
120 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "NEIGHBORS" ) ) );
121
122 const std::unique_ptr<QgsProcessingFeatureSource> gaps( parameterAsSource( parameters, QStringLiteral( "GAPS" ), context ) );
123 if ( !gaps )
124 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "GAPS" ) ) );
125
126 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
127
128 const QString featIdFieldName = parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context );
129 const QString errorIdFieldName = parameterAsString( parameters, QStringLiteral( "ERROR_ID_IDX" ), context );
130
131 // Specific inputs for this check
132 int method = parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context );
133 switch ( method )
134 {
135 case 0:
137 break;
138 case 1:
140 break;
141 case 2:
143 break;
144 default:
145 throw QgsProcessingException( QObject::tr( "Unknown resolution method" ) );
146 }
147
148 // Verify that input fields exists
149 if ( gaps->fields().indexFromName( errorIdFieldName ) == -1 )
150 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the gaps layer." ).arg( errorIdFieldName ) );
151 if ( neighbors->fields().indexFromName( featIdFieldName ) == -1 )
152 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the neighbors layer." ).arg( featIdFieldName ) );
153 int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
154 if ( inputIdFieldIndex == -1 )
155 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in input layer." ).arg( featIdFieldName ) );
156
157 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
158 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
159 if ( inputFeatIdFieldType != neighbors->fields().at( neighbors->fields().indexFromName( featIdFieldName ) ).type() )
160 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as in the neighbors layer." ).arg( featIdFieldName ) );
161
162 QString dest_output;
163 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink(
164 parameters, QStringLiteral( "OUTPUT" ), context, dest_output, input->fields(), input->wkbType(), input->sourceCrs()
165 ) );
166 if ( !sink_output )
167 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
168
169 QString dest_report;
170 QgsFields reportFields = gaps->fields();
171 reportFields.append( QgsField( QStringLiteral( "report" ), QMetaType::QString ) );
172 reportFields.append( QgsField( QStringLiteral( "error_fixed" ), QMetaType::Bool ) );
173 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink(
174 parameters, QStringLiteral( "REPORT" ), context, dest_report, reportFields, Qgis::WkbType::Point, gaps->sourceCrs()
175 ) );
176 if ( !sink_report )
177 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "REPORT" ) ) );
178
179 QgsProject *project = QgsProject::instance();
181 mTolerance, input->sourceCrs(), project->transformContext(), project
182 );
183 QStringList messages;
184
185 const QgsGeometryGapCheck check( &checkContext, QVariantMap() );
186
187 multiStepFeedback.setCurrentStep( 1 );
188 multiStepFeedback.setProgressText( QObject::tr( "Preparing features..." ) );
189 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize( QgsFeatureRequest() ) );
190 QgsVectorDataProviderFeaturePool featurePool = QgsVectorDataProviderFeaturePool( fixedLayer.get(), false );
191 QMap<QString, QgsFeaturePool *> featurePools;
192 featurePools.insert( fixedLayer->id(), &featurePool );
193
194 // To add features into the layer, the geometry checker looks for the layer in the project
196 {
197 project->addMapLayer( fixedLayer.get(), false, false );
198 fixedLayer->startEditing();
199 }
200
201 QgsFeature gapFeature;
202 QgsFeatureIterator gapsFeaturesIt = gaps->getFeatures();
203 QgsFeature reportFeature;
204 reportFeature.setFields( reportFields );
205 long long progression = 0;
206 long long totalProgression = gaps->featureCount();
207 multiStepFeedback.setCurrentStep( 2 );
208 multiStepFeedback.setProgressText( QObject::tr( "Fixing errors..." ) );
209 while ( gapsFeaturesIt.nextFeature( gapFeature ) )
210 {
211 progression++;
212 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
213 reportFeature.setGeometry( gapFeature.geometry().centroid() );
214
215 QVariant gapId = gapFeature.attribute( errorIdFieldName );
216 if ( !gapId.isValid() || gapId.isNull() )
217 throw QgsProcessingException( QObject::tr( "NULL or invalid value found in field \"%1\"" ).arg( errorIdFieldName ) );
218
219 // Get the neighbor features of the current gap to fill the neighbors ids
220 QgsFeature f;
221 QgsFeatureIds neighborIds;
222 const QString errorIdValue = gapFeature.attribute( errorIdFieldName ).toString();
223 QgsFeatureIterator it = neighbors->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + errorIdFieldName + "\" = " + errorIdValue ) );
224 while ( it.nextFeature( f ) )
225 {
226 QString neighborIdValue = f.attribute( featIdFieldName ).toString();
227 if ( inputFeatIdFieldType == QMetaType::QString )
228 neighborIdValue = "'" + neighborIdValue + "'";
229 QgsFeature neighborFeature;
230 if ( fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + neighborIdValue ) ).nextFeature( neighborFeature ) )
231 neighborIds << neighborFeature.id();
232 }
233
234 QMap<QString, QgsFeatureIds> neighborsMap;
235 neighborsMap.insert( fixedLayer->id(), neighborIds );
237 &check,
238 fixedLayer->id(),
239 gapFeature.geometry(),
240 neighborsMap,
241 0,
242 QgsRectangle(),
244 );
245
247 check.fixError( featurePools, &gapError, method, QMap<QString, int>(), changes );
248
249 QString resolutionMessage = gapError.resolutionMessage();
251 resolutionMessage = QObject::tr( "Error is obsolete" );
252
253 reportFeature.setAttributes( gapFeature.attributes() << resolutionMessage << ( gapError.status() == QgsGeometryCheckError::StatusFixed ) );
254
255 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
256 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
257 }
258 multiStepFeedback.setProgress( 100 );
259
261 {
262 if ( !fixedLayer->commitChanges() )
263 throw QgsProcessingException( QObject::tr( "Unable to add gap features" ) );
264 project->removeMapLayer( fixedLayer.get() );
265 }
266
267 progression = 0;
268 totalProgression = fixedLayer->featureCount();
269 multiStepFeedback.setCurrentStep( 2 );
270 multiStepFeedback.setProgressText( QObject::tr( "Exporting fixed layer..." ) );
271 QgsFeature fixedFeature;
272 QgsFeatureIterator fixedFeaturesIt = fixedLayer->getFeatures();
273 while ( fixedFeaturesIt.nextFeature( fixedFeature ) )
274 {
275 progression++;
276 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
277 if ( !sink_output->addFeature( fixedFeature, QgsFeatureSink::FastInsert ) )
278 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
279 }
280 multiStepFeedback.setProgress( 100 );
281
282 QVariantMap outputs;
283 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
284 outputs.insert( QStringLiteral( "REPORT" ), dest_report );
285
286 return outputs;
287}
288
289bool QgsFixGeometryGapAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
290{
291 mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );
292
293 return true;
294}
295
296Qgis::ProcessingAlgorithmFlags QgsFixGeometryGapAlgorithm::flags() const
297{
299}
300
@ 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.
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