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