QGIS API Documentation 3.99.0-Master (26c88405ac0)
Loading...
Searching...
No Matches
qgsalgorithmjoinbynearest.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmjoinbynearest.cpp
3 ---------------------
4 begin : April 2017
5 copyright : (C) 2017 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 <algorithm>
21
22#include "qgslinestring.h"
24#include "qgsspatialindex.h"
25
27
28QString QgsJoinByNearestAlgorithm::name() const
29{
30 return QStringLiteral( "joinbynearest" );
31}
32
33QString QgsJoinByNearestAlgorithm::displayName() const
34{
35 return QObject::tr( "Join attributes by nearest" );
36}
37
38QStringList QgsJoinByNearestAlgorithm::tags() const
39{
40 return QObject::tr( "join,connect,attributes,values,fields,tables,proximity,closest,neighbour,neighbor,n-nearest,distance" ).split( ',' );
41}
42
43QString QgsJoinByNearestAlgorithm::group() const
44{
45 return QObject::tr( "Vector general" );
46}
47
48QString QgsJoinByNearestAlgorithm::groupId() const
49{
50 return QStringLiteral( "vectorgeneral" );
51}
52
53void QgsJoinByNearestAlgorithm::initAlgorithm( const QVariantMap & )
54{
55 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ) ) );
56 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT_2" ), QObject::tr( "Input layer 2" ) ) );
57
58 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELDS_TO_COPY" ), QObject::tr( "Layer 2 fields to copy (leave empty to copy all fields)" ), QVariant(), QStringLiteral( "INPUT_2" ), Qgis::ProcessingFieldParameterDataType::Any, true, true ) );
59
60 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "DISCARD_NONMATCHING" ), QObject::tr( "Discard records which could not be joined" ), false ) );
61
62 addParameter( new QgsProcessingParameterString( QStringLiteral( "PREFIX" ), QObject::tr( "Joined field prefix" ), QVariant(), false, true ) );
63
64 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "NEIGHBORS" ), QObject::tr( "Maximum nearest neighbors" ), Qgis::ProcessingNumberParameterType::Integer, 1, false, 1 ) );
65
66 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "MAX_DISTANCE" ), QObject::tr( "Maximum distance" ), QVariant(), QStringLiteral( "INPUT" ), true, 0 ) );
67
68 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Joined layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true, true ) );
69
70 auto nonMatchingSink = std::make_unique<QgsProcessingParameterFeatureSink>(
71 QStringLiteral( "NON_MATCHING" ), QObject::tr( "Unjoinable features from first layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true, false
72 );
73 // TODO GUI doesn't support advanced outputs yet
74 //nonMatchingSink->setFlags(nonMatchingSink->flags() | Qgis::ProcessingParameterFlag::Advanced );
75 addParameter( nonMatchingSink.release() );
76
77 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "JOINED_COUNT" ), QObject::tr( "Number of joined features from input table" ) ) );
78 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "UNJOINABLE_COUNT" ), QObject::tr( "Number of unjoinable features from input table" ) ) );
79}
80
81QString QgsJoinByNearestAlgorithm::shortHelpString() const
82{
83 return QObject::tr( "This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the "
84 "input one, with additional attributes in its attribute table.\n\n"
85 "The additional attributes and their values are taken from a second vector layer, where features are joined "
86 "by finding the closest features from each layer. By default only the single nearest feature is joined,"
87 "but optionally the join can use the n-nearest neighboring features instead. If multiple features are found "
88 "with identical distances these will all be returned (even if the total number of features exceeds the specified "
89 "maximum feature count).\n\n"
90 "If a maximum distance is specified, then only features which are closer than this distance "
91 "will be matched.\n\n"
92 "The output features will contain the selected attributes from the nearest feature, "
93 "along with new attributes for the distance to the near feature, the index of the feature, "
94 "and the coordinates of the closest point on the input feature (feature_x, feature_y) "
95 "to the matched nearest feature, and the coordinates of the closet point on the matched feature "
96 "(nearest_x, nearest_y).\n\n"
97 "This algorithm uses purely Cartesian calculations for distance, and does not consider "
98 "geodetic or ellipsoid properties when determining feature proximity." );
99}
100
101QString QgsJoinByNearestAlgorithm::shortDescription() const
102{
103 return QObject::tr( "Joins a layer to another layer, using the closest features (nearest neighbors)." );
104}
105
106Qgis::ProcessingAlgorithmDocumentationFlags QgsJoinByNearestAlgorithm::documentationFlags() const
107{
109}
110
111QgsJoinByNearestAlgorithm *QgsJoinByNearestAlgorithm::createInstance() const
112{
113 return new QgsJoinByNearestAlgorithm();
114}
115
116QVariantMap QgsJoinByNearestAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
117{
118 const int neighbors = parameterAsInt( parameters, QStringLiteral( "NEIGHBORS" ), context );
119 const bool discardNonMatching = parameterAsBoolean( parameters, QStringLiteral( "DISCARD_NONMATCHING" ), context );
120 const double maxDistance = parameters.value( QStringLiteral( "MAX_DISTANCE" ) ).isValid() ? parameterAsDouble( parameters, QStringLiteral( "MAX_DISTANCE" ), context ) : std::numeric_limits<double>::quiet_NaN();
121 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
122 if ( !input )
123 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
124
125 std::unique_ptr<QgsProcessingFeatureSource> input2( parameterAsSource( parameters, QStringLiteral( "INPUT_2" ), context ) );
126 if ( !input2 )
127 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT_2" ) ) );
128
129 const bool sameSourceAndTarget = parameters.value( QStringLiteral( "INPUT" ) ) == parameters.value( QStringLiteral( "INPUT_2" ) );
130
131 const QString prefix = parameterAsString( parameters, QStringLiteral( "PREFIX" ), context );
132 const QStringList fieldsToCopy = parameterAsStrings( parameters, QStringLiteral( "FIELDS_TO_COPY" ), context );
133
134 QgsFields outFields2;
135 QgsAttributeList fields2Indices;
136 if ( fieldsToCopy.empty() )
137 {
138 outFields2 = input2->fields();
139 fields2Indices.reserve( outFields2.count() );
140 for ( int i = 0; i < outFields2.count(); ++i )
141 {
142 fields2Indices << i;
143 }
144 }
145 else
146 {
147 fields2Indices.reserve( fieldsToCopy.count() );
148 for ( const QString &field : fieldsToCopy )
149 {
150 const int index = input2->fields().lookupField( field );
151 if ( index >= 0 )
152 {
153 fields2Indices << index;
154 outFields2.append( input2->fields().at( index ) );
155 }
156 }
157 }
158
159 if ( !prefix.isEmpty() )
160 {
161 for ( int i = 0; i < outFields2.count(); ++i )
162 {
163 outFields2.rename( i, prefix + outFields2[i].name() );
164 }
165 }
166
167 const QgsAttributeList fields2Fetch = fields2Indices;
168
169 QgsFields outFields = QgsProcessingUtils::combineFields( input->fields(), outFields2 );
170
171 QgsFields resultFields;
172 resultFields.append( QgsField( QStringLiteral( "n" ), QMetaType::Type::Int ) );
173 resultFields.append( QgsField( QStringLiteral( "distance" ), QMetaType::Type::Double ) );
174 resultFields.append( QgsField( QStringLiteral( "feature_x" ), QMetaType::Type::Double ) );
175 resultFields.append( QgsField( QStringLiteral( "feature_y" ), QMetaType::Type::Double ) );
176 resultFields.append( QgsField( QStringLiteral( "nearest_x" ), QMetaType::Type::Double ) );
177 resultFields.append( QgsField( QStringLiteral( "nearest_y" ), QMetaType::Type::Double ) );
178 outFields = QgsProcessingUtils::combineFields( outFields, resultFields );
179
180 QString dest;
181 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, input->wkbType(), input->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
182 if ( parameters.value( QStringLiteral( "OUTPUT" ) ).isValid() && !sink )
183 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
184
185 QString destNonMatching1;
186 std::unique_ptr<QgsFeatureSink> sinkNonMatching1( parameterAsSink( parameters, QStringLiteral( "NON_MATCHING" ), context, destNonMatching1, input->fields(), input->wkbType(), input->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
187 if ( parameters.value( QStringLiteral( "NON_MATCHING" ) ).isValid() && !sinkNonMatching1 )
188 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "NON_MATCHING" ) ) );
189
190 // make spatial index
191 const QgsFeatureIterator f2 = input2->getFeatures( QgsFeatureRequest().setDestinationCrs( input->sourceCrs(), context.transformContext() ).setSubsetOfAttributes( fields2Fetch ) );
192 QHash<QgsFeatureId, QgsAttributes> input2AttributeCache;
193 double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1;
194 int i = 0;
195 const QgsSpatialIndex index( f2, [&]( const QgsFeature &f ) -> bool {
196 i++;
197 if ( feedback->isCanceled() )
198 return false;
199
200 feedback->setProgress( i * step );
201
202 if ( !f.hasGeometry() )
203 return true;
204
205 // only keep selected attributes
206 QgsAttributes attributes;
207 for ( int field2Index : fields2Indices )
208 {
209 attributes << f.attribute( field2Index );
210 }
211 input2AttributeCache.insert( f.id(), attributes );
212
214
215 QgsFeature f;
216
217 // create extra null attributes for non-matched records (the +2 is for the "n" and "distance", and start/end x/y fields)
218 QgsAttributes nullMatch;
219 nullMatch.reserve( fields2Indices.size() + 6 );
220 for ( int i = 0; i < fields2Indices.count() + 6; ++i )
221 nullMatch << QVariant();
222
223 long long joinedCount = 0;
224 long long unjoinedCount = 0;
225
226 // Create output vector layer with additional attributes
227 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
228 QgsFeatureIterator features = input->getFeatures();
229 i = 0;
230 while ( features.nextFeature( f ) )
231 {
232 i++;
233 if ( feedback->isCanceled() )
234 {
235 break;
236 }
237
238 feedback->setProgress( 50 + i * step );
239
240 if ( !f.hasGeometry() )
241 {
242 unjoinedCount++;
243 if ( sinkNonMatching1 )
244 {
245 if ( !sinkNonMatching1->addFeature( f, QgsFeatureSink::FastInsert ) )
246 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral( "NON_MATCHING" ) ) );
247 }
248 if ( sink && !discardNonMatching )
249 {
250 QgsAttributes attr = f.attributes();
251 attr.append( nullMatch );
252 f.setAttributes( attr );
253 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
254 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
255 }
256 }
257 else
258 {
259 // note - if using same source as target, we have to get one extra neighbor, since the first match will be the input feature
260
261 // if the user didn't specify a distance (isnan), then use 0 for nearestNeighbor() parameter
262 // if the user specified 0 exactly, then use the smallest positive double value instead
263 const double searchDistance = std::isnan( maxDistance ) ? 0 : std::max( std::numeric_limits<double>::min(), maxDistance );
264 const QList<QgsFeatureId> nearest = index.nearestNeighbor( f.geometry(), neighbors + ( sameSourceAndTarget ? 1 : 0 ), searchDistance );
265
266 if ( nearest.count() > neighbors + ( sameSourceAndTarget ? 1 : 0 ) )
267 {
268 feedback->pushInfo( QObject::tr( "Multiple matching features found at same distance from search feature, found %n feature(s) instead of %1", nullptr, nearest.count() - ( sameSourceAndTarget ? 1 : 0 ) ).arg( neighbors ) );
269 }
270 QgsFeature out;
271 out.setGeometry( f.geometry() );
272 int j = 0;
273 for ( const QgsFeatureId id : nearest )
274 {
275 if ( sameSourceAndTarget && id == f.id() )
276 continue; // don't match to same feature if using a single input table
277 j++;
278 if ( sink )
279 {
280 QgsAttributes attr = f.attributes();
281 attr.append( input2AttributeCache.value( id ) );
282 attr.append( j );
283
284 const QgsGeometry closestLine = f.geometry().shortestLine( index.geometry( id ) );
285 if ( const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( closestLine.constGet() ) )
286 {
287 attr.append( line->length() );
288 attr.append( line->startPoint().x() );
289 attr.append( line->startPoint().y() );
290 attr.append( line->endPoint().x() );
291 attr.append( line->endPoint().y() );
292 }
293 else
294 {
295 attr.append( QVariant() ); //distance
296 attr.append( QVariant() ); //start x
297 attr.append( QVariant() ); //start y
298 attr.append( QVariant() ); //end x
299 attr.append( QVariant() ); //end y
300 }
301 out.setAttributes( attr );
302 if ( !sink->addFeature( out, QgsFeatureSink::FastInsert ) )
303 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
304 }
305 }
306 if ( j > 0 )
307 joinedCount++;
308 else
309 {
310 if ( sinkNonMatching1 )
311 {
312 if ( !sinkNonMatching1->addFeature( f, QgsFeatureSink::FastInsert ) )
313 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral( "NON_MATCHING" ) ) );
314 }
315 if ( !discardNonMatching && sink )
316 {
317 QgsAttributes attr = f.attributes();
318 attr.append( nullMatch );
319 f.setAttributes( attr );
320 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
321 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
322 }
323 unjoinedCount++;
324 }
325 }
326 }
327
328 QVariantMap outputs;
329 outputs.insert( QStringLiteral( "JOINED_COUNT" ), joinedCount );
330 outputs.insert( QStringLiteral( "UNJOINABLE_COUNT" ), unjoinedCount );
331 if ( sink )
332 {
333 sink->finalize();
334 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
335 }
336 if ( sinkNonMatching1 )
337 {
338 sinkNonMatching1->finalize();
339 outputs.insert( QStringLiteral( "NON_MATCHING" ), destNonMatching1 );
340 }
341 return outputs;
342}
343
344
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3533
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3619
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
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.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsFeatureId id
Definition qgsfeature.h:66
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's 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
int count
Definition qgsfields.h:50
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
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 shortestLine(const QgsGeometry &other) const
Returns the shortest line joining this geometry to another geometry.
Line string geometry type, with support for z-dimension and m-values.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
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.
A numeric output for processing algorithms.
A boolean parameter 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 vector layer or feature source field parameter for processing algorithms.
A numeric parameter for processing algorithms.
A string 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 spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
T qgsgeometry_cast(QgsAbstractGeometry *geom)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QList< int > QgsAttributeList
Definition qgsfield.h:28