QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmfixgeometrydeletefeatures.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmfixgeometrydeletefeatures.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
21
22QString QgsFixGeometryDeleteFeaturesAlgorithm::name() const
23{
24 return QStringLiteral( "fixgeometrydeletefeatures" );
25}
26
27QString QgsFixGeometryDeleteFeaturesAlgorithm::displayName() const
28{
29 return QObject::tr( "Delete features" );
30}
31
32QString QgsFixGeometryDeleteFeaturesAlgorithm::shortDescription() const
33{
34 return QObject::tr( "Deletes features detected with an algorithm from the \"Check geometry\" section." );
35}
36
37QStringList QgsFixGeometryDeleteFeaturesAlgorithm::tags() const
38{
39 return QObject::tr( "fix,delete,features" ).split( ',' );
40}
41
42QString QgsFixGeometryDeleteFeaturesAlgorithm::group() const
43{
44 return QObject::tr( "Fix geometry" );
45}
46
47QString QgsFixGeometryDeleteFeaturesAlgorithm::groupId() const
48{
49 return QStringLiteral( "fixgeometry" );
50}
51
52QString QgsFixGeometryDeleteFeaturesAlgorithm::shortHelpString() const
53{
54 return QObject::tr( "This algorithm deletes error features listed in the errors layer from an algorithm in the \"Check geometry\" section.\n"
55 "The required inputs are the original layer used in the check algorithm, its unique id field, and its corresponding errors layer.\n\n"
56 "For instance, it can be used after the following check algorithms to delete error features:"
57 "<html><ul><li>Feature inside polygon</li>"
58 "<li>Degenerate polygons</li>"
59 "<li>Small segments</li>"
60 "<li>Duplicated geometries</li>"
61 "<li>etc.</li></ul></html>" );
62}
63
64QgsFixGeometryDeleteFeaturesAlgorithm *QgsFixGeometryDeleteFeaturesAlgorithm::createInstance() const
65{
66 return new QgsFixGeometryDeleteFeaturesAlgorithm();
67}
68
69void QgsFixGeometryDeleteFeaturesAlgorithm::initAlgorithm( const QVariantMap &configuration )
70{
71 Q_UNUSED( configuration )
72
73 // Inputs
75 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ),
76 QList<int>()
77 << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
78 << static_cast<int>( Qgis::ProcessingSourceType::VectorLine )
80 ) );
82 QStringLiteral( "ERRORS" ), QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
83 ) );
84 addParameter( new QgsProcessingParameterField(
85 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Field of original feature unique identifier" ),
86 QString(), QStringLiteral( "ERRORS" )
87 ) );
88
89 // Outputs
90 addParameter( new QgsProcessingParameterFeatureSink(
91 QStringLiteral( "OUTPUT" ), QObject::tr( "Cleaned layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry
92 ) );
93 addParameter( new QgsProcessingParameterFeatureSink(
94 QStringLiteral( "REPORT" ), QObject::tr( "Report layer from deleting features" ), Qgis::ProcessingSourceType::VectorPoint
95 ) );
96}
97
98QVariantMap QgsFixGeometryDeleteFeaturesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
99{
100 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
101 if ( !input )
102 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
103
104 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, QStringLiteral( "ERRORS" ), context ) );
105 if ( !errors )
106 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "ERRORS" ) ) );
107
108 const QString featIdFieldName = parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context );
109
110 // Verify that input fields exists
111 const int errorsIdFieldIndex = errors->fields().indexFromName( featIdFieldName );
112 if ( errorsIdFieldIndex == -1 )
113 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( featIdFieldName ) );
114 const int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
115 if ( inputIdFieldIndex == -1 )
116 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in input layer." ).arg( featIdFieldName ) );
117
118 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
119 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
120 if ( inputFeatIdFieldType != errors->fields().at( errorsIdFieldIndex ).type() )
121 throw QgsProcessingException( QObject::tr( "Input field %1 does not have the same type as in the error layer." ).arg( featIdFieldName ) );
122
123 QString dest_output;
124 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
125 if ( !sink_output )
126 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
127
128 QString dest_report;
129 QgsFields reportFields = errors->fields();
130 reportFields.append( QgsField( QStringLiteral( "report" ), QMetaType::QString ) );
131 reportFields.append( QgsField( QStringLiteral( "error_fixed" ), QMetaType::Bool ) );
132 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, QStringLiteral( "REPORT" ), context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
133 if ( !sink_report )
134 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "REPORT" ) ) );
135
136 QgsFeature inputFeature, errorFeature, reportFeature;
137 reportFeature.setFields( reportFields );
138 long long progression = 0;
139 long long totalProgression = input->featureCount();
140 feedback->setProgressText( QObject::tr( "Fixing errors..." ) );
141
142 QgsFeatureIterator inputFeaturesIt = input->getFeatures();
143 while ( inputFeaturesIt.nextFeature( inputFeature ) )
144 {
145 if ( feedback->isCanceled() )
146 break;
147
148 progression++;
149 feedback->setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
150
151 QString idValue = inputFeature.attribute( featIdFieldName ).toString();
152 if ( inputFeatIdFieldType == QMetaType::QString )
153 idValue = "'" + idValue + "'";
154
155 QgsFeatureIterator errorFeaturesIt = errors->getFeatures(
157 .setFlags( Qgis::FeatureRequestFlag::SubsetOfAttributes ) // the request will select only the fields referenced in the expression
158 .setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue )
159 );
160 if ( errorFeaturesIt.nextFeature( errorFeature ) && errorFeature.isValid() )
161 {
162 // We found an error feature corresponding to the input feature we are iterating
163 // so it means that we want to delete this feature.
164 // Just don't add this feature to the output sink, and add a report feature saying
165 // that everything went fine.
166 reportFeature.setGeometry( errorFeature.geometry() );
167 reportFeature.setAttributes( errorFeature.attributes() << QStringLiteral( "Feature deleted" ) << true );
168 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
169 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
170 }
171 else
172 {
173 // We didn't find an error corresponding to this feature, so we must keep this feature.
174 // Just add it to the output sink.
175 if ( !sink_output->addFeature( inputFeature, QgsFeatureSink::FastInsert ) )
176 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
177 }
178 }
179 feedback->setProgress( 100 );
180
181 QVariantMap outputs;
182 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
183 outputs.insert( QStringLiteral( "REPORT" ), dest_report );
184
185 return outputs;
186}
187
188Qgis::ProcessingAlgorithmFlags QgsFixGeometryDeleteFeaturesAlgorithm::flags() const
189{
191}
192
@ VectorAnyGeometry
Any vector layer with geometry.
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ VectorLine
Vector line layers.
@ SubsetOfAttributes
Fetch only a subset of attributes (setSubsetOfAttributes sets this flag)
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...
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
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
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
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.
virtual void setProgressText(const QString &text)
Sets a progress report text string.
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.