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