QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
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(
69 "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 "
70 "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"
71 "The new attribute is not added to the input layer but a new layer is generated instead.\n\n"
72 "Optionally, a separate table can be output which contains a summary of the class field values mapped to the new unique numeric value."
73 );
74}
75
76QString QgsAddUniqueValueIndexAlgorithm::shortDescription() const
77{
78 return QObject::tr( "Adds a numeric field and assigns the same index to features of the same attribute value." );
79}
80
81QgsAddUniqueValueIndexAlgorithm *QgsAddUniqueValueIndexAlgorithm::createInstance() const
82{
83 return new QgsAddUniqueValueIndexAlgorithm();
84}
85
86QVariantMap QgsAddUniqueValueIndexAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
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 QString newFieldName = parameterAsString( parameters, u"FIELD_NAME"_s, context );
93 QgsFields fields = source->fields();
94
95 if ( fields.lookupField( newFieldName ) >= 0 )
96 {
97 throw QgsProcessingException( QObject::tr( "A field with the same name (%1) already exists" ).arg( newFieldName ) );
98 }
99
100 const QgsField newField = QgsField( newFieldName, QMetaType::Type::Int );
101 fields.append( newField );
102
103 QString dest;
104 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, source->wkbType(), source->sourceCrs() ) );
105
106 const QString sourceFieldName = parameterAsString( parameters, u"FIELD"_s, context );
107 const int fieldIndex = source->fields().lookupField( sourceFieldName );
108 if ( fieldIndex < 0 )
109 throw QgsProcessingException( QObject::tr( "Invalid field name %1" ).arg( sourceFieldName ) );
110
111 QString summaryDest;
112 QgsFields summaryFields;
113 summaryFields.append( newField );
114 summaryFields.append( source->fields().at( fieldIndex ) );
115 std::unique_ptr<QgsFeatureSink> summarySink( parameterAsSink( parameters, u"SUMMARY_OUTPUT"_s, context, summaryDest, summaryFields, Qgis::WkbType::NoGeometry ) );
116
117 QHash<QVariant, int> classes;
118
120
121 const long count = source->featureCount();
122 const double step = count > 0 ? 100.0 / count : 1;
123 int current = 0;
124 QgsFeature feature;
125 while ( it.nextFeature( feature ) )
126 {
127 if ( feedback->isCanceled() )
128 {
129 break;
130 }
131
132 QgsAttributes attributes = feature.attributes();
133 const QVariant clazz = attributes.at( fieldIndex );
134
135 int thisValue = classes.value( clazz, -1 );
136 if ( thisValue == -1 )
137 {
138 thisValue = classes.count();
139 classes.insert( clazz, thisValue );
140 }
141
142 if ( sink )
143 {
144 attributes.append( thisValue );
145 feature.setAttributes( attributes );
146 if ( !sink->addFeature( feature, QgsFeatureSink::FastInsert ) )
147 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
148 }
149
150 feedback->setProgress( current * step );
151 current++;
152 }
153
154 if ( summarySink )
155 {
156 //generate summary table - first we make a sorted version of the classes
157 QMap<int, QVariant> sorted;
158 for ( auto classIt = classes.constBegin(); classIt != classes.constEnd(); ++classIt )
159 {
160 sorted.insert( classIt.value(), classIt.key() );
161 }
162 // now save them
163 for ( auto sortedIt = sorted.constBegin(); sortedIt != sorted.constEnd(); ++sortedIt )
164 {
165 QgsFeature f;
166 f.setAttributes( QgsAttributes() << sortedIt.key() << sortedIt.value() );
167 if ( !summarySink->addFeature( f, QgsFeatureSink::FastInsert ) )
168 throw QgsProcessingException( writeFeatureError( summarySink.get(), parameters, u"SUMMARY_OUTPUT"_s ) );
169 }
170 }
171
172 QVariantMap results;
173 if ( sink )
174 {
175 sink->finalize();
176 results.insert( u"OUTPUT"_s, dest );
177 }
178 if ( summarySink )
179 {
180 summarySink->finalize();
181 results.insert( u"SUMMARY_OUTPUT"_s, summaryDest );
182 }
183 return results;
184}
185
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3653
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3647
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3828
@ NoGeometry
No geometry.
Definition qgis.h:312
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: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
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
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.