QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
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 QGS_MARK_ALGORITHM_SOURCE
96
97 if ( parameters.value( u"INPUT"_s ) == parameters.value( u"HUBS"_s ) )
98 throw QgsProcessingException( QObject::tr( "The same layer was specified for both the hubs and spokes. The hubs and spoke layers must be different layers." ) );
99
100 std::unique_ptr<QgsProcessingFeatureSource> hubSource( parameterAsSource( parameters, u"HUBS"_s, context ) );
101 if ( !hubSource )
102 throw QgsProcessingException( invalidSourceError( parameters, u"HUBS"_s ) );
103
104 std::unique_ptr<QgsProcessingFeatureSource> spokeSource( parameterAsSource( parameters, u"INPUT"_s, context ) );
105 if ( !spokeSource )
106 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
107
108 const QString fieldHubName = parameterAsString( parameters, u"FIELD"_s, context );
109 const int hubNameIndex = hubSource->fields().lookupField( fieldHubName );
110
111 const int unitIndex = parameterAsEnum( parameters, u"UNIT"_s, context );
113 switch ( unitIndex )
114 {
115 case 0:
117 break;
118 case 1:
120 break;
121 case 2:
123 break;
124 case 3:
126 break;
127 }
128
129 QgsFields fields;
130 fields.append( QgsField( u"HubName"_s, QMetaType::Type::QString ) );
131 fields.append( QgsField( u"HubDist"_s, QMetaType::Type::Double ) );
132 fields = QgsProcessingUtils::combineFields( spokeSource->fields(), fields );
133
134 QString linesDest;
135 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, u"OUTPUT_LINES"_s, context, linesDest, fields, Qgis::WkbType::LineString, hubSource->sourceCrs() ) );
136 if ( !linesSink )
137 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_LINES"_s ) );
138
139 QString pointsDest;
140 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, u"OUTPUT_POINTS"_s, context, pointsDest, fields, Qgis::WkbType::Point, hubSource->sourceCrs() ) );
141 if ( !pointsSink )
142 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT_POINTS"_s ) );
143
144 QgsFeatureRequest request;
145 request.setSubsetOfAttributes( QgsAttributeList() << hubNameIndex );
146 request.setDestinationCrs( spokeSource->sourceCrs(), context.transformContext() );
147 QHash<QgsFeatureId, QVariant> hubsAttributeCache;
148 double step = hubSource->featureCount() > 0 ? 50.0 / hubSource->featureCount() : 1;
149 long long i = 0;
150 const QgsSpatialIndex hubsIndex(
151 hubSource->getFeatures( request ),
152 [&]( 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 );
162 return true;
163 },
165 );
166
168 da.setSourceCrs( spokeSource->sourceCrs(), context.transformContext() );
169 da.setEllipsoid( context.ellipsoid() );
170
171 // Scan source points, find nearest hub, and write to output file
172 i = 0;
173 QgsFeature spokeFeature, outputFeature;
174 step = spokeSource->featureCount() > 0 ? 50.0 / spokeSource->featureCount() : 1;
175 QgsFeatureIterator features = spokeSource->getFeatures();
176 while ( features.nextFeature( spokeFeature ) )
177 {
178 if ( feedback->isCanceled() )
179 {
180 break;
181 }
182
183 i++;
184 feedback->setProgress( i * step );
185
186 if ( !spokeFeature.hasGeometry() )
187 {
188 spokeFeature.setAttributes( spokeFeature.attributes() << QVariant() << QVariant() );
189 if ( linesSink && !linesSink->addFeature( spokeFeature, QgsFeatureSink::Flag::FastInsert ) )
190 {
191 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, u"OUTPUT_LINES"_s ) );
192 }
193 else if ( linesSink )
194 {
195 feedback->featureAddedToSink( u"OUTPUT_LINES"_s );
196 }
197 if ( pointsSink && !pointsSink->addFeature( spokeFeature, QgsFeatureSink::Flag::FastInsert ) )
198 {
199 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT_POINTS"_s ) );
200 }
201 else if ( pointsSink )
202 {
203 feedback->featureAddedToSink( u"OUTPUT_POINTS"_s );
204 }
205 continue;
206 }
207
208 QgsPointXY point = spokeFeature.geometry().boundingBox().center();
209
210 const QList<QgsFeatureId> neighbors = hubsIndex.nearestNeighbor( point, 1 );
211 if ( neighbors.isEmpty() )
212 {
213 feedback->pushWarning( QObject::tr( "Feature %1 does not have any neighbour hubs." ) );
214 continue;
215 }
216
217 const QgsPointXY hub = hubsIndex.geometry( neighbors.at( 0 ) ).boundingBox().center();
218 double hubDistance = da.measureLine( point, hub );
219
220 if ( unit != Qgis::DistanceUnit::Unknown )
221 {
222 hubDistance = da.convertLengthMeasurement( hubDistance, unit );
223 }
224
225 QgsAttributes attrs = spokeFeature.attributes();
226 attrs << hubsAttributeCache.value( neighbors.at( 0 ) ) << hubDistance;
227 outputFeature = QgsFeature();
228 outputFeature.setAttributes( attrs );
229
230 if ( linesSink )
231 {
232 outputFeature.setGeometry( QgsGeometry::fromPolylineXY( QgsPolylineXY() << point << hub ) );
233 if ( !linesSink->addFeature( outputFeature, QgsFeatureSink::Flag::FastInsert ) )
234 {
235 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, u"OUTPUT_LINES"_s ) );
236 }
237 else
238 {
239 feedback->featureAddedToSink( u"OUTPUT_LINES"_s );
240 }
241 }
242
243 if ( pointsSink )
244 {
245 outputFeature.setGeometry( QgsGeometry::fromPointXY( point ) );
246 if ( !pointsSink->addFeature( outputFeature, QgsFeatureSink::Flag::FastInsert ) )
247 {
248 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT_POINTS"_s ) );
249 }
250 else
251 {
252 feedback->featureAddedToSink( u"OUTPUT_POINTS"_s );
253 }
254 }
255 }
256
257 if ( linesSink )
258 {
259 linesSink->finalize();
260 feedback->featureSinkFinalized( u"OUTPUT_LINES"_s );
261 }
262 if ( pointsSink )
263 {
264 pointsSink->finalize();
265 feedback->featureSinkFinalized( u"OUTPUT_POINTS"_s );
266 }
267
268 QVariantMap results;
269 if ( linesSink )
270 {
271 results.insert( u"OUTPUT_LINES"_s, linesDest );
272 }
273 if ( pointsSink )
274 {
275 results.insert( u"OUTPUT_POINTS"_s, pointsDest );
276 }
277 return results;
278}
279
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3749
@ VectorPoint
Vector point layers.
Definition qgis.h:3750
@ VectorLine
Vector line layers.
Definition qgis.h:3751
DistanceUnit
Units of distance.
Definition qgis.h:5512
@ Feet
Imperial feet.
Definition qgis.h:5515
@ Miles
Terrestrial miles.
Definition qgis.h:5518
@ Meters
Meters.
Definition qgis.h:5513
@ Unknown
Unknown distance unit.
Definition qgis.h:5562
@ Kilometers
Kilometers.
Definition qgis.h:5514
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3838
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3847
@ 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:64
QgsFeatureId id
Definition qgsfeature.h:63
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:66
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:45
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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
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