QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
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
19
23#include "qgsvectorfilewriter.h"
24
25#include <QString>
26
27using namespace Qt::StringLiterals;
28
30
31QString QgsFixGeometryAreaAlgorithm::name() const
32{
33 return u"fixgeometryarea"_s;
34}
35
36QString QgsFixGeometryAreaAlgorithm::displayName() const
37{
38 return QObject::tr( "Fix small polygons" );
39}
40
41QString QgsFixGeometryAreaAlgorithm::shortDescription() const
42{
43 return QObject::tr( "Merges small polygons detected with the \"Small polygons\" algorithm from the \"Check geometry\" section." );
44}
45
46QStringList QgsFixGeometryAreaAlgorithm::tags() const
47{
48 return QObject::tr( "merge,polygons,neighbor,fix,area" ).split( ',' );
49}
50
51QString QgsFixGeometryAreaAlgorithm::group() const
52{
53 return QObject::tr( "Fix geometry" );
54}
55
56QString QgsFixGeometryAreaAlgorithm::groupId() const
57{
58 return u"fixgeometry"_s;
59}
60
61QString QgsFixGeometryAreaAlgorithm::shortHelpString() const
62{
63 return QObject::tr( "This algorithm merges neighboring polygons according to the chosen method, "
64 "based on an error layer from the \"Small polygons\" algorithm in the \"Check geometry\" section." );
65}
66
67QgsFixGeometryAreaAlgorithm *QgsFixGeometryAreaAlgorithm::createInstance() const
68{
69 return new QgsFixGeometryAreaAlgorithm();
70}
71
72void QgsFixGeometryAreaAlgorithm::initAlgorithm( const QVariantMap &configuration )
73{
74 Q_UNUSED( configuration )
75
77 u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
78 ) );
80 u"ERRORS"_s, QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
81 ) );
82
83 QStringList methods;
84 {
85 QList<QgsGeometryCheckResolutionMethod> checkMethods = QgsGeometryAreaCheck( nullptr, QVariantMap() ).availableResolutionMethods();
86 std::transform(
87 checkMethods.cbegin(), checkMethods.cend() - 2, std::inserter( methods, methods.begin() ),
88 []( const QgsGeometryCheckResolutionMethod &checkMethod ) { return checkMethod.name(); }
89 );
90 }
91 addParameter( new QgsProcessingParameterEnum( u"METHOD"_s, QObject::tr( "Method" ), methods ) );
92 addParameter( new QgsProcessingParameterField(
93 u"MERGE_ATTRIBUTE"_s, QObject::tr( "Field to consider when merging polygons with the identical attribute method" ),
94 QString(), u"INPUT"_s,
96 ) );
97
98 addParameter( new QgsProcessingParameterField(
99 u"UNIQUE_ID"_s, QObject::tr( "Field of original feature unique identifier" ),
100 u"id"_s, u"ERRORS"_s
101 ) );
102 addParameter( new QgsProcessingParameterField(
103 u"PART_IDX"_s, QObject::tr( "Field of part index" ),
104 u"gc_partidx"_s, u"ERRORS"_s,
106 ) );
107 addParameter( new QgsProcessingParameterField(
108 u"RING_IDX"_s, QObject::tr( "Field of ring index" ),
109 u"gc_ringidx"_s, u"ERRORS"_s,
111 ) );
112 addParameter( new QgsProcessingParameterField(
113 u"VERTEX_IDX"_s, QObject::tr( "Field of vertex index" ),
114 u"gc_vertidx"_s, u"ERRORS"_s,
116 ) );
117
118 addParameter( new QgsProcessingParameterFeatureSink(
119 u"OUTPUT"_s, QObject::tr( "Small polygons merged layer" ), Qgis::ProcessingSourceType::VectorPolygon
120 ) );
121 addParameter( new QgsProcessingParameterFeatureSink(
122 u"REPORT"_s, QObject::tr( "Report layer from merging small polygons" ), Qgis::ProcessingSourceType::VectorPoint
123 ) );
124
125 auto tolerance = std::make_unique<QgsProcessingParameterNumber>(
126 u"TOLERANCE"_s, QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
127 );
128 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
129 tolerance->setHelp( QObject::tr( "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
130 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
131 addParameter( tolerance.release() );
132}
133
134QVariantMap QgsFixGeometryAreaAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
135{
136 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
137 if ( !input )
138 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
139
140 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, u"ERRORS"_s, context ) );
141 if ( !errors )
142 throw QgsProcessingException( invalidSourceError( parameters, u"ERRORS"_s ) );
143
144 QgsProcessingMultiStepFeedback multiStepFeedback( 2, feedback );
145
146 const QString featIdFieldName = parameterAsString( parameters, u"UNIQUE_ID"_s, context );
147 const QString partIdxFieldName = parameterAsString( parameters, u"PART_IDX"_s, context );
148 const QString ringIdxFieldName = parameterAsString( parameters, u"RING_IDX"_s, context );
149 const QString vertexIdxFieldName = parameterAsString( parameters, u"VERTEX_IDX"_s, context );
150
151 // Specific inputs for this check
152 const QString mergeAttributeName = parameterAsString( parameters, u"MERGE_ATTRIBUTE"_s, context );
153 const int method = parameterAsEnum( parameters, u"METHOD"_s, context );
154
155 // Verify that input fields exists
156 if ( errors->fields().indexFromName( featIdFieldName ) == -1 )
157 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( featIdFieldName ) );
158 if ( errors->fields().indexFromName( partIdxFieldName ) == -1 )
159 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( partIdxFieldName ) );
160 if ( errors->fields().indexFromName( ringIdxFieldName ) == -1 )
161 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( ringIdxFieldName ) );
162 if ( errors->fields().indexFromName( vertexIdxFieldName ) == -1 )
163 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( vertexIdxFieldName ) );
164 const int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
165 if ( inputIdFieldIndex == -1 )
166 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in input layer." ).arg( featIdFieldName ) );
167
168 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
169 if ( inputFeatIdField.type() != errors->fields().at( errors->fields().indexFromName( featIdFieldName ) ).type() )
170 throw QgsProcessingException( QObject::tr( "Field %1 does not have the same type as in the error layer." ).arg( featIdFieldName ) );
171
172 QString dest_output;
173 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, u"OUTPUT"_s, context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
174 if ( !sink_output )
175 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
176
177 QString dest_report;
178 QgsFields reportFields = errors->fields();
179 reportFields.append( QgsField( u"report"_s, QMetaType::QString ) );
180 reportFields.append( QgsField( u"error_fixed"_s, QMetaType::Bool ) );
181 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, u"REPORT"_s, context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
182 if ( !sink_report )
183 throw QgsProcessingException( invalidSinkError( parameters, u"REPORT"_s ) );
184
185 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), context.transformContext(), context.project() );
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, 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 ( const QgsGeometryCheck::Changes &changes : std::as_const( 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, u"REPORT"_s ) );
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, u"OUTPUT"_s ) );
292 }
293 multiStepFeedback.setProgress( 100 );
294
295 QVariantMap outputs;
296 outputs.insert( u"OUTPUT"_s, dest_output );
297 outputs.insert( u"REPORT"_s, dest_report );
298
299 return outputs;
300}
301
302bool QgsFixGeometryAreaAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
303{
304 mTolerance = parameterAsInt( parameters, u"TOLERANCE"_s, context );
305
306 return true;
307}
308
309Qgis::ProcessingAlgorithmFlags QgsFixGeometryAreaAlgorithm::flags() const
310{
312}
313
@ VectorPoint
Vector point layers.
Definition qgis.h:3605
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3607
@ Numeric
Accepts numeric fields.
Definition qgis.h:3889
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3680
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3659
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3667
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
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:55
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:76
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.
virtual bool handleChanges(const QgsGeometryCheck::Changes &changes)
Apply a list of changes.
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.
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.
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:34