QGIS API Documentation 3.99.0-Master (21b3aa880ba)
Loading...
Searching...
No Matches
qgsalgorithmhubdistance.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmhubdistance.cpp
3 ---------------------
4 begin : April 2025
5 copyright : (C) 2025 by Alexander Bruy
6 email : alexander dot bruy 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 "qgsfeaturerequest.h"
21#include "qgsspatialindex.h"
22
24
25QString QgsHubDistanceAlgorithm::name() const
26{
27 return QStringLiteral( "distancetonearesthub" );
28}
29
30QString QgsHubDistanceAlgorithm::displayName() const
31{
32 return QObject::tr( "Distance to nearest hub" );
33}
34
35QStringList QgsHubDistanceAlgorithm::tags() const
36{
37 return QObject::tr( "lines,points,hub,spoke,distance" ).split( ',' );
38}
39
40QString QgsHubDistanceAlgorithm::group() const
41{
42 return QObject::tr( "Vector analysis" );
43}
44
45QString QgsHubDistanceAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectoranalysis" );
48}
49
50QString QgsHubDistanceAlgorithm::shortHelpString() const
51{
52 return QObject::tr( "This algorithm computes the distance between features from the source layer to the closest feature "
53 "from the destination layer.\n\n"
54 "Distance calculations are based on the feature's bounding box center.\n\n"
55 "The resulting line layer contains lines linking each origin point with its nearest destination feature.\n\n"
56 "The resulting point layer contains each origin feature's center point with additional fields indicating the identifier "
57 "of the nearest destination feature and the distance to it."
58 );
59}
60
61QString QgsHubDistanceAlgorithm::shortDescription() const
62{
63 return QObject::tr( "Computes the distance between features from the source layer to the closest feature from the destination layer." );
64}
65
66Qgis::ProcessingAlgorithmDocumentationFlags QgsHubDistanceAlgorithm::documentationFlags() const
67{
69}
70
71QgsHubDistanceAlgorithm *QgsHubDistanceAlgorithm::createInstance() const
72{
73 return new QgsHubDistanceAlgorithm();
74}
75
76void QgsHubDistanceAlgorithm::initAlgorithm( const QVariantMap & )
77{
78 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Source layer (spokes)" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
79 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "HUBS" ), QObject::tr( "Destination layer (hubs)" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
80 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD" ), QObject::tr( "Hub layer name attribute" ), QVariant(), QStringLiteral( "HUBS" ) ) );
81
82 const QStringList options = QStringList()
83 << QObject::tr( "Meters" )
84 << QObject::tr( "Feet" )
85 << QObject::tr( "Miles" )
86 << QObject::tr( "Kilometers" )
87 << QObject::tr( "Layer Units" );
88 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "UNIT" ), QObject::tr( "Measurement unit" ), options, false, 0 ) );
89 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT_LINES" ), QObject::tr( "Hub lines" ), Qgis::ProcessingSourceType::VectorLine, QVariant(), true, true ) );
90 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT_POINTS" ), QObject::tr( "Hub points" ), Qgis::ProcessingSourceType::VectorPoint, QVariant(), true, false ) );
91}
92
93QVariantMap QgsHubDistanceAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
94{
95 if ( parameters.value( QStringLiteral( "INPUT" ) ) == parameters.value( QStringLiteral( "HUBS" ) ) )
96 throw QgsProcessingException( QObject::tr( "The same layer was specified for both the hubs and spokes. The hubs and spoke layers must be different layers." ) );
97
98 std::unique_ptr<QgsProcessingFeatureSource> hubSource( parameterAsSource( parameters, QStringLiteral( "HUBS" ), context ) );
99 if ( !hubSource )
100 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "HUBS" ) ) );
101
102 std::unique_ptr<QgsProcessingFeatureSource> spokeSource( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
103 if ( !spokeSource )
104 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
105
106 const QString fieldHubName = parameterAsString( parameters, QStringLiteral( "FIELD" ), context );
107 const int hubNameIndex = hubSource->fields().lookupField( fieldHubName );
108
109 const int unitIndex = parameterAsEnum( parameters, QStringLiteral( "UNIT" ), context );
111 switch ( unitIndex )
112 {
113 case 0:
115 break;
116 case 1:
118 break;
119 case 2:
121 break;
122 case 3:
124 break;
125 }
126
127 QgsFields fields;
128 fields.append( QgsField( QStringLiteral( "HubName" ), QMetaType::Type::QString ) );
129 fields.append( QgsField( QStringLiteral( "HubDist" ), QMetaType::Type::Double ) );
130 fields = QgsProcessingUtils::combineFields( spokeSource->fields(), fields );
131
132 QString linesDest;
133 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, QStringLiteral( "OUTPUT_LINES" ), context, linesDest, fields, Qgis::WkbType::LineString, hubSource->sourceCrs() ) );
134 if ( !linesSink )
135 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT_LINES" ) ) );
136
137 QString pointsDest;
138 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, QStringLiteral( "OUTPUT_POINTS" ), context, pointsDest, fields, Qgis::WkbType::Point, hubSource->sourceCrs() ) );
139 if ( !pointsSink )
140 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT_POINTS" ) ) );
141
142 QgsFeatureRequest request;
143 request.setSubsetOfAttributes( QgsAttributeList() << hubNameIndex );
144 request.setDestinationCrs( spokeSource->sourceCrs(), context.transformContext() );
145 QHash<QgsFeatureId, QVariant> hubsAttributeCache;
146 double step = hubSource->featureCount() > 0 ? 50.0 / hubSource->featureCount() : 1;
147 long long i = 0;
148 const QgsSpatialIndex hubsIndex( hubSource->getFeatures( request ), [&]( const QgsFeature &f ) -> bool {
149 if ( feedback-> isCanceled() )
150 {
151 return false;
152 }
153
154 hubsAttributeCache.insert( f.id(), f.attributes().at( hubNameIndex ) );
155
156 i++;
157 feedback->setProgress( i * step );
159
161 da.setSourceCrs( spokeSource->sourceCrs(), context.transformContext() );
162 da.setEllipsoid( context.ellipsoid() );
163
164 // Scan source points, find nearest hub, and write to output file
165 i = 0;
166 QgsFeature spokeFeature, outputFeature;
167 step = spokeSource->featureCount() > 0 ? 50.0 / spokeSource->featureCount() : 1;
168 QgsFeatureIterator features = spokeSource->getFeatures();
169 while ( features.nextFeature( spokeFeature ) )
170 {
171 if ( feedback->isCanceled() )
172 {
173 break;
174 }
175
176 i++;
177 feedback->setProgress( i * step );
178
179 if ( !spokeFeature.hasGeometry() )
180 {
181 spokeFeature.setAttributes( spokeFeature.attributes() << QVariant() << QVariant() );
182 if ( linesSink && !linesSink->addFeature( spokeFeature, QgsFeatureSink::Flag::FastInsert ) )
183 {
184 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, QStringLiteral( "OUTPUT_LINES" ) ) );
185 }
186 if ( pointsSink && !pointsSink->addFeature( spokeFeature, QgsFeatureSink::Flag::FastInsert ) )
187 {
188 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral( "OUTPUT_POINTS" ) ) );
189 }
190 continue;
191 }
192
193 QgsPointXY point = spokeFeature.geometry().boundingBox().center();
194
195 const QList<QgsFeatureId> neighbors = hubsIndex.nearestNeighbor( point, 1 );
196 if ( neighbors.isEmpty() )
197 {
198 feedback->pushWarning( QObject::tr( "Feature %1 does not have any neighbour hubs." ) );
199 continue;
200 }
201
202 const QgsPointXY hub = hubsIndex.geometry( neighbors.at( 0 ) ).boundingBox().center();
203 double hubDistance = da.measureLine( point, hub );
204
205 if ( unit != Qgis::DistanceUnit::Unknown )
206 {
207 hubDistance = da.convertLengthMeasurement( hubDistance, unit );
208 }
209
210 QgsAttributes attrs = spokeFeature.attributes();
211 attrs << hubsAttributeCache.value( neighbors.at( 0 ) ) << hubDistance;
212 outputFeature = QgsFeature();
213 outputFeature.setAttributes( attrs );
214
215 if ( linesSink )
216 {
217 outputFeature.setGeometry( QgsGeometry::fromPolylineXY( QgsPolylineXY() << point << hub ) );
218 if ( !linesSink->addFeature( outputFeature, QgsFeatureSink::Flag::FastInsert ) )
219 {
220 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, QStringLiteral( "OUTPUT_LINES" ) ) );
221 }
222 }
223
224 if ( pointsSink )
225 {
226 outputFeature.setGeometry( QgsGeometry::fromPointXY( point ) );
227 if ( !pointsSink->addFeature( outputFeature, QgsFeatureSink::Flag::FastInsert ) )
228 {
229 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral( "OUTPUT_POINTS" ) ) );
230 }
231 }
232 }
233
234 if ( linesSink )
235 {
236 linesSink->finalize();
237 }
238 if ( pointsSink )
239 {
240 pointsSink->finalize();
241 }
242
243 QVariantMap results;
244 if ( linesSink )
245 {
246 results.insert( QStringLiteral( "OUTPUT_LINES" ), linesDest );
247 }
248 if ( pointsSink )
249 {
250 results.insert( QStringLiteral( "OUTPUT_POINTS" ), pointsDest );
251 }
252 return results;
253}
254
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3533
@ VectorPoint
Vector point layers.
Definition qgis.h:3534
@ VectorLine
Vector line layers.
Definition qgis.h:3535
DistanceUnit
Units of distance.
Definition qgis.h:5013
@ Feet
Imperial feet.
Definition qgis.h:5016
@ Miles
Terrestrial miles.
Definition qgis.h:5019
@ Meters
Meters.
Definition qgis.h:5014
@ Unknown
Unknown distance unit.
Definition qgis.h:5063
@ Kilometers
Kilometers.
Definition qgis.h:5015
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3621
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
@ Point
Point.
Definition qgis.h:279
@ LineString
LineString.
Definition qgis.h:280
A vector of attributes.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
double convertLengthMeasurement(double length, Qgis::DistanceUnit toUnits) const
Takes a length measurement calculated by this QgsDistanceArea object and converts it to a different d...
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
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.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsAttributes attributes
Definition qgsfeature.h:67
QgsFeatureId id
Definition qgsfeature.h:66
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
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:54
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:73
static QgsGeometry fromPolylineXY(const QgsPolylineXY &polyline)
Creates a new LineString geometry from a list of QgsPointXY points.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Represents a 2D point.
Definition qgspointxy.h:60
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.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
An enum based parameter for processing algorithms, allowing for selection from predefined 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.
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).
QgsPointXY center
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
QList< int > QgsAttributeList
Definition qgsfield.h:28
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.
Definition qgsgeometry.h:61