QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmserviceareafrompoint.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmserviceareafrompoint.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 QgsServiceAreaFromPointAlgorithm::name() const
26{
27 return QStringLiteral( "serviceareafrompoint" );
28}
29
30QString QgsServiceAreaFromPointAlgorithm::displayName() const
31{
32 return QObject::tr( "Service area (from point)" );
33}
34
35QStringList QgsServiceAreaFromPointAlgorithm::tags() const
36{
37 return QObject::tr( "network,service,area,shortest,fastest" ).split( ',' );
38}
39
40QString QgsServiceAreaFromPointAlgorithm::shortHelpString() const
41{
42 return QObject::tr( "This algorithm creates a new vector layer with all the edges or parts of edges "
43 "of a network line layer that can be reached within a distance or a time, "
44 "starting from a point feature. The distance and the time (both referred to "
45 "as \"travel cost\") must be specified respectively in the network layer "
46 "units or in hours." );
47}
48
49QString QgsServiceAreaFromPointAlgorithm::shortDescription() const
50{
51 return QObject::tr( "Creates a vector layer with all the edges or parts of edges "
52 "of a network line layer that can be reached within a distance or a time, "
53 "starting from a point feature." );
54}
55
56QgsServiceAreaFromPointAlgorithm *QgsServiceAreaFromPointAlgorithm::createInstance() const
57{
58 return new QgsServiceAreaFromPointAlgorithm();
59}
60
61void QgsServiceAreaFromPointAlgorithm::initAlgorithm( const QVariantMap & )
62{
63 addCommonParams();
64 addParameter( new QgsProcessingParameterPoint( QStringLiteral( "START_POINT" ), QObject::tr( "Start point" ) ) );
65
66 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 );
67 travelCost->setFlags( travelCost->flags() | Qgis::ProcessingParameterFlag::Hidden );
68 addParameter( travelCost.release() );
69
70 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "TRAVEL_COST2" ), QObject::tr( "Travel cost (distance for 'Shortest', time for 'Fastest')" ), Qgis::ProcessingNumberParameterType::Double, 0, false, 0 ) );
71
72 std::unique_ptr<QgsProcessingParameterNumber> maxPointDistanceFromNetwork = std::make_unique<QgsProcessingParameterDistance>( QStringLiteral( "POINT_TOLERANCE" ), QObject::tr( "Maximum point distance from network" ), QVariant(), QStringLiteral( "INPUT" ), true, 0 );
73 maxPointDistanceFromNetwork->setFlags( maxPointDistanceFromNetwork->flags() | Qgis::ProcessingParameterFlag::Advanced );
74 maxPointDistanceFromNetwork->setHelp( QObject::tr( "Specifies an optional limit on the distance from the point to the network layer. If the point is further from the network than this distance an error will be raised." ) );
75 addParameter( maxPointDistanceFromNetwork.release() );
76
77 auto includeBounds = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "INCLUDE_BOUNDS" ), QObject::tr( "Include upper/lower bound points" ), false, true );
78 includeBounds->setFlags( includeBounds->flags() | Qgis::ProcessingParameterFlag::Advanced );
79 addParameter( includeBounds.release() );
80
81 auto outputLines = std::make_unique<QgsProcessingParameterFeatureSink>( QStringLiteral( "OUTPUT_LINES" ), QObject::tr( "Service area (lines)" ), Qgis::ProcessingSourceType::VectorLine, QVariant(), true );
82 outputLines->setCreateByDefault( true );
83 addParameter( outputLines.release() );
84
85 auto outputPoints = std::make_unique<QgsProcessingParameterFeatureSink>( QStringLiteral( "OUTPUT" ), QObject::tr( "Service area (boundary nodes)" ), Qgis::ProcessingSourceType::VectorPoint, QVariant(), true );
86 outputPoints->setCreateByDefault( false );
87 addParameter( outputPoints.release() );
88}
89
90QVariantMap QgsServiceAreaFromPointAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
91{
92 loadCommonParams( parameters, context, feedback );
93
94 const QgsPointXY startPoint = parameterAsPoint( parameters, QStringLiteral( "START_POINT" ), context, mNetwork->sourceCrs() );
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 const 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 feedback->pushInfo( QObject::tr( "Building graph…" ) );
111 QVector<QgsPointXY> snappedPoints;
112 mDirector->makeGraph( mBuilder.get(), { startPoint }, snappedPoints, feedback );
113 const QgsPointXY snappedStartPoint = snappedPoints[0];
114
115 // check distance for the snapped point
116 if ( parameters.value( QStringLiteral( "POINT_TOLERANCE" ) ).isValid() )
117 {
118 const double pointDistanceThreshold = parameterAsDouble( parameters, QStringLiteral( "POINT_TOLERANCE" ), context );
119
120 double distancePointToNetwork = 0;
121 try
122 {
123 distancePointToNetwork = mBuilder->distanceArea()->measureLine( startPoint, snappedStartPoint );
124 }
125 catch ( QgsCsException & )
126 {
127 throw QgsProcessingException( QObject::tr( "An error occurred while calculating length" ) );
128 }
129
130
131 if ( distancePointToNetwork > pointDistanceThreshold )
132 {
133 throw QgsProcessingException( QObject::tr( "Point is too far from the network layer (%1, maximum permitted is %2)" ).arg( distancePointToNetwork ).arg( pointDistanceThreshold ) );
134 }
135 }
136
137 feedback->pushInfo( QObject::tr( "Calculating service area…" ) );
138 std::unique_ptr<QgsGraph> graph( mBuilder->takeGraph() );
139 const int idxStart = graph->findVertex( snappedStartPoint );
140
141 QVector<int> tree;
142 QVector<double> costs;
143 QgsGraphAnalyzer::dijkstra( graph.get(), idxStart, 0, &tree, &costs );
144
145 QgsMultiPointXY points;
146 QgsMultiPolylineXY lines;
147 QSet<int> vertices;
148
149 int inboundEdgeIndex;
150 double startVertexCost, endVertexCost;
151 QgsPointXY edgeStart, edgeEnd;
152 QgsGraphEdge edge;
153
154 for ( int i = 0; i < costs.size(); i++ )
155 {
156 inboundEdgeIndex = tree.at( i );
157 if ( inboundEdgeIndex == -1 && i != idxStart )
158 {
159 // unreachable vertex
160 continue;
161 }
162
163 startVertexCost = costs.at( i );
164 if ( startVertexCost > travelCost )
165 {
166 // vertex is too expensive, discard
167 continue;
168 }
169
170 vertices.insert( i );
171 edgeStart = graph->vertex( i ).point();
172
173 // find all edges coming from this vertex
174 const QList<int> outgoingEdges = graph->vertex( i ).outgoingEdges();
175 for ( const int edgeId : outgoingEdges )
176 {
177 edge = graph->edge( edgeId );
178 endVertexCost = startVertexCost + edge.cost( 0 ).toDouble();
179 edgeEnd = graph->vertex( edge.toVertex() ).point();
180 if ( endVertexCost <= travelCost )
181 {
182 // end vertex is cheap enough to include
183 vertices.insert( edge.toVertex() );
184 lines.push_back( QgsPolylineXY() << edgeStart << edgeEnd );
185 }
186 else
187 {
188 // travelCost sits somewhere on this edge, interpolate position
189 const QgsPointXY interpolatedEndPoint = QgsGeometryUtils::interpolatePointOnLineByValue( edgeStart.x(), edgeStart.y(), startVertexCost, edgeEnd.x(), edgeEnd.y(), endVertexCost, travelCost );
190
191 points.push_back( interpolatedEndPoint );
192 lines.push_back( QgsPolylineXY() << edgeStart << interpolatedEndPoint );
193 }
194 } // edges
195 } // costs
196
197 // convert to list and sort to maintain same order of points between algorithm runs
198 QList<int> verticesList = qgis::setToList( vertices );
199 points.reserve( verticesList.size() );
200 std::sort( verticesList.begin(), verticesList.end() );
201 for ( const int v : verticesList )
202 {
203 points.push_back( graph->vertex( v ).point() );
204 }
205
206 feedback->pushInfo( QObject::tr( "Writing results…" ) );
207
208 QVariantMap outputs;
209
210 QgsFields fields;
211 fields.append( QgsField( QStringLiteral( "type" ), QMetaType::Type::QString ) );
212 fields.append( QgsField( QStringLiteral( "start" ), QMetaType::Type::QString ) );
213
214 QgsFeature feat;
215 feat.setFields( fields );
216
217 QString pointsSinkId;
218 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, pointsSinkId, fields, Qgis::WkbType::MultiPoint, mNetwork->sourceCrs() ) );
219
220 if ( pointsSink )
221 {
222 outputs.insert( QStringLiteral( "OUTPUT" ), pointsSinkId );
223
224 const QgsGeometry geomPoints = QgsGeometry::fromMultiPointXY( points );
225 feat.setGeometry( geomPoints );
226 feat.setAttributes( QgsAttributes() << QStringLiteral( "within" ) << startPoint.toString() );
227 if ( !pointsSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
228 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
229
230 if ( includeBounds )
231 {
232 QgsMultiPointXY upperBoundary, lowerBoundary;
233 QVector<int> nodes;
234
235 int vertexId;
236 for ( int i = 0; i < costs.size(); i++ )
237 {
238 if ( costs.at( i ) > travelCost && tree.at( i ) != -1 )
239 {
240 vertexId = graph->edge( tree.at( i ) ).fromVertex();
241 if ( costs.at( vertexId ) <= travelCost )
242 {
243 nodes.push_back( i );
244 }
245 }
246 } // costs
247
248 upperBoundary.reserve( nodes.size() );
249 lowerBoundary.reserve( nodes.size() );
250 for ( const int i : nodes )
251 {
252 upperBoundary.push_back( graph->vertex( graph->edge( tree.at( i ) ).toVertex() ).point() );
253 lowerBoundary.push_back( graph->vertex( graph->edge( tree.at( i ) ).fromVertex() ).point() );
254 } // nodes
255
256 const QgsGeometry geomUpper = QgsGeometry::fromMultiPointXY( upperBoundary );
257 const QgsGeometry geomLower = QgsGeometry::fromMultiPointXY( lowerBoundary );
258
259 feat.setGeometry( geomUpper );
260 feat.setAttributes( QgsAttributes() << QStringLiteral( "upper" ) << startPoint.toString() );
261 if ( !pointsSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
262 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
263
264 feat.setGeometry( geomLower );
265 feat.setAttributes( QgsAttributes() << QStringLiteral( "lower" ) << startPoint.toString() );
266 if ( !pointsSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
267 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
268 } // includeBounds
269
270 pointsSink->finalize();
271 }
272
273 QString linesSinkId;
274 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, QStringLiteral( "OUTPUT_LINES" ), context, linesSinkId, fields, Qgis::WkbType::MultiLineString, mNetwork->sourceCrs() ) );
275
276 if ( linesSink )
277 {
278 outputs.insert( QStringLiteral( "OUTPUT_LINES" ), linesSinkId );
279 const QgsGeometry geomLines = QgsGeometry::fromMultiPolylineXY( lines );
280 feat.setGeometry( geomLines );
281 feat.setAttributes( QgsAttributes() << QStringLiteral( "lines" ) << startPoint.toString() );
282 if ( !linesSink->addFeature( feat, QgsFeatureSink::FastInsert ) )
283 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, QStringLiteral( "OUTPUT_LINES" ) ) );
284 linesSink->finalize();
285 }
286
287 return outputs;
288}
289
@ 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 setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
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 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.
A numeric parameter for processing algorithms.
A point parameter for processing algorithms.
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