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