QGIS API Documentation  3.0.2-Girona (307d082)
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 
22 QString QgsAddUniqueValueIndexAlgorithm::name() const
23 {
24  return QStringLiteral( "adduniquevalueindexfield" );
25 }
26 
27 QString QgsAddUniqueValueIndexAlgorithm::displayName() const
28 {
29  return QObject::tr( "Add unique value index field" );
30 }
31 
32 QStringList QgsAddUniqueValueIndexAlgorithm::tags() const
33 {
34  return QObject::tr( "categorize,categories,category,reclassify,classes,create" ).split( ',' );
35 }
36 
37 QString QgsAddUniqueValueIndexAlgorithm::group() const
38 {
39  return QObject::tr( "Vector table" );
40 }
41 
42 QString QgsAddUniqueValueIndexAlgorithm::groupId() const
43 {
44  return QStringLiteral( "vectortable" );
45 }
46 
47 void QgsAddUniqueValueIndexAlgorithm::initAlgorithm( const QVariantMap & )
48 {
49  addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ) ) );
50  addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD" ), QObject::tr( "Class field" ), QVariant(),
51  QStringLiteral( "INPUT" ), QgsProcessingParameterField::Any ) );
52  addParameter( new QgsProcessingParameterString( QStringLiteral( "FIELD_NAME" ),
53  QObject::tr( "Output field name" ), QStringLiteral( "NUM_FIELD" ) ) );
54 
55  std::unique_ptr< QgsProcessingParameterFeatureSink > classedOutput = qgis::make_unique< QgsProcessingParameterFeatureSink >( QStringLiteral( "OUTPUT" ), QObject::tr( "Layer with index field" ), QgsProcessing::TypeVectorAnyGeometry, QVariant(), true );
56  classedOutput->setCreateByDefault( true );
57  addParameter( classedOutput.release() );
58 
59  std::unique_ptr< QgsProcessingParameterFeatureSink > summaryOutput = qgis::make_unique< QgsProcessingParameterFeatureSink >( QStringLiteral( "SUMMARY_OUTPUT" ), QObject::tr( "Class summary" ),
60  QgsProcessing::TypeVector, QVariant(), true );
61  summaryOutput->setCreateByDefault( false );
62  addParameter( summaryOutput.release() );
63 }
64 
65 QString QgsAddUniqueValueIndexAlgorithm::shortHelpString() const
66 {
67  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 "
68  "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"
69  "The new attribute is not added to the input layer but a new layer is generated instead.\n\n"
70  "Optionally, a separate table can be output which contains a summary of the class field values mapped to the new unique numeric value." );
71 }
72 
73 QgsAddUniqueValueIndexAlgorithm *QgsAddUniqueValueIndexAlgorithm::createInstance() const
74 {
75  return new QgsAddUniqueValueIndexAlgorithm();
76 }
77 
78 QVariantMap QgsAddUniqueValueIndexAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
79 {
80  std::unique_ptr< QgsProcessingFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
81  if ( !source )
82  throw QgsProcessingException( QObject::tr( "Could not load source layer for INPUT" ) );
83 
84  QString newFieldName = parameterAsString( parameters, QStringLiteral( "FIELD_NAME" ), context );
85  QgsFields fields = source->fields();
86  QgsField newField = QgsField( newFieldName, QVariant::Int );
87  fields.append( newField );
88 
89  QString dest;
90  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, source->wkbType(), source->sourceCrs() ) );
91 
92  QString sourceFieldName = parameterAsString( parameters, QStringLiteral( "FIELD" ), context );
93  int fieldIndex = source->fields().lookupField( sourceFieldName );
94  if ( fieldIndex < 0 )
95  throw QgsProcessingException( QObject::tr( "Invalid field name %1" ).arg( sourceFieldName ) );
96 
97  QString summaryDest;
98  QgsFields summaryFields;
99  summaryFields.append( newField );
100  summaryFields.append( source->fields().at( fieldIndex ) );
101  std::unique_ptr< QgsFeatureSink > summarySink( parameterAsSink( parameters, QStringLiteral( "SUMMARY_OUTPUT" ), context, summaryDest, summaryFields, QgsWkbTypes::NoGeometry ) );
102 
103  QHash< QVariant, int > classes;
104 
106 
107  long count = source->featureCount();
108  double step = count > 0 ? 100.0 / count : 1;
109  int current = 0;
110  QgsFeature feature;
111  while ( it.nextFeature( feature ) )
112  {
113  if ( feedback->isCanceled() )
114  {
115  break;
116  }
117 
118  QgsAttributes attributes = feature.attributes();
119  QVariant clazz = attributes.at( fieldIndex );
120 
121  int thisValue = classes.value( clazz, -1 );
122  if ( thisValue == -1 )
123  {
124  thisValue = classes.count();
125  classes.insert( clazz, thisValue );
126  }
127 
128  if ( sink )
129  {
130  attributes.append( thisValue );
131  feature.setAttributes( attributes );
132  sink->addFeature( feature, QgsFeatureSink::FastInsert );
133  }
134 
135  feedback->setProgress( current * step );
136  current++;
137  }
138 
139  if ( summarySink )
140  {
141  //generate summary table - first we make a sorted version of the classes
142  QMap< int, QVariant > sorted;
143  for ( auto classIt = classes.constBegin(); classIt != classes.constEnd(); ++classIt )
144  {
145  sorted.insert( classIt.value(), classIt.key() );
146  }
147  // now save them
148  for ( auto sortedIt = sorted.constBegin(); sortedIt != sorted.constEnd(); ++sortedIt )
149  {
150  QgsFeature f;
151  f.setAttributes( QgsAttributes() << sortedIt.key() << sortedIt.value() );
152  summarySink->addFeature( f, QgsFeatureSink::FastInsert );
153  }
154  }
155 
156  QVariantMap results;
157  if ( sink )
158  results.insert( QStringLiteral( "OUTPUT" ), dest );
159  if ( summarySink )
160  results.insert( QStringLiteral( "SUMMARY_OUTPUT" ), summaryDest );
161  return results;
162 }
163 
Wrapper for iterator of features from vector data provider or vector layer.
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
Base class for providing feedback from a processing algorithm.
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
A vector layer or feature source field parameter for processing algorithms.
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:63
Container of fields for a vector layer.
Definition: qgsfields.h:42
void setAttributes(const QgsAttributes &attrs)
Sets the feature&#39;s attributes.
Definition: qgsfeature.cpp:127
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:62
This class wraps a request for features to a vector layer (or directly its vector data provider)...
Custom exception class for processing related exceptions.
Definition: qgsexception.h:82
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Append a field. The field must have unique name, otherwise it is rejected (returns false) ...
Definition: qgsfields.cpp:59
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:48
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
An input feature source (such as vector layers) parameter for processing algorithms.
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition: qgsprocessing.h:54
bool nextFeature(QgsFeature &f)
A vector of attributes.
Definition: qgsattributes.h:58
Contains information about the context in which a processing algorithm is executed.
A string parameter for processing algorithms.
Any vector layer with geometry.
Definition: qgsprocessing.h:48
QgsAttributes attributes
Definition: qgsfeature.h:72