QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsalgorithmserviceareafromlayer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmserviceareafromlayer.cpp
3 ---------------------
4 begin : July 2018
5 copyright : (C) 2018 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 "qgsgeometryutils.h"
21#include "qgsgraphanalyzer.h"
22
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29QString QgsServiceAreaFromLayerAlgorithm::name() const
30{
31 return u"serviceareafromlayer"_s;
32}
33
34QString QgsServiceAreaFromLayerAlgorithm::displayName() const
35{
36 return QObject::tr( "Service area (from layer)" );
37}
38
39QStringList QgsServiceAreaFromLayerAlgorithm::tags() const
40{
41 return QObject::tr( "network,service,area,shortest,fastest" ).split( ',' );
42}
43
44QString QgsServiceAreaFromLayerAlgorithm::shortHelpString() const
45{
46 return QObject::tr(
47 "This algorithm creates a new vector layer with all the edges or parts of "
48 "edges of a network line layer that can be reached within a distance "
49 "or a time, starting from features of a point layer. The distance and "
50 "the time (both referred to as \"travel cost\") must be specified "
51 "respectively in the network layer units or in hours."
52 );
53}
54
55QString QgsServiceAreaFromLayerAlgorithm::shortDescription() const
56{
57 return QObject::tr(
58 "Creates a vector layer with all the edges or parts of "
59 "edges of a network line layer that can be reached within a distance "
60 "or a time, starting from features of a point layer."
61 );
62}
63
64QgsServiceAreaFromLayerAlgorithm *QgsServiceAreaFromLayerAlgorithm::createInstance() const
65{
66 return new QgsServiceAreaFromLayerAlgorithm();
67}
68
69void QgsServiceAreaFromLayerAlgorithm::initAlgorithm( const QVariantMap & )
70{
71 addCommonParams();
72 addParameter( new QgsProcessingParameterFeatureSource( u"START_POINTS"_s, QObject::tr( "Vector layer with start points" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
73
74 auto travelCost
75 = std::make_unique<QgsProcessingParameterNumber>( u"TRAVEL_COST"_s, QObject::tr( "Travel cost (distance for 'Shortest', time for 'Fastest')" ), Qgis::ProcessingNumberParameterType::Double, 0, true, 0 );
76 travelCost->setFlags( travelCost->flags() | Qgis::ProcessingParameterFlag::Hidden );
77 addParameter( std::move( travelCost ) );
78
79 auto travelCost2 = std::make_unique<
80 QgsProcessingParameterNumber>( u"TRAVEL_COST2"_s, QObject::tr( "Travel cost (distance for 'Shortest', time for 'Fastest')" ), Qgis::ProcessingNumberParameterType::Double, 0, false, 0 );
81 travelCost2->setIsDynamic( true );
82 travelCost2->setDynamicPropertyDefinition( QgsPropertyDefinition( u"Travel Cost"_s, QObject::tr( "Travel cost (distance for 'Shortest', time for 'Fastest')" ), QgsPropertyDefinition::DoublePositive ) );
83 travelCost2->setDynamicLayerParameterName( u"START_POINTS"_s );
84 addParameter( std::move( travelCost2 ) );
85
86 auto includeBounds = std::make_unique<QgsProcessingParameterBoolean>( u"INCLUDE_BOUNDS"_s, QObject::tr( "Include upper/lower bound points" ), false, true );
87 includeBounds->setFlags( includeBounds->flags() | Qgis::ProcessingParameterFlag::Advanced );
88 addParameter( includeBounds.release() );
89
90 std::unique_ptr<QgsProcessingParameterNumber> maxPointDistanceFromNetwork
91 = std::make_unique<QgsProcessingParameterDistance>( u"POINT_TOLERANCE"_s, QObject::tr( "Maximum point distance from network" ), QVariant(), u"INPUT"_s, true, 0 );
92 maxPointDistanceFromNetwork->setFlags( maxPointDistanceFromNetwork->flags() | Qgis::ProcessingParameterFlag::Advanced );
93 maxPointDistanceFromNetwork->setHelp(
94 QObject::tr( "Specifies an optional limit on the distance from the points to the network layer. If a point is further from the network than this distance it will be treated as non-routable." )
95 );
96 addParameter( maxPointDistanceFromNetwork.release() );
97
98 auto outputLines = std::make_unique<QgsProcessingParameterFeatureSink>( u"OUTPUT_LINES"_s, QObject::tr( "Service area (lines)" ), Qgis::ProcessingSourceType::VectorLine, QVariant(), true );
99 outputLines->setCreateByDefault( true );
100 addParameter( outputLines.release() );
101
102 auto outputPoints = std::make_unique<QgsProcessingParameterFeatureSink>( u"OUTPUT"_s, QObject::tr( "Service area (boundary nodes)" ), Qgis::ProcessingSourceType::VectorPoint, QVariant(), true );
103 outputPoints->setCreateByDefault( false );
104 addParameter( outputPoints.release() );
105
106 auto outputNonRoutable = std::make_unique<QgsProcessingParameterFeatureSink>( u"OUTPUT_NON_ROUTABLE"_s, QObject::tr( "Non-routable features" ), Qgis::ProcessingSourceType::VectorPoint, QVariant(), true );
107 outputNonRoutable->setHelp( QObject::tr( "An optional output which will be used to store any input features which could not be routed (e.g. those which are too far from the network layer)." ) );
108 outputNonRoutable->setCreateByDefault( false );
109 addParameter( outputNonRoutable.release() );
110}
111
112QVariantMap QgsServiceAreaFromLayerAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
113{
114 loadCommonParams( parameters, context, feedback );
115
116 std::unique_ptr<QgsProcessingFeatureSource> startPoints( parameterAsSource( parameters, u"START_POINTS"_s, context ) );
117 if ( !startPoints )
118 throw QgsProcessingException( invalidSourceError( parameters, u"START_POINTS"_s ) );
119
120 // use older deprecated travel cost style if specified, to maintain old api
121 const bool useOldTravelCost = parameters.value( u"TRAVEL_COST"_s ).isValid();
122 const double defaultTravelCost = parameterAsDouble( parameters, useOldTravelCost ? u"TRAVEL_COST"_s : u"TRAVEL_COST2"_s, context );
123
124 const bool dynamicTravelCost = QgsProcessingParameters::isDynamic( parameters, u"TRAVEL_COST2"_s );
125 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, startPoints.get() );
126 QgsProperty travelCostProperty;
127 if ( dynamicTravelCost )
128 {
129 travelCostProperty = parameters.value( u"TRAVEL_COST2"_s ).value<QgsProperty>();
130 }
131
132 const int strategy = parameterAsInt( parameters, u"STRATEGY"_s, context );
133 const double multiplier = ( strategy && !useOldTravelCost ) ? mMultiplier : 1;
134
135 bool includeBounds = true; // default to true to maintain 3.0 API
136 if ( parameters.contains( u"INCLUDE_BOUNDS"_s ) )
137 {
138 includeBounds = parameterAsBool( parameters, u"INCLUDE_BOUNDS"_s, context );
139 }
140
141 QVector<QgsPointXY> points;
142 QHash<int, QgsFeature> sourceFeatures;
143 loadPoints( startPoints.get(), &points, nullptr, context, feedback, &sourceFeatures );
144
145 feedback->pushInfo( QObject::tr( "Building graph…" ) );
146 QVector<QgsPointXY> snappedPoints;
147 mDirector->makeGraph( mBuilder.get(), points, snappedPoints, feedback );
148
149 feedback->pushInfo( QObject::tr( "Calculating service areas…" ) );
150 std::unique_ptr<QgsGraph> graph( mBuilder->takeGraph() );
151
152 QgsFields newFields;
153 newFields.append( QgsField( u"type"_s, QMetaType::Type::QString ) );
154 newFields.append( QgsField( u"start"_s, QMetaType::Type::QString ) );
155 QgsFields fields = QgsProcessingUtils::combineFields( startPoints->fields(), newFields );
156
157 QString pointsSinkId;
158 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, u"OUTPUT"_s, context, pointsSinkId, fields, Qgis::WkbType::MultiPoint, mNetwork->sourceCrs() ) );
159
160 QString linesSinkId;
161 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, u"OUTPUT_LINES"_s, context, linesSinkId, fields, Qgis::WkbType::MultiLineString, mNetwork->sourceCrs() ) );
162
163 QString nonRoutableSinkId;
164 std::unique_ptr<QgsFeatureSink> nonRoutableSink( parameterAsSink( parameters, u"OUTPUT_NON_ROUTABLE"_s, context, nonRoutableSinkId, startPoints->fields(), Qgis::WkbType::Point, mNetwork->sourceCrs() ) );
165
166 const double pointDistanceThreshold = parameters.value( u"POINT_TOLERANCE"_s ).isValid() ? parameterAsDouble( parameters, u"POINT_TOLERANCE"_s, context ) : -1;
167
168 int idxStart;
169 QVector<int> tree;
170 QVector<double> costs;
171
172 int inboundEdgeIndex;
173 double startVertexCost, endVertexCost;
174 QgsPointXY startPoint, endPoint;
175 QgsGraphEdge edge;
176
177 QgsFeature feat;
178 QgsAttributes attributes;
179
180 const double step = snappedPoints.size() > 0 ? 100.0 / snappedPoints.size() : 1;
181 for ( int i = 0; i < snappedPoints.size(); i++ )
182 {
183 if ( feedback->isCanceled() )
184 {
185 break;
186 }
187
188 double travelCost = defaultTravelCost;
189 if ( dynamicTravelCost )
190 {
191 expressionContext.setFeature( sourceFeatures.value( i + 1 ) );
192 travelCost = travelCostProperty.valueAsDouble( expressionContext, travelCost );
193 }
194 travelCost *= multiplier;
195
196 const QgsPointXY snappedPoint = snappedPoints.at( i );
197 const QgsPointXY originalPoint = points.at( i );
198
199 if ( pointDistanceThreshold >= 0 )
200 {
201 double distancePointToNetwork = 0;
202 try
203 {
204 distancePointToNetwork = mBuilder->distanceArea()->measureLine( originalPoint, snappedPoint );
205 }
206 catch ( QgsCsException & )
207 {
208 throw QgsProcessingException( QObject::tr( "An error occurred while calculating length" ) );
209 }
210
211 if ( distancePointToNetwork > pointDistanceThreshold )
212 {
213 feedback->pushWarning( QObject::tr( "Point is too far from the network layer (%1, maximum permitted is %2)" ).arg( distancePointToNetwork ).arg( pointDistanceThreshold ) );
214 if ( nonRoutableSink )
215 {
216 feat.setGeometry( QgsGeometry::fromPointXY( originalPoint ) );
217 attributes = sourceFeatures.value( i + 1 ).attributes();
218 feat.setAttributes( attributes );
219 if ( !nonRoutableSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
220 throw QgsProcessingException( writeFeatureError( nonRoutableSink.get(), parameters, u"OUTPUT_NON_ROUTABLE"_s ) );
221 }
222
223 feedback->setProgress( i * step );
224 continue;
225 }
226 }
227
228 const QString originalPointString = originalPoint.toString();
229
230 idxStart = graph->findVertex( snappedPoint );
231
232 QgsGraphAnalyzer::dijkstra( graph.get(), idxStart, 0, &tree, &costs );
233
234 QgsMultiPointXY areaPoints;
235 QgsMultiPolylineXY lines;
236 QSet<int> vertices;
237
238 for ( int j = 0; j < costs.size(); j++ )
239 {
240 inboundEdgeIndex = tree.at( j );
241
242 if ( inboundEdgeIndex == -1 && j != idxStart )
243 {
244 // unreachable vertex
245 continue;
246 }
247
248 startVertexCost = costs.at( j );
249 if ( startVertexCost > travelCost )
250 {
251 // vertex is too expensive, discard
252 continue;
253 }
254
255 vertices.insert( j );
256 startPoint = graph->vertex( j ).point();
257
258 // find all edges coming from this vertex
259 const QList<int> outgoingEdges = graph->vertex( j ).outgoingEdges();
260 for ( int edgeId : outgoingEdges )
261 {
262 edge = graph->edge( edgeId );
263 endVertexCost = startVertexCost + edge.cost( 0 ).toDouble();
264 endPoint = graph->vertex( edge.toVertex() ).point();
265 if ( endVertexCost <= travelCost )
266 {
267 // end vertex is cheap enough to include
268 vertices.insert( edge.toVertex() );
269 lines.push_back( QgsPolylineXY() << startPoint << endPoint );
270 }
271 else
272 {
273 // travelCost sits somewhere on this edge, interpolate position
274 QgsPointXY interpolatedEndPoint = QgsGeometryUtils::interpolatePointOnLineByValue( startPoint.x(), startPoint.y(), startVertexCost, endPoint.x(), endPoint.y(), endVertexCost, travelCost );
275
276 areaPoints.push_back( interpolatedEndPoint );
277 lines.push_back( QgsPolylineXY() << startPoint << interpolatedEndPoint );
278 }
279 } // edges
280 } // costs
281
282 // convert to list and sort to maintain same order of points between algorithm runs
283 QList<int> verticesList = qgis::setToList( vertices );
284 areaPoints.reserve( verticesList.size() );
285 std::sort( verticesList.begin(), verticesList.end() );
286 for ( int v : verticesList )
287 {
288 areaPoints.push_back( graph->vertex( v ).point() );
289 }
290
291 if ( pointsSink )
292 {
293 QgsGeometry geomPoints = QgsGeometry::fromMultiPointXY( areaPoints );
294 feat.setGeometry( geomPoints );
295 attributes = sourceFeatures.value( i + 1 ).attributes();
296 attributes << u"within"_s << originalPointString;
297 feat.setAttributes( attributes );
298 if ( !pointsSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
299 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT"_s ) );
300
301 if ( includeBounds )
302 {
303 QgsMultiPointXY upperBoundary, lowerBoundary;
304 QVector<int> nodes;
305 nodes.reserve( costs.size() );
306
307 int vertexId;
308 for ( int v = 0; v < costs.size(); v++ )
309 {
310 if ( costs.at( v ) > travelCost && tree.at( v ) != -1 )
311 {
312 vertexId = graph->edge( tree.at( v ) ).fromVertex();
313 if ( costs.at( vertexId ) <= travelCost )
314 {
315 nodes.push_back( v );
316 }
317 }
318 } // costs
319
320 upperBoundary.reserve( nodes.size() );
321 lowerBoundary.reserve( nodes.size() );
322 for ( int n : std::as_const( nodes ) )
323 {
324 upperBoundary.push_back( graph->vertex( graph->edge( tree.at( n ) ).toVertex() ).point() );
325 lowerBoundary.push_back( graph->vertex( graph->edge( tree.at( n ) ).fromVertex() ).point() );
326 } // nodes
327
328 QgsGeometry geomUpper = QgsGeometry::fromMultiPointXY( upperBoundary );
329 QgsGeometry geomLower = QgsGeometry::fromMultiPointXY( lowerBoundary );
330
331 feat.setGeometry( geomUpper );
332 attributes = sourceFeatures.value( i + 1 ).attributes();
333 attributes << u"upper"_s << originalPointString;
334 feat.setAttributes( attributes );
335 if ( !pointsSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
336 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT"_s ) );
337
338 feat.setGeometry( geomLower );
339 attributes = sourceFeatures.value( i + 1 ).attributes();
340 attributes << u"lower"_s << originalPointString;
341 feat.setAttributes( attributes );
342 if ( !pointsSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
343 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, u"OUTPUT"_s ) );
344 } // includeBounds
345 }
346
347 if ( linesSink )
348 {
350 feat.setGeometry( geomLines );
351 attributes = sourceFeatures.value( i + 1 ).attributes();
352 attributes << u"lines"_s << originalPointString;
353 feat.setAttributes( attributes );
354 if ( !linesSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
355 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, u"OUTPUT_LINES"_s ) );
356 }
357
358 feedback->setProgress( i * step );
359 } // snappedPoints
360
361 QVariantMap outputs;
362 if ( pointsSink )
363 {
364 pointsSink->finalize();
365 outputs.insert( u"OUTPUT"_s, pointsSinkId );
366 }
367 if ( linesSink )
368 {
369 linesSink->finalize();
370 outputs.insert( u"OUTPUT_LINES"_s, linesSinkId );
371 }
372 if ( nonRoutableSink )
373 {
374 nonRoutableSink->finalize();
375 outputs.insert( u"OUTPUT_NON_ROUTABLE"_s, nonRoutableSinkId );
376 }
377
378 return outputs;
379}
380
@ VectorPoint
Vector point layers.
Definition qgis.h:3648
@ VectorLine
Vector line layers.
Definition qgis.h:3649
@ Point
Point.
Definition qgis.h:296
@ MultiPoint
MultiPoint.
Definition qgis.h:300
@ MultiLineString
MultiLineString.
Definition qgis.h:301
@ Hidden
Parameter is hidden and should not be shown to users.
Definition qgis.h:3881
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3880
@ Double
Double/float values.
Definition qgis.h:3921
A vector of attributes.
Custom exception class for Coordinate Reference System related exceptions.
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.
@ 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
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
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 QgsPointXY interpolatePointOnLineByValue(double x1, double y1, double v1, double x2, double y2, double v2, double value)
Interpolates the position of a point along the line from (x1, y1) to (x2, y2).
A geometry is the spatial representation of a feature.
static QgsGeometry fromMultiPolylineXY(const QgsMultiPolylineXY &multiline)
Creates a new geometry from a QgsMultiPolylineXY object.
static QgsGeometry fromMultiPointXY(const QgsMultiPointXY &multipoint)
Creates a new geometry from a QgsMultiPointXY object.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
static void dijkstra(const QgsGraph *source, int startVertexIdx, int criterionNum, QVector< int > *resultTree=nullptr, QVector< double > *resultCost=nullptr)
Solve shortest path problem using Dijkstra algorithm.
Represents an edge in a graph.
Definition qgsgraph.h:44
int toVertex() const
Returns the index of the vertex at the end of this edge.
Definition qgsgraph.cpp:185
QVariant cost(int strategyIndex) const
Returns edge cost calculated using specified strategy.
Definition qgsgraph.cpp:170
Represents a 2D point.
Definition qgspointxy.h:62
QString toString(int precision=-1) const
Returns a string representation of the point (x, y) with a preset precision.
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
void setIsDynamic(bool dynamic)
Sets whether the parameter is dynamic, and can support data-defined values (i.e.
An input feature source (such as vector layers) parameter for processing algorithms.
A numeric 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:47
@ DoublePositive
Positive double value (including 0).
Definition qgsproperty.h:57
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.
QVector< QgsPolylineXY > QgsMultiPolylineXY
A collection of QgsPolylines that share a common collection of attributes.
QVector< QgsPointXY > QgsMultiPointXY
A collection of QgsPoints that share a common collection of attributes.
Definition qgsgeometry.h:98
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.
Definition qgsgeometry.h:63