QGIS API Documentation 3.99.0-Master (2fe06baccd8)
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
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
74 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ),
75 QList<int>()
76 << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
77 << static_cast<int>( Qgis::ProcessingSourceType::VectorLine )
79 ) );
81 QStringLiteral( "ERRORS" ), QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
82 ) );
83 addParameter( new QgsProcessingParameterField(
84 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Field of original feature unique identifier" ),
85 QString(), QStringLiteral( "ERRORS" )
86 ) );
87
88 addParameter( new QgsProcessingParameterFeatureSink(
89 QStringLiteral( "OUTPUT" ), QObject::tr( "Cleaned layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry
90 ) );
91 addParameter( new QgsProcessingParameterFeatureSink(
92 QStringLiteral( "REPORT" ), QObject::tr( "Report layer from deleting features" ), Qgis::ProcessingSourceType::VectorPoint
93 ) );
94}
95
96QVariantMap QgsFixGeometryDeleteFeaturesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
97{
98 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
99 if ( !input )
100 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
101
102 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, QStringLiteral( "ERRORS" ), context ) );
103 if ( !errors )
104 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "ERRORS" ) ) );
105
106 const QString featIdFieldName = parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context );
107
108 // Verify that input fields exists
109 const int errorsIdFieldIndex = errors->fields().indexFromName( featIdFieldName );
110 if ( errorsIdFieldIndex == -1 )
111 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in the error layer." ).arg( featIdFieldName ) );
112 const int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
113 if ( inputIdFieldIndex == -1 )
114 throw QgsProcessingException( QObject::tr( "Field %1 does not exist in input layer." ).arg( featIdFieldName ) );
115
116 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
117 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.type();
118 if ( inputFeatIdFieldType != errors->fields().at( errorsIdFieldIndex ).type() )
119 throw QgsProcessingException( QObject::tr( "Input field %1 does not have the same type as in the error layer." ).arg( featIdFieldName ) );
120
121 QString dest_output;
122 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
123 if ( !sink_output )
124 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
125
126 QString dest_report;
127 QgsFields reportFields = errors->fields();
128 reportFields.append( QgsField( QStringLiteral( "report" ), QMetaType::QString ) );
129 reportFields.append( QgsField( QStringLiteral( "error_fixed" ), QMetaType::Bool ) );
130 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, QStringLiteral( "REPORT" ), context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
131 if ( !sink_report )
132 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "REPORT" ) ) );
133
134 QgsFeature inputFeature, errorFeature, reportFeature;
135 reportFeature.setFields( reportFields );
136 long long progression = 0;
137 long long totalProgression = input->featureCount();
138 feedback->setProgressText( QObject::tr( "Fixing errors..." ) );
139
140 QgsFeatureIterator inputFeaturesIt = input->getFeatures();
141 while ( inputFeaturesIt.nextFeature( inputFeature ) )
142 {
143 if ( feedback->isCanceled() )
144 break;
145
146 progression++;
147 feedback->setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
148
149 QString idValue = inputFeature.attribute( featIdFieldName ).toString();
150 if ( inputFeatIdFieldType == QMetaType::QString )
151 idValue = "'" + idValue + "'";
152
153 QgsFeatureIterator errorFeaturesIt = errors->getFeatures(
155 .setFlags( Qgis::FeatureRequestFlag::SubsetOfAttributes ) // the request will select only the fields referenced in the expression
156 .setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue )
157 );
158 if ( errorFeaturesIt.nextFeature( errorFeature ) && errorFeature.isValid() )
159 {
160 // We found an error feature corresponding to the input feature we are iterating
161 // so it means that we want to delete this feature.
162 // Just don't add this feature to the output sink, and add a report feature saying
163 // that everything went fine.
164 reportFeature.setGeometry( errorFeature.geometry() );
165 reportFeature.setAttributes( errorFeature.attributes() << QStringLiteral( "Feature deleted" ) << true );
166 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
167 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
168 }
169 else
170 {
171 // We didn't find an error corresponding to this feature, so we must keep this feature.
172 // Just add it to the output sink.
173 if ( !sink_output->addFeature( inputFeature, QgsFeatureSink::FastInsert ) )
174 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
175 }
176 }
177 feedback->setProgress( 100 );
178
179 QVariantMap outputs;
180 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
181 outputs.insert( QStringLiteral( "REPORT" ), dest_report );
182
183 return outputs;
184}
185
186Qgis::ProcessingAlgorithmFlags QgsFixGeometryDeleteFeaturesAlgorithm::flags() const
187{
189}
190
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3533
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
@ VectorLine
Vector line layers.
Definition qgis.h:3535
@ SubsetOfAttributes
Fetch only a subset of attributes (setSubsetOfAttributes sets this flag).
Definition qgis.h:2197
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3609
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3588
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:54
QMetaType::Type type
Definition qgsfield.h:61
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:73
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.