QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsalgorithmfixgeometryoverlap.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmfixgeometryoverlap.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#include "qgsvectorlayer.h"
26
27#include <QString>
28
29using namespace Qt::StringLiterals;
30
32
33QString QgsFixGeometryOverlapAlgorithm::name() const
34{
35 return u"fixgeometryoverlap"_s;
36}
37
38QString QgsFixGeometryOverlapAlgorithm::displayName() const
39{
40 return QObject::tr( "Delete overlaps" );
41}
42
43QString QgsFixGeometryOverlapAlgorithm::shortDescription() const
44{
45 return QObject::tr( "Deletes overlaps detected with the \"Overlaps\" algorithm from the \"Check geometry\" section." );
46}
47
48QStringList QgsFixGeometryOverlapAlgorithm::tags() const
49{
50 return QObject::tr( "delete,area,fix,overlap" ).split( ',' );
51}
52
53QString QgsFixGeometryOverlapAlgorithm::group() const
54{
55 return QObject::tr( "Fix geometry" );
56}
57
58QString QgsFixGeometryOverlapAlgorithm::groupId() const
59{
60 return u"fixgeometry"_s;
61}
62
63QString QgsFixGeometryOverlapAlgorithm::shortHelpString() const
64{
65 return QObject::tr( "This algorithm deletes overlap sections based on an error layer from the \"Overlap\" algorithm in the \"Check geometry\" section.\n" );
66}
67
68QgsFixGeometryOverlapAlgorithm *QgsFixGeometryOverlapAlgorithm::createInstance() const
69{
70 return new QgsFixGeometryOverlapAlgorithm();
71}
72
73void QgsFixGeometryOverlapAlgorithm::initAlgorithm( const QVariantMap &configuration )
74{
75 Q_UNUSED( configuration )
76
77 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
78 addParameter( new QgsProcessingParameterFeatureSource( u"ERRORS"_s, QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
79 addParameter( new QgsProcessingParameterField( u"UNIQUE_ID"_s, QObject::tr( "Field of original feature unique identifier" ), QString(), u"ERRORS"_s ) );
80 addParameter(
81 new QgsProcessingParameterField( u"OVERLAP_FEATURE_UNIQUE_IDX"_s, QObject::tr( "Field of overlap feature unique identifier" ), QString(), u"ERRORS"_s, Qgis::ProcessingFieldParameterDataType::Numeric )
82 );
83 addParameter( new QgsProcessingParameterField( u"ERROR_VALUE_ID"_s, QObject::tr( "Field of error value" ), u"gc_error"_s, u"ERRORS"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
84
85 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "No-overlap layer" ), Qgis::ProcessingSourceType::VectorPolygon ) );
86 addParameter( new QgsProcessingParameterFeatureSink( u"REPORT"_s, QObject::tr( "Report layer from fixing overlaps" ), Qgis::ProcessingSourceType::VectorPoint ) );
87
88 auto tolerance = std::make_unique<QgsProcessingParameterNumber>( u"TOLERANCE"_s, QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13 );
89 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
90 tolerance->setHelp(
91 QObject::tr(
92 "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
93 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero."
94 )
95 );
96 addParameter( tolerance.release() );
97}
98
99QVariantMap QgsFixGeometryOverlapAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
100{
101 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
102 if ( !input )
103 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
104
105 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, u"ERRORS"_s, context ) );
106 if ( !errors )
107 throw QgsProcessingException( invalidSourceError( parameters, u"ERRORS"_s ) );
108
109 QgsProcessingMultiStepFeedback multiStepFeedback( 2, feedback );
110
111 const QString featIdFieldName = parameterAsString( parameters, u"UNIQUE_ID"_s, context );
112 const QString overlapFeatIdFieldName = parameterAsString( parameters, u"OVERLAP_FEATURE_UNIQUE_IDX"_s, context );
113 const QString errorValueIdFieldName = parameterAsString( parameters, u"ERROR_VALUE_ID"_s, context );
114
115 // Verify that input fields exists
116 if ( errors->fields().indexFromName( featIdFieldName ) == -1 )
117 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( featIdFieldName ) );
118 if ( errors->fields().indexFromName( errorValueIdFieldName ) == -1 )
119 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( errorValueIdFieldName ) );
120 int overlapIdFieldIndex = errors->fields().indexFromName( overlapFeatIdFieldName );
121 if ( overlapIdFieldIndex == -1 )
122 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( overlapFeatIdFieldName ) );
123 int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
124 if ( inputIdFieldIndex == -1 )
125 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in input layer." ).arg( featIdFieldName ) );
126
127 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
128 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
129 if ( inputFeatIdFieldType != errors->fields().at( errors->fields().indexFromName( featIdFieldName ) ).type() )
130 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as in the error layer." ).arg( featIdFieldName ) );
131
132 const QgsField overlapFeatIdField = errors->fields().at( overlapIdFieldIndex );
133 const QMetaType::Type overlapFeatIdFieldType = overlapFeatIdField.type();
134 if ( inputFeatIdFieldType != errors->fields().at( errors->fields().indexFromName( overlapFeatIdFieldName ) ).type() )
135 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as \"%2\" in the input layer." ).arg( overlapFeatIdFieldName ).arg( featIdFieldName ) );
136
137 QString dest_output;
138 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, u"OUTPUT"_s, context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
139 if ( !sink_output )
140 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
141
142 QString dest_report;
143 QgsFields reportFields = errors->fields();
144 reportFields.append( QgsField( u"report"_s, QMetaType::QString ) );
145 reportFields.append( QgsField( u"error_fixed"_s, QMetaType::Bool ) );
146 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, u"REPORT"_s, context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
147 if ( !sink_report )
148 throw QgsProcessingException( invalidSinkError( parameters, u"REPORT"_s ) );
149
150 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), context.transformContext(), context.project() );
151
152 const QgsGeometryOverlapCheck check( &checkContext, QVariantMap() );
153
154 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize( QgsFeatureRequest() ) );
156 QMap<QString, QgsFeaturePool *> featurePools;
157 featurePools.insert( fixedLayer->id(), &featurePool );
158
159 QgsFeature errorFeature, inputFeature, overlapFeature, testDuplicateIdFeature;
160 QgsFeatureIterator errorFeaturesIt = errors->getFeatures();
161 QList<QgsGeometryCheck::Changes> changesList;
162 QgsFeature reportFeature;
163 reportFeature.setFields( reportFields );
164 long long progression = 0;
165 long long totalProgression = errors->featureCount();
166 multiStepFeedback.setCurrentStep( 1 );
167 multiStepFeedback.setProgressText( QObject::tr( "Fixing errors..." ) );
168 while ( errorFeaturesIt.nextFeature( errorFeature ) )
169 {
170 if ( feedback->isCanceled() )
171 break;
172
173 progression++;
174 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
175 reportFeature.setGeometry( errorFeature.geometry() );
176
177 QString idValue = errorFeature.attribute( featIdFieldName ).toString();
178 if ( inputFeatIdFieldType == QMetaType::QString )
179 idValue = "'" + idValue + "'";
180 QgsFeatureIterator it = fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue ) );
181
182 QString overlapIdValue = errorFeature.attribute( overlapFeatIdFieldName ).toString();
183 if ( overlapFeatIdFieldType == QMetaType::QString )
184 overlapIdValue = "'" + overlapIdValue + "'";
185 QgsFeatureIterator overlapIt = fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + overlapIdValue ) );
186
187 if ( !it.nextFeature( inputFeature ) || !inputFeature.isValid() )
188 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Source feature not found or invalid" ) << false );
189
190 else if ( !overlapIt.nextFeature( overlapFeature ) || !overlapFeature.isValid() )
191 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Overlap feature not found or invalid" ) << false );
192
193 else if ( it.nextFeature( testDuplicateIdFeature ) )
194 throw QgsProcessingException( QObject::tr( "More than one feature found in input layer with value \"%1\" in unique field \"%2\"" ).arg( idValue, featIdFieldName ) );
195
196 else if ( overlapIt.nextFeature( testDuplicateIdFeature ) )
197 throw QgsProcessingException( QObject::tr( "More than one overlap feature found in input layer with value \"%1\" in unique field \"%2\"" ).arg( overlapIdValue, overlapFeatIdFieldName ) );
198
199 else if ( inputFeature.geometry().isNull() )
200 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Feature geometry is null" ) << false );
201
202 else if ( overlapFeature.geometry().isNull() )
203 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Overlap feature geometry is null" ) << false );
204
205 else
206 {
208 &check,
209 QgsGeometryCheckerUtils::LayerFeature( &featurePool, inputFeature, &checkContext, false ),
210 inputFeature.geometry(),
211 errorFeature.geometry().asPoint(),
212 errorFeature.attribute( errorValueIdFieldName ),
213 QgsGeometryCheckerUtils::LayerFeature( &featurePool, overlapFeature, &checkContext, false )
214 );
215 for ( const QgsGeometryCheck::Changes &changes : std::as_const( changesList ) )
216 checkError.handleChanges( changes );
217
219 check.fixError( featurePools, &checkError, QgsGeometryOverlapCheck::ResolutionMethod::Subtract, QMap<QString, int>(), changes );
220 changesList << changes;
221 QString resolutionMessage = checkError.resolutionMessage();
222 if ( checkError.status() == QgsGeometryCheckError::StatusObsolete )
223 resolutionMessage = QObject::tr( "Error is obsolete" );
224 reportFeature.setAttributes( errorFeature.attributes() << resolutionMessage << ( checkError.status() == QgsGeometryCheckError::StatusFixed ) );
225 }
226
227 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
228 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, u"REPORT"_s ) );
229 }
230 multiStepFeedback.setProgress( 100 );
231
232 progression = 0;
233 totalProgression = fixedLayer->featureCount();
234 multiStepFeedback.setCurrentStep( 2 );
235 multiStepFeedback.setProgressText( QObject::tr( "Exporting fixed layer..." ) );
236 QgsFeature fixedFeature;
237 QgsFeatureIterator fixedFeaturesIt = fixedLayer->getFeatures();
238 while ( fixedFeaturesIt.nextFeature( fixedFeature ) )
239 {
240 if ( feedback->isCanceled() )
241 break;
242
243 progression++;
244 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
245 if ( !sink_output->addFeature( fixedFeature, QgsFeatureSink::FastInsert ) )
246 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, u"OUTPUT"_s ) );
247 }
248 multiStepFeedback.setProgress( 100 );
249
250 QVariantMap outputs;
251 outputs.insert( u"OUTPUT"_s, dest_output );
252 outputs.insert( u"REPORT"_s, dest_report );
253
254 return outputs;
255}
256
257bool QgsFixGeometryOverlapAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
258{
259 mTolerance = parameterAsInt( parameters, u"TOLERANCE"_s, context );
260
261 return true;
262}
263
264Qgis::ProcessingAlgorithmFlags QgsFixGeometryOverlapAlgorithm::flags() const
265{
267}
268
@ VectorPoint
Vector point layers.
Definition qgis.h:3648
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3650
@ 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
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.
@ 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.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
A layer feature combination to uniquely identify and access a feature in a set of layers.
An error of a QgsGeometryOverlapCheck.
bool handleChanges(const QgsGeometryCheck::Changes &changes) override
Apply a list of changes.
Checks if geometries overlap.
@ Subtract
Subtract the overlap region from the polygon.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
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.
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.