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