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