QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
Loading...
Searching...
No Matches
qgsalgorithmjoinwithlines.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmjoinwithlines.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 "qgsdistancearea.h"
21#include "qgslinestring.h"
22#include "qgsmultilinestring.h"
23
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsJoinWithLinesAlgorithm::name() const
31{
32 return u"hublines"_s;
33}
34
35QString QgsJoinWithLinesAlgorithm::displayName() const
36{
37 return QObject::tr( "Join by lines (hub lines)" );
38}
39
40QStringList QgsJoinWithLinesAlgorithm::tags() const
41{
42 return QObject::tr( "join,connect,lines,points,hub,spoke,geodesic,great,circle" ).split( ',' );
43}
44
45QString QgsJoinWithLinesAlgorithm::group() const
46{
47 return QObject::tr( "Vector analysis" );
48}
49
50QString QgsJoinWithLinesAlgorithm::groupId() const
51{
52 return u"vectoranalysis"_s;
53}
54
55void QgsJoinWithLinesAlgorithm::initAlgorithm( const QVariantMap & )
56{
57 addParameter( new QgsProcessingParameterFeatureSource( u"HUBS"_s, QObject::tr( "Hub layer" ) ) );
58 addParameter( new QgsProcessingParameterField( u"HUB_FIELD"_s, QObject::tr( "Hub ID field" ), QVariant(), u"HUBS"_s ) );
59
60 addParameter(
61 new QgsProcessingParameterField( u"HUB_FIELDS"_s, QObject::tr( "Hub layer fields to copy (leave empty to copy all fields)" ), QVariant(), u"HUBS"_s, Qgis::ProcessingFieldParameterDataType::Any, true, true )
62 );
63
64 addParameter( new QgsProcessingParameterFeatureSource( u"SPOKES"_s, QObject::tr( "Spoke layer" ) ) );
65 addParameter( new QgsProcessingParameterField( u"SPOKE_FIELD"_s, QObject::tr( "Spoke ID field" ), QVariant(), u"SPOKES"_s ) );
66
67 addParameter(
68 new QgsProcessingParameterField( u"SPOKE_FIELDS"_s, QObject::tr( "Spoke layer fields to copy (leave empty to copy all fields)" ), QVariant(), u"SPOKES"_s, Qgis::ProcessingFieldParameterDataType::Any, true, true )
69 );
70
71 addParameter( new QgsProcessingParameterBoolean( u"GEODESIC"_s, QObject::tr( "Create geodesic lines" ), false ) );
72
73 auto distanceParam = std::make_unique<QgsProcessingParameterDistance>( u"GEODESIC_DISTANCE"_s, QObject::tr( "Distance between vertices (geodesic lines only)" ), 1000 );
74 distanceParam->setFlags( distanceParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
75 distanceParam->setDefaultUnit( Qgis::DistanceUnit::Kilometers );
76 distanceParam->setIsDynamic( true );
77 distanceParam->setDynamicPropertyDefinition( QgsPropertyDefinition( u"Geodesic Distance"_s, QObject::tr( "Distance between vertices" ), QgsPropertyDefinition::DoublePositive ) );
78 distanceParam->setDynamicLayerParameterName( u"HUBS"_s );
79 addParameter( distanceParam.release() );
80
81 auto breakParam = std::make_unique<QgsProcessingParameterBoolean>( u"ANTIMERIDIAN_SPLIT"_s, QObject::tr( "Split lines at antimeridian (±180 degrees longitude)" ), false );
82 breakParam->setFlags( breakParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
83 addParameter( breakParam.release() );
84
85 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Hub lines" ), Qgis::ProcessingSourceType::VectorLine ) );
86}
87
88QString QgsJoinWithLinesAlgorithm::shortHelpString() const
89{
90 return QObject::tr(
91 "This algorithm creates hub and spoke diagrams by connecting lines from points on the Spoke layer to matching points in the Hub layer.\n\n"
92 "Determination of which hub goes with each point is based on a match between the Hub ID field on the hub points and the Spoke ID field on the spoke points.\n\n"
93 "If input layers are not point layers, a point on the surface of the geometries will be taken as the connecting location.\n\n"
94 "Optionally, geodesic lines can be created, which represent the shortest path on the surface of an ellipsoid. When "
95 "geodesic mode is used, it is possible to split the created lines at the antimeridian (±180 degrees longitude), which can improve "
96 "rendering of the lines. Additionally, the distance between vertices can be specified. A smaller distance results in a denser, more "
97 "accurate line."
98 );
99}
100
101QString QgsJoinWithLinesAlgorithm::shortDescription() const
102{
103 return QObject::tr( "Creates lines joining two point layers, based on a common attribute value." );
104}
105
106Qgis::ProcessingAlgorithmDocumentationFlags QgsJoinWithLinesAlgorithm::documentationFlags() const
107{
109}
110
111QgsJoinWithLinesAlgorithm *QgsJoinWithLinesAlgorithm::createInstance() const
112{
113 return new QgsJoinWithLinesAlgorithm();
114}
115
116QVariantMap QgsJoinWithLinesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
117{
118 QGS_MARK_ALGORITHM_SOURCE
119
120 if ( parameters.value( u"SPOKES"_s ) == parameters.value( u"HUBS"_s ) )
121 throw QgsProcessingException( QObject::tr( "Same layer given for both hubs and spokes" ) );
122
123 std::unique_ptr<QgsProcessingFeatureSource> hubSource( parameterAsSource( parameters, u"HUBS"_s, context ) );
124 if ( !hubSource )
125 throw QgsProcessingException( invalidSourceError( parameters, u"HUBS"_s ) );
126
127 std::unique_ptr<QgsProcessingFeatureSource> spokeSource( parameterAsSource( parameters, u"SPOKES"_s, context ) );
128 if ( !spokeSource )
129 throw QgsProcessingException( invalidSourceError( parameters, u"SPOKES"_s ) );
130
131 const QString fieldHubName = parameterAsString( parameters, u"HUB_FIELD"_s, context );
132 const int fieldHubIndex = hubSource->fields().lookupField( fieldHubName );
133 const QStringList hubFieldsToCopy = parameterAsStrings( parameters, u"HUB_FIELDS"_s, context );
134
135 const QString fieldSpokeName = parameterAsString( parameters, u"SPOKE_FIELD"_s, context );
136 const int fieldSpokeIndex = spokeSource->fields().lookupField( fieldSpokeName );
137 const QStringList spokeFieldsToCopy = parameterAsStrings( parameters, u"SPOKE_FIELDS"_s, context );
138
139 if ( fieldHubIndex < 0 || fieldSpokeIndex < 0 )
140 throw QgsProcessingException( QObject::tr( "Invalid ID field" ) );
141
142 const bool geodesic = parameterAsBoolean( parameters, u"GEODESIC"_s, context );
143 const double geodesicDistance = parameterAsDouble( parameters, u"GEODESIC_DISTANCE"_s, context ) * 1000;
144 const bool dynamicGeodesicDistance = QgsProcessingParameters::isDynamic( parameters, u"GEODESIC_DISTANCE"_s );
145 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, hubSource.get() );
146 QgsProperty geodesicDistanceProperty;
147 if ( dynamicGeodesicDistance )
148 {
149 geodesicDistanceProperty = parameters.value( u"GEODESIC_DISTANCE"_s ).value<QgsProperty>();
150 }
151
152 const bool splitAntimeridian = parameterAsBoolean( parameters, u"ANTIMERIDIAN_SPLIT"_s, context );
154 da.setSourceCrs( hubSource->sourceCrs(), context.transformContext() );
155 da.setEllipsoid( context.ellipsoid() );
156
157 QgsFields hubOutFields;
158 QgsAttributeList hubFieldIndices;
159 if ( hubFieldsToCopy.empty() )
160 {
161 hubOutFields = hubSource->fields();
162 hubFieldIndices.reserve( hubOutFields.count() );
163 for ( int i = 0; i < hubOutFields.count(); ++i )
164 {
165 hubFieldIndices << i;
166 }
167 }
168 else
169 {
170 hubFieldIndices.reserve( hubOutFields.count() );
171 for ( const QString &field : hubFieldsToCopy )
172 {
173 const int index = hubSource->fields().lookupField( field );
174 if ( index >= 0 )
175 {
176 hubFieldIndices << index;
177 hubOutFields.append( hubSource->fields().at( index ) );
178 }
179 }
180 }
181
182 QgsAttributeList hubFields2Fetch = hubFieldIndices;
183 hubFields2Fetch << fieldHubIndex;
184
185 QgsFields spokeOutFields;
186 QgsAttributeList spokeFieldIndices;
187 if ( spokeFieldsToCopy.empty() )
188 {
189 spokeOutFields = spokeSource->fields();
190 spokeFieldIndices.reserve( spokeOutFields.count() );
191 for ( int i = 0; i < spokeOutFields.count(); ++i )
192 {
193 spokeFieldIndices << i;
194 }
195 }
196 else
197 {
198 for ( const QString &field : spokeFieldsToCopy )
199 {
200 const int index = spokeSource->fields().lookupField( field );
201 if ( index >= 0 )
202 {
203 spokeFieldIndices << index;
204 spokeOutFields.append( spokeSource->fields().at( index ) );
205 }
206 }
207 }
208
209 QgsAttributeList spokeFields2Fetch = spokeFieldIndices;
210 spokeFields2Fetch << fieldSpokeIndex;
211
212
213 const QgsFields fields = QgsProcessingUtils::combineFields( hubOutFields, spokeOutFields );
214
216 bool hasZ = false;
217 if ( !geodesic && ( QgsWkbTypes::hasZ( hubSource->wkbType() ) || QgsWkbTypes::hasZ( spokeSource->wkbType() ) ) )
218 {
219 outType = QgsWkbTypes::addZ( outType );
220 hasZ = true;
221 }
222 bool hasM = false;
223 if ( !geodesic && ( QgsWkbTypes::hasM( hubSource->wkbType() ) || QgsWkbTypes::hasM( spokeSource->wkbType() ) ) )
224 {
225 outType = QgsWkbTypes::addM( outType );
226 hasM = true;
227 }
228
229 QString dest;
230 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, outType, hubSource->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
231 if ( !sink )
232 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
233
234 auto getPointFromFeature = [hasZ, hasM]( const QgsFeature &feature ) -> QgsPoint {
235 QgsPoint p;
236 if ( feature.geometry().type() == Qgis::GeometryType::Point && !feature.geometry().isMultipart() )
237 p = *static_cast<const QgsPoint *>( feature.geometry().constGet() );
238 else
239 p = *static_cast<const QgsPoint *>( feature.geometry().pointOnSurface().constGet() );
240 if ( hasZ && !p.is3D() )
241 p.addZValue( 0 );
242 if ( hasM && !p.isMeasure() )
243 p.addMValue( 0 );
244 return p;
245 };
246
247 QgsFeatureIterator hubFeatures = hubSource->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( hubFields2Fetch ), Qgis::ProcessingFeatureSourceFlag::SkipGeometryValidityChecks );
248 const double step = hubSource->featureCount() > 0 ? 100.0 / hubSource->featureCount() : 1;
249 int i = 0;
250 QgsFeature hubFeature;
251 while ( hubFeatures.nextFeature( hubFeature ) )
252 {
253 i++;
254 if ( feedback->isCanceled() )
255 {
256 break;
257 }
258
259 feedback->setProgress( i * step );
260
261 if ( !hubFeature.hasGeometry() )
262 continue;
263
264 const QgsPoint hubPoint = getPointFromFeature( hubFeature );
265
266 // only keep selected attributes
267 QgsAttributes hubAttributes;
268 const int attributeCount = hubFeature.attributeCount();
269 for ( int j = 0; j < attributeCount; ++j )
270 {
271 if ( !hubFieldIndices.contains( j ) )
272 continue;
273 hubAttributes << hubFeature.attribute( j );
274 }
275
276 QgsFeatureRequest spokeRequest = QgsFeatureRequest().setDestinationCrs( hubSource->sourceCrs(), context.transformContext() );
277 spokeRequest.setSubsetOfAttributes( spokeFields2Fetch );
278 spokeRequest.setFilterExpression( QgsExpression::createFieldEqualityExpression( fieldSpokeName, hubFeature.attribute( fieldHubIndex ) ) );
279
280 QgsFeatureIterator spokeFeatures = spokeSource->getFeatures( spokeRequest, Qgis::ProcessingFeatureSourceFlag::SkipGeometryValidityChecks );
281 QgsFeature spokeFeature;
282 while ( spokeFeatures.nextFeature( spokeFeature ) )
283 {
284 if ( feedback->isCanceled() )
285 {
286 break;
287 }
288 if ( !spokeFeature.hasGeometry() )
289 continue;
290
291 const QgsPoint spokePoint = getPointFromFeature( spokeFeature );
292 QgsGeometry line;
293 if ( !geodesic )
294 {
295 line = QgsGeometry( new QgsLineString( QVector<QgsPoint>() << hubPoint << spokePoint ) );
296 if ( splitAntimeridian )
297 line = da.splitGeometryAtAntimeridian( line );
298 }
299 else
300 {
301 double distance = geodesicDistance;
302 if ( dynamicGeodesicDistance )
303 {
304 expressionContext.setFeature( hubFeature );
305 distance = geodesicDistanceProperty.valueAsDouble( expressionContext, distance );
306 }
307
308 auto ml = std::make_unique<QgsMultiLineString>();
309 auto l = std::make_unique<QgsLineString>( QVector<QgsPoint>() << hubPoint );
310 const QVector<QVector<QgsPointXY>> points = da.geodesicLine( QgsPointXY( hubPoint ), QgsPointXY( spokePoint ), distance, splitAntimeridian );
311 QVector<QgsPointXY> points1 = points.at( 0 );
312 points1.pop_front();
313 if ( points.count() == 1 )
314 points1.pop_back();
315
316 const QgsLineString geodesicPoints( points1 );
317 l->append( &geodesicPoints );
318 if ( points.count() == 1 )
319 l->addVertex( spokePoint );
320
321 ml->addGeometry( l.release() );
322 if ( points.count() > 1 )
323 {
324 QVector<QgsPointXY> points2 = points.at( 1 );
325 points2.pop_back();
326 l = std::make_unique<QgsLineString>( points2 );
327 if ( hasZ )
328 l->addZValue( std::numeric_limits<double>::quiet_NaN() );
329 if ( hasM )
330 l->addMValue( std::numeric_limits<double>::quiet_NaN() );
331
332 l->addVertex( spokePoint );
333 ml->addGeometry( l.release() );
334 }
335 line = QgsGeometry( std::move( ml ) );
336 }
337
338 QgsFeature outFeature;
339 QgsAttributes outAttributes = hubAttributes;
340
341 // only keep selected attributes
342 QgsAttributes spokeAttributes;
343 const int attributeCount = spokeFeature.attributeCount();
344 for ( int j = 0; j < attributeCount; ++j )
345 {
346 if ( !spokeFieldIndices.contains( j ) )
347 continue;
348 spokeAttributes << spokeFeature.attribute( j );
349 }
350
351 outAttributes.append( spokeAttributes );
352 outFeature.setAttributes( outAttributes );
353 outFeature.setGeometry( line );
354 if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
355 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
356 else
357 feedback->featureAddedToSink( u"OUTPUT"_s );
358 }
359 }
360 sink->finalize();
361 feedback->featureSinkFinalized( u"OUTPUT"_s );
362
363 QVariantMap outputs;
364 outputs.insert( u"OUTPUT"_s, dest );
365 return outputs;
366}
367
@ VectorLine
Vector line layers.
Definition qgis.h:3751
@ Kilometers
Kilometers.
Definition qgis.h:5514
@ Point
Points.
Definition qgis.h:380
@ 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
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3930
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:294
@ LineString
LineString.
Definition qgis.h:297
@ MultiLineString
MultiLineString.
Definition qgis.h:301
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3982
bool isMeasure() const
Returns true if the geometry contains m values.
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
A vector of attributes.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
QVector< QVector< QgsPointXY > > geodesicLine(const QgsPointXY &p1, const QgsPointXY &p2, double interval, bool breakLine=false) const
Calculates the geodesic line between p1 and p2, which represents the shortest path on the ellipsoid b...
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
QgsGeometry splitGeometryAtAntimeridian(const QgsGeometry &geometry) const
Splits a (Multi)LineString geometry at the antimeridian (longitude +/- 180 degrees).
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
static QString createFieldEqualityExpression(const QString &fieldName, const QVariant &value, QMetaType::Type fieldType=QMetaType::Type::UnknownType)
Create an expression allowing to evaluate if a field is equal to a value.
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.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
@ 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
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:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
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
A geometry is the spatial representation of a feature.
Line string geometry type, with support for z-dimension and m-values.
Represents a 2D point.
Definition qgspointxy.h:62
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
bool addMValue(double mValue=0) override
Adds a measure to the geometry, initialized to a preset value.
Definition qgspoint.cpp:614
bool addZValue(double zValue=0) override
Adds a z-dimension to the geometry, initialized to a preset value.
Definition qgspoint.cpp:603
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
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.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
A boolean parameter for processing algorithms.
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.
static bool isDynamic(const QVariantMap &parameters, const QString &name)
Returns true if the parameter with matching name is a dynamic parameter, and must be evaluated once f...
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).
Definition for a property.
Definition qgsproperty.h:47
@ DoublePositive
Positive double value (including 0).
Definition qgsproperty.h:57
A store for object properties.
QVariant value(const QgsExpressionContext &context, const QVariant &defaultValue=QVariant(), bool *ok=nullptr) const
Calculates the current value of the property, including any transforms which are set for the property...
double valueAsDouble(const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property and interprets it as a double.
static Qgis::WkbType addM(Qgis::WkbType type)
Adds the m dimension to a WKB type and returns the new type.
static Qgis::WkbType addZ(Qgis::WkbType type)
Adds the z dimension to a WKB type and returns the new type.
static Q_INVOKABLE bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static Q_INVOKABLE bool hasM(Qgis::WkbType type)
Tests whether a WKB type contains m values.
QList< int > QgsAttributeList
Definition qgsfield.h:30