QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
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(
59 "This algorithm deletes error features listed in the errors layer from an algorithm in the \"Check geometry\" section.\n"
60 "The required inputs are the original layer used in the check algorithm, its unique id field, and its corresponding errors layer.\n\n"
61 "For instance, it can be used after the following check algorithms to delete error features:"
62 "<html><ul><li>Feature inside polygon</li>"
63 "<li>Degenerate polygons</li>"
64 "<li>Small segments</li>"
65 "<li>Duplicated geometries</li>"
66 "<li>etc.</li></ul></html>"
67 );
68}
69
70QgsFixGeometryDeleteFeaturesAlgorithm *QgsFixGeometryDeleteFeaturesAlgorithm::createInstance() const
71{
72 return new QgsFixGeometryDeleteFeaturesAlgorithm();
73}
74
75void QgsFixGeometryDeleteFeaturesAlgorithm::initAlgorithm( const QVariantMap &configuration )
76{
77 Q_UNUSED( configuration )
78
80 u"INPUT"_s,
81 QObject::tr( "Input layer" ),
82 QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
83 ) );
84 addParameter( new QgsProcessingParameterFeatureSource( u"ERRORS"_s, QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
85 addParameter( new QgsProcessingParameterField( u"UNIQUE_ID"_s, QObject::tr( "Field of original feature unique identifier" ), QString(), u"ERRORS"_s ) );
86
87 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Cleaned layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry ) );
88 addParameter( new QgsProcessingParameterFeatureSink( u"REPORT"_s, QObject::tr( "Report layer from deleting features" ), Qgis::ProcessingSourceType::VectorPoint ) );
89}
90
91QVariantMap QgsFixGeometryDeleteFeaturesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
92{
93 QGS_MARK_ALGORITHM_SOURCE
94
95 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
96 if ( !input )
97 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
98
99 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, u"ERRORS"_s, context ) );
100 if ( !errors )
101 throw QgsProcessingException( invalidSourceError( parameters, u"ERRORS"_s ) );
102
103 const QString featIdFieldName = parameterAsString( parameters, u"UNIQUE_ID"_s, context );
104
105 // Verify that input fields exists
106 const int errorsIdFieldIndex = errors->fields().indexFromName( featIdFieldName );
107 if ( errorsIdFieldIndex == -1 )
108 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( featIdFieldName ) );
109 const int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
110 if ( inputIdFieldIndex == -1 )
111 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in input layer." ).arg( featIdFieldName ) );
112
113 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
114 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
115 if ( inputFeatIdFieldType != errors->fields().at( errorsIdFieldIndex ).type() )
116 throw QgsProcessingException( QObject::tr( "Input field %1 does not have the same type as in the error layer." ).arg( featIdFieldName ) );
117
118 QString dest_output;
119 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, u"OUTPUT"_s, context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
120 if ( !sink_output )
121 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
122
123 QString dest_report;
124 QgsFields reportFields = errors->fields();
125 reportFields.append( QgsField( u"report"_s, QMetaType::QString ) );
126 reportFields.append( QgsField( u"error_fixed"_s, QMetaType::Bool ) );
127 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, u"REPORT"_s, context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
128 if ( !sink_report )
129 throw QgsProcessingException( invalidSinkError( parameters, u"REPORT"_s ) );
130
131 QgsFeature inputFeature, errorFeature, reportFeature;
132 reportFeature.setFields( reportFields );
133 long long progression = 0;
134 long long totalProgression = input->featureCount();
135 feedback->setProgressText( QObject::tr( "Fixing errors..." ) );
136
137 QgsFeatureIterator inputFeaturesIt = input->getFeatures();
138 while ( inputFeaturesIt.nextFeature( inputFeature ) )
139 {
140 if ( feedback->isCanceled() )
141 break;
142
143 progression++;
144 feedback->setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
145
146 QString idValue = inputFeature.attribute( featIdFieldName ).toString();
147 if ( inputFeatIdFieldType == QMetaType::QString )
148 idValue = "'" + idValue + "'";
149
150 QgsFeatureIterator errorFeaturesIt = errors->getFeatures(
152 .setFlags( Qgis::FeatureRequestFlag::SubsetOfAttributes ) // the request will select only the fields referenced in the expression
153 .setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue )
154 );
155 if ( errorFeaturesIt.nextFeature( errorFeature ) && errorFeature.isValid() )
156 {
157 // We found an error feature corresponding to the input feature we are iterating
158 // so it means that we want to delete this feature.
159 // Just don't add this feature to the output sink, and add a report feature saying
160 // that everything went fine.
161 reportFeature.setGeometry( errorFeature.geometry() );
162 reportFeature.setAttributes( errorFeature.attributes() << u"Feature deleted"_s << true );
163 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
164 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, u"REPORT"_s ) );
165 else
166 feedback->featureAddedToSink( u"REPORT"_s );
167 }
168 else
169 {
170 // We didn't find an error corresponding to this feature, so we must keep this feature.
171 // Just add it to the output sink.
172 if ( !sink_output->addFeature( inputFeature, QgsFeatureSink::FastInsert ) )
173 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, u"OUTPUT"_s ) );
174 else
175 feedback->featureAddedToSink( u"OUTPUT"_s );
176 }
177 }
178 feedback->setProgress( 100 );
179
180 sink_report->finalize();
181 feedback->featureSinkFinalized( u"REPORT"_s );
182 sink_output->finalize();
183 feedback->featureSinkFinalized( u"OUTPUT"_s );
184
185 QVariantMap outputs;
186 outputs.insert( u"OUTPUT"_s, dest_output );
187 outputs.insert( u"REPORT"_s, dest_report );
188
189 return outputs;
190}
191
192Qgis::ProcessingAlgorithmFlags QgsFixGeometryDeleteFeaturesAlgorithm::flags() const
193{
195}
196
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3749
@ VectorPoint
Vector point layers.
Definition qgis.h:3750
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3752
@ VectorLine
Vector line layers.
Definition qgis.h:3751
@ SubsetOfAttributes
Fetch only a subset of attributes (setSubsetOfAttributes sets this flag).
Definition qgis.h:2361
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3826
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3805
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:64
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:66
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
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
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:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
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.