QGIS API Documentation 3.99.0-Master (09f76ad7019)
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
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29QString QgsHubDistanceAlgorithm::name() const
30{
31 return u"distancetonearesthub"_s;
32}
33
34QString QgsHubDistanceAlgorithm::displayName() const
35{
36 return QObject::tr( "Distance to nearest hub" );
37}
38
39QStringList QgsHubDistanceAlgorithm::tags() const
40{
41 return QObject::tr( "lines,points,hub,spoke,distance" ).split( ',' );
42}
43
44QString QgsHubDistanceAlgorithm::group() const
45{
46 return QObject::tr( "Vector analysis" );
47}
48
49QString QgsHubDistanceAlgorithm::groupId() const
50{
51 return u"vectoranalysis"_s;
52}
53
54QString QgsHubDistanceAlgorithm::shortHelpString() const
55{
56 return QObject::tr( "This algorithm computes the distance between features from the source layer to the closest feature "
57 "from the destination layer.\n\n"
58 "Distance calculations are based on the feature's bounding box center.\n\n"
59 "The resulting line layer contains lines linking each origin point with its nearest destination feature.\n\n"
60 "The resulting point layer contains each origin feature's center point with additional fields indicating the identifier "
61 "of the nearest destination feature and the distance to it."
62 );
63}
64
65QString QgsHubDistanceAlgorithm::shortDescription() const
66{
67 return QObject::tr( "Computes the distance between features from the source layer to the closest feature from the destination layer." );
68}
69
70Qgis::ProcessingAlgorithmDocumentationFlags QgsHubDistanceAlgorithm::documentationFlags() const
71{
73}
74
75QgsHubDistanceAlgorithm *QgsHubDistanceAlgorithm::createInstance() const
76{
77 return new QgsHubDistanceAlgorithm();
78}
79
80void QgsHubDistanceAlgorithm::initAlgorithm( const QVariantMap & )
81{
82 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Source layer (spokes)" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
83 addParameter( new QgsProcessingParameterFeatureSource( u"HUBS"_s, QObject::tr( "Destination layer (hubs)" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
84 addParameter( new QgsProcessingParameterField( u"FIELD"_s, QObject::tr( "Hub layer name attribute" ), QVariant(), u"HUBS"_s ) );
85
86 const QStringList options = QStringList()
87 << QObject::tr( "Meters" )
88 << QObject::tr( "Feet" )
89 << QObject::tr( "Miles" )
90 << QObject::tr( "Kilometers" )
91 << QObject::tr( "Layer Units" );
92 addParameter( new QgsProcessingParameterEnum( u"UNIT"_s, QObject::tr( "Measurement unit" ), options, false, 0 ) );
93 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT_LINES"_s, QObject::tr( "Hub lines" ), Qgis::ProcessingSourceType::VectorLine, QVariant(), true, true ) );
94 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT_POINTS"_s, QObject::tr( "Hub points" ), Qgis::ProcessingSourceType::VectorPoint, QVariant(), true, false ) );
95}
96
97QVariantMap QgsHubDistanceAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
98{
99 if ( parameters.value( u"INPUT"_s ) == parameters.value( u"HUBS"_s ) )
100 throw QgsProcessingException( QObject::tr( "The same layer was specified for both the hubs and spokes. The hubs and spoke layers must be different layers." ) );
101
102 std::unique_ptr<QgsProcessingFeatureSource> hubSource( parameterAsSource( parameters, u"HUBS"_s, context ) );
103 if ( !hubSource )
104 throw QgsProcessingException( invalidSourceError( parameters, u"HUBS"_s ) );
105
106 std::unique_ptr<QgsProcessingFeatureSource> spokeSource( parameterAsSource( parameters, u"INPUT"_s, context ) );
107 if ( !spokeSource )
108 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
109
110 const QString fieldHubName = parameterAsString( parameters, u"FIELD"_s, context );
111 const int hubNameIndex = hubSource->fields().lookupField( fieldHubName );
112
113 const int unitIndex = parameterAsEnum( parameters, u"UNIT"_s, context );
115 switch ( unitIndex )
116 {
117 case 0:
119 break;
120 case 1:
122 break;
123 case 2:
125 break;
126 case 3:
128 break;
129 }
130
131 QgsFields fields;
132 fields.append( QgsField( u"HubName"_s, QMetaType::Type::QString ) );
133 fields.append( QgsField( u"HubDist"_s, QMetaType::Type::Double ) );
134 fields = QgsProcessingUtils::combineFields( spokeSource->fields(), fields );
135
136 QString linesDest;
137 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, u"OUTPUT_LINES"_s, context, linesDest, fields, Qgis::WkbType::LineString, hubSource->sourceCrs() ) );
138 if ( !linesSink )
139 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_LINES"_s ) );
140
141 QString pointsDest;
142 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, u"OUTPUT_POINTS"_s, context, pointsDest, fields, Qgis::WkbType::Point, hubSource->sourceCrs() ) );
143 if ( !pointsSink )
144 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_POINTS"_s ) );
145
146 QgsFeatureRequest request;
147 request.setSubsetOfAttributes( QgsAttributeList() << hubNameIndex );
148 request.setDestinationCrs( spokeSource->sourceCrs(), context.transformContext() );
149 QHash<QgsFeatureId, QVariant> hubsAttributeCache;
150 double step = hubSource->featureCount() > 0 ? 50.0 / hubSource->featureCount() : 1;
151 long long i = 0;
152 const QgsSpatialIndex hubsIndex( hubSource->getFeatures( request ), [&]( const QgsFeature &f ) -> bool {
153 if ( feedback-> isCanceled() )
154 {
155 return false;
156 }
157
158 hubsAttributeCache.insert( f.id(), f.attributes().at( hubNameIndex ) );
159
160 i++;
161 feedback->setProgress( i * step );
163
165 da.setSourceCrs( spokeSource->sourceCrs(), context.transformContext() );
166 da.setEllipsoid( context.ellipsoid() );
167
168 // Scan source points, find nearest hub, and write to output file
169 i = 0;
170 QgsFeature spokeFeature, outputFeature;
171 step = spokeSource->featureCount() > 0 ? 50.0 / spokeSource->featureCount() : 1;
172 QgsFeatureIterator features = spokeSource->getFeatures();
173 while ( features.nextFeature( spokeFeature ) )
174 {
175 if ( feedback->isCanceled() )
176 {
177 break;
178 }
179
180 i++;
181 feedback->setProgress( i * step );
182
183 if ( !spokeFeature.hasGeometry() )
184 {
185 spokeFeature.setAttributes( spokeFeature.attributes() << QVariant() << QVariant() );
186 if ( linesSink && !linesSink->addFeature( spokeFeature, QgsFeatureSink::Flag::FastInsert ) )
187 {
188 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, u"OUTPUT_LINES"_s ) );
189 }
190 if ( pointsSink && !pointsSink->addFeature( spokeFeature, QgsFeatureSink::Flag::FastInsert ) )
191 {
192 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT_POINTS"_s ) );
193 }
194 continue;
195 }
196
197 QgsPointXY point = spokeFeature.geometry().boundingBox().center();
198
199 const QList<QgsFeatureId> neighbors = hubsIndex.nearestNeighbor( point, 1 );
200 if ( neighbors.isEmpty() )
201 {
202 feedback->pushWarning( QObject::tr( "Feature %1 does not have any neighbour hubs." ) );
203 continue;
204 }
205
206 const QgsPointXY hub = hubsIndex.geometry( neighbors.at( 0 ) ).boundingBox().center();
207 double hubDistance = da.measureLine( point, hub );
208
209 if ( unit != Qgis::DistanceUnit::Unknown )
210 {
211 hubDistance = da.convertLengthMeasurement( hubDistance, unit );
212 }
213
214 QgsAttributes attrs = spokeFeature.attributes();
215 attrs << hubsAttributeCache.value( neighbors.at( 0 ) ) << hubDistance;
216 outputFeature = QgsFeature();
217 outputFeature.setAttributes( attrs );
218
219 if ( linesSink )
220 {
221 outputFeature.setGeometry( QgsGeometry::fromPolylineXY( QgsPolylineXY() << point << hub ) );
222 if ( !linesSink->addFeature( outputFeature, QgsFeatureSink::Flag::FastInsert ) )
223 {
224 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, u"OUTPUT_LINES"_s ) );
225 }
226 }
227
228 if ( pointsSink )
229 {
230 outputFeature.setGeometry( QgsGeometry::fromPointXY( point ) );
231 if ( !pointsSink->addFeature( outputFeature, QgsFeatureSink::Flag::FastInsert ) )
232 {
233 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT_POINTS"_s ) );
234 }
235 }
236 }
237
238 if ( linesSink )
239 {
240 linesSink->finalize();
241 }
242 if ( pointsSink )
243 {
244 pointsSink->finalize();
245 }
246
247 QVariantMap results;
248 if ( linesSink )
249 {
250 results.insert( u"OUTPUT_LINES"_s, linesDest );
251 }
252 if ( pointsSink )
253 {
254 results.insert( u"OUTPUT_POINTS"_s, pointsDest );
255 }
256 return results;
257}
258
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3604
@ VectorPoint
Vector point layers.
Definition qgis.h:3605
@ VectorLine
Vector line layers.
Definition qgis.h:3606
DistanceUnit
Units of distance.
Definition qgis.h:5120
@ Feet
Imperial feet.
Definition qgis.h:5123
@ Miles
Terrestrial miles.
Definition qgis.h:5126
@ Meters
Meters.
Definition qgis.h:5121
@ Unknown
Unknown distance unit.
Definition qgis.h:5170
@ Kilometers
Kilometers.
Definition qgis.h:5122
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3692
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3701
@ Point
Point.
Definition qgis.h:282
@ LineString
LineString.
Definition qgis.h:283
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:60
QgsAttributes attributes
Definition qgsfeature.h:69
QgsFeatureId id
Definition qgsfeature.h:68
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
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: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
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:62
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:30
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.
Definition qgsgeometry.h:63