QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmuniquevalueindex.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmuniquevalueindex.cpp
3 ---------------------
4 begin : January 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
21
22QString QgsAddUniqueValueIndexAlgorithm::name() const
23{
24 return QStringLiteral( "adduniquevalueindexfield" );
25}
26
27QString QgsAddUniqueValueIndexAlgorithm::displayName() const
28{
29 return QObject::tr( "Add unique value index field" );
30}
31
32QStringList QgsAddUniqueValueIndexAlgorithm::tags() const
33{
34 return QObject::tr( "categorize,categories,category,reclassify,classes,create" ).split( ',' );
35}
36
37QString QgsAddUniqueValueIndexAlgorithm::group() const
38{
39 return QObject::tr( "Vector table" );
40}
41
42QString QgsAddUniqueValueIndexAlgorithm::groupId() const
43{
44 return QStringLiteral( "vectortable" );
45}
46
47void QgsAddUniqueValueIndexAlgorithm::initAlgorithm( const QVariantMap & )
48{
49 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
50 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD" ), QObject::tr( "Class field" ), QVariant(), QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Any ) );
51 addParameter( new QgsProcessingParameterString( QStringLiteral( "FIELD_NAME" ), QObject::tr( "Output field name" ), QStringLiteral( "NUM_FIELD" ) ) );
52
53 auto classedOutput = std::make_unique<QgsProcessingParameterFeatureSink>( QStringLiteral( "OUTPUT" ), QObject::tr( "Layer with index field" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true );
54 classedOutput->setCreateByDefault( true );
55 addParameter( classedOutput.release() );
56
57 auto summaryOutput = std::make_unique<QgsProcessingParameterFeatureSink>( QStringLiteral( "SUMMARY_OUTPUT" ), QObject::tr( "Class summary" ), Qgis::ProcessingSourceType::Vector, QVariant(), true );
58 summaryOutput->setCreateByDefault( false );
59 addParameter( summaryOutput.release() );
60}
61
62QString QgsAddUniqueValueIndexAlgorithm::shortHelpString() const
63{
64 return QObject::tr( "This algorithm takes a vector layer and an attribute and adds a new numeric field. Values in this field correspond to values in the specified attribute, so features with the same "
65 "value for the attribute will have the same value in the new numeric field. This creates a numeric equivalent of the specified attribute, which defines the same classes.\n\n"
66 "The new attribute is not added to the input layer but a new layer is generated instead.\n\n"
67 "Optionally, a separate table can be output which contains a summary of the class field values mapped to the new unique numeric value." );
68}
69
70QString QgsAddUniqueValueIndexAlgorithm::shortDescription() const
71{
72 return QObject::tr( "Adds a numeric field and assigns the same index to features of the same attribute value." );
73}
74
75QgsAddUniqueValueIndexAlgorithm *QgsAddUniqueValueIndexAlgorithm::createInstance() const
76{
77 return new QgsAddUniqueValueIndexAlgorithm();
78}
79
80QVariantMap QgsAddUniqueValueIndexAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
81{
82 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
83 if ( !source )
84 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
85
86 const QString newFieldName = parameterAsString( parameters, QStringLiteral( "FIELD_NAME" ), context );
87 QgsFields fields = source->fields();
88
89 if ( fields.lookupField( newFieldName ) >= 0 )
90 {
91 throw QgsProcessingException( QObject::tr( "A field with the same name (%1) already exists" ).arg( newFieldName ) );
92 }
93
94 const QgsField newField = QgsField( newFieldName, QMetaType::Type::Int );
95 fields.append( newField );
96
97 QString dest;
98 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, source->wkbType(), source->sourceCrs() ) );
99
100 const QString sourceFieldName = parameterAsString( parameters, QStringLiteral( "FIELD" ), context );
101 const int fieldIndex = source->fields().lookupField( sourceFieldName );
102 if ( fieldIndex < 0 )
103 throw QgsProcessingException( QObject::tr( "Invalid field name %1" ).arg( sourceFieldName ) );
104
105 QString summaryDest;
106 QgsFields summaryFields;
107 summaryFields.append( newField );
108 summaryFields.append( source->fields().at( fieldIndex ) );
109 std::unique_ptr<QgsFeatureSink> summarySink( parameterAsSink( parameters, QStringLiteral( "SUMMARY_OUTPUT" ), context, summaryDest, summaryFields, Qgis::WkbType::NoGeometry ) );
110
111 QHash<QVariant, int> classes;
112
114
115 const long count = source->featureCount();
116 const double step = count > 0 ? 100.0 / count : 1;
117 int current = 0;
118 QgsFeature feature;
119 while ( it.nextFeature( feature ) )
120 {
121 if ( feedback->isCanceled() )
122 {
123 break;
124 }
125
126 QgsAttributes attributes = feature.attributes();
127 const QVariant clazz = attributes.at( fieldIndex );
128
129 int thisValue = classes.value( clazz, -1 );
130 if ( thisValue == -1 )
131 {
132 thisValue = classes.count();
133 classes.insert( clazz, thisValue );
134 }
135
136 if ( sink )
137 {
138 attributes.append( thisValue );
139 feature.setAttributes( attributes );
140 if ( !sink->addFeature( feature, QgsFeatureSink::FastInsert ) )
141 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
142 }
143
144 feedback->setProgress( current * step );
145 current++;
146 }
147
148 if ( summarySink )
149 {
150 //generate summary table - first we make a sorted version of the classes
151 QMap<int, QVariant> sorted;
152 for ( auto classIt = classes.constBegin(); classIt != classes.constEnd(); ++classIt )
153 {
154 sorted.insert( classIt.value(), classIt.key() );
155 }
156 // now save them
157 for ( auto sortedIt = sorted.constBegin(); sortedIt != sorted.constEnd(); ++sortedIt )
158 {
159 QgsFeature f;
160 f.setAttributes( QgsAttributes() << sortedIt.key() << sortedIt.value() );
161 if ( !summarySink->addFeature( f, QgsFeatureSink::FastInsert ) )
162 throw QgsProcessingException( writeFeatureError( summarySink.get(), parameters, QStringLiteral( "SUMMARY_OUTPUT" ) ) );
163 }
164 }
165
166 QVariantMap results;
167 if ( sink )
168 {
169 sink->finalize();
170 results.insert( QStringLiteral( "OUTPUT" ), dest );
171 }
172 if ( summarySink )
173 {
174 summarySink->finalize();
175 results.insert( QStringLiteral( "SUMMARY_OUTPUT" ), summaryDest );
176 }
177 return results;
178}
179
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ VectorAnyGeometry
Any vector layer with geometry.
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
@ NoGeometry
No geometry.
A vector of attributes.
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.
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:53
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
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
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.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A string parameter for processing algorithms.