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 layer 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." );
49QString QgsServiceAreaFromLayerAlgorithm::shortDescription()
const
51 return QObject::tr(
"Creates a vector layer with all the edges or parts of "
52 "edges of a network line layer that can be reached within a distance "
53 "or a time, starting from features of a point layer." );
56QgsServiceAreaFromLayerAlgorithm *QgsServiceAreaFromLayerAlgorithm::createInstance()
const
58 return new QgsServiceAreaFromLayerAlgorithm();
61void QgsServiceAreaFromLayerAlgorithm::initAlgorithm(
const QVariantMap & )
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 );
68 addParameter( travelCost.release() );
72 auto includeBounds = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral(
"INCLUDE_BOUNDS" ), QObject::tr(
"Include upper/lower bound points" ),
false,
true );
74 addParameter( includeBounds.release() );
76 std::unique_ptr<QgsProcessingParameterNumber> maxPointDistanceFromNetwork = std::make_unique<QgsProcessingParameterDistance>( QStringLiteral(
"POINT_TOLERANCE" ), QObject::tr(
"Maximum point distance from network" ), QVariant(), QStringLiteral(
"INPUT" ),
true, 0 );
78 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." ) );
79 addParameter( maxPointDistanceFromNetwork.release() );
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() );
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() );
89 auto outputNonRoutable = std::make_unique<QgsProcessingParameterFeatureSink>( QStringLiteral(
"OUTPUT_NON_ROUTABLE" ), QObject::tr(
"Non-routable features" ),
Qgis::ProcessingSourceType::VectorPoint, QVariant(),
true );
90 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)." ) );
91 outputNonRoutable->setCreateByDefault(
false );
92 addParameter( outputNonRoutable.release() );
97 loadCommonParams( parameters, context, feedback );
99 std::unique_ptr<QgsFeatureSource> startPoints( parameterAsSource( parameters, QStringLiteral(
"START_POINTS" ), context ) );
104 const bool useOldTravelCost = parameters.value( QStringLiteral(
"TRAVEL_COST" ) ).isValid();
105 double travelCost = parameterAsDouble( parameters, useOldTravelCost ? QStringLiteral(
"TRAVEL_COST" ) : QStringLiteral(
"TRAVEL_COST2" ), context );
107 int strategy = parameterAsInt( parameters, QStringLiteral(
"STRATEGY" ), context );
108 if ( strategy && !useOldTravelCost )
109 travelCost *= mMultiplier;
111 bool includeBounds =
true;
112 if ( parameters.contains( QStringLiteral(
"INCLUDE_BOUNDS" ) ) )
114 includeBounds = parameterAsBool( parameters, QStringLiteral(
"INCLUDE_BOUNDS" ), context );
117 QVector<QgsPointXY> points;
118 QHash<int, QgsAttributes> sourceAttributes;
119 loadPoints( startPoints.get(), points, sourceAttributes, context, feedback );
121 feedback->
pushInfo( QObject::tr(
"Building graph…" ) );
122 QVector<QgsPointXY> snappedPoints;
123 mDirector->makeGraph( mBuilder.get(), points, snappedPoints, feedback );
125 feedback->
pushInfo( QObject::tr(
"Calculating service areas…" ) );
126 std::unique_ptr<QgsGraph> graph( mBuilder->takeGraph() );
129 newFields.
append(
QgsField( QStringLiteral(
"type" ), QMetaType::Type::QString ) );
130 newFields.
append(
QgsField( QStringLiteral(
"start" ), QMetaType::Type::QString ) );
133 QString pointsSinkId;
134 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT" ), context, pointsSinkId, fields,
Qgis::WkbType::MultiPoint, mNetwork->sourceCrs() ) );
137 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT_LINES" ), context, linesSinkId, fields,
Qgis::WkbType::MultiLineString, mNetwork->sourceCrs() ) );
139 QString nonRoutableSinkId;
140 std::unique_ptr<QgsFeatureSink> nonRoutableSink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT_NON_ROUTABLE" ), context, nonRoutableSinkId, startPoints->fields(),
Qgis::WkbType::Point, mNetwork->sourceCrs() ) );
142 const double pointDistanceThreshold = parameters.value( QStringLiteral(
"POINT_TOLERANCE" ) ).isValid() ? parameterAsDouble( parameters, QStringLiteral(
"POINT_TOLERANCE" ), context ) : -1;
146 QVector<double> costs;
148 int inboundEdgeIndex;
149 double startVertexCost, endVertexCost;
156 const double step = snappedPoints.size() > 0 ? 100.0 / snappedPoints.size() : 1;
157 for (
int i = 0; i < snappedPoints.size(); i++ )
164 const QgsPointXY snappedPoint = snappedPoints.at( i );
165 const QgsPointXY originalPoint = points.at( i );
167 if ( pointDistanceThreshold >= 0 )
169 double distancePointToNetwork = 0;
172 distancePointToNetwork = mBuilder->distanceArea()->measureLine( originalPoint, snappedPoint );
179 if ( distancePointToNetwork > pointDistanceThreshold )
181 feedback->
pushWarning( QObject::tr(
"Point is too far from the network layer (%1, maximum permitted is %2)" ).arg( distancePointToNetwork ).arg( pointDistanceThreshold ) );
182 if ( nonRoutableSink )
185 attributes = sourceAttributes.value( i + 1 );
188 throw QgsProcessingException( writeFeatureError( nonRoutableSink.get(), parameters, QStringLiteral(
"OUTPUT_NON_ROUTABLE" ) ) );
196 const QString originalPointString = originalPoint.
toString();
198 idxStart = graph->findVertex( snappedPoint );
206 for (
int j = 0; j < costs.size(); j++ )
208 inboundEdgeIndex = tree.at( j );
210 if ( inboundEdgeIndex == -1 && j != idxStart )
216 startVertexCost = costs.at( j );
217 if ( startVertexCost > travelCost )
223 vertices.insert( j );
224 startPoint = graph->vertex( j ).point();
227 const QList<int> outgoingEdges = graph->vertex( j ).outgoingEdges();
228 for (
int edgeId : outgoingEdges )
230 edge = graph->edge( edgeId );
231 endVertexCost = startVertexCost + edge.
cost( 0 ).toDouble();
232 endPoint = graph->vertex( edge.
toVertex() ).point();
233 if ( endVertexCost <= travelCost )
237 lines.push_back(
QgsPolylineXY() << startPoint << endPoint );
244 areaPoints.push_back( interpolatedEndPoint );
245 lines.push_back(
QgsPolylineXY() << startPoint << interpolatedEndPoint );
251 QList<int> verticesList = qgis::setToList( vertices );
252 areaPoints.reserve( verticesList.size() );
253 std::sort( verticesList.begin(), verticesList.end() );
254 for (
int v : verticesList )
256 areaPoints.push_back( graph->vertex( v ).point() );
263 attributes = sourceAttributes.value( i + 1 );
264 attributes << QStringLiteral(
"within" ) << originalPointString;
267 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral(
"OUTPUT" ) ) );
273 nodes.reserve( costs.size() );
276 for (
int v = 0; v < costs.size(); v++ )
278 if ( costs.at( v ) > travelCost && tree.at( v ) != -1 )
280 vertexId = graph->edge( tree.at( v ) ).fromVertex();
281 if ( costs.at( vertexId ) <= travelCost )
283 nodes.push_back( v );
288 upperBoundary.reserve( nodes.size() );
289 lowerBoundary.reserve( nodes.size() );
290 for (
int n : std::as_const( nodes ) )
292 upperBoundary.push_back( graph->vertex( graph->edge( tree.at( n ) ).toVertex() ).point() );
293 lowerBoundary.push_back( graph->vertex( graph->edge( tree.at( n ) ).fromVertex() ).point() );
300 attributes = sourceAttributes.value( i + 1 );
301 attributes << QStringLiteral(
"upper" ) << originalPointString;
304 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral(
"OUTPUT" ) ) );
307 attributes = sourceAttributes.value( i + 1 );
308 attributes << QStringLiteral(
"lower" ) << originalPointString;
311 throw QgsProcessingException( writeFeatureError( pointsSink.get(), parameters, QStringLiteral(
"OUTPUT" ) ) );
319 attributes = sourceAttributes.value( i + 1 );
320 attributes << QStringLiteral(
"lines" ) << originalPointString;
323 throw QgsProcessingException( writeFeatureError( linesSink.get(), parameters, QStringLiteral(
"OUTPUT_LINES" ) ) );
332 pointsSink->finalize();
333 outputs.insert( QStringLiteral(
"OUTPUT" ), pointsSinkId );
337 linesSink->finalize();
338 outputs.insert( QStringLiteral(
"OUTPUT_LINES" ), linesSinkId );
340 if ( nonRoutableSink )
342 nonRoutableSink->finalize();
343 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.
Represents an edge in a graph.
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.
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.
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.
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.