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