Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
RailwayRouter.h
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2001-2025 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
18// The RailwayRouter builds a special network for railway routing to handle train reversal restrictions (delegates to a SUMOAbstractRouter)
19/****************************************************************************/
20#pragma once
21#include <config.h>
22
23#include <string>
24#include <vector>
25#include <algorithm>
26#include <assert.h>
27#ifdef HAVE_FOX
29#endif
34#include "SUMOAbstractRouter.h"
35#include "DijkstraRouter.h"
36#include "RailEdge.h"
37
38
39//#define RailwayRouter_DEBUG_ROUTES
40
41// ===========================================================================
42// class definitions
43// ===========================================================================
66template<class E, class V>
67class RailwayRouter : public SUMOAbstractRouter<E, V> {
68
69private:
70
71
75 typedef std::map<const E*, double> Prohibitions;
76
77public:
78
80 RailwayRouter(const std::vector<E*>& edges, bool unbuildIsWarning, typename SUMOAbstractRouter<E, V>::Operation effortOperation,
81 typename SUMOAbstractRouter<E, V>::Operation ttOperation = nullptr, bool silent = false,
82 const bool havePermissions = false, const bool haveRestrictions = false, double maxTrainLength = 5000) :
83 SUMOAbstractRouter<E, V>("RailwayRouter", unbuildIsWarning, effortOperation, ttOperation, havePermissions, haveRestrictions),
84 myInternalRouter(nullptr), myOriginal(nullptr), mySilent(silent),
85 myMaxTrainLength(maxTrainLength) {
86 myStaticOperation = effortOperation;
87 for (const E* const edge : edges) {
88 myInitialEdges.push_back(edge->getRailwayRoutingEdge());
89 }
90 }
91
93 virtual ~RailwayRouter() {
94 delete myInternalRouter;
95 }
96
98 return new RailwayRouter<E, V>(this);
99 }
100
103 bool compute(const E* from, const E* to, const V* const vehicle, SUMOTime msTime, std::vector<const E*>& into, bool silent = false) {
105 if (vehicle->getLength() > myMaxTrainLength) {
106 WRITE_WARNINGF("Vehicle '%' with length % exceeds configured value of --railway.max-train-length %",
107 vehicle->getID(), toString(vehicle->getLength()), toString(myMaxTrainLength));
108 }
109 return _compute(from, to, vehicle, msTime, into, silent, false);
110 }
111
112 void prohibit(const Prohibitions& toProhibit) {
114 std::map<const _RailEdge*, double> railEdges;
115 for (auto item : toProhibit) {
116 railEdges[item.first->getRailwayRoutingEdge()] = item.second;
117 }
118 myInternalRouter->prohibit(railEdges);
119 this->myProhibited = toProhibit;
120#ifdef RailwayRouter_DEBUG_ROUTES
121 std::cout << "RailRouter prohibit=" << toString(toProhibit) << "\n";
122#endif
123 }
124
125
126 double recomputeCosts(const std::vector<const E*>& edges, const V* const v, SUMOTime msTime, double* lengthp = nullptr) const {
127 double effort = SUMOAbstractRouter<E, V>::recomputeCosts(edges, v, msTime, lengthp);
128 const E* prev = nullptr;
129 // reversal corrections
130 double timeCorrection = STEPS2TIME(msTime);
131 for (const E* const e : edges) {
132 if (prev != nullptr && e->getBidiEdge() == prev) {
133 if (e->getLength() > v->getLength()) {
134 // vehicle doesn't need to drive to the end of the edge
135 // @note exact timing correction for time-dependent effort is not done
136 const double savingsFactor = 1 - v->getLength() / e->getLength();
137 double effortCorrection = 0;
138 double lengthCorrection = 0.;
139 effortCorrection += this->getEffort(prev, v, timeCorrection);
140 this->updateViaCost(prev, e, v, timeCorrection, effortCorrection, lengthCorrection);
141 effort -= savingsFactor * effortCorrection;
142 if (lengthp != nullptr) {
143 *lengthp -= savingsFactor * lengthCorrection;
144 }
145 }
146 }
147 prev = e;
148 }
149 return effort;
150 }
151
152
153private:
155 SUMOAbstractRouter<E, V>(other),
156 myInternalRouter(nullptr),
157 myOriginal(other),
158 mySilent(other->mySilent),
160 {}
161
168
169 bool _compute(const E* from, const E* to, const V* const vehicle, SUMOTime msTime, std::vector<const E*>& into, bool silent, bool avoidUnsafeBackTracking) {
170 // make sure that the vehicle can turn-around when starting on a short edge (the virtual turn-around for this lies backwards along the route / track)
171 std::vector<double> backLengths;
172 double backDist = vehicle->getLength() - from->getLength();
173 const E* start = from;
174 while (backDist > 0) {
175 const E* prev = getStraightPredecessor(start, into, (int)backLengths.size());
176 if (prev == nullptr) {
177#ifdef RailwayRouter_DEBUG_ROUTES
178 std::cout << " Could not determine back edge for vehicle '" << vehicle->getID() << "' when routing from edge '" << from->getID() << "' at time=" << time2string(msTime) << "\n";
179#endif
180 //WRITE_WARNING("Could not determine back edge for vehicle '" + vehicle->getID() + "' when routing from edge '" + from->getID() + "' at time=" + time2string(msTime));
181 break;
182 }
183 backDist -= prev->getLength();
184 if (avoidUnsafeBackTracking && prev->getSuccessors().size() > 1) {
185 bool foundSwitch = false;
186 for (const E* succ : prev->getSuccessors()) {
187 if (succ != start && succ != prev->getBidiEdge()) {
188 foundSwitch = true;
189 break;
190 }
191 }
192 if (foundSwitch) {
193 break;
194 }
195 }
196 backLengths.push_back(prev->getLength() + (backLengths.empty()
197 ? MIN2(vehicle->getLength(), from->getLength())
198 : backLengths.back()));
199 start = prev;
200 }
201
202 std::vector<const _RailEdge*> intoTmp;
203 bool success = myInternalRouter->compute(start->getRailwayRoutingEdge(), to->getRailwayRoutingEdge(), vehicle, msTime, intoTmp, silent);
204#ifdef RailwayRouter_DEBUG_ROUTES
205 std::cout << "RailRouter veh=" << vehicle->getID() << " from=" << from->getID() << " to=" << to->getID() << " t=" << time2string(msTime)
206 << " safe=" << avoidUnsafeBackTracking << " success=" << success << " into=" << toString(into) << "\n";
207#endif
208 if (success) {
209 const size_t intoSize = into.size();
210 int backIndex = (int)backLengths.size();
211 for (const _RailEdge* railEdge : intoTmp) {
212 if (railEdge->getOriginal() != nullptr) {
213 backIndex--;
214 }
215 // prevent premature reversal on back edge (extend train length)
216 const double length = backIndex >= 0 ? backLengths[backIndex] : vehicle->getLength();
217 railEdge->insertOriginalEdges(length, into);
218 }
219#ifdef RailwayRouter_DEBUG_ROUTES
220 std::cout << "RailRouter: internal result=" << toString(intoTmp) << "\n";
221 std::cout << "RailRouter: expanded result=" << toString(into) << "\n";
222#endif
223 if (backLengths.size() > 0) {
224 // skip the virtual back-edges
225 into.erase(into.begin() + intoSize, into.begin() + intoSize + backLengths.size());
226#ifdef RailwayRouter_DEBUG_ROUTES
227 std::cout << "RailRouter: backLengths=" << toString(backLengths) << " intoSize=" << intoSize << " final result=" << toString(into) << "\n";
228#endif
229 if (*(into.begin() + intoSize) != from) {
230 if (!avoidUnsafeBackTracking) {
231 // try again, this time with more safety (but unable to
232 // make use of turn-arounds on short edge)
233 into.erase(into.begin() + intoSize, into.end());
234 return _compute(from, to, vehicle, msTime, into, silent, true);
235 } else {
236 WRITE_WARNING("Railway routing failure due to turn-around on short edge '" + from->getID()
237 + "' for vehicle '" + vehicle->getID() + "' time=" + time2string(msTime) + ".");
238 }
239 }
240 }
241 if (this->myProhibited.size() > 0) {
242 // make sure that turnarounds don't use prohibited edges
243 for (const E* e : into) {
244 if (this->myProhibited.find(e) != this->myProhibited.end()) {
245 into.clear();
246 success = false;
247 break;
248 }
249 }
250 }
251 }
252 return success;
253
254 }
255
256 const std::vector<_RailEdge*>& getRailEdges() {
257 if (myOriginal != nullptr) {
258 return myOriginal->getRailEdges();
259 }
260#ifdef HAVE_FOX
261 FXMutexLock locker(myLock);
262#endif
263 if (myRailEdges.empty()) {
265 int numericalID = myInitialEdges.back()->getNumericalID() + 1;
266 for (_RailEdge* railEdge : myInitialEdges) {
267 railEdge->init(myRailEdges, numericalID, myMaxTrainLength);
268 }
269 }
270 return myRailEdges;
271 }
272
273 static inline double getTravelTimeStatic(const RailEdge<E, V>* const edge, const V* const veh, double time) {
274 if (edge->getOriginal() != nullptr) {
275 return (*myStaticOperation)(edge->getOriginal(), veh, time);
276 } else {
277 // turnaround edge
278 if (edge->isVirtual()) {
279 // add up time for replacement edges
280 std::vector<const E*> repl;
281 edge->insertOriginalEdges(veh->getLength(), repl);
282 assert(repl.size() > 0);
283 double seenDist = 0;
284 double result = 0;
285 repl.pop_back(); // last edge must not be used fully
286 for (const E* e : repl) {
287 result += (*myStaticOperation)(e, veh, time + result);
288 seenDist += e->getLength();
289 }
290 const double lengthOnLastEdge = MAX2(0.0, veh->getLength() - seenDist);
291 return result + myReversalPenalty + lengthOnLastEdge * myReversalPenaltyFactor;
292 } else {
293 // if the edge from which this turnaround starts is longer
294 // than the vehicle then we are overstimating the cost
295 // (because the turnaround may happen before driving to the end)
296 // However, unless the vehicle starts on this edge, we should be taking a
297 // virtual turnaround at the end of the previous edge. Otherwise, the exaggerated cost doesn't
298 return myReversalPenalty;
299 }
300 }
301 }
302
303
304 static const E* getStraightPredecessor(const E* edge, std::vector<const E*>& prevRoute, int backIndex) {
305 const E* result = nullptr;
306#ifdef RailwayRouter_DEBUG_ROUTES
307 std::cout << " getStraightPredecessor edge=" << edge->getID() << " prevRouteSize=" << prevRoute.size() << " backIndex=" << backIndex << "\n";
308#endif
309 if ((int)prevRoute.size() > backIndex) {
310 return prevRoute[(int)prevRoute.size() - 1 - backIndex];
311 }
312 for (const E* cand : edge->getPredecessors()) {
313 if (!cand->isInternal() && cand->getBidiEdge() != edge) {
314 //std::cout << " cand=" << cand->getID() << "\n";
315 if (result == nullptr) {
316 result = cand;
317 } else {
318 // predecessor not unique. Better abort with a warning
319 return nullptr;
320 }
321 }
322 }
323 return result;
324 }
325
326private:
330 std::vector<_RailEdge*> myInitialEdges;
332 std::vector<_RailEdge*> myRailEdges;
333
335 const bool mySilent;
336
337 const double myMaxTrainLength;
338
339#ifdef HAVE_FOX
341 mutable FXMutex myLock;
342#endif
343
346
347 static double myReversalPenalty;
349
350private:
353
354};
355
356template<class E, class V>
358template<class E, class V>
360template<class E, class V>
long long int SUMOTime
Definition GUI.h:36
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:288
#define WRITE_WARNING(msg)
Definition MsgHandler.h:287
std::string time2string(SUMOTime t, bool humanReadable)
convert SUMOTime to string (independently of global format setting)
Definition SUMOTime.cpp:91
#define STEPS2TIME(x)
Definition SUMOTime.h:55
T MIN2(T a, T b)
Definition StdDefs.h:80
T MAX2(T a, T b)
Definition StdDefs.h:86
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:46
Computes the shortest path through a network using the Dijkstra algorithm.
static MsgHandler * getWarningInstance()
Returns the instance to add warnings to.
the edge type representing backward edges
Definition RailEdge.h:38
void insertOriginalEdges(double length, std::vector< const E * > &into) const
Definition RailEdge.h:181
bool isVirtual() const
Definition RailEdge.h:261
const E * getOriginal() const
Returns the original edge.
Definition RailEdge.h:170
SUMOAbstractRouter< _RailEdge, V > _InternalRouter
static double myReversalPenaltyFactor
RailwayRouter< E, V > *const myOriginal
RailwayRouter(RailwayRouter *other)
DijkstraRouter< _RailEdge, V > _InternalDijkstra
std::vector< _RailEdge * > myInitialEdges
a RailEdge for every existing edge, filled on construction (but not in clones)
RailwayRouter & operator=(const RailwayRouter &s)
Invalidated assignment operator.
std::vector< _RailEdge * > myRailEdges
complete rail network filled on demand (but not in clones)
void prohibit(const Prohibitions &toProhibit)
double recomputeCosts(const std::vector< const E * > &edges, const V *const v, SUMOTime msTime, double *lengthp=nullptr) const
const bool mySilent
whether to suppress warning/error if no route was found
bool compute(const E *from, const E *to, const V *const vehicle, SUMOTime msTime, std::vector< const E * > &into, bool silent=false)
Builds the route between the given edges using the minimum effort at the given time The definition of...
RailwayRouter(const std::vector< E * > &edges, bool unbuildIsWarning, typename SUMOAbstractRouter< E, V >::Operation effortOperation, typename SUMOAbstractRouter< E, V >::Operation ttOperation=nullptr, bool silent=false, const bool havePermissions=false, const bool haveRestrictions=false, double maxTrainLength=5000)
Constructor.
_InternalRouter * myInternalRouter
static SUMOAbstractRouter< E, V >::Operation myStaticOperation
The object's operation to perform. (hack)
const double myMaxTrainLength
bool _compute(const E *from, const E *to, const V *const vehicle, SUMOTime msTime, std::vector< const E * > &into, bool silent, bool avoidUnsafeBackTracking)
void ensureInternalRouter()
const std::vector< _RailEdge * > & getRailEdges()
RailEdge< E, V > _RailEdge
static double myReversalPenalty
static const E * getStraightPredecessor(const E *edge, std::vector< const E * > &prevRoute, int backIndex)
static double getTravelTimeStatic(const RailEdge< E, V > *const edge, const V *const veh, double time)
std::map< const E *, double > Prohibitions
SUMOAbstractRouter< E, V > * clone()
virtual ~RailwayRouter()
Destructor.
MsgHandler *const myErrorMsgHandler
the handler for routing errors
const bool myHavePermissions
whether edge permissions need to be considered
void updateViaCost(const E *const prev, const E *const e, const V *const v, double &time, double &effort, double &length) const
double getEffort(const E *const e, const V *const v, double t) const
virtual void prohibit(const Prohibitions &toProhibit)
Prohibitions myProhibited
The list of explicitly prohibited edges and estimated end time of prohibition.
const bool myHaveRestrictions
whether edge restrictions need to be considered
virtual bool compute(const E *from, const E *to, const V *const vehicle, SUMOTime msTime, std::vector< const E * > &into, bool silent=false)=0
Builds the route between the given edges using the minimum effort at the given time The definition of...
virtual double recomputeCosts(const std::vector< const E * > &edges, const V *const v, SUMOTime msTime, double *lengthp=nullptr) const