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