25using namespace Qt::StringLiterals;
29QString QgsServiceAreaFromLayerAlgorithm::name()
const
31 return u
"serviceareafromlayer"_s;
34QString QgsServiceAreaFromLayerAlgorithm::displayName()
const
36 return QObject::tr(
"Service area (from layer)" );
39QStringList QgsServiceAreaFromLayerAlgorithm::tags()
const
41 return QObject::tr(
"network,service,area,shortest,fastest" ).split(
',' );
44QString QgsServiceAreaFromLayerAlgorithm::shortHelpString()
const
47 "This algorithm creates a new vector layer with all the edges or parts of "
48 "edges of a network line layer that can be reached within a distance "
49 "or a time, starting from features of a point layer. The distance and "
50 "the time (both referred to as \"travel cost\") must be specified "
51 "respectively in the network layer units or in hours."
55QString QgsServiceAreaFromLayerAlgorithm::shortDescription()
const
58 "Creates a vector layer with all the edges or parts of "
59 "edges of a network line layer that can be reached within a distance "
60 "or a time, starting from features of a point layer."
64QgsServiceAreaFromLayerAlgorithm *QgsServiceAreaFromLayerAlgorithm::createInstance()
const
66 return new QgsServiceAreaFromLayerAlgorithm();
69void QgsServiceAreaFromLayerAlgorithm::initAlgorithm(
const QVariantMap & )
77 addParameter( std::move( travelCost ) );
79 auto travelCost2 = std::make_unique<
83 travelCost2->setDynamicLayerParameterName( u
"START_POINTS"_s );
84 addParameter( std::move( travelCost2 ) );
86 auto includeBounds = std::make_unique<QgsProcessingParameterBoolean>( u
"INCLUDE_BOUNDS"_s, QObject::tr(
"Include upper/lower bound points" ),
false,
true );
88 addParameter( includeBounds.release() );
90 std::unique_ptr<QgsProcessingParameterNumber> maxPointDistanceFromNetwork
91 = std::make_unique<QgsProcessingParameterDistance>( u
"POINT_TOLERANCE"_s, QObject::tr(
"Maximum point distance from network" ), QVariant(), u
"INPUT"_s,
true, 0 );
93 maxPointDistanceFromNetwork->setHelp(
94 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." )
96 addParameter( maxPointDistanceFromNetwork.release() );
98 auto outputLines = std::make_unique<QgsProcessingParameterFeatureSink>( u
"OUTPUT_LINES"_s, QObject::tr(
"Service area (lines)" ),
Qgis::ProcessingSourceType::VectorLine, QVariant(),
true );
99 outputLines->setCreateByDefault(
true );
100 addParameter( outputLines.release() );
102 auto outputPoints = std::make_unique<QgsProcessingParameterFeatureSink>( u
"OUTPUT"_s, QObject::tr(
"Service area (boundary nodes)" ),
Qgis::ProcessingSourceType::VectorPoint, QVariant(),
true );
103 outputPoints->setCreateByDefault(
false );
104 addParameter( outputPoints.release() );
106 auto outputNonRoutable = std::make_unique<QgsProcessingParameterFeatureSink>( u
"OUTPUT_NON_ROUTABLE"_s, QObject::tr(
"Non-routable features" ),
Qgis::ProcessingSourceType::VectorPoint, QVariant(),
true );
107 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)." ) );
108 outputNonRoutable->setCreateByDefault(
false );
109 addParameter( outputNonRoutable.release() );
114 loadCommonParams( parameters, context, feedback );
116 std::unique_ptr<QgsProcessingFeatureSource> startPoints( parameterAsSource( parameters, u
"START_POINTS"_s, context ) );
121 const bool useOldTravelCost = parameters.value( u
"TRAVEL_COST"_s ).isValid();
122 const double defaultTravelCost = parameterAsDouble( parameters, useOldTravelCost ? u
"TRAVEL_COST"_s : u
"TRAVEL_COST2"_s, context );
125 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, startPoints.get() );
127 if ( dynamicTravelCost )
129 travelCostProperty = parameters.
value( u
"TRAVEL_COST2"_s ).value<
QgsProperty>();
132 const int strategy = parameterAsInt( parameters, u
"STRATEGY"_s, context );
133 const double multiplier = ( strategy && !useOldTravelCost ) ? mMultiplier : 1;
135 bool includeBounds =
true;
136 if ( parameters.contains( u
"INCLUDE_BOUNDS"_s ) )
138 includeBounds = parameterAsBool( parameters, u
"INCLUDE_BOUNDS"_s, context );
141 QVector<QgsPointXY> points;
142 QHash<int, QgsFeature> sourceFeatures;
143 loadPoints( startPoints.get(), &points,
nullptr, context, feedback, &sourceFeatures );
145 feedback->
pushInfo( QObject::tr(
"Building graph…" ) );
146 QVector<QgsPointXY> snappedPoints;
147 mDirector->makeGraph( mBuilder.get(), points, snappedPoints, feedback );
149 feedback->
pushInfo( QObject::tr(
"Calculating service areas…" ) );
150 std::unique_ptr<QgsGraph> graph( mBuilder->takeGraph() );
153 newFields.
append(
QgsField( u
"type"_s, QMetaType::Type::QString ) );
154 newFields.
append(
QgsField( u
"start"_s, QMetaType::Type::QString ) );
157 QString pointsSinkId;
158 std::unique_ptr<QgsFeatureSink> pointsSink( parameterAsSink( parameters, u
"OUTPUT"_s, context, pointsSinkId, fields,
Qgis::WkbType::MultiPoint, mNetwork->sourceCrs() ) );
161 std::unique_ptr<QgsFeatureSink> linesSink( parameterAsSink( parameters, u
"OUTPUT_LINES"_s, context, linesSinkId, fields,
Qgis::WkbType::MultiLineString, mNetwork->sourceCrs() ) );
163 QString nonRoutableSinkId;
164 std::unique_ptr<QgsFeatureSink> nonRoutableSink( parameterAsSink( parameters, u
"OUTPUT_NON_ROUTABLE"_s, context, nonRoutableSinkId, startPoints->fields(),
Qgis::WkbType::Point, mNetwork->sourceCrs() ) );
166 const double pointDistanceThreshold = parameters.value( u
"POINT_TOLERANCE"_s ).isValid() ? parameterAsDouble( parameters, u
"POINT_TOLERANCE"_s, context ) : -1;
170 QVector<double> costs;
172 int inboundEdgeIndex;
173 double startVertexCost, endVertexCost;
180 const double step = snappedPoints.size() > 0 ? 100.0 / snappedPoints.size() : 1;
181 for (
int i = 0; i < snappedPoints.size(); i++ )
188 double travelCost = defaultTravelCost;
189 if ( dynamicTravelCost )
191 expressionContext.
setFeature( sourceFeatures.value( i + 1 ) );
192 travelCost = travelCostProperty.
valueAsDouble( expressionContext, travelCost );
194 travelCost *= multiplier;
196 const QgsPointXY snappedPoint = snappedPoints.at( i );
197 const QgsPointXY originalPoint = points.at( i );
199 if ( pointDistanceThreshold >= 0 )
201 double distancePointToNetwork = 0;
204 distancePointToNetwork = mBuilder->distanceArea()->measureLine( originalPoint, snappedPoint );
211 if ( distancePointToNetwork > pointDistanceThreshold )
213 feedback->
pushWarning( QObject::tr(
"Point is too far from the network layer (%1, maximum permitted is %2)" ).arg( distancePointToNetwork ).arg( pointDistanceThreshold ) );
214 if ( nonRoutableSink )
217 attributes = sourceFeatures.value( i + 1 ).attributes();
220 throw QgsProcessingException( writeFeatureError( nonRoutableSink.get(), parameters, u
"OUTPUT_NON_ROUTABLE"_s ) );
230 const QString originalPointString = originalPoint.
toString();
232 idxStart = graph->findVertex( snappedPoint );
240 for (
int j = 0; j < costs.size(); j++ )
242 inboundEdgeIndex = tree.at( j );
244 if ( inboundEdgeIndex == -1 && j != idxStart )
250 startVertexCost = costs.at( j );
251 if ( startVertexCost > travelCost )
257 vertices.insert( j );
258 startPoint = graph->vertex( j ).point();
261 const QList<int> outgoingEdges = graph->vertex( j ).outgoingEdges();
262 for (
int edgeId : outgoingEdges )
264 edge = graph->edge( edgeId );
265 endVertexCost = startVertexCost + edge.
cost( 0 ).toDouble();
266 endPoint = graph->vertex( edge.
toVertex() ).point();
267 if ( endVertexCost <= travelCost )
271 lines.push_back(
QgsPolylineXY() << startPoint << endPoint );
278 areaPoints.push_back( interpolatedEndPoint );
279 lines.push_back(
QgsPolylineXY() << startPoint << interpolatedEndPoint );
285 QList<int> verticesList = qgis::setToList( vertices );
286 areaPoints.reserve( verticesList.size() );
287 std::sort( verticesList.begin(), verticesList.end() );
288 for (
int v : verticesList )
290 areaPoints.push_back( graph->vertex( v ).point() );
297 attributes = sourceFeatures.value( i + 1 ).attributes();
298 attributes << u
"within"_s << originalPointString;
309 nodes.reserve( costs.size() );
312 for (
int v = 0; v < costs.size(); v++ )
314 if ( costs.at( v ) > travelCost && tree.at( v ) != -1 )
316 vertexId = graph->edge( tree.at( v ) ).fromVertex();
317 if ( costs.at( vertexId ) <= travelCost )
319 nodes.push_back( v );
324 upperBoundary.reserve( nodes.size() );
325 lowerBoundary.reserve( nodes.size() );
326 for (
int n : std::as_const( nodes ) )
328 upperBoundary.push_back( graph->vertex( graph->edge( tree.at( n ) ).toVertex() ).point() );
329 lowerBoundary.push_back( graph->vertex( graph->edge( tree.at( n ) ).fromVertex() ).point() );
336 attributes = sourceFeatures.value( i + 1 ).attributes();
337 attributes << u
"upper"_s << originalPointString;
345 attributes = sourceFeatures.value( i + 1 ).attributes();
346 attributes << u
"lower"_s << originalPointString;
359 attributes = sourceFeatures.value( i + 1 ).attributes();
360 attributes << u
"lines"_s << originalPointString;
374 pointsSink->finalize();
376 outputs.insert( u
"OUTPUT"_s, pointsSinkId );
380 linesSink->finalize();
382 outputs.insert( u
"OUTPUT_LINES"_s, linesSinkId );
384 if ( nonRoutableSink )
386 nonRoutableSink->finalize();
388 outputs.insert( u
"OUTPUT_NON_ROUTABLE"_s, 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.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
@ 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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
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.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
void setIsDynamic(bool dynamic)
Sets whether the parameter is dynamic, and can support data-defined values (i.e.
An input feature source (such as vector layers) parameter for processing algorithms.
A numeric parameter for processing algorithms.
static bool isDynamic(const QVariantMap ¶meters, const QString &name)
Returns true if the parameter with matching name is a dynamic parameter, and must be evaluated once f...
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).
Definition for a property.
@ DoublePositive
Positive double value (including 0).
A store for object properties.
QVariant value(const QgsExpressionContext &context, const QVariant &defaultValue=QVariant(), bool *ok=nullptr) const
Calculates the current value of the property, including any transforms which are set for the property...
double valueAsDouble(const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property and interprets it as a double.
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.