QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmfixgeometryarea.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmfixgeometryarea.cpp
3 ---------------------
4 begin : June 2024
5 copyright : (C) 2024 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
22#include "qgsvectorfilewriter.h"
23
25
26QString QgsFixGeometryAreaAlgorithm::name() const
27{
28 return QStringLiteral( "fixgeometryarea" );
29}
30
31QString QgsFixGeometryAreaAlgorithm::displayName() const
32{
33 return QObject::tr( "Fix small polygons" );
34}
35
36QString QgsFixGeometryAreaAlgorithm::shortDescription() const
37{
38 return QObject::tr( "Merges small polygons detected with the \"Small polygons\" algorithm from the \"Check geometry\" section." );
39}
40
41QStringList QgsFixGeometryAreaAlgorithm::tags() const
42{
43 return QObject::tr( "merge,polygons,neighbor,fix,area" ).split( ',' );
44}
45
46QString QgsFixGeometryAreaAlgorithm::group() const
47{
48 return QObject::tr( "Fix geometry" );
49}
50
51QString QgsFixGeometryAreaAlgorithm::groupId() const
52{
53 return QStringLiteral( "fixgeometry" );
54}
55
56QString QgsFixGeometryAreaAlgorithm::shortHelpString() const
57{
58 return QObject::tr( "This algorithm merges neighboring polygons according to the chosen method, "
59 "based on an error layer from the \"Small polygons\" algorithm in the \"Check geometry\" section." );
60}
61
62QgsFixGeometryAreaAlgorithm *QgsFixGeometryAreaAlgorithm::createInstance() const
63{
64 return new QgsFixGeometryAreaAlgorithm();
65}
66
67void QgsFixGeometryAreaAlgorithm::initAlgorithm( const QVariantMap &configuration )
68{
69 Q_UNUSED( configuration )
70
71 // Inputs
73 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
74 ) );
76 QStringLiteral( "ERRORS" ), QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
77 ) );
78
79 // Specific inputs for this check
80 QStringList methods;
81 {
82 QList<QgsGeometryCheckResolutionMethod> checkMethods = QgsGeometryAreaCheck( nullptr, QVariantMap() ).availableResolutionMethods();
83 std::transform(
84 checkMethods.cbegin(), checkMethods.cend() - 2, std::inserter( methods, methods.begin() ),
85 []( const QgsGeometryCheckResolutionMethod &checkMethod ) { return checkMethod.name(); }
86 );
87 }
88 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Method" ), methods ) );
89 addParameter( new QgsProcessingParameterField(
90 QStringLiteral( "MERGE_ATTRIBUTE" ), QObject::tr( "Field to consider when merging polygons with the identical attribute method" ),
91 QString(), QStringLiteral( "INPUT" ),
93 ) );
94
95 addParameter( new QgsProcessingParameterField(
96 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Field of original feature unique identifier" ),
97 QStringLiteral( "id" ), QStringLiteral( "ERRORS" )
98 ) );
99 addParameter( new QgsProcessingParameterField(
100 QStringLiteral( "PART_IDX" ), QObject::tr( "Field of part index" ),
101 QStringLiteral( "gc_partidx" ), QStringLiteral( "ERRORS" ),
103 ) );
104 addParameter( new QgsProcessingParameterField(
105 QStringLiteral( "RING_IDX" ), QObject::tr( "Field of ring index" ),
106 QStringLiteral( "gc_ringidx" ), QStringLiteral( "ERRORS" ),
108 ) );
109 addParameter( new QgsProcessingParameterField(
110 QStringLiteral( "VERTEX_IDX" ), QObject::tr( "Field of vertex index" ),
111 QStringLiteral( "gc_vertidx" ), QStringLiteral( "ERRORS" ),
113 ) );
114
115 // Outputs
116 addParameter( new QgsProcessingParameterFeatureSink(
117 QStringLiteral( "OUTPUT" ), QObject::tr( "Small polygons merged layer" ), Qgis::ProcessingSourceType::VectorPolygon
118 ) );
119 addParameter( new QgsProcessingParameterFeatureSink(
120 QStringLiteral( "REPORT" ), QObject::tr( "Report layer from merging small polygons" ), Qgis::ProcessingSourceType::VectorPoint
121 ) );
122
123 std::unique_ptr<QgsProcessingParameterNumber> tolerance = std::make_unique<QgsProcessingParameterNumber>(
124 QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
125 );
126 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
127 tolerance->setHelp( QObject::tr( "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
128 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
129 addParameter( tolerance.release() );
130}
131
132QVariantMap QgsFixGeometryAreaAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
133{
134 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
135 if ( !input )
136 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
137
138 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, QStringLiteral( "ERRORS" ), context ) );
139 if ( !errors )
140 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "ERRORS" ) ) );
141
142 QgsProcessingMultiStepFeedback multiStepFeedback( 2, feedback );
143
144 const QString featIdFieldName = parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context );
145 const QString partIdxFieldName = parameterAsString( parameters, QStringLiteral( "PART_IDX" ), context );
146 const QString ringIdxFieldName = parameterAsString( parameters, QStringLiteral( "RING_IDX" ), context );
147 const QString vertexIdxFieldName = parameterAsString( parameters, QStringLiteral( "VERTEX_IDX" ), context );
148
149 // Specific inputs for this check
150 const QString mergeAttributeName = parameterAsString( parameters, QStringLiteral( "MERGE_ATTRIBUTE" ), context );
151 const int method = parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context );
152
153 // Verify that input fields exists
154 if ( errors->fields().indexFromName( featIdFieldName ) == -1 )
155 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( featIdFieldName ) );
156 if ( errors->fields().indexFromName( partIdxFieldName ) == -1 )
157 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( partIdxFieldName ) );
158 if ( errors->fields().indexFromName( ringIdxFieldName ) == -1 )
159 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( ringIdxFieldName ) );
160 if ( errors->fields().indexFromName( vertexIdxFieldName ) == -1 )
161 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( vertexIdxFieldName ) );
162 int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
163 if ( inputIdFieldIndex == -1 )
164 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in input layer." ).arg( featIdFieldName ) );
165
166 QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
167 if ( inputFeatIdField.type() != errors->fields().at( errors->fields().indexFromName( featIdFieldName ) ).type() )
168 throw QgsProcessingException( QObject::tr( "Field %1 does not have the same type as in the error layer." ).arg( featIdFieldName ) );
169
170 QString dest_output;
171 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
172 if ( !sink_output )
173 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
174
175 QString dest_report;
176 QgsFields reportFields = errors->fields();
177 reportFields.append( QgsField( QStringLiteral( "report" ), QMetaType::QString ) );
178 reportFields.append( QgsField( QStringLiteral( "error_fixed" ), QMetaType::Bool ) );
179 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, QStringLiteral( "REPORT" ), context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
180 if ( !sink_report )
181 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "REPORT" ) ) );
182
183 const QgsProject *project = QgsProject::instance();
184 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), project->transformContext(), project );
185 QStringList messages;
186 QVariantMap configurationCheck;
187
188 // maximum limit, we know that every feature to process is an error (otherwise it is not treated and marked as obsolete)
189 configurationCheck.insert( "areaThreshold", std::numeric_limits<double>::max() );
190 const QgsGeometryAreaCheck check( &checkContext, configurationCheck );
191
192 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize( QgsFeatureRequest() ) );
193 QgsVectorDataProviderFeaturePool featurePool = QgsVectorDataProviderFeaturePool( fixedLayer.get(), false );
194 QMap<QString, QgsFeaturePool *> featurePools;
195 featurePools.insert( fixedLayer->id(), &featurePool );
196
197 QMap<QString, int> attributeIndex;
199 {
200 if ( mergeAttributeName.isEmpty() )
201 throw QgsProcessingException( QObject::tr( "Merge field to merge polygons with identical attribute method is empty" ) );
202 if ( !fixedLayer->fields().names().contains( mergeAttributeName ) )
203 throw QgsProcessingException( QObject::tr( "Merge field %1 does not exist in input layer" ).arg( mergeAttributeName ) );
204 attributeIndex.insert( fixedLayer->id(), fixedLayer->fields().indexOf( mergeAttributeName ) );
205 }
206
207 QgsFeature errorFeature, inputFeature, testDuplicateIdFeature;
208 QgsFeatureIterator errorFeaturesIt = errors->getFeatures();
209 QList<QgsGeometryCheck::Changes> changesList;
210 QgsFeature reportFeature;
211 reportFeature.setFields( reportFields );
212 long long progression = 0;
213 long long totalProgression = errors->featureCount();
214 multiStepFeedback.setCurrentStep( 1 );
215 multiStepFeedback.setProgressText( QObject::tr( "Fixing errors..." ) );
216 while ( errorFeaturesIt.nextFeature( errorFeature ) )
217 {
218 if ( feedback->isCanceled() )
219 break;
220
221 progression++;
222 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
223 reportFeature.setGeometry( errorFeature.geometry() );
224
225 QVariant attr = errorFeature.attribute( featIdFieldName );
226 if ( !attr.isValid() || attr.isNull() )
227 throw QgsProcessingException( QObject::tr( "NULL or invalid value found in unique field %1" ).arg( featIdFieldName ) );
228
229 QString idValue = errorFeature.attribute( featIdFieldName ).toString();
230 if ( inputFeatIdField.type() == QMetaType::QString )
231 idValue = "'" + idValue + "'";
232
233 QgsFeatureIterator it = fixedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue ) );
234 if ( !it.nextFeature( inputFeature ) || !inputFeature.isValid() )
235 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Source feature not found or invalid" ) << false );
236
237 else 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 ).arg( featIdFieldName ) );
239
240 else if ( inputFeature.geometry().isNull() )
241 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Feature geometry is null" ) << false );
242
243 else if ( QgsGeometryCheckerUtils::getGeomPart( inputFeature.geometry().constGet(), errorFeature.attribute( partIdxFieldName ).toInt() ) == nullptr )
244 reportFeature.setAttributes( errorFeature.attributes() << QObject::tr( "Feature geometry part is null" ) << false );
245
246 else
247 {
249 &check,
250 QgsGeometryCheckerUtils::LayerFeature( &featurePool, inputFeature, &checkContext, false ),
251 errorFeature.geometry().asPoint(),
253 errorFeature.attribute( partIdxFieldName ).toInt(),
254 errorFeature.attribute( ringIdxFieldName ).toInt(),
255 errorFeature.attribute( vertexIdxFieldName ).toInt()
256 )
257 );
258 for ( QgsGeometryCheck::Changes changes : changesList )
259 checkError.handleChanges( changes );
260
262 check.fixError( featurePools, &checkError, method, attributeIndex, changes );
263 changesList << changes;
264
265 QString resolutionMessage = checkError.resolutionMessage();
266 if ( checkError.status() == QgsGeometryCheckError::StatusObsolete )
267 resolutionMessage = QObject::tr( "Error is obsolete" );
268
269 reportFeature.setAttributes( errorFeature.attributes() << resolutionMessage << ( checkError.status() == QgsGeometryCheckError::StatusFixed ) );
270 }
271
272 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
273 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
274 }
275 multiStepFeedback.setProgress( 100 );
276
277 progression = 0;
278 totalProgression = fixedLayer->featureCount();
279 multiStepFeedback.setCurrentStep( 2 );
280 multiStepFeedback.setProgressText( QObject::tr( "Exporting fixed layer..." ) );
281 QgsFeature fixedFeature;
282 QgsFeatureIterator fixedFeaturesIt = fixedLayer->getFeatures();
283 while ( fixedFeaturesIt.nextFeature( fixedFeature ) )
284 {
285 if ( feedback->isCanceled() )
286 break;
287
288 progression++;
289 multiStepFeedback.setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
290 if ( !sink_output->addFeature( fixedFeature, QgsFeatureSink::FastInsert ) )
291 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
292 }
293 multiStepFeedback.setProgress( 100 );
294
295 QVariantMap outputs;
296 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
297 outputs.insert( QStringLiteral( "REPORT" ), dest_report );
298
299 return outputs;
300}
301
302bool QgsFixGeometryAreaAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
303{
304 mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );
305
306 return true;
307}
308
309Qgis::ProcessingAlgorithmFlags QgsFixGeometryAreaAlgorithm::flags() const
310{
312}
313
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon 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
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: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.
This represents an error reported by a geometry check.
@ 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.
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.
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.
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30