QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
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
26#include <QString>
27
28using namespace Qt::StringLiterals;
29
31
32QString QgsFixGeometrySelfIntersectionAlgorithm::name() const
33{
34 return u"fixgeometryselfintersection"_s;
35}
36
37QString QgsFixGeometrySelfIntersectionAlgorithm::displayName() const
38{
39 return QObject::tr( "Split self-intersecting geometries" );
40}
41
42QString QgsFixGeometrySelfIntersectionAlgorithm::shortDescription() const
43{
44 return QObject::tr( "Splits features detected with the \"Self-intersections\" algorithm from the \"Check geometry\" section." );
45}
46
47QStringList QgsFixGeometrySelfIntersectionAlgorithm::tags() const
48{
49 return QObject::tr( "fix,self,intersection,split,multipart" ).split( ',' );
50}
51
52QString QgsFixGeometrySelfIntersectionAlgorithm::group() const
53{
54 return QObject::tr( "Fix geometry" );
55}
56
57QString QgsFixGeometrySelfIntersectionAlgorithm::groupId() const
58{
59 return u"fixgeometry"_s;
60}
61
62QString QgsFixGeometrySelfIntersectionAlgorithm::shortHelpString() const
63{
64 return QObject::tr(
65 "This algorithm splits self intersecting lines or polygons according to the chosen method, "
66 "based on an error layer from the \"Self-intersections\" algorithm in the \"Check geometry\" section."
67 );
68}
69
70QgsFixGeometrySelfIntersectionAlgorithm *QgsFixGeometrySelfIntersectionAlgorithm::createInstance() const
71{
72 return new QgsFixGeometrySelfIntersectionAlgorithm();
73}
74
75void QgsFixGeometrySelfIntersectionAlgorithm::initAlgorithm( const QVariantMap &configuration )
76{
77 Q_UNUSED( configuration )
78
79 addParameter(
80 new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) )
81 );
82 addParameter( new QgsProcessingParameterFeatureSource( u"ERRORS"_s, QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
83
84 QStringList methods;
85 {
86 QList<QgsGeometryCheckResolutionMethod> checkMethods = QgsGeometrySelfIntersectionCheck( nullptr, QVariantMap() ).availableResolutionMethods();
87 std::transform( checkMethods.cbegin(), checkMethods.cend() - 1, std::inserter( methods, methods.begin() ), []( const QgsGeometryCheckResolutionMethod &checkMethod ) { return checkMethod.name(); } );
88 }
89 addParameter( new QgsProcessingParameterEnum( u"METHOD"_s, QObject::tr( "Method" ), methods ) );
90
91 addParameter( new QgsProcessingParameterField( u"UNIQUE_ID"_s, QObject::tr( "Field of original feature unique identifier" ), QString(), u"ERRORS"_s ) );
92 addParameter( new QgsProcessingParameterField( u"PART_IDX"_s, QObject::tr( "Field of part index" ), u"gc_partidx"_s, u"ERRORS"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
93 addParameter( new QgsProcessingParameterField( u"RING_IDX"_s, QObject::tr( "Field of ring index" ), u"gc_ringidx"_s, u"ERRORS"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
94 addParameter( new QgsProcessingParameterField( u"VERTEX_IDX"_s, QObject::tr( "Field of vertex index" ), u"gc_vertidx"_s, u"ERRORS"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
95 addParameter( new QgsProcessingParameterField( u"SEGMENT_1"_s, QObject::tr( "Field of segment 1" ), u"gc_segment_1"_s, u"ERRORS"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
96 addParameter( new QgsProcessingParameterField( u"SEGMENT_2"_s, QObject::tr( "Field of segment 2" ), u"gc_segment_2"_s, u"ERRORS"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
97
98 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Self-intersections fixed layer" ), Qgis::ProcessingSourceType::VectorPolygon ) );
99 addParameter( new QgsProcessingParameterFeatureSink( u"REPORT"_s, QObject::tr( "Report layer from fixing self-intersections" ), Qgis::ProcessingSourceType::VectorPoint ) );
100
101 auto tolerance = std::make_unique<QgsProcessingParameterNumber>( u"TOLERANCE"_s, QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13 );
102 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
103 tolerance->setHelp(
104 QObject::tr(
105 "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
106 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero."
107 )
108 );
109 addParameter( tolerance.release() );
110}
111
112QVariantMap QgsFixGeometrySelfIntersectionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
113{
114 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
115 if ( !input )
116 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
117
118 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, u"ERRORS"_s, context ) );
119 if ( !errors )
120 throw QgsProcessingException( invalidSourceError( parameters, u"ERRORS"_s ) );
121
122 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
123
124 const QString featIdFieldName = parameterAsString( parameters, u"UNIQUE_ID"_s, context );
125 const QString partIdxFieldName = parameterAsString( parameters, u"PART_IDX"_s, context );
126 const QString ringIdxFieldName = parameterAsString( parameters, u"RING_IDX"_s, context );
127 const QString vertexIdxFieldName = parameterAsString( parameters, u"VERTEX_IDX"_s, context );
128 const QString segment1FieldName = parameterAsString( parameters, u"SEGMENT_1"_s, context );
129 const QString segment2FieldName = parameterAsString( parameters, u"SEGMENT_2"_s, context );
130
131 const int method = parameterAsEnum( parameters, u"METHOD"_s, context );
132
133 // Verify that input fields exists
134 if ( errors->fields().indexFromName( featIdFieldName ) == -1 )
135 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( featIdFieldName ) );
136 if ( errors->fields().indexFromName( partIdxFieldName ) == -1 )
137 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( partIdxFieldName ) );
138 if ( errors->fields().indexFromName( ringIdxFieldName ) == -1 )
139 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( ringIdxFieldName ) );
140 if ( errors->fields().indexFromName( vertexIdxFieldName ) == -1 )
141 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( vertexIdxFieldName ) );
142 if ( errors->fields().indexFromName( segment1FieldName ) == -1 )
143 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( segment1FieldName ) );
144 if ( errors->fields().indexFromName( segment2FieldName ) == -1 )
145 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( segment2FieldName ) );
146 const int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
147 if ( inputIdFieldIndex == -1 )
148 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in input layer." ).arg( featIdFieldName ) );
149
150 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
151 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
152 if ( inputFeatIdFieldType != errors->fields().at( errors->fields().indexFromName( featIdFieldName ) ).type() )
153 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as in the error layer." ).arg( featIdFieldName ) );
154
155 QString dest_output;
156 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, u"OUTPUT"_s, context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
157 if ( !sink_output )
158 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
159
160 QString dest_report;
161 QgsFields reportFields = errors->fields();
162 reportFields.append( QgsField( u"report"_s, QMetaType::QString ) );
163 reportFields.append( QgsField( u"error_fixed"_s, QMetaType::Bool ) );
164 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, u"REPORT"_s, context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
165 if ( !sink_report )
166 throw QgsProcessingException( invalidSinkError( parameters, u"REPORT"_s ) );
167
168 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), context.transformContext(), context.project() );
169
170 const QgsGeometrySelfIntersectionCheck check( &checkContext, QVariantMap() );
171
172 multiStepFeedback.setCurrentStep( 1 );
173 multiStepFeedback.setProgressText( QObject::tr( "Preparing features..." ) );
174 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize( QgsFeatureRequest() ) );
175 QgsVectorDataProviderFeaturePool featurePool = QgsVectorDataProviderFeaturePool( fixedLayer.get(), false );
176 QMap<QString, QgsFeaturePool *> featurePools;
177 featurePools.insert( fixedLayer->id(), &featurePool );
178
179 QgsFeature errorFeature, inputFeature, testDuplicateIdFeature;
180 QgsFeatureIterator errorFeaturesIt = errors->getFeatures();
181 QList<QgsGeometryCheck::Changes> changesList;
182 QgsFeature reportFeature;
183 reportFeature.setFields( reportFields );
184 long long progression = 0;
185 QgsFeatureIds fixedFeatures;
186 long long totalProgression = errors->featureCount();
187 multiStepFeedback.setCurrentStep( 2 );
188 multiStepFeedback.setProgressText( QObject::tr( "Fixing errors..." ) );
189 while ( errorFeaturesIt.nextFeature( errorFeature ) )
190 {
191 if ( feedback->isCanceled() )
192 break;
193
194 progression++;
195 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
196 reportFeature.setGeometry( errorFeature.geometry() );
197
198 QVariant attr = errorFeature.attribute( featIdFieldName );
199 if ( !attr.isValid() || attr.isNull() )
200 throw QgsProcessingException( QObject::tr( "NULL or invalid value found in unique field \"%1\"" ).arg( featIdFieldName ) );
201
202 QString idValue = errorFeature.attribute( featIdFieldName ).toString();
203 if ( inputFeatIdFieldType == QMetaType::QString )
204 idValue = "'" + idValue + "'";
205
206 QgsFeatureIterator it = fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue ) );
207 if ( !it.nextFeature( inputFeature ) || !inputFeature.isValid() )
208 {
209 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Source feature not found or invalid" ) << false );
210 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
211 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, u"REPORT"_s ) );
212 continue;
213 }
214
215 // If a previous input feature has been fixed with the ToSingleObjects method, it means
216 // that we have split the input feature into two features, with the same attribute value for
217 // the uniqiue id field...
218 // As a result, we must keep track of the internal feature ids of already fixed features,
219 // which IS unique within the layer even after the split.
220 // Here we get the next feature with the user unique id which has not been already fixed.
221 bool skip = false;
223 {
224 while ( true )
225 {
226 if ( fixedFeatures.contains( inputFeature.id() ) )
227 {
228 if ( !it.nextFeature( inputFeature ) )
229 skip = true; // should not happen if the errors layer and the input layer are coherent.
230 }
231 else
232 break;
233 }
234 }
236 {
237 if ( it.nextFeature( testDuplicateIdFeature ) )
238 throw QgsProcessingException( QObject::tr( "More than one feature found in input layer with value %1 in unique field %2" ).arg( idValue, featIdFieldName ) );
239 }
240 if ( skip )
241 continue;
242
243 if ( inputFeature.geometry().isNull() )
244 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Feature geometry is null" ) << false );
245
246 else if ( QgsGeometryCheckerUtils::getGeomPart( inputFeature.geometry().constGet(), errorFeature.attribute( partIdxFieldName ).toInt() ) == nullptr )
247 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Feature geometry part is null" ) << false );
248
249 else
250 {
252 intersection.segment1 = errorFeature.attribute( segment1FieldName ).toInt();
253 intersection.segment2 = errorFeature.attribute( segment2FieldName ).toInt();
255 &check,
256 inputFeature.geometry(),
257 errorFeature.geometry(),
258 QgsVertexId( errorFeature.attribute( partIdxFieldName ).toInt(), errorFeature.attribute( ringIdxFieldName ).toInt(), errorFeature.attribute( vertexIdxFieldName ).toInt() ),
259 intersection
260 );
261 QgsGeometryCheckErrorSingle checkError = QgsGeometryCheckErrorSingle( &intersectionError, QgsGeometryCheckerUtils::LayerFeature( &featurePool, inputFeature, &checkContext, false ) );
262 for ( const QgsGeometryCheck::Changes &changes : std::as_const( changesList ) )
263 checkError.handleChanges( changes );
264
266
267 check.fixError( featurePools, &checkError, method, QMap<QString, int>(), changes );
268 changesList << changes;
269
270 QString resolutionMessage = checkError.resolutionMessage();
271 if ( checkError.status() == QgsGeometryCheckError::StatusObsolete )
272 resolutionMessage = QObject::tr( "Error is obsolete" );
273 else if ( checkError.status() == QgsGeometryCheckError::StatusFixed )
274 fixedFeatures << inputFeature.id();
275
276 reportFeature.setAttributes( errorFeature.attributes() << resolutionMessage << ( checkError.status() == QgsGeometryCheckError::StatusFixed ) );
277 }
278
279 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
280 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, u"REPORT"_s ) );
281 }
282 multiStepFeedback.setProgress( 100 );
283
284 progression = 0;
285 totalProgression = fixedLayer->featureCount();
286 multiStepFeedback.setCurrentStep( 2 );
287 multiStepFeedback.setProgressText( QObject::tr( "Exporting fixed layer..." ) );
288 QgsFeature fixedFeature;
289 QgsFeatureIterator fixedFeaturesIt = fixedLayer->getFeatures();
290 while ( fixedFeaturesIt.nextFeature( fixedFeature ) )
291 {
292 if ( feedback->isCanceled() )
293 break;
294
295 progression++;
296 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
297 if ( !sink_output->addFeature( fixedFeature, QgsFeatureSink::FastInsert ) )
298 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, u"OUTPUT"_s ) );
299 }
300 multiStepFeedback.setProgress( 100 );
301
302 QVariantMap outputs;
303 outputs.insert( u"OUTPUT"_s, dest_output );
304 outputs.insert( u"REPORT"_s, dest_report );
305
306 return outputs;
307}
308
309bool QgsFixGeometrySelfIntersectionAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
310{
311 mTolerance = parameterAsInt( parameters, u"TOLERANCE"_s, context );
312
313 return true;
314}
315
316Qgis::ProcessingAlgorithmFlags QgsFixGeometrySelfIntersectionAlgorithm::flags() const
317{
319}
320
@ VectorPoint
Vector point layers.
Definition qgis.h:3648
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3650
@ VectorLine
Vector line layers.
Definition qgis.h:3649
@ Numeric
Accepts numeric fields.
Definition qgis.h:3935
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3724
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3703
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3711
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3880
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:69
QgsFeatureId id
Definition qgsfeature.h:68
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:71
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: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:46
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.
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:34