QGIS API Documentation 3.43.0-Master (c4a2e9c6d2f)
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( "Fix geometry (delete features)" );
30}
31
32QStringList QgsFixGeometryDeleteFeaturesAlgorithm::tags() const
33{
34 return QObject::tr( "fix,delete,features" ).split( ',' );
35}
36
37QString QgsFixGeometryDeleteFeaturesAlgorithm::group() const
38{
39 return QObject::tr( "Fix geometry" );
40}
41
42QString QgsFixGeometryDeleteFeaturesAlgorithm::groupId() const
43{
44 return QStringLiteral( "fixgeometry" );
45}
46
47QString QgsFixGeometryDeleteFeaturesAlgorithm::shortHelpString() const
48{
49 return QObject::tr( "This algorithm deletes error features listed in the errors layer from a check geometry algorithm.\n"
50 "The required inputs are the original layer used in the check algorithm, its unique id field, and its corresponding errors layer.\n\n"
51 "For instance, it can be used after the following check algorithms to delete error features:"
52 "<html><ul><li>contained</li>"
53 "<li>degenerate</li>"
54 "<li>segment length</li>"
55 "<li>duplicate</li>"
56 "<li>etc.</li></ul></html>" );
57}
58
59QgsFixGeometryDeleteFeaturesAlgorithm *QgsFixGeometryDeleteFeaturesAlgorithm::createInstance() const
60{
61 return new QgsFixGeometryDeleteFeaturesAlgorithm();
62}
63
64void QgsFixGeometryDeleteFeaturesAlgorithm::initAlgorithm( const QVariantMap &configuration )
65{
66 Q_UNUSED( configuration )
67
68 // Inputs
70 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ),
71 QList<int>()
72 << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
73 << static_cast<int>( Qgis::ProcessingSourceType::VectorLine )
75 ) );
77 QStringLiteral( "ERRORS" ), QObject::tr( "Error layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint )
78 ) );
79 addParameter( new QgsProcessingParameterField(
80 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Field of original feature unique identifier" ),
81 QString(), QStringLiteral( "ERRORS" )
82 ) );
83
84 // Outputs
85 addParameter( new QgsProcessingParameterFeatureSink(
86 QStringLiteral( "OUTPUT" ), QObject::tr( "Output layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry
87 ) );
88 addParameter( new QgsProcessingParameterFeatureSink(
89 QStringLiteral( "REPORT" ), QObject::tr( "Report layer" ), Qgis::ProcessingSourceType::VectorPoint
90 ) );
91}
92
93QVariantMap QgsFixGeometryDeleteFeaturesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
94{
95 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
96 if ( !input )
97 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
98
99 const std::unique_ptr<QgsProcessingFeatureSource> errors( parameterAsSource( parameters, QStringLiteral( "ERRORS" ), context ) );
100 if ( !errors )
101 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "ERRORS" ) ) );
102
103 const QString featIdFieldName = parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), 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, QStringLiteral( "OUTPUT" ), context, dest_output, input->fields(), input->wkbType(), input->sourceCrs() ) );
120 if ( !sink_output )
121 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
122
123 QString dest_report;
124 QgsFields reportFields = errors->fields();
125 reportFields.append( QgsField( QStringLiteral( "report" ), QMetaType::QString ) );
126 reportFields.append( QgsField( QStringLiteral( "error_fixed" ), QMetaType::Bool ) );
127 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink( parameters, QStringLiteral( "REPORT" ), context, dest_report, reportFields, errors->wkbType(), errors->sourceCrs() ) );
128 if ( !sink_report )
129 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "REPORT" ) ) );
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 progression++;
141 feedback->setProgress( static_cast<double>( static_cast<long double>( progression ) / totalProgression ) * 100 );
142
143 QString idValue = inputFeature.attribute( featIdFieldName ).toString();
144 if ( inputFeatIdFieldType == QMetaType::QString )
145 idValue = "'" + idValue + "'";
146
147 QgsFeatureIterator errorFeaturesIt = errors->getFeatures(
149 .setFlags( Qgis::FeatureRequestFlag::SubsetOfAttributes ) // the request will select only the fields referenced in the expression
150 .setFilterExpression( "\"" + featIdFieldName + "\" = " + idValue )
151 );
152 if ( errorFeaturesIt.nextFeature( errorFeature ) && errorFeature.isValid() )
153 {
154 // We found an error feature corresponding to the input feature we are iterating
155 // so it means that we want to delete this feature.
156 // Just don't add this feature to the output sink, and add a report feature saying
157 // that everything went fine.
158 reportFeature.setGeometry( errorFeature.geometry() );
159 reportFeature.setAttributes( errorFeature.attributes() << QStringLiteral( "Feature deleted" ) << true );
160 if ( !sink_report->addFeature( reportFeature, QgsFeatureSink::FastInsert ) )
161 throw QgsProcessingException( writeFeatureError( sink_report.get(), parameters, QStringLiteral( "REPORT" ) ) );
162 }
163 else
164 {
165 // We didn't find an error corresponding to this feature, so we must keep this feature.
166 // Just add it to the output sink.
167 if ( !sink_output->addFeature( inputFeature, QgsFeatureSink::FastInsert ) )
168 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
169 }
170 }
171 feedback->setProgress( 100 );
172
173 QVariantMap outputs;
174 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
175 outputs.insert( QStringLiteral( "REPORT" ), dest_report );
176
177 return outputs;
178}
179
180Qgis::ProcessingAlgorithmFlags QgsFixGeometryDeleteFeaturesAlgorithm::flags() const
181{
183}
184
@ 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.
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.