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