QGIS API Documentation 4.1.0-Master (376402f9aeb)
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( new QgsProcessingParameterField( u"OVERLAP_FEATURE_UNIQUE_IDX"_s, QObject::tr( "Field of overlap feature unique identifier" ), QString(), u"ERRORS"_s ) );
81 addParameter( new QgsProcessingParameterField( u"ERROR_VALUE_ID"_s, QObject::tr( "Field of error value" ), u"gc_error"_s, u"ERRORS"_s, Qgis::ProcessingFieldParameterDataType::Numeric ) );
82
83 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "No-overlap layer" ), Qgis::ProcessingSourceType::VectorPolygon ) );
84 addParameter( new QgsProcessingParameterFeatureSink( u"REPORT"_s, QObject::tr( "Report layer from fixing overlaps" ), Qgis::ProcessingSourceType::VectorPoint ) );
85
86 auto tolerance = std::make_unique<QgsProcessingParameterNumber>( u"TOLERANCE"_s, QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13 );
87 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
88 tolerance->setHelp(
89 QObject::tr(
90 "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
91 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero."
92 )
93 );
94 addParameter( tolerance.release() );
95}
96
97QVariantMap QgsFixGeometryOverlapAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
98{
99 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
100 if ( !input )
101 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
102
103 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, u"ERRORS"_s, context ) );
104 if ( !errors )
105 throw QgsProcessingException( invalidSourceError( parameters, u"ERRORS"_s ) );
106
107 QgsProcessingMultiStepFeedback multiStepFeedback( 2, feedback );
108
109 const QString featIdFieldName = parameterAsString( parameters, u"UNIQUE_ID"_s, context );
110 const QString overlapFeatIdFieldName = parameterAsString( parameters, u"OVERLAP_FEATURE_UNIQUE_IDX"_s, context );
111 const QString errorValueIdFieldName = parameterAsString( parameters, u"ERROR_VALUE_ID"_s, context );
112
113 // Verify that input fields exists
114 if ( errors->fields().indexFromName( featIdFieldName ) == -1 )
115 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( featIdFieldName ) );
116 if ( errors->fields().indexFromName( errorValueIdFieldName ) == -1 )
117 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( errorValueIdFieldName ) );
118 int overlapIdFieldIndex = errors->fields().indexFromName( overlapFeatIdFieldName );
119 if ( overlapIdFieldIndex == -1 )
120 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in the error layer." ).arg( overlapFeatIdFieldName ) );
121 int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
122 if ( inputIdFieldIndex == -1 )
123 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not exist in input layer." ).arg( featIdFieldName ) );
124
125 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
126 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
127 if ( inputFeatIdFieldType != errors->fields().at( errors->fields().indexFromName( featIdFieldName ) ).type() )
128 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as in the error layer." ).arg( featIdFieldName ) );
129
130 const QgsField overlapFeatIdField = errors->fields().at( overlapIdFieldIndex );
131 const QMetaType::Type overlapFeatIdFieldType = overlapFeatIdField.type();
132 if ( inputFeatIdFieldType != errors->fields().at( errors->fields().indexFromName( overlapFeatIdFieldName ) ).type() )
133 throw QgsProcessingException( QObject::tr( "Field \"%1\" does not have the same type as \"%2\" in the input layer." ).arg( overlapFeatIdFieldName ).arg( featIdFieldName ) );
134
135 QString dest_output;
136 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, u"OUTPUT"_s, context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
137 if ( !sink_output )
138 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
139
140 QString dest_report;
141 QgsFields reportFields = errors->fields();
142 reportFields.append( QgsField( u"report"_s, QMetaType::QString ) );
143 reportFields.append( QgsField( u"error_fixed"_s, QMetaType::Bool ) );
144 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, u"REPORT"_s, context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
145 if ( !sink_report )
146 throw QgsProcessingException( invalidSinkError( parameters, u"REPORT"_s ) );
147
148 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), context.transformContext(), context.project() );
149
150 const QgsGeometryOverlapCheck check( &checkContext, QVariantMap() );
151
152 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize( QgsFeatureRequest() ) );
154 QMap<QString, QgsFeaturePool *> featurePools;
155 featurePools.insert( fixedLayer->id(), &featurePool );
156
157 QgsFeature errorFeature, inputFeature, overlapFeature, testDuplicateIdFeature;
158 QgsFeatureIterator errorFeaturesIt = errors->getFeatures();
159 QList<QgsGeometryCheck::Changes> changesList;
160 QgsFeature reportFeature;
161 reportFeature.setFields( reportFields );
162 long long progression = 0;
163 long long totalProgression = errors->featureCount();
164 multiStepFeedback.setCurrentStep( 1 );
165 multiStepFeedback.setProgressText( QObject::tr( "Fixing errors..." ) );
166 while ( errorFeaturesIt.nextFeature( errorFeature ) )
167 {
168 if ( feedback->isCanceled() )
169 break;
170
171 progression++;
172 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
173 reportFeature.setGeometry( errorFeature.geometry() );
174
175 QString idValue = errorFeature.attribute( featIdFieldName ).toString();
176 if ( inputFeatIdFieldType == QMetaType::QString )
177 idValue = "'" + idValue + "'";
178 QgsFeatureIterator it = fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue ) );
179
180 QString overlapIdValue = errorFeature.attribute( overlapFeatIdFieldName ).toString();
181 if ( overlapFeatIdFieldType == QMetaType::QString )
182 overlapIdValue = "'" + overlapIdValue + "'";
183 QgsFeatureIterator overlapIt = fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + overlapIdValue ) );
184
185 if ( !it.nextFeature( inputFeature ) || !inputFeature.isValid() )
186 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Source feature not found or invalid" ) << false );
187
188 else if ( !overlapIt.nextFeature( overlapFeature ) || !overlapFeature.isValid() )
189 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Overlap feature not found or invalid" ) << false );
190
191 else if ( it.nextFeature( testDuplicateIdFeature ) )
192 throw QgsProcessingException( QObject::tr( "More than one feature found in input layer with value \"%1\" in unique field \"%2\"" ).arg( idValue, featIdFieldName ) );
193
194 else if ( overlapIt.nextFeature( testDuplicateIdFeature ) )
195 throw QgsProcessingException( QObject::tr( "More than one overlap feature found in input layer with value \"%1\" in unique field \"%2\"" ).arg( overlapIdValue, overlapFeatIdFieldName ) );
196
197 else if ( inputFeature.geometry().isNull() )
198 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Feature geometry is null" ) << false );
199
200 else if ( overlapFeature.geometry().isNull() )
201 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Overlap feature geometry is null" ) << false );
202
203 else
204 {
206 &check,
207 QgsGeometryCheckerUtils::LayerFeature( &featurePool, inputFeature, &checkContext, false ),
208 inputFeature.geometry(),
209 errorFeature.geometry().asPoint(),
210 errorFeature.attribute( errorValueIdFieldName ),
211 QgsGeometryCheckerUtils::LayerFeature( &featurePool, overlapFeature, &checkContext, false )
212 );
213 for ( const QgsGeometryCheck::Changes &changes : std::as_const( changesList ) )
214 checkError.handleChanges( changes );
215
217 check.fixError( featurePools, &checkError, QgsGeometryOverlapCheck::ResolutionMethod::Subtract, QMap<QString, int>(), changes );
218 changesList << changes;
219 QString resolutionMessage = checkError.resolutionMessage();
220 if ( checkError.status() == QgsGeometryCheckError::StatusObsolete )
221 resolutionMessage = QObject::tr( "Error is obsolete" );
222 reportFeature.setAttributes( errorFeature.attributes() << resolutionMessage << ( checkError.status() == QgsGeometryCheckError::StatusFixed ) );
223 }
224
225 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
226 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, u"REPORT"_s ) );
227 }
228 multiStepFeedback.setProgress( 100 );
229
230 progression = 0;
231 totalProgression = fixedLayer->featureCount();
232 multiStepFeedback.setCurrentStep( 2 );
233 multiStepFeedback.setProgressText( QObject::tr( "Exporting fixed layer..." ) );
234 QgsFeature fixedFeature;
235 QgsFeatureIterator fixedFeaturesIt = fixedLayer->getFeatures();
236 while ( fixedFeaturesIt.nextFeature( fixedFeature ) )
237 {
238 if ( feedback->isCanceled() )
239 break;
240
241 progression++;
242 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
243 if ( !sink_output->addFeature( fixedFeature, QgsFeatureSink::FastInsert ) )
244 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, u"OUTPUT"_s ) );
245 }
246 multiStepFeedback.setProgress( 100 );
247
248 QVariantMap outputs;
249 outputs.insert( u"OUTPUT"_s, dest_output );
250 outputs.insert( u"REPORT"_s, dest_report );
251
252 return outputs;
253}
254
255bool QgsFixGeometryOverlapAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
256{
257 mTolerance = parameterAsInt( parameters, u"TOLERANCE"_s, context );
258
259 return true;
260}
261
262Qgis::ProcessingAlgorithmFlags QgsFixGeometryOverlapAlgorithm::flags() const
263{
265}
266
@ VectorPoint
Vector point layers.
Definition qgis.h:3715
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3717
@ Numeric
Accepts numeric fields.
Definition qgis.h:4002
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3791
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3770
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3778
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3947
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.