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