QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
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(
57 "This algorithm computes the distance between features from the source layer to the closest feature "
58 "from the destination layer.\n\n"
59 "Distance calculations are based on the feature's bounding box center.\n\n"
60 "The resulting line layer contains lines linking each origin point with its nearest destination feature.\n\n"
61 "The resulting point layer contains each origin feature's center point with additional fields indicating the identifier "
62 "of the nearest destination feature and the distance to it."
63 );
64}
65
66QString QgsHubDistanceAlgorithm::shortDescription() const
67{
68 return QObject::tr( "Computes the distance between features from the source layer to the closest feature from the destination layer." );
69}
70
71Qgis::ProcessingAlgorithmDocumentationFlags QgsHubDistanceAlgorithm::documentationFlags() const
72{
74}
75
76QgsHubDistanceAlgorithm *QgsHubDistanceAlgorithm::createInstance() const
77{
78 return new QgsHubDistanceAlgorithm();
79}
80
81void QgsHubDistanceAlgorithm::initAlgorithm( const QVariantMap & )
82{
83 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Source layer (spokes)" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
84 addParameter( new QgsProcessingParameterFeatureSource( u"HUBS"_s, QObject::tr( "Destination layer (hubs)" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
85 addParameter( new QgsProcessingParameterField( u"FIELD"_s, QObject::tr( "Hub layer name attribute" ), QVariant(), u"HUBS"_s ) );
86
87 const QStringList options = QStringList() << QObject::tr( "Meters" ) << QObject::tr( "Feet" ) << QObject::tr( "Miles" ) << QObject::tr( "Kilometers" ) << QObject::tr( "Layer Units" );
88 addParameter( new QgsProcessingParameterEnum( u"UNIT"_s, QObject::tr( "Measurement unit" ), options, false, 0 ) );
89 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT_LINES"_s, QObject::tr( "Hub lines" ), Qgis::ProcessingSourceType::VectorLine, QVariant(), true, true ) );
90 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT_POINTS"_s, 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( u"INPUT"_s ) == parameters.value( u"HUBS"_s ) )
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, u"HUBS"_s, context ) );
99 if ( !hubSource )
100 throw QgsProcessingException( invalidSourceError( parameters, u"HUBS"_s ) );
101
102 std::unique_ptr<QgsProcessingFeatureSource> spokeSource( parameterAsSource( parameters, u"INPUT"_s, context ) );
103 if ( !spokeSource )
104 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
105
106 const QString fieldHubName = parameterAsString( parameters, u"FIELD"_s, context );
107 const int hubNameIndex = hubSource->fields().lookupField( fieldHubName );
108
109 const int unitIndex = parameterAsEnum( parameters, u"UNIT"_s, 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( u"HubName"_s, QMetaType::Type::QString ) );
129 fields.append( QgsField( u"HubDist"_s, QMetaType::Type::Double ) );
130 fields = QgsProcessingUtils::combineFields( spokeSource->fields(), fields );
131
132 QString linesDest;
133 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, u"OUTPUT_LINES"_s, context, linesDest, fields, Qgis::WkbType::LineString, hubSource->sourceCrs() ) );
134 if ( !linesSink )
135 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_LINES"_s ) );
136
137 QString pointsDest;
138 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, u"OUTPUT_POINTS"_s, context, pointsDest, fields, Qgis::WkbType::Point, hubSource->sourceCrs() ) );
139 if ( !pointsSink )
140 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_POINTS"_s ) );
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(
149 hubSource->getFeatures( request ),
150 [&]( const QgsFeature &f ) -> bool {
151 if ( feedback->isCanceled() )
152 {
153 return false;
154 }
155
156 hubsAttributeCache.insert( f.id(), f.attributes().at( hubNameIndex ) );
157
158 i++;
159 feedback->setProgress( i * step );
160 return true;
161 },
163 );
164
166 da.setSourceCrs( spokeSource->sourceCrs(), context.transformContext() );
167 da.setEllipsoid( context.ellipsoid() );
168
169 // Scan source points, find nearest hub, and write to output file
170 i = 0;
171 QgsFeature spokeFeature, outputFeature;
172 step = spokeSource->featureCount() > 0 ? 50.0 / spokeSource->featureCount() : 1;
173 QgsFeatureIterator features = spokeSource->getFeatures();
174 while ( features.nextFeature( spokeFeature ) )
175 {
176 if ( feedback->isCanceled() )
177 {
178 break;
179 }
180
181 i++;
182 feedback->setProgress( i * step );
183
184 if ( !spokeFeature.hasGeometry() )
185 {
186 spokeFeature.setAttributes( spokeFeature.attributes() << QVariant() << QVariant() );
187 if ( linesSink && !linesSink->addFeature( spokeFeature, QgsFeatureSink::Flag::FastInsert ) )
188 {
189 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, u"OUTPUT_LINES"_s ) );
190 }
191 if ( pointsSink && !pointsSink->addFeature( spokeFeature, QgsFeatureSink::Flag::FastInsert ) )
192 {
193 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT_POINTS"_s ) );
194 }
195 continue;
196 }
197
198 QgsPointXY point = spokeFeature.geometry().boundingBox().center();
199
200 const QList<QgsFeatureId> neighbors = hubsIndex.nearestNeighbor( point, 1 );
201 if ( neighbors.isEmpty() )
202 {
203 feedback->pushWarning( QObject::tr( "Feature %1 does not have any neighbour hubs." ) );
204 continue;
205 }
206
207 const QgsPointXY hub = hubsIndex.geometry( neighbors.at( 0 ) ).boundingBox().center();
208 double hubDistance = da.measureLine( point, hub );
209
210 if ( unit != Qgis::DistanceUnit::Unknown )
211 {
212 hubDistance = da.convertLengthMeasurement( hubDistance, unit );
213 }
214
215 QgsAttributes attrs = spokeFeature.attributes();
216 attrs << hubsAttributeCache.value( neighbors.at( 0 ) ) << hubDistance;
217 outputFeature = QgsFeature();
218 outputFeature.setAttributes( attrs );
219
220 if ( linesSink )
221 {
222 outputFeature.setGeometry( QgsGeometry::fromPolylineXY( QgsPolylineXY() << point << hub ) );
223 if ( !linesSink->addFeature( outputFeature, QgsFeatureSink::Flag::FastInsert ) )
224 {
225 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, u"OUTPUT_LINES"_s ) );
226 }
227 }
228
229 if ( pointsSink )
230 {
231 outputFeature.setGeometry( QgsGeometry::fromPointXY( point ) );
232 if ( !pointsSink->addFeature( outputFeature, QgsFeatureSink::Flag::FastInsert ) )
233 {
234 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT_POINTS"_s ) );
235 }
236 }
237 }
238
239 if ( linesSink )
240 {
241 linesSink->finalize();
242 }
243 if ( pointsSink )
244 {
245 pointsSink->finalize();
246 }
247
248 QVariantMap results;
249 if ( linesSink )
250 {
251 results.insert( u"OUTPUT_LINES"_s, linesDest );
252 }
253 if ( pointsSink )
254 {
255 results.insert( u"OUTPUT_POINTS"_s, pointsDest );
256 }
257 return results;
258}
259
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3647
@ VectorPoint
Vector point layers.
Definition qgis.h:3648
@ VectorLine
Vector line layers.
Definition qgis.h:3649
DistanceUnit
Units of distance.
Definition qgis.h:5170
@ Feet
Imperial feet.
Definition qgis.h:5173
@ Miles
Terrestrial miles.
Definition qgis.h:5176
@ Meters
Meters.
Definition qgis.h:5171
@ Unknown
Unknown distance unit.
Definition qgis.h:5220
@ Kilometers
Kilometers.
Definition qgis.h:5172
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3736
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3745
@ Point
Point.
Definition qgis.h:296
@ LineString
LineString.
Definition qgis.h:297
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:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
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:75
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