QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsalgorithmdbscanclustering.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmdbscanclustering.cpp
3 ---------------------
4 begin : July 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 <unordered_set>
21
23
25
26QString QgsDbscanClusteringAlgorithm::name() const
27{
28 return QStringLiteral( "dbscanclustering" );
29}
30
31QString QgsDbscanClusteringAlgorithm::displayName() const
32{
33 return QObject::tr( "DBSCAN clustering" );
34}
35
36QString QgsDbscanClusteringAlgorithm::shortDescription() const
37{
38 return QObject::tr( "Clusters point features using a density based scan algorithm." );
39}
40
41QStringList QgsDbscanClusteringAlgorithm::tags() const
42{
43 return QObject::tr( "clustering,clusters,density,based,points,distance" ).split( ',' );
44}
45
46QString QgsDbscanClusteringAlgorithm::group() const
47{
48 return QObject::tr( "Vector analysis" );
49}
50
51QString QgsDbscanClusteringAlgorithm::groupId() const
52{
53 return QStringLiteral( "vectoranalysis" );
54}
55
56void QgsDbscanClusteringAlgorithm::initAlgorithm( const QVariantMap & )
57{
58 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
59 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "MIN_SIZE" ), QObject::tr( "Minimum cluster size" ), Qgis::ProcessingNumberParameterType::Integer, 5, false, 1 ) );
60 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "EPS" ), QObject::tr( "Maximum distance between clustered points" ), 1, QStringLiteral( "INPUT" ), false, 0 ) );
61
62 auto dbscanStarParam = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "DBSCAN*" ), QObject::tr( "Treat border points as noise (DBSCAN*)" ), false );
63 dbscanStarParam->setFlags( dbscanStarParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
64 addParameter( dbscanStarParam.release() );
65
66 auto fieldNameParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "FIELD_NAME" ), QObject::tr( "Cluster field name" ), QStringLiteral( "CLUSTER_ID" ) );
67 fieldNameParam->setFlags( fieldNameParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
68 addParameter( fieldNameParam.release() );
69 auto sizeFieldNameParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "SIZE_FIELD_NAME" ), QObject::tr( "Cluster size field name" ), QStringLiteral( "CLUSTER_SIZE" ) );
70 sizeFieldNameParam->setFlags( sizeFieldNameParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
71 addParameter( sizeFieldNameParam.release() );
72
73 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Clusters" ), Qgis::ProcessingSourceType::VectorPoint ) );
74
75 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "NUM_CLUSTERS" ), QObject::tr( "Number of clusters" ) ) );
76}
77
78QString QgsDbscanClusteringAlgorithm::shortHelpString() const
79{
80 return QObject::tr( "This algorithm clusters point features based on a 2D implementation of Density-based spatial clustering of applications with noise (DBSCAN) algorithm.\n\n"
81 "The algorithm requires two parameters, a minimum cluster size (“minPts”), and the maximum distance allowed between clustered points (“eps”)." );
82}
83
84QgsDbscanClusteringAlgorithm *QgsDbscanClusteringAlgorithm::createInstance() const
85{
86 return new QgsDbscanClusteringAlgorithm();
87}
88
89struct KDBushDataEqualById
90{
91 bool operator()( const QgsSpatialIndexKDBushData &a, const QgsSpatialIndexKDBushData &b ) const
92 {
93 return a.id == b.id;
94 }
95};
96
97struct KDBushDataHashById
98{
99 std::size_t operator()( const QgsSpatialIndexKDBushData &a ) const
100 {
101 return std::hash<QgsFeatureId> {}( a.id );
102 }
103};
104
105QVariantMap QgsDbscanClusteringAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
106{
107 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
108 if ( !source )
109 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
110
111 const std::size_t minSize = static_cast<std::size_t>( parameterAsInt( parameters, QStringLiteral( "MIN_SIZE" ), context ) );
112 const double eps1 = parameterAsDouble( parameters, QStringLiteral( "EPS" ), context );
113 const double eps2 = parameterAsDouble( parameters, QStringLiteral( "EPS2" ), context );
114 const bool borderPointsAreNoise = parameterAsBoolean( parameters, QStringLiteral( "DBSCAN*" ), context );
115
116 QgsFields outputFields = source->fields();
117 QgsFields newFields;
118 const QString clusterFieldName = parameterAsString( parameters, QStringLiteral( "FIELD_NAME" ), context );
119 newFields.append( QgsField( clusterFieldName, QMetaType::Type::Int ) );
120 const QString clusterSizeFieldName = parameterAsString( parameters, QStringLiteral( "SIZE_FIELD_NAME" ), context );
121 newFields.append( QgsField( clusterSizeFieldName, QMetaType::Type::Int ) );
122 outputFields = QgsProcessingUtils::combineFields( outputFields, newFields );
123
124 QString dest;
125 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outputFields, source->wkbType(), source->sourceCrs() ) );
126 if ( !sink )
127 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
128
129 QgsFeatureRequest indexRequest;
130
131 std::unordered_map<QgsFeatureId, QDateTime> idToDateTime;
132 const QString dateTimeFieldName = parameterAsString( parameters, QStringLiteral( "DATETIME_FIELD" ), context );
133 int dateTimefieldIndex = -1;
134 if ( !dateTimeFieldName.isEmpty() )
135 {
136 dateTimefieldIndex = source->fields().lookupField( dateTimeFieldName );
137 if ( dateTimefieldIndex == -1 )
138 throw QgsProcessingException( QObject::tr( "Datetime field missing" ) );
139
140 indexRequest.setSubsetOfAttributes( QgsAttributeList() << dateTimefieldIndex );
141 }
142 else
143 {
144 indexRequest.setNoAttributes();
145 }
146
147 // build spatial index, also collecting feature datetimes if required
148 feedback->pushInfo( QObject::tr( "Building spatial index" ) );
149 QgsFeatureIterator indexIterator = source->getFeatures( indexRequest );
150 QgsSpatialIndexKDBush index( indexIterator, [&idToDateTime, dateTimefieldIndex]( const QgsFeature &feature ) -> bool {
151 if ( dateTimefieldIndex >= 0 )
152 idToDateTime[ feature.id() ] = feature.attributes().at( dateTimefieldIndex ).toDateTime();
153 return true; }, feedback );
154
155 if ( feedback->isCanceled() )
156 return QVariantMap();
157
158 // stdbscan!
159 feedback->pushInfo( QObject::tr( "Analysing clusters" ) );
160 std::unordered_map<QgsFeatureId, int> idToCluster;
161 idToCluster.reserve( index.size() );
162 const long featureCount = source->featureCount();
163 QgsFeatureIterator features = source->getFeatures( QgsFeatureRequest().setNoAttributes() );
164 stdbscan( minSize, eps1, eps2, borderPointsAreNoise, featureCount, features, index, idToCluster, idToDateTime, feedback );
165
166 // cluster size
167 std::unordered_map<int, int> clusterSize;
168 std::for_each( idToCluster.begin(), idToCluster.end(), [&clusterSize]( std::pair<QgsFeatureId, int> idCluster ) { clusterSize[idCluster.second]++; } );
169
170 // write clusters
171 const double writeStep = featureCount > 0 ? 10.0 / featureCount : 1;
172 features = source->getFeatures();
173 int i = 0;
174 QgsFeature feat;
175 while ( features.nextFeature( feat ) )
176 {
177 i++;
178 if ( feedback->isCanceled() )
179 {
180 break;
181 }
182
183 feedback->setProgress( 90 + i * writeStep );
184 QgsAttributes attr = feat.attributes();
185 const auto cluster = idToCluster.find( feat.id() );
186 if ( cluster != idToCluster.end() )
187 {
188 attr << cluster->second << clusterSize[cluster->second];
189 }
190 else
191 {
192 attr << QVariant() << QVariant();
193 }
194 feat.setAttributes( attr );
195 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
196 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
197 }
198
199 sink->finalize();
200
201 QVariantMap outputs;
202 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
203 outputs.insert( QStringLiteral( "NUM_CLUSTERS" ), static_cast<unsigned int>( clusterSize.size() ) );
204 return outputs;
205}
206
207void QgsDbscanClusteringAlgorithm::stdbscan( const std::size_t minSize, const double eps1, const double eps2, const bool borderPointsAreNoise, const long featureCount, QgsFeatureIterator features, QgsSpatialIndexKDBush &index, std::unordered_map<QgsFeatureId, int> &idToCluster, std::unordered_map<QgsFeatureId, QDateTime> &idToDateTime, QgsProcessingFeedback *feedback )
208{
209 const double step = featureCount > 0 ? 90.0 / featureCount : 1;
210
211 std::unordered_set<QgsFeatureId> visited;
212 visited.reserve( index.size() );
213
214 QgsFeature feat;
215 int i = 0;
216 int clusterCount = 0;
217
218 while ( features.nextFeature( feat ) )
219 {
220 if ( feedback->isCanceled() )
221 {
222 break;
223 }
224
225 if ( !feat.hasGeometry() )
226 {
227 feedback->setProgress( ++i * step );
228 continue;
229 }
230
231 if ( visited.find( feat.id() ) != visited.end() )
232 {
233 // already visited!
234 continue;
235 }
236
237 QgsPointXY point;
240 else
241 {
242 // not a point geometry
243 feedback->reportError( QObject::tr( "Feature %1 is a %2 feature, not a point." ).arg( feat.id() ).arg( QgsWkbTypes::displayString( feat.geometry().wkbType() ) ) );
244 feedback->setProgress( ++i * step );
245 continue;
246 }
247
248 if ( !idToDateTime.empty() && !idToDateTime[feat.id()].isValid() )
249 {
250 // missing datetime value
251 feedback->reportError( QObject::tr( "Feature %1 is missing a valid datetime value." ).arg( feat.id() ).arg( QgsWkbTypes::displayString( feat.geometry().wkbType() ) ) );
252 feedback->setProgress( ++i * step );
253 continue;
254 }
255
256 std::unordered_set<QgsSpatialIndexKDBushData, KDBushDataHashById, KDBushDataEqualById> within;
257
258 if ( minSize > 1 )
259 {
260 index.within( point, eps1, [&within, pointId = feat.id(), &idToDateTime, &eps2]( const QgsSpatialIndexKDBushData &data ) {
261 if ( idToDateTime.empty() || ( idToDateTime[data.id].isValid() && std::abs( idToDateTime[pointId].msecsTo( idToDateTime[data.id] ) ) <= eps2 ) )
262 within.insert( data );
263 } );
264 if ( within.size() < minSize )
265 continue;
266
267 visited.insert( feat.id() );
268 }
269 else
270 {
271 // optimised case for minSize == 1, we can skip the initial check
272 within.insert( QgsSpatialIndexKDBushData( feat.id(), point.x(), point.y() ) );
273 }
274
275 // start new cluster
276 clusterCount++;
277 idToCluster[feat.id()] = clusterCount;
278 feedback->setProgress( ++i * step );
279
280 while ( !within.empty() )
281 {
282 if ( feedback->isCanceled() )
283 {
284 break;
285 }
286
287 const QgsSpatialIndexKDBushData j = *within.begin();
288 within.erase( within.begin() );
289
290 if ( visited.find( j.id ) != visited.end() )
291 {
292 // already visited!
293 continue;
294 }
295
296 visited.insert( j.id );
297 feedback->setProgress( ++i * step );
298
299 // check from this point
300 const QgsPointXY point2 = j.point();
301
302 std::unordered_set<QgsSpatialIndexKDBushData, KDBushDataHashById, KDBushDataEqualById> within2;
303 index.within( point2, eps1, [&within2, point2Id = j.id, &idToDateTime, &eps2]( const QgsSpatialIndexKDBushData &data ) {
304 if ( idToDateTime.empty() || ( idToDateTime[data.id].isValid() && std::abs( idToDateTime[point2Id].msecsTo( idToDateTime[data.id] ) ) <= eps2 ) )
305 within2.insert( data );
306 } );
307
308 if ( within2.size() >= minSize )
309 {
310 // expand neighbourhood
311 std::copy_if( within2.begin(), within2.end(), std::inserter( within, within.end() ), [&visited]( const QgsSpatialIndexKDBushData &needle ) {
312 return visited.find( needle.id ) == visited.end();
313 } );
314 }
315 if ( !borderPointsAreNoise || within2.size() >= minSize )
316 {
317 idToCluster[j.id] = clusterCount;
318 }
319 }
320 }
321}
322
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
@ Point
Point.
Definition qgis.h:279
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
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).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
@ 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
QgsFeatureId id
Definition qgsfeature.h:66
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
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: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:54
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:73
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.).
Represents a 2D point.
Definition qgspointxy.h:60
double y
Definition qgspointxy.h:64
double x
Definition qgspointxy.h:63
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 reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A numeric output for processing algorithms.
A double numeric parameter for distance 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).
A container for data stored inside a QgsSpatialIndexKDBush index.
QgsPointXY point() const
Returns the indexed point.
A very fast static spatial index for 2D points based on a flat KD-tree.
qgssize size() const
Returns the size of the index, i.e.
QList< QgsSpatialIndexKDBushData > within(const QgsPointXY &point, double radius) const
Returns the list of features which are within the given search radius of point.
static Q_INVOKABLE QString displayString(Qgis::WkbType type)
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
T qgsgeometry_cast(QgsAbstractGeometry *geom)
QList< int > QgsAttributeList
Definition qgsfield.h:28