QGIS API Documentation 4.3.0-Master (45633be667c)
Loading...
Searching...
No Matches
qgsalgorithmremoveduplicatesbyattribute.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmremoveduplicatesbyattribute.cpp
3 ----------------------------------
4 begin : October 2018
5 copyright : (C) 2018 by Nyall Dawson
6 email : nyall dot dawson at gmail 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 QgsRemoveDuplicatesByAttributeAlgorithm::name() const
27{
28 return u"removeduplicatesbyattribute"_s;
29}
30
31QString QgsRemoveDuplicatesByAttributeAlgorithm::displayName() const
32{
33 return QObject::tr( "Delete duplicates by attribute" );
34}
35
36QStringList QgsRemoveDuplicatesByAttributeAlgorithm::tags() const
37{
38 return QObject::tr( "drop,remove,field,value,same,filter" ).split( ',' );
39}
40
41QString QgsRemoveDuplicatesByAttributeAlgorithm::group() const
42{
43 return QObject::tr( "Vector general" );
44}
45
46QString QgsRemoveDuplicatesByAttributeAlgorithm::groupId() const
47{
48 return u"vectorgeneral"_s;
49}
50
51void QgsRemoveDuplicatesByAttributeAlgorithm::initAlgorithm( const QVariantMap & )
52{
53 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
54 addParameter( new QgsProcessingParameterField( u"FIELDS"_s, QObject::tr( "Field to match duplicates by" ), QVariant(), u"INPUT"_s, Qgis::ProcessingFieldParameterDataType::Any, true ) );
55
56 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Filtered (no duplicates)" ) ) );
58 = new QgsProcessingParameterFeatureSink( u"DUPLICATES"_s, QObject::tr( "Filtered (duplicates)" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true );
59 failOutput->setCreateByDefault( false );
60 addParameter( failOutput );
61
62 addOutput( new QgsProcessingOutputNumber( u"RETAINED_COUNT"_s, QObject::tr( "Count of retained records" ) ) );
63 addOutput( new QgsProcessingOutputNumber( u"DUPLICATE_COUNT"_s, QObject::tr( "Count of discarded duplicate records" ) ) );
64}
65
66QString QgsRemoveDuplicatesByAttributeAlgorithm::shortHelpString() const
67{
68 return QObject::tr(
69 "This algorithm removes duplicate rows by a field value (or multiple field values). The first matching row will be retained, and duplicates will be discarded.\n\n"
70 "Optionally, these duplicate records can be saved to a separate output for analysis."
71 );
72}
73
74QString QgsRemoveDuplicatesByAttributeAlgorithm::shortDescription() const
75{
76 return QObject::tr( "Removes duplicate rows by a field value (or multiple field values)." );
77}
78
79QgsRemoveDuplicatesByAttributeAlgorithm *QgsRemoveDuplicatesByAttributeAlgorithm::createInstance() const
80{
81 return new QgsRemoveDuplicatesByAttributeAlgorithm();
82}
83
84QVariantMap QgsRemoveDuplicatesByAttributeAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
85{
86 QGS_MARK_ALGORITHM_SOURCE
87
88 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
89 if ( !source )
90 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
91
92 const QStringList fieldNames = parameterAsStrings( parameters, u"FIELDS"_s, context );
93
94 QgsAttributeList attributes;
95 for ( const QString &field : fieldNames )
96 {
97 const int index = source->fields().lookupField( field );
98 if ( index < 0 )
99 feedback->reportError( QObject::tr( "Field %1 not found in INPUT layer, skipping" ).arg( field ) );
100 else
101 attributes.append( index );
102 }
103 if ( attributes.isEmpty() )
104 throw QgsProcessingException( QObject::tr( "No input fields found" ) );
105
106
107 QString noDupeSinkId;
108 std::unique_ptr<QgsFeatureSink> noDupeSink( parameterAsSink( parameters, u"OUTPUT"_s, context, noDupeSinkId, source->fields(), source->wkbType(), source->sourceCrs() ) );
109 if ( !noDupeSink )
110 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
111
112 QString dupeSinkId;
113 std::unique_ptr<QgsFeatureSink> dupesSink( parameterAsSink( parameters, u"DUPLICATES"_s, context, dupeSinkId, source->fields(), source->wkbType(), source->sourceCrs() ) );
114
115 const long count = source->featureCount();
116 const double step = count > 0 ? 100.0 / count : 1;
117 int current = 0;
118
119 long long keptCount = 0;
120 long long discardedCount = 0;
121
122 QSet<QVariantList> matched;
123
125 QgsFeature f;
126
127 QVariantList dupeKey;
128 dupeKey.reserve( attributes.size() );
129 for ( const int i : attributes )
130 {
131 ( void ) i;
132 dupeKey.append( QVariant() );
133 }
134
135 while ( it.nextFeature( f ) )
136 {
137 if ( feedback->isCanceled() )
138 {
139 break;
140 }
141
142 int i = 0;
143 for ( const int attr : attributes )
144 dupeKey[i++] = f.attribute( attr );
145
146 if ( matched.contains( dupeKey ) )
147 {
148 // duplicate
149 discardedCount++;
150 if ( dupesSink )
151 {
152 if ( !dupesSink->addFeature( f, QgsFeatureSink::FastInsert ) )
153 throw QgsProcessingException( writeFeatureError( dupesSink.get(), parameters, u"DUPLICATES"_s ) );
154 else
155 feedback->featureAddedToSink( u"DUPLICATES"_s );
156 }
157 }
158 else
159 {
160 // not duplicate
161 keptCount++;
162 matched.insert( dupeKey );
163 if ( !noDupeSink->addFeature( f, QgsFeatureSink::FastInsert ) )
164 throw QgsProcessingException( writeFeatureError( noDupeSink.get(), parameters, u"OUTPUT"_s ) );
165 else
166 feedback->featureAddedToSink( u"OUTPUT"_s );
167 }
168
169 feedback->setProgress( current * step );
170 current++;
171 }
172
173 if ( noDupeSink )
174 {
175 noDupeSink->finalize();
176 feedback->featureSinkFinalized( u"OUTPUT"_s );
177 }
178
179 QVariantMap outputs;
180 outputs.insert( u"RETAINED_COUNT"_s, keptCount );
181 outputs.insert( u"DUPLICATE_COUNT"_s, discardedCount );
182 outputs.insert( u"OUTPUT"_s, noDupeSinkId );
183 if ( dupesSink )
184 {
185 dupesSink->finalize();
186 feedback->featureSinkFinalized( u"DUPLICATES"_s );
187 outputs.insert( u"DUPLICATES"_s, dupeSinkId );
188 }
189 return outputs;
190}
191
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3757
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3751
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3954
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
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
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
Contains information about the context in which a processing algorithm is executed.
void setCreateByDefault(bool createByDefault)
Sets whether the destination should be created by default.
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 reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A numeric output for processing algorithms.
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.
QList< int > QgsAttributeList
Definition qgsfield.h:30