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