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