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