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