QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmfixgeometryselfintersection.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmfixgeometryselfintersection.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
23#include "qgsvectorfilewriter.h"
24
26
27QString QgsFixGeometrySelfIntersectionAlgorithm::name() const
28{
29 return QStringLiteral( "fixgeometryselfintersection" );
30}
31
32QString QgsFixGeometrySelfIntersectionAlgorithm::displayName() const
33{
34 return QObject::tr( "Split self-intersecting geometries" );
35}
36
37QString QgsFixGeometrySelfIntersectionAlgorithm::shortDescription() const
38{
39 return QObject::tr( "Splits features detected with the \"Self-intersections\" algorithm from the \"Check geometry\" section." );
40}
41
42QStringList QgsFixGeometrySelfIntersectionAlgorithm::tags() const
43{
44 return QObject::tr( "fix,self,intersection,split,multipart" ).split( ',' );
45}
46
47QString QgsFixGeometrySelfIntersectionAlgorithm::group() const
48{
49 return QObject::tr( "Fix geometry" );
50}
51
52QString QgsFixGeometrySelfIntersectionAlgorithm::groupId() const
53{
54 return QStringLiteral( "fixgeometry" );
55}
56
57QString QgsFixGeometrySelfIntersectionAlgorithm::shortHelpString() const
58{
59 return QObject::tr( "This algorithm splits self intersecting lines or polygons according to the chosen method, "
60 "based on an error layer from the \"Self-intersections\" algorithm in the \"Check geometry\" section." );
61}
62
63QgsFixGeometrySelfIntersectionAlgorithm *QgsFixGeometrySelfIntersectionAlgorithm::createInstance() const
64{
65 return new QgsFixGeometrySelfIntersectionAlgorithm();
66}
67
68void QgsFixGeometrySelfIntersectionAlgorithm::initAlgorithm( const QVariantMap &configuration )
69{
70 Q_UNUSED( configuration )
71
72 // Inputs
74 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ),
75 QList<int>()
76 << static_cast<int>( Qgis::ProcessingSourceType::VectorLine )
78 ) );
80 QStringLiteral( "ERRORS" ), QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
81 ) );
82
83 // Specific inputs for this check
84 QStringList methods;
85 {
86 QList<QgsGeometryCheckResolutionMethod> checkMethods = QgsGeometrySelfIntersectionCheck( nullptr, QVariantMap() ).availableResolutionMethods();
87 std::transform(
88 checkMethods.cbegin(), checkMethods.cend() - 1, std::inserter( methods, methods.begin() ),
89 []( const QgsGeometryCheckResolutionMethod &checkMethod ) { return checkMethod.name(); }
90 );
91 }
92 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Method" ), methods ) );
93
94 addParameter( new QgsProcessingParameterField(
95 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Field of original feature unique identifier" ),
96 QString(), QStringLiteral( "ERRORS" )
97 ) );
98 addParameter( new QgsProcessingParameterField(
99 QStringLiteral( "PART_IDX" ), QObject::tr( "Field of part index" ),
100 QStringLiteral( "gc_partidx" ), QStringLiteral( "ERRORS" ),
102 ) );
103 addParameter( new QgsProcessingParameterField(
104 QStringLiteral( "RING_IDX" ), QObject::tr( "Field of ring index" ),
105 QStringLiteral( "gc_ringidx" ), QStringLiteral( "ERRORS" ),
107 ) );
108 addParameter( new QgsProcessingParameterField(
109 QStringLiteral( "VERTEX_IDX" ), QObject::tr( "Field of vertex index" ),
110 QStringLiteral( "gc_vertidx" ), QStringLiteral( "ERRORS" ),
112 ) );
113 addParameter( new QgsProcessingParameterField(
114 QStringLiteral( "SEGMENT_1" ), QObject::tr( "Field of segment 1" ),
115 QStringLiteral( "gc_segment_1" ), QStringLiteral( "ERRORS" ),
117 ) );
118 addParameter( new QgsProcessingParameterField(
119 QStringLiteral( "SEGMENT_2" ), QObject::tr( "Field of segment 2" ),
120 QStringLiteral( "gc_segment_2" ), QStringLiteral( "ERRORS" ),
122 ) );
123
124 // Outputs
125 addParameter( new QgsProcessingParameterFeatureSink(
126 QStringLiteral( "OUTPUT" ), QObject::tr( "Self-intersections fixed layer" ), Qgis::ProcessingSourceType::VectorPolygon
127 ) );
128 addParameter( new QgsProcessingParameterFeatureSink(
129 QStringLiteral( "REPORT" ), QObject::tr( "Report layer from fixing self-intersections" ), Qgis::ProcessingSourceType::VectorPoint
130 ) );
131
132 std::unique_ptr<QgsProcessingParameterNumber> tolerance = std::make_unique<QgsProcessingParameterNumber>(
133 QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
134 );
135 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
136 tolerance->setHelp( QObject::tr( "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
137 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
138 addParameter( tolerance.release() );
139}
140
141QVariantMap QgsFixGeometrySelfIntersectionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
142{
143 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
144 if ( !input )
145 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
146
147 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, QStringLiteral( "ERRORS" ), context ) );
148 if ( !errors )
149 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "ERRORS" ) ) );
150
151 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
152
153 const QString featIdFieldName = parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context );
154 const QString partIdxFieldName = parameterAsString( parameters, QStringLiteral( "PART_IDX" ), context );
155 const QString ringIdxFieldName = parameterAsString( parameters, QStringLiteral( "RING_IDX" ), context );
156 const QString vertexIdxFieldName = parameterAsString( parameters, QStringLiteral( "VERTEX_IDX" ), context );
157 const QString segment1FieldName = parameterAsString( parameters, QStringLiteral( "SEGMENT_1" ), context );
158 const QString segment2FieldName = parameterAsString( parameters, QStringLiteral( "SEGMENT_2" ), context );
159
160 // Specific inputs for this check
161 const int method = parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context );
162
163 // Verify that input fields exists
164 if ( errors->fields().indexFromName( featIdFieldName ) == -1 )
165 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( featIdFieldName ) );
166 if ( errors->fields().indexFromName( partIdxFieldName ) == -1 )
167 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( partIdxFieldName ) );
168 if ( errors->fields().indexFromName( ringIdxFieldName ) == -1 )
169 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( ringIdxFieldName ) );
170 if ( errors->fields().indexFromName( vertexIdxFieldName ) == -1 )
171 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( vertexIdxFieldName ) );
172 if ( errors->fields().indexFromName( segment1FieldName ) == -1 )
173 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( segment1FieldName ) );
174 if ( errors->fields().indexFromName( segment2FieldName ) == -1 )
175 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( segment2FieldName ) );
176 int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
177 if ( inputIdFieldIndex == -1 )
178 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in input layer." ).arg( featIdFieldName ) );
179
180 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
181 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
182 if ( inputFeatIdFieldType != errors->fields().at( errors->fields().indexFromName( featIdFieldName ) ).type() )
183 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as in the error layer." ).arg( featIdFieldName ) );
184
185 QString dest_output;
186 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink(
187 parameters, QStringLiteral( "OUTPUT" ), context, dest_output, input->fields(), input->wkbType(), input->sourceCrs()
188 ) );
189 if ( !sink_output )
190 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
191
192 QString dest_report;
193 QgsFields reportFields = errors->fields();
194 reportFields.append( QgsField( QStringLiteral( "report" ), QMetaType::QString ) );
195 reportFields.append( QgsField( QStringLiteral( "error_fixed" ), QMetaType::Bool ) );
196 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink(
197 parameters, QStringLiteral( "REPORT" ), context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs()
198 ) );
199 if ( !sink_report )
200 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "REPORT" ) ) );
201
202 const QgsProject *project = QgsProject::instance();
203 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), project->transformContext(), project );
204 QStringList messages;
205
206 const QgsGeometrySelfIntersectionCheck check( &checkContext, QVariantMap() );
207
208 multiStepFeedback.setCurrentStep( 1 );
209 multiStepFeedback.setProgressText( QObject::tr( "Preparing features..." ) );
210 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize( QgsFeatureRequest() ) );
211 QgsVectorDataProviderFeaturePool featurePool = QgsVectorDataProviderFeaturePool( fixedLayer.get(), false );
212 QMap<QString, QgsFeaturePool *> featurePools;
213 featurePools.insert( fixedLayer->id(), &featurePool );
214
215 QgsFeature errorFeature, inputFeature, testDuplicateIdFeature;
216 QgsFeatureIterator errorFeaturesIt = errors->getFeatures();
217 QList<QgsGeometryCheck::Changes> changesList;
218 QgsFeature reportFeature;
219 reportFeature.setFields( reportFields );
220 long long progression = 0;
221 QgsFeatureIds fixedFeatures;
222 long long totalProgression = errors->featureCount();
223 multiStepFeedback.setCurrentStep( 2 );
224 multiStepFeedback.setProgressText( QObject::tr( "Fixing errors..." ) );
225 while ( errorFeaturesIt.nextFeature( errorFeature ) )
226 {
227 if ( feedback->isCanceled() )
228 break;
229
230 progression++;
231 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
232 reportFeature.setGeometry( errorFeature.geometry() );
233
234 QVariant attr = errorFeature.attribute( featIdFieldName );
235 if ( !attr.isValid() || attr.isNull() )
236 throw QgsProcessingException( QObject::tr( "NULL or invalid value found in unique field \"%1\"" ).arg( featIdFieldName ) );
237
238 QString idValue = errorFeature.attribute( featIdFieldName ).toString();
239 if ( inputFeatIdFieldType == QMetaType::QString )
240 idValue = "'" + idValue + "'";
241
242 QgsFeatureIterator it = fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue ) );
243 if ( !it.nextFeature( inputFeature ) || !inputFeature.isValid() )
244 {
245 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Source feature not found or invalid" ) << false );
246 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
247 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
248 continue;
249 }
250
251 // If a previous input feature has been fixed with the ToSingleObjects method, it means
252 // that we have split the input feature into two features, with the same attribute value for
253 // the uniqiue id field...
254 // As a result, we must keep track of the internal feature ids of already fixed features,
255 // which IS unique within the layer even after the split.
256 // Here we get the next feature with the user unique id which has not been already fixed.
257 bool skip = false;
259 {
260 while ( true )
261 {
262 if ( fixedFeatures.contains( inputFeature.id() ) )
263 {
264 if ( !it.nextFeature( inputFeature ) )
265 skip = true; // should not happen if the errors layer and the input layer are coherent.
266 }
267 else
268 break;
269 }
270 }
272 {
273 if ( it.nextFeature( testDuplicateIdFeature ) )
274 throw QgsProcessingException( QObject::tr( "More than one feature found in input layer with value %1 in unique field %2" ).arg( idValue ).arg( featIdFieldName ) );
275 }
276 if ( skip )
277 continue;
278
279 if ( inputFeature.geometry().isNull() )
280 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Feature geometry is null" ) << false );
281
282 else if ( QgsGeometryCheckerUtils::getGeomPart( inputFeature.geometry().constGet(), errorFeature.attribute( partIdxFieldName ).toInt() ) == nullptr )
283 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Feature geometry part is null" ) << false );
284
285 else
286 {
288 intersection.segment1 = errorFeature.attribute( segment1FieldName ).toInt();
289 intersection.segment2 = errorFeature.attribute( segment2FieldName ).toInt();
291 &check,
292 inputFeature.geometry(),
293 errorFeature.geometry(),
295 errorFeature.attribute( partIdxFieldName ).toInt(),
296 errorFeature.attribute( ringIdxFieldName ).toInt(),
297 errorFeature.attribute( vertexIdxFieldName ).toInt()
298 ),
299 intersection
300 );
302 &intersectionError,
303 QgsGeometryCheckerUtils::LayerFeature( &featurePool, inputFeature, &checkContext, false )
304 );
305 for ( QgsGeometryCheck::Changes changes : changesList )
306 checkError.handleChanges( changes );
307
309
310 check.fixError( featurePools, &checkError, method, QMap<QString, int>(), changes );
311 changesList << changes;
312
313 QString resolutionMessage = checkError.resolutionMessage();
314 if ( checkError.status() == QgsGeometryCheckError::StatusObsolete )
315 resolutionMessage = QObject::tr( "Error is obsolete" );
316 else if ( checkError.status() == QgsGeometryCheckError::StatusFixed )
317 fixedFeatures << inputFeature.id();
318
319 reportFeature.setAttributes( errorFeature.attributes() << resolutionMessage << ( checkError.status() == QgsGeometryCheckError::StatusFixed ) );
320 }
321
322 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
323 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
324 }
325 multiStepFeedback.setProgress( 100 );
326
327 progression = 0;
328 totalProgression = fixedLayer->featureCount();
329 multiStepFeedback.setCurrentStep( 2 );
330 multiStepFeedback.setProgressText( QObject::tr( "Exporting fixed layer..." ) );
331 QgsFeature fixedFeature;
332 QgsFeatureIterator fixedFeaturesIt = fixedLayer->getFeatures();
333 while ( fixedFeaturesIt.nextFeature( fixedFeature ) )
334 {
335 if ( feedback->isCanceled() )
336 break;
337
338 progression++;
339 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
340 if ( !sink_output->addFeature( fixedFeature, QgsFeatureSink::FastInsert ) )
341 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
342 }
343 multiStepFeedback.setProgress( 100 );
344
345 QVariantMap outputs;
346 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
347 outputs.insert( QStringLiteral( "REPORT" ), dest_report );
348
349 return outputs;
350}
351
352bool QgsFixGeometrySelfIntersectionAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
353{
354 mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );
355
356 return true;
357}
358
359Qgis::ProcessingAlgorithmFlags QgsFixGeometrySelfIntersectionAlgorithm::flags() const
360{
362}
363
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ VectorLine
Vector line 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
bool isValid() const
Returns the validity of this feature.
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.
Wraps a QgsSingleGeometryError into a standard QgsGeometryCheckError.
@ 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.
virtual QList< QgsGeometryCheckResolutionMethod > availableResolutionMethods() const
Returns a list of available resolution methods.
A layer feature combination to uniquely identify and access a feature in a set of layers.
static QgsAbstractGeometry * getGeomPart(QgsAbstractGeometry *geom, int partIdx)
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
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
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsCoordinateTransformContext transformContext
Definition qgsproject.h:113
A feature pool based on a vector data provider.
QSet< QgsFeatureId > QgsFeatureIds
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30