25QString QgsServiceAreaFromLayerAlgorithm::name()
const
27 return QStringLiteral(
"serviceareafromlayer" );
30QString QgsServiceAreaFromLayerAlgorithm::displayName()
const
32 return QObject::tr(
"Service area (from layer)" );
35QStringList QgsServiceAreaFromLayerAlgorithm::tags()
const
37 return QObject::tr(
"network,service,area,shortest,fastest" ).split(
',' );
40QString QgsServiceAreaFromLayerAlgorithm::shortHelpString()
const
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." );
49QgsServiceAreaFromLayerAlgorithm *QgsServiceAreaFromLayerAlgorithm::createInstance()
const
51 return new QgsServiceAreaFromLayerAlgorithm();
54void QgsServiceAreaFromLayerAlgorithm::initAlgorithm(
const QVariantMap & )
59 std::unique_ptr<QgsProcessingParameterNumber> travelCost = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral(
"TRAVEL_COST" ), QObject::tr(
"Travel cost (distance for 'Shortest', time for 'Fastest')" ),
Qgis::ProcessingNumberParameterType::Double, 0,
true, 0 );
61 addParameter( travelCost.release() );
65 std::unique_ptr<QgsProcessingParameterBoolean> includeBounds = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral(
"INCLUDE_BOUNDS" ), QObject::tr(
"Include upper/lower bound points" ),
false,
true );
67 addParameter( includeBounds.release() );
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 );
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() );
74 std::unique_ptr<QgsProcessingParameterFeatureSink> 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() );
78 std::unique_ptr<QgsProcessingParameterFeatureSink> 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() );
82 std::unique_ptr<QgsProcessingParameterFeatureSink> 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() );
90 loadCommonParams( parameters, context, feedback );
92 std::unique_ptr<QgsFeatureSource> startPoints( parameterAsSource( parameters, QStringLiteral(
"START_POINTS" ), context ) );
97 const bool useOldTravelCost = parameters.value( QStringLiteral(
"TRAVEL_COST" ) ).isValid();
98 double travelCost = parameterAsDouble( parameters, useOldTravelCost ? QStringLiteral(
"TRAVEL_COST" ) : QStringLiteral(
"TRAVEL_COST2" ), context );
100 int strategy = parameterAsInt( parameters, QStringLiteral(
"STRATEGY" ), context );
101 if ( strategy && !useOldTravelCost )
102 travelCost *= mMultiplier;
104 bool includeBounds =
true;
105 if ( parameters.contains( QStringLiteral(
"INCLUDE_BOUNDS" ) ) )
107 includeBounds = parameterAsBool( parameters, QStringLiteral(
"INCLUDE_BOUNDS" ), context );
110 QVector<QgsPointXY> points;
111 QHash<int, QgsAttributes> sourceAttributes;
112 loadPoints( startPoints.get(), points, sourceAttributes, context, feedback );
114 feedback->
pushInfo( QObject::tr(
"Building graph…" ) );
115 QVector<QgsPointXY> snappedPoints;
116 mDirector->makeGraph( mBuilder.get(), points, snappedPoints, feedback );
118 feedback->
pushInfo( QObject::tr(
"Calculating service areas…" ) );
119 std::unique_ptr<QgsGraph> graph( mBuilder->takeGraph() );
121 QgsFields fields = startPoints->fields();
122 fields.
append(
QgsField( QStringLiteral(
"type" ), QMetaType::Type::QString ) );
123 fields.
append(
QgsField( QStringLiteral(
"start" ), QMetaType::Type::QString ) );
125 QString pointsSinkId;
126 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT" ), context, pointsSinkId, fields,
Qgis::WkbType::MultiPoint, mNetwork->sourceCrs() ) );
129 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT_LINES" ), context, linesSinkId, fields,
Qgis::WkbType::MultiLineString, mNetwork->sourceCrs() ) );
131 QString nonRoutableSinkId;
132 std::unique_ptr<QgsFeatureSink> nonRoutableSink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT_NON_ROUTABLE" ), context, nonRoutableSinkId, startPoints->fields(),
Qgis::WkbType::Point, mNetwork->sourceCrs() ) );
134 const double pointDistanceThreshold = parameters.value( QStringLiteral(
"POINT_TOLERANCE" ) ).isValid() ? parameterAsDouble( parameters, QStringLiteral(
"POINT_TOLERANCE" ), context ) : -1;
138 QVector<double> costs;
140 int inboundEdgeIndex;
141 double startVertexCost, endVertexCost;
148 const double step = snappedPoints.size() > 0 ? 100.0 / snappedPoints.size() : 1;
149 for (
int i = 0; i < snappedPoints.size(); i++ )
156 const QgsPointXY snappedPoint = snappedPoints.at( i );
157 const QgsPointXY originalPoint = points.at( i );
159 if ( pointDistanceThreshold >= 0 )
161 double distancePointToNetwork = 0;
164 distancePointToNetwork = mBuilder->distanceArea()->measureLine( originalPoint, snappedPoint );
171 if ( distancePointToNetwork > pointDistanceThreshold )
173 feedback->
pushWarning( QObject::tr(
"Point is too far from the network layer (%1, maximum permitted is %2)" ).arg( distancePointToNetwork ).arg( pointDistanceThreshold ) );
174 if ( nonRoutableSink )
177 attributes = sourceAttributes.value( i + 1 );
180 throw QgsProcessingException( writeFeatureError( nonRoutableSink.get(), parameters, QStringLiteral(
"OUTPUT_NON_ROUTABLE" ) ) );
188 const QString originalPointString = originalPoint.
toString();
190 idxStart = graph->findVertex( snappedPoint );
198 for (
int j = 0; j < costs.size(); j++ )
200 inboundEdgeIndex = tree.at( j );
202 if ( inboundEdgeIndex == -1 && j != idxStart )
208 startVertexCost = costs.at( j );
209 if ( startVertexCost > travelCost )
215 vertices.insert( j );
216 startPoint = graph->vertex( j ).point();
219 const QList<int> outgoingEdges = graph->vertex( j ).outgoingEdges();
220 for (
int edgeId : outgoingEdges )
222 edge = graph->edge( edgeId );
223 endVertexCost = startVertexCost + edge.
cost( 0 ).toDouble();
224 endPoint = graph->vertex( edge.
toVertex() ).point();
225 if ( endVertexCost <= travelCost )
229 lines.push_back(
QgsPolylineXY() << startPoint << endPoint );
236 areaPoints.push_back( interpolatedEndPoint );
237 lines.push_back(
QgsPolylineXY() << startPoint << interpolatedEndPoint );
243 QList<int> verticesList = qgis::setToList( vertices );
244 areaPoints.reserve( verticesList.size() );
245 std::sort( verticesList.begin(), verticesList.end() );
246 for (
int v : verticesList )
248 areaPoints.push_back( graph->vertex( v ).point() );
255 attributes = sourceAttributes.value( i + 1 );
256 attributes << QStringLiteral(
"within" ) << originalPointString;
259 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral(
"OUTPUT" ) ) );
265 nodes.reserve( costs.size() );
268 for (
int v = 0; v < costs.size(); v++ )
270 if ( costs.at( v ) > travelCost && tree.at( v ) != -1 )
272 vertexId = graph->edge( tree.at( v ) ).fromVertex();
273 if ( costs.at( vertexId ) <= travelCost )
275 nodes.push_back( v );
280 upperBoundary.reserve( nodes.size() );
281 lowerBoundary.reserve( nodes.size() );
282 for (
int n : std::as_const( nodes ) )
284 upperBoundary.push_back( graph->vertex( graph->edge( tree.at( n ) ).toVertex() ).point() );
285 lowerBoundary.push_back( graph->vertex( graph->edge( tree.at( n ) ).fromVertex() ).point() );
292 attributes = sourceAttributes.value( i + 1 );
293 attributes << QStringLiteral(
"upper" ) << originalPointString;
296 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral(
"OUTPUT" ) ) );
299 attributes = sourceAttributes.value( i + 1 );
300 attributes << QStringLiteral(
"lower" ) << originalPointString;
303 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral(
"OUTPUT" ) ) );
311 attributes = sourceAttributes.value( i + 1 );
312 attributes << QStringLiteral(
"lines" ) << originalPointString;
315 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, QStringLiteral(
"OUTPUT_LINES" ) ) );
324 pointsSink->finalize();
325 outputs.insert( QStringLiteral(
"OUTPUT" ), pointsSinkId );
329 linesSink->finalize();
330 outputs.insert( QStringLiteral(
"OUTPUT_LINES" ), linesSinkId );
332 if ( nonRoutableSink )
334 nonRoutableSink->finalize();
335 outputs.insert( QStringLiteral(
"OUTPUT_NON_ROUTABLE" ), nonRoutableSinkId );
@ VectorPoint
Vector point layers.
@ VectorLine
Vector line layers.
@ 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.
@ Double
Double/float values.
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...
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.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
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.
This class implements a graph edge.
int toVertex() const
Returns the index of the vertex at the end of this edge.
QVariant cost(int strategyIndex) const
Returns edge cost calculated using specified strategy.
A class to represent a 2D point.
QString toString(int precision=-1) const
Returns a string representation of the point (x, y) with a preset precision.
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.
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.
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.