QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
qgsalgorithmkmeansclustering.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmkmeansclustering.cpp
3 ---------------------
4 begin : June 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 <random>
21#include <unordered_map>
22
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29constexpr uint KMEANS_MAX_ITERATIONS = 1000;
30
31QString QgsKMeansClusteringAlgorithm::name() const
32{
33 return u"kmeansclustering"_s;
34}
35
36QString QgsKMeansClusteringAlgorithm::displayName() const
37{
38 return QObject::tr( "K-means clustering" );
39}
40
41QStringList QgsKMeansClusteringAlgorithm::tags() const
42{
43 return QObject::tr( "clustering,clusters,kmeans,points" ).split( ',' );
44}
45
46QString QgsKMeansClusteringAlgorithm::group() const
47{
48 return QObject::tr( "Vector analysis" );
49}
50
51QString QgsKMeansClusteringAlgorithm::groupId() const
52{
53 return u"vectoranalysis"_s;
54}
55
56void QgsKMeansClusteringAlgorithm::initAlgorithm( const QVariantMap & )
57{
58 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
59 addParameter( new QgsProcessingParameterNumber( u"CLUSTERS"_s, QObject::tr( "Number of clusters" ), Qgis::ProcessingNumberParameterType::Integer, 5, false, 1 ) );
60
61 QStringList initializationMethods;
62 initializationMethods << QObject::tr( "Farthest points" )
63 << QObject::tr( "K-means++" );
64 addParameter( new QgsProcessingParameterEnum( u"METHOD"_s, QObject::tr( "Method" ), initializationMethods, false, 0, false ) );
65
66 auto fieldNameParam = std::make_unique<QgsProcessingParameterString>( u"FIELD_NAME"_s, QObject::tr( "Cluster field name" ), u"CLUSTER_ID"_s );
67 fieldNameParam->setFlags( fieldNameParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
68 addParameter( fieldNameParam.release() );
69 auto sizeFieldNameParam = std::make_unique<QgsProcessingParameterString>( u"SIZE_FIELD_NAME"_s, QObject::tr( "Cluster size field name" ), u"CLUSTER_SIZE"_s );
70 sizeFieldNameParam->setFlags( sizeFieldNameParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
71 addParameter( sizeFieldNameParam.release() );
72
73 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Clusters" ), Qgis::ProcessingSourceType::VectorAnyGeometry ) );
74}
75
76QString QgsKMeansClusteringAlgorithm::shortHelpString() const
77{
78 return QObject::tr( "This algorithm calculates the 2D distance based k-means cluster number for each input feature.\n\n"
79 "If input geometries are lines or polygons, the clustering is based on the centroid of the feature.\n\n"
80 "References:\n"
81 "Arthur, David & Vassilvitskii, Sergei. (2007). K-Means++: The Advantages of Careful Seeding. Proc. of the Annu. ACM-SIAM Symp. on Discrete Algorithms. 8.\n\n"
82 "Bhattacharya, Anup & Eube, Jan & Röglin, Heiko & Schmidt, Melanie. (2019). Noisy, Greedy and Not So Greedy k-means++" );
83}
84
85QString QgsKMeansClusteringAlgorithm::shortDescription() const
86{
87 return QObject::tr( "Calculates the 2D distance based k-means cluster number for each input feature." );
88}
89
90QgsKMeansClusteringAlgorithm *QgsKMeansClusteringAlgorithm::createInstance() const
91{
92 return new QgsKMeansClusteringAlgorithm();
93}
94
95QVariantMap QgsKMeansClusteringAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
96{
97 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
98 if ( !source )
99 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
100
101 int k = parameterAsInt( parameters, u"CLUSTERS"_s, context );
102 int initializationMethod = parameterAsInt( parameters, u"METHOD"_s, context );
103
104 QgsFields outputFields = source->fields();
105 QgsFields newFields;
106 const QString clusterFieldName = parameterAsString( parameters, u"FIELD_NAME"_s, context );
107 newFields.append( QgsField( clusterFieldName, QMetaType::Type::Int ) );
108 const QString clusterSizeFieldName = parameterAsString( parameters, u"SIZE_FIELD_NAME"_s, context );
109 newFields.append( QgsField( clusterSizeFieldName, QMetaType::Type::Int ) );
110 outputFields = QgsProcessingUtils::combineFields( outputFields, newFields );
111
112 QString dest;
113 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, outputFields, source->wkbType(), source->sourceCrs() ) );
114 if ( !sink )
115 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
116
117 // build list of point inputs - if it's already a point, use that. If not, take the centroid.
118 feedback->pushInfo( QObject::tr( "Collecting input points" ) );
119 const double step = source->featureCount() > 0 ? 50.0 / static_cast< double >( source->featureCount() ) : 1;
120 int i = 0;
121 int n = 0;
122 int featureWithGeometryCount = 0;
123 QgsFeature feat;
124
125 std::vector<Feature> clusterFeatures;
126 QgsFeatureIterator features = source->getFeatures( QgsFeatureRequest().setNoAttributes() );
127 QHash<QgsFeatureId, std::size_t> idToObj;
128 while ( features.nextFeature( feat ) )
129 {
130 i++;
131 if ( feedback->isCanceled() )
132 {
133 break;
134 }
135
136 feedback->setProgress( i * step );
137 if ( !feat.hasGeometry() )
138 continue;
139 featureWithGeometryCount++;
140
141 QgsPointXY point;
144 else
145 {
146 const QgsGeometry centroid = feat.geometry().centroid();
147 if ( centroid.isNull() )
148 continue; // centroid failed, e.g. empty linestring
149
151 }
152
153 n++;
154
155 idToObj[feat.id()] = clusterFeatures.size();
156 clusterFeatures.emplace_back( Feature( point ) );
157 }
158
159 if ( n < k )
160 {
161 feedback->reportError( QObject::tr( "Number of geometries is less than the number of clusters requested, not all clusters will get data" ) );
162 k = n;
163 }
164
165 if ( k > 1 )
166 {
167 feedback->pushInfo( QObject::tr( "Calculating clusters" ) );
168
169 // cluster centers
170 std::vector<QgsPointXY> centers( k );
171 switch ( initializationMethod )
172 {
173 case 0: // farthest points
174 initClustersFarthestPoints( clusterFeatures, centers, k, feedback );
175 break;
176 case 1: // k-means++
177 initClustersPlusPlus( clusterFeatures, centers, k, feedback );
178 break;
179 default:
180 break;
181 }
182 calculateKMeans( clusterFeatures, centers, k, feedback );
183 }
184
185 // cluster size
186 std::unordered_map<int, int> clusterSize;
187 for ( auto it = idToObj.constBegin(); it != idToObj.constEnd(); ++it )
188 {
189 clusterSize[clusterFeatures[it.value()].cluster]++;
190 }
191
192 features = source->getFeatures();
193 i = 0;
194 while ( features.nextFeature( feat ) )
195 {
196 i++;
197 if ( feedback->isCanceled() )
198 {
199 break;
200 }
201
202 feedback->setProgress( 50 + i * step );
203 QgsAttributes attr = feat.attributes();
204 const auto obj = idToObj.find( feat.id() );
205 if ( !feat.hasGeometry() || obj == idToObj.end() )
206 {
207 attr << QVariant() << QVariant();
208 }
209 else if ( k <= 1 )
210 {
211 attr << 0 << featureWithGeometryCount;
212 }
213 else
214 {
215 const int cluster = clusterFeatures[*obj].cluster;
216 attr << cluster << clusterSize[cluster];
217 }
218 feat.setAttributes( attr );
219 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
220 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
221 }
222
223 sink->finalize();
224
225 QVariantMap outputs;
226 outputs.insert( u"OUTPUT"_s, dest );
227 return outputs;
228}
229
230// ported from https://github.com/postgis/postgis/blob/svn-trunk/liblwgeom/lwkmeans.c
231
232void QgsKMeansClusteringAlgorithm::initClustersFarthestPoints( std::vector<Feature> &points, std::vector<QgsPointXY> &centers, const int k, QgsProcessingFeedback *feedback )
233{
234 const std::size_t n = points.size();
235 if ( n == 0 )
236 return;
237
238 if ( n == 1 )
239 {
240 for ( int i = 0; i < k; i++ )
241 centers[i] = points[0].point;
242 return;
243 }
244
245 std::size_t duplicateCount = 1;
246 // initially scan for two most distance points from each other, p1 and p2
247 std::size_t p1 = 0;
248 std::size_t p2 = 0;
249 double distanceP1 = 0;
250 double distanceP2 = 0;
251 double maxDistance = -1;
252 for ( std::size_t i = 1; i < n; i++ )
253 {
254 distanceP1 = points[i].point.sqrDist( points[p1].point );
255 distanceP2 = points[i].point.sqrDist( points[p2].point );
256
257 // if this point is further then existing candidates, replace our choice
258 if ( ( distanceP1 > maxDistance ) || ( distanceP2 > maxDistance ) )
259 {
260 maxDistance = std::max( distanceP1, distanceP2 );
261 if ( distanceP1 > distanceP2 )
262 p2 = i;
263 else
264 p1 = i;
265 }
266
267 // also record count of duplicate points
268 if ( qgsDoubleNear( distanceP1, 0 ) || qgsDoubleNear( distanceP2, 0 ) )
269 duplicateCount++;
270 }
271
272 if ( feedback && duplicateCount > 1 )
273 {
274 feedback->pushWarning( QObject::tr( "There are at least %n duplicate input(s), the number of output clusters may be less than was requested", nullptr, static_cast< int >( duplicateCount ) ) );
275 }
276
277 // By now two points should be found and be not the same
278 // Q_ASSERT( p1 != p2 && maxDistance >= 0 );
279
280 // Accept these two points as our initial centers
281 centers[0] = points[p1].point;
282 centers[1] = points[p2].point;
283
284 if ( k > 2 )
285 {
286 // array of minimum distance to a point from accepted cluster centers
287 std::vector<double> distances( n );
288
289 // initialize array with distance to first object
290 for ( std::size_t j = 0; j < n; j++ )
291 {
292 distances[j] = points[j].point.sqrDist( centers[0] );
293 }
294 distances[p1] = -1;
295 distances[p2] = -1;
296
297 // loop i on clusters, skip 0 and 1 as found already
298 for ( int i = 2; i < k; i++ )
299 {
300 std::size_t candidateCenter = 0;
301 double maxDistance = std::numeric_limits<double>::lowest();
302
303 // loop j on points
304 for ( std::size_t j = 0; j < n; j++ )
305 {
306 // accepted clusters are already marked with distance = -1
307 if ( distances[j] < 0 )
308 continue;
309
310 // update minimal distance with previously accepted cluster
311 distances[j] = std::min( points[j].point.sqrDist( centers[i - 1] ), distances[j] );
312
313 // greedily take a point that's farthest from any of accepted clusters
314 if ( distances[j] > maxDistance )
315 {
316 candidateCenter = j;
317 maxDistance = distances[j];
318 }
319 }
320
321 // checked earlier by counting entries on input, just in case
322 Q_ASSERT( maxDistance >= 0 );
323
324 // accept candidate to centers
325 distances[candidateCenter] = -1;
326 // copy the point coordinates into the initial centers array
327 centers[i] = points[candidateCenter].point;
328 }
329 }
330}
331
332void QgsKMeansClusteringAlgorithm::initClustersPlusPlus( std::vector<Feature> &points, std::vector<QgsPointXY> &centers, const int k, QgsProcessingFeedback *feedback )
333{
334 const std::size_t n = points.size();
335 if ( n == 0 )
336 return;
337
338 if ( n == 1 )
339 {
340 for ( int i = 0; i < k; i++ )
341 centers[i] = points[0].point;
342 return;
343 }
344
345 // randomly select the first point
346 std::random_device rd;
347 std::mt19937 gen( rd() );
348 std::uniform_int_distribution<size_t> distrib( 0, n - 1 );
349
350 std::size_t p1 = distrib( gen );
351 centers[0] = points[p1].point;
352
353 // calculate distances and total error (sum of distances of points to center)
354 std::vector<double> distances( n );
355 double totalError = 0;
356 std::size_t duplicateCount = 1;
357 for ( size_t i = 0; i < n; i++ )
358 {
359 double distance = points[i].point.sqrDist( centers[0] );
360 distances[i] = distance;
361 totalError += distance;
362 if ( qgsDoubleNear( distance, 0 ) )
363 {
364 duplicateCount++;
365 }
366 }
367 if ( feedback && duplicateCount > 1 )
368 {
369 feedback->pushWarning( QObject::tr( "There are at least %n duplicate input(s), the number of output clusters may be less than was requested", nullptr, static_cast< int >( duplicateCount ) ) );
370 }
371
372 // greedy kmeans++
373 // test not only one center but L possible centers
374 // chosen independently according to the same probability distribution), and then among these L
375 // centers, the one that decreases the k-means cost the most is chosen
376 // Bhattacharya, Anup & Eube, Jan & Röglin, Heiko & Schmidt, Melanie. (2019). Noisy, greedy and Not So greedy k-means++
377 unsigned int numCandidateCenters = 2 + static_cast< int >( std::floor( std::log( k ) ) );
378 std::vector<double> randomNumbers( numCandidateCenters );
379 std::vector<size_t> candidateCenters( numCandidateCenters );
380
381 std::uniform_real_distribution<double> dis( 0.0, 1.0 );
382 for ( int i = 1; i < k; i++ )
383 {
384 // sampling with probability proportional to the squared distance to the closest existing center
385 for ( unsigned int j = 0; j < numCandidateCenters; j++ )
386 {
387 randomNumbers[j] = dis( gen ) * totalError;
388 }
389
390 // cumulative sum, keep distances for later use
391 std::vector<double> cumSum = distances;
392 for ( size_t j = 1; j < n; j++ )
393 {
394 cumSum[j] += cumSum[j - 1];
395 }
396
397 // binary search for the index of the first element greater than or equal to random numbers
398 for ( unsigned int j = 0; j < numCandidateCenters; j++ )
399 {
400 size_t low = 0;
401 size_t high = n - 1;
402
403 while ( low <= high )
404 {
405 size_t mid = low + ( high - low ) / 2;
406 if ( cumSum[mid] < randomNumbers[j] )
407 {
408 low = mid + 1;
409 }
410 else
411 {
412 // size_t cannot be negative
413 if ( mid == 0 )
414 break;
415
416 high = mid - 1;
417 }
418 }
419 // clip candidate center to the number of points
420 if ( low >= n )
421 {
422 low = n - 1;
423 }
424 candidateCenters[j] = low;
425 }
426
427 std::vector<std::vector<double>> distancesCandidateCenters( numCandidateCenters, std::vector<double>( n ) );
428 ;
429
430 // store distances between previous and new candidate center, error and best candidate index
431 double currentError = 0;
432 double lowestError = std::numeric_limits<double>::max();
433 unsigned int bestCandidateIndex = 0;
434 for ( unsigned int j = 0; j < numCandidateCenters; j++ )
435 {
436 for ( size_t z = 0; z < n; z++ )
437 {
438 // distance to candidate center
439 double distance = points[candidateCenters[j]].point.sqrDist( points[z].point );
440 // if distance to previous center is less than the current distance, use that
441 if ( distance > distances[z] )
442 {
443 distance = distances[z];
444 }
445 distancesCandidateCenters[j][z] = distance;
446 currentError += distance;
447 }
448 if ( lowestError > currentError )
449 {
450 lowestError = currentError;
451 bestCandidateIndex = j;
452 }
453 }
454
455 // update distances with the best candidate center values
456 for ( size_t j = 0; j < n; j++ )
457 {
458 distances[j] = distancesCandidateCenters[bestCandidateIndex][j];
459 }
460 // store the best candidate center
461 centers[i] = points[candidateCenters[bestCandidateIndex]].point;
462 // update error
463 totalError = lowestError;
464 }
465}
466
467// ported from https://github.com/postgis/postgis/blob/svn-trunk/liblwgeom/lwkmeans.c
468
469void QgsKMeansClusteringAlgorithm::calculateKMeans( std::vector<QgsKMeansClusteringAlgorithm::Feature> &objs, std::vector<QgsPointXY> &centers, int k, QgsProcessingFeedback *feedback )
470{
471 int converged = false;
472 bool changed = false;
473
474 // avoid reallocating weights array for every iteration
475 std::vector<uint> weights( k );
476
477 uint i = 0;
478 for ( i = 0; i < KMEANS_MAX_ITERATIONS && !converged; i++ )
479 {
480 if ( feedback && feedback->isCanceled() )
481 break;
482
483 findNearest( objs, centers, k, changed );
484 updateMeans( objs, centers, weights, k );
485 converged = !changed;
486 }
487
488 if ( !converged && feedback )
489 feedback->reportError( QObject::tr( "Clustering did not converge after %n iteration(s)", nullptr, static_cast<int>( i ) ) );
490 else if ( feedback )
491 feedback->pushInfo( QObject::tr( "Clustering converged after %n iteration(s)", nullptr, static_cast<int>( i ) ) );
492}
493
494// ported from https://github.com/postgis/postgis/blob/svn-trunk/liblwgeom/lwkmeans.c
495
496void QgsKMeansClusteringAlgorithm::findNearest( std::vector<QgsKMeansClusteringAlgorithm::Feature> &points, const std::vector<QgsPointXY> &centers, const int k, bool &changed )
497{
498 changed = false;
499 const std::size_t n = points.size();
500 for ( std::size_t i = 0; i < n; i++ )
501 {
502 Feature &point = points[i];
503
504 // Initialize with distance to first cluster
505 double currentDistance = point.point.sqrDist( centers[0] );
506 int currentCluster = 0;
507
508 // Check all other cluster centers and find the nearest
509 for ( int cluster = 1; cluster < k; cluster++ )
510 {
511 const double distance = point.point.sqrDist( centers[cluster] );
512 if ( distance < currentDistance )
513 {
514 currentDistance = distance;
515 currentCluster = cluster;
516 }
517 }
518
519 // Store the nearest cluster this object is in
520 if ( point.cluster != currentCluster )
521 {
522 changed = true;
523 point.cluster = currentCluster;
524 }
525 }
526}
527
528// ported from https://github.com/postgis/postgis/blob/svn-trunk/liblwgeom/lwkmeans.c
529
530void QgsKMeansClusteringAlgorithm::updateMeans( const std::vector<Feature> &points, std::vector<QgsPointXY> &centers, std::vector<uint> &weights, const int k )
531{
532 const uint n = points.size();
533 std::fill( weights.begin(), weights.end(), 0 );
534 for ( int i = 0; i < k; i++ )
535 {
536 centers[i].setX( 0.0 );
537 centers[i].setY( 0.0 );
538 }
539 for ( uint i = 0; i < n; i++ )
540 {
541 const int cluster = points[i].cluster;
542 centers[cluster] += QgsVector( points[i].point.x(), points[i].point.y() );
543 weights[cluster] += 1;
544 }
545 for ( int i = 0; i < k; i++ )
546 {
547 centers[i] /= weights[i];
548 }
549}
550
551
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3604
@ Point
Point.
Definition qgis.h:282
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
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
QgsFeatureId id
Definition qgsfeature.h:68
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
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
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.).
Represents a 2D point.
Definition qgspointxy.h:62
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.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A numeric parameter for processing algorithms.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
Represent a 2-dimensional vector.
Definition qgsvector.h:34
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6935
T qgsgeometry_cast(QgsAbstractGeometry *geom)