Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
eclipse
GitHub Repository: eclipse/sumo
Path: blob/main/src/utils/router/RailwayRouter.h
169678 views
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
/****************************************************************************/
14
/// @file RailwayRouter.h
15
/// @author Jakob Erdmann
16
/// @date Tue, 25 Feb 2020
17
///
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
28
#include <utils/foxtools/fxheader.h>
29
#endif
30
#include <utils/common/MsgHandler.h>
31
#include <utils/common/SUMOTime.h>
32
#include <utils/common/ToString.h>
33
#include <utils/iodevices/OutputDevice.h>
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
// ===========================================================================
44
/**
45
* @class RailwayRouter
46
* The router for rail vehicles for track networks where some sections may be used in both directions
47
* and trains may reverse depending on location and train length
48
*
49
* Example (assume each track section is 100m long) running from left to right and a negative sign indicates reverse direction
50
*
51
* A C D
52
* .______.______.______.
53
* ._____/
54
* B
55
*
56
* Consider a train of 200m length that enters on B and must move to A (with a reversal):
57
* The necessary route is B C D -D -C -A were D,-D are needed for the train to fully pass the switch
58
*
59
* We shadow the normal edge graph with a railEdge graph to include virtual
60
* turnarounds that look at the train length.
61
* The graph extension takes place via RailEdge::init()
62
* For edge C we create a virtual turnaround (as successor of C) that connectes C with -C and is then expanded to C D -D -C for trains longer than 100m.
63
* The expension takes place via RailEdge::insertOriginalEdges()
64
*
65
*/
66
template<class E, class V>
67
class RailwayRouter : public SUMOAbstractRouter<E, V> {
68
69
private:
70
71
72
typedef RailEdge<E, V> _RailEdge;
73
typedef SUMOAbstractRouter<_RailEdge, V> _InternalRouter;
74
typedef DijkstraRouter<_RailEdge, V> _InternalDijkstra;
75
typedef std::map<const E*, double> Prohibitions;
76
77
public:
78
79
/// Constructor
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
92
/// Destructor
93
virtual ~RailwayRouter() {
94
delete myInternalRouter;
95
}
96
97
SUMOAbstractRouter<E, V>* clone() {
98
return new RailwayRouter<E, V>(this);
99
}
100
101
/** @brief Builds the route between the given edges using the minimum effort at the given time
102
The definition of the effort depends on the wished routing scheme */
103
bool compute(const E* from, const E* to, const V* const vehicle, SUMOTime msTime, std::vector<const E*>& into, bool silent = false) {
104
ensureInternalRouter();
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) {
113
ensureInternalRouter();
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
153
private:
154
RailwayRouter(RailwayRouter* other) :
155
SUMOAbstractRouter<E, V>(other),
156
myInternalRouter(nullptr),
157
myOriginal(other),
158
mySilent(other->mySilent),
159
myMaxTrainLength(other->myMaxTrainLength)
160
{}
161
162
void ensureInternalRouter() {
163
if (myInternalRouter == nullptr) {
164
myInternalRouter = new _InternalDijkstra(getRailEdges(), this->myErrorMsgHandler == MsgHandler::getWarningInstance(), &getTravelTimeStatic,
165
nullptr, mySilent, nullptr, this->myHavePermissions, this->myHaveRestrictions);
166
}
167
}
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()) {
264
myRailEdges = myInitialEdges;
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
326
private:
327
_InternalRouter* myInternalRouter;
328
RailwayRouter<E, V>* const myOriginal;
329
/// @brief a RailEdge for every existing edge, filled on construction (but not in clones)
330
std::vector<_RailEdge*> myInitialEdges;
331
/// @brief complete rail network filled on demand (but not in clones)
332
std::vector<_RailEdge*> myRailEdges;
333
334
/// @brief whether to suppress warning/error if no route was found
335
const bool mySilent;
336
337
const double myMaxTrainLength;
338
339
#ifdef HAVE_FOX
340
/// The mutex used to avoid concurrent updates of myRailEdges
341
mutable FXMutex myLock;
342
#endif
343
344
/// @brief The object's operation to perform. (hack)
345
static typename SUMOAbstractRouter<E, V>::Operation myStaticOperation;
346
347
static double myReversalPenalty;
348
static double myReversalPenaltyFactor;
349
350
private:
351
/// @brief Invalidated assignment operator
352
RailwayRouter& operator=(const RailwayRouter& s);
353
354
};
355
356
template<class E, class V>
357
typename SUMOAbstractRouter<E, V>::Operation RailwayRouter<E, V>::myStaticOperation(nullptr);
358
template<class E, class V>
359
double RailwayRouter<E, V>::myReversalPenalty(60);
360
template<class E, class V>
361
double RailwayRouter<E, V>::myReversalPenaltyFactor(0.2); // 1/v
362
363