Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
MSRailSignalControl.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2001-2026 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// Centralized services for rail signal control (Singleton)
19/****************************************************************************/
20#include <config.h>
21
22#include <cassert>
23#include <utility>
24#include <vector>
25#include <bitset>
26#include <microsim/MSNet.h>
28#include <microsim/MSRoute.h>
29#include <microsim/MSEdge.h>
30#include <microsim/MSLane.h>
31#include <microsim/MSGlobals.h>
32#ifdef HAVE_FOX
34#endif
35#include "MSRailSignal.h"
37#include "MSDriveWay.h"
38#include "MSRailSignalControl.h"
39
40
41//#define DEBUG_BUILD_DEADLOCK_CHECK
42
43// ===========================================================================
44// static value definitions
45// ===========================================================================
49
50// ===========================================================================
51// method definitions
52// ===========================================================================
54 myMaxTrainLength(OptionsCont::getOptions().getFloat("railway.max-train-length"))
55{}
56
65
66void
68 delete myInstance;
69 myInstance = nullptr;
70}
71
72void
74 if (myInstance != nullptr) {
81 //myInstance->myActiveSignals.clear();
82 }
83}
84
85
88
89void
90MSRailSignalControl::vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& /*info*/) {
91 if (vehicle->isRail()) {
92 std::string dummyMsg;
93 if ((to == MSNet::VehicleState::BUILT && (!vehicle->getParameter().wasSet(VEHPARS_FORCE_REROUTE) || vehicle->hasValidRoute(dummyMsg)))
95 // @note we could delay initialization until the departure time
98 }
99 }
100 if (to == MSNet::VehicleState::BUILT) {
102 }
103 }
104}
105
106
107void
109 mySignals.push_back(signal);
110 for (const auto& links : signal->getLinks()) {
111 for (const MSLink* link : links) {
112 mySignalizedClasses |= (link->getPermissions() & myMBClasses);
113 }
114 }
115}
116
117
118void
120 //std::cout << time2string(SIMSTEP) << " addWaitRelation waits=" << waits->getID() << " foe=" << reason->getID() << "\n";
121 myWaitRelations[waits] = WaitRelation(rs, reason, constraint);
122}
123
124
125bool
127 std::set<const SUMOVehicle*> seen;
128 std::vector<WaitRelation> list;
129 const SUMOVehicle* cur = veh;
130 std::vector<MSRailSignalConstraint*> constraints;
131 std::vector<const SUMOVehicle*> constraintBlocked;
132 std::vector<const MSRailSignal*> constraintSignals;
133 //std::cout << time2string(SIMSTEP) << " haveDeadlock veh=" << veh->getID() << "\n";
134 while (seen.count(cur) == 0) {
135 auto it = myWaitRelations.find(cur);
136 if (it != myWaitRelations.end()) {
137 if (it->second.constraint != nullptr) {
138 constraints.push_back(it->second.constraint);
139 constraintBlocked.push_back(cur);
140 constraintSignals.push_back(it->second.railSignal);
141 }
142 seen.insert(cur);
143 list.push_back(it->second);
144 cur = it->second.foe;
145 } else {
146 return false;
147 }
148 }
149 if (cur == veh) {
150 const bool newDeadlock = myWrittenDeadlocks.count(seen) == 0;
151 myWrittenDeadlocks.insert(seen);
153 MSRailSignalConstraint* resolved = nullptr;
154 const SUMOVehicle* resolvedUnblocked = nullptr;
155 const MSRailSignal* resolvedSignal = nullptr;
156 if (!constraints.empty() && oc.getBool("time-to-teleport.remove-constraint")) {
157 resolved = constraints.front();
158 if (newDeadlock) {
159 std::vector<std::string> vehicles;
160 for (auto item : list) {
161 vehicles.push_back(item.foe->getID());
162 }
163 WRITE_WARNINGF("Deactivating constraint to resolve deadlock between vehicles % at time %.", toString(vehicles), time2string(SIMSTEP));
164 resolved->setActive(false);
165 resolvedUnblocked = constraintBlocked.front();
166 resolvedSignal = constraintSignals.front();
167 }
168 }
169
170 if (oc.isSet("deadlock-output")) {
171 if (newDeadlock) {
172 myWrittenDeadlocks.insert(seen);
173 std::vector<std::string> signals;
174 std::vector<std::string> vehicles;
175 std::vector<std::string> tripIDs;
176 for (auto item : list) {
177 signals.push_back(item.railSignal == nullptr ? "INSERTION" : item.railSignal->getID());
178 vehicles.push_back(item.foe->getID());
179 tripIDs.push_back(item.foe->getParameter().getParameter("tripId", item.foe->getID()));
180 }
181 // rotate signals so their are aligned with the vehicle waiting
182 // at that signal instead of the foe that is blocking the signal
183 std::rotate(signals.begin(), signals.begin() + 1, signals.end());
184 OutputDevice& od = OptionsCont::getDeviceByOption("deadlock-output");
185 if (constraints.empty()) {
187 } else {
188 od.openTag("constraintDeadlock");
189 }
191 od.writeAttr(SUMO_ATTR_SIGNALS, signals);
192 od.writeAttr("vehicles", vehicles);
193 if (!constraints.empty()) {
194 od.writeAttr("tripIds", tripIDs);
195 }
196 if (resolved != nullptr) {
197 od.openTag("resolvedConstraint");
198 od.writeAttr(SUMO_ATTR_ID, resolvedSignal->getID());
199 resolved->write(od, resolvedUnblocked->getParameter().getParameter("tripId", resolvedUnblocked->getID()));
200 od.closeTag();
201 }
202 for (auto item : list) {
203 int start = item.foe->getRoutePosition();
205 const std::vector<MSLane*>& further = dynamic_cast<const MSVehicle*>(item.foe)->getFurtherLanes();
206 start = MAX2(0, start - (int)(MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks() ? further.size() / 2 : further.size()));
207 }
208 const MSRoute& route = item.foe->getRoute();
209 ConstMSEdgeVector future(route.begin() + start, route.end());
212 od.closeTag();
213 }
214 od.closeTag();
215 }
216 }
217 return resolved == nullptr;
218 } else {
219 // it's a deadlock but does not involve veh
220 return false;
221 }
222}
223
224
225void
226MSRailSignalControl::loadDeadlockCheck(std::vector<const MSRailSignal*> signals) {
228 WRITE_WARNING("Deadlocks should be loaded before any vehicles");
229 }
230#ifdef DEBUG_BUILD_DEADLOCK_CHECK
231 std::cout << " loadedDeadlockCheck signals=" << toString(signals) << "\n";
232#endif
233 const int deadlockIndex = (int)myLoadedDeadlocks.size();
234 myLoadedDeadlocks.push_back(Deadlock());
235 myLoadedDeadlocks.back().signals = signals;
236 const int n = (int)signals.size();
237 for (int i = 0; i < n; i++) {
238 mySignalDeadlocks[signals[i]].push_back(std::make_pair(deadlockIndex, i));
239 }
240}
241
242
243void
245 Deadlock& dl = myLoadedDeadlocks.back();
246 const int signalIndex = (int)dl.edges.size();
247 const MSRailSignal* rs = dl.signals[signalIndex];
248 const MSJunction* j = rs->getJunction();
249 auto it = edges.begin();
250 while (it != edges.end() && (*it)->getToJunction() != j) {
251 it++;
252 }
253 if (it == edges.end()) {
254 throw ProcessError("Rail signal junction '" + j->getID() + "' not passed by loaded deadlock edges '" + toString(edges) + "'.");
255 }
256 const MSEdge* firstSignalEdge = *it;
257 // maybe there is an earlier signal, in this case we must look for driveways that start there
258 for (auto it2 = edges.begin(); it2 != it; it2++) {
259 if ((*it2)->getToJunction()->getType() == SumoXMLNodeType::RAIL_SIGNAL) {
260 const MSLink* link = (*it2)->getLanes().front()->getLinkTo((*(it2 + 1))->getLanes().front());
261 if (link != nullptr && link->isTLSControlled()) {
262 firstSignalEdge = *it2;
263 break;
264 }
265 }
266 }
267 dl.forwardEnds.push_back(firstSignalEdge);
268 dl.edges.push_back(edges);
269#ifdef DEBUG_BUILD_DEADLOCK_CHECK
270 std::cout << " loadedDeadlockRoute signal=" << rs->getID() << " signalEdge=" << firstSignalEdge->getID() << " edges=" << toString(edges) << "\n";
271#endif
272}
273
274
275void
277 //std::cout << " addDrivewayFollower " << dw->getID() << " " << dw2->getID() << "\n";
278 myDriveWaySucc[dw].insert(dw2);
279 myDriveWayPred[dw2].insert(dw);
280}
281
282
283void
285 auto itDL = mySignalDeadlocks.find(rs);
286 if (itDL == mySignalDeadlocks.end()) {
287 return;
288 }
289#ifdef DEBUG_BUILD_DEADLOCK_CHECK
290 std::cout << " needsDeadlockChecks? rs=" << rs->getID() << " dw=" << dw->getID() << "\n";
291#endif
292 // the driveway dw ends at signal rs and could be part of a deadlock.
293 // check whether we can form a sequence of driveways that link it with all others (railsignals)
294 // findDeadlockFoes calls itself recursively until all circles have been found
295 for (const auto& pair : itDL->second) {
296 const Deadlock& dl = myLoadedDeadlocks[pair.first];
297 std::vector<const MSDriveWay*> deadlockFoes;
298 if (dl.edges.empty()) {
299 findDeadlockFoes(dw, dl, pair.second, deadlockFoes);
300 } else {
301 const MSEdge* forwardEnd = dl.forwardEnds[pair.second];
302 if (forwardEnd == &dw->getForward().back()->getEdge()) {
303 findDeadlockFoesFromRoutes(dw, dl, pair.second, deadlockFoes);
304 } else {
305 for (MSDriveWay* cand : MSDriveWay::getEndingDriveWays(forwardEnd)) {
306 findDeadlockFoesFromRoutes(cand, dl, pair.second, deadlockFoes);
307 }
308 }
309 }
310 }
311}
312
313
314void
315MSRailSignalControl::findDeadlockFoes(const MSDriveWay* dw, const Deadlock& dl, int signalIndex, std::vector<const MSDriveWay*> deadlockFoes) {
316 if (deadlockFoes.size() < dl.signals.size()) {
317 signalIndex = (signalIndex + 1) % dl.signals.size();
318 const MSRailSignal* other = dl.signals[signalIndex];
319 const MSJunction* otherJ = other->getJunction();
320#ifdef DEBUG_BUILD_DEADLOCK_CHECK
321 std::cout << " findDLfoes dw=" << dw->getID() << " foundFoes=" << toString(deadlockFoes) << " otherRS=" << other->getID() << "\n";
322#endif
323 deadlockFoes.push_back(dw);
324 for (const MSDriveWay* follower : myDriveWaySucc[dw]) {
325#ifdef DEBUG_BUILD_DEADLOCK_CHECK
326 std::cout << " follower=" << follower->getID() << " followerFoes=" << toString(follower->getFoes()) << "\n";
327#endif
328 for (MSDriveWay* foe : follower->getFoes()) {
329 if (foe->getForward().back()->getToJunction() == otherJ) {
330 findDeadlockFoes(foe, dl, signalIndex, deadlockFoes);
331 } else if (foe->isSubDriveWay() && foe->getParent()->getForward().back()->getToJunction() == otherJ && foe->getParentRemainingLength() < myMaxTrainLength) {
332 // subdriveway-parents where the remaining part is short and thus a long train might reach back onto the subdriveway
333 // @note: technically we do not need to check this in meso because train ends cannot reach into multiple segments
334 // but it wouldn't help to make meso "better" by ignoring this foe relationship
335 findDeadlockFoes(foe->getParent(), dl, signalIndex, deadlockFoes);
336 }
337 }
338 }
339 } else {
340#ifdef DEBUG_BUILD_DEADLOCK_CHECK
341 std::cout << " add deadlock check dlFoes=" << toString(deadlockFoes) << "\n";;
342#endif
343 for (const MSDriveWay* dldw : deadlockFoes) {
344 if (!dldw->isDepartDriveway()) {
345 const MSRailSignal* rs = dynamic_cast<const MSRailSignal*>(dldw->getOrigin()->getTLLogic());
346 if (std::find(dl.signals.begin(), dl.signals.end(), rs) != dl.signals.end()) {
347 // moving into dldw frees up another part of the deadlock
348 continue;
349 }
350 }
351 std::vector<const MSDriveWay*> df(deadlockFoes);
352 df.erase(std::find(df.begin(), df.end(), dldw));
353#ifdef DEBUG_BUILD_DEADLOCK_CHECK
354 std::cout << " dldw=" << dldw->getID() << " df=" << toString(df) << "\n";
355#endif
356 const_cast<MSDriveWay*>(dldw)->addDWDeadlock(df);
357 }
358 }
359}
360
361
362void
363MSRailSignalControl::findDeadlockFoesFromRoutes(const MSDriveWay* dw, const Deadlock& dl, int signalIndex, std::vector<const MSDriveWay*> deadlockFoes) {
364 // the loaded edges must match the end of the driveway route
365 const ConstMSEdgeVector& de = dl.edges[signalIndex];
366 const size_t n = de.size();
367#ifdef DEBUG_BUILD_DEADLOCK_CHECK
368 std::cout << " findDLfoesFromRoutes dw=" << dw->getID() << " foundFoes=" << toString(deadlockFoes)
369 << "\n dle=" << toString(de)
370 << "\n dwe=" << toString(ConstMSEdgeVector(dw->getRoute().end() - MIN2(n, dw->getRoute().size()), dw->getRoute().end()))
371 << "\n";
372#endif
373 if (dw->getRoute().size() >= n && std::equal(de.begin(), de.end(),
374 dw->getRoute().end() - n, dw->getRoute().end())) {
375 deadlockFoes.push_back(dw);
376 if (deadlockFoes.size() < dl.signals.size()) {
377 signalIndex = (signalIndex + 1) % dl.signals.size();
378 const MSEdge* forwardEnd = dl.forwardEnds[signalIndex];
379 for (MSDriveWay* cand : MSDriveWay::getEndingDriveWays(forwardEnd)) {
380 findDeadlockFoesFromRoutes(cand, dl, signalIndex, deadlockFoes);
381 }
382 } else {
383 findDeadlockFoes(dw, dl, signalIndex, deadlockFoes);
384 }
385 }
386}
387
388
389void
391 const MSRailSignal* rs = dynamic_cast<const MSRailSignal*>(link->getTLLogic());
392 assert(rs != nullptr);
393#ifdef HAVE_FOX
394 ScopedLocker<> lock(myActiveSignalsMutex, MSGlobals::gNumSimThreads > 1);
395#endif
396 myActiveSignals.insert(const_cast<MSRailSignal*>(rs));
397}
398
399
400void
403 // there are 4 states for a signal
404 // 1. approached and green
405 // 2. approached and red
406 // 3. not approached and trains could pass
407 // 4. not approached and trains coult not pass
408 //
409 // for understanding conflicts better in sumo-gui, we want to show (3) as green. This
410 // means we have to keep updating signals in state (4) until they change to (3)
411
412 //std::cout << SIMTIME << " activeSignals=" << myActiveSignals.size() << "\n";
413 for (auto it = myActiveSignals.begin(); it != myActiveSignals.end();) {
414 MSRailSignal* rs = *it;
415 const bool keepActive = rs->updateCurrentPhase();
416 // std::cout << SIMTIME << " update " << rs->getID() << " keepActive=" << keepActive << "\n";
417 if (rs->isActive()) {
419 }
420 if (!keepActive) {
421 it = myActiveSignals.erase(it);
422 } else {
423 it++;
424 }
425 }
426}
427
428
429/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
std::vector< const MSEdge * > ConstMSEdgeVector
Definition MSEdge.h:75
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
std::string time2string(SUMOTime t, bool humanReadable)
convert SUMOTime to string (independently of global format setting)
Definition SUMOTime.cpp:107
#define SIMSTEP
Definition SUMOTime.h:69
const SVCPermissions SVC_UNSPECIFIED
permissions not specified
bool isRailwayOrShared(SVCPermissions permissions)
Returns whether an edge with the given permissions is a railway edge or a shared road/rail edge.
long long int SVCPermissions
bitset where each bit declares whether a certain SVC may use this edge/lane
const long long int VEHPARS_FORCE_REROUTE
@ SUMO_TAG_ROUTEPART
@ SUMO_TAG_DEADLOCK
Saved deadlock information, also for loading as an extra check.
@ SUMO_ATTR_EDGES
the edges of a route
@ SUMO_ATTR_SIGNALS
@ SUMO_ATTR_ID
@ SUMO_ATTR_TIME
trigger: the time of the step
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:57
static bool haveDriveWays()
Definition MSDriveWay.h:72
static const std::vector< MSDriveWay * > & getEndingDriveWays(const MSEdge *edge)
const std::vector< const MSLane * > & getForward() const
Definition MSDriveWay.h:157
const std::vector< const MSEdge * > & getRoute() const
Definition MSDriveWay.h:117
A road/street connecting two junctions.
Definition MSEdge.h:78
SVCPermissions getPermissions() const
Returns the combined permissions of all lanes of this edge.
Definition MSEdge.h:659
SumoXMLEdgeFunc getFunction() const
Returns the edge type (SumoXMLEdgeFunc)
Definition MSEdge.h:260
static bool gUseMesoSim
Definition MSGlobals.h:106
static int gNumSimThreads
how many threads to use for simulation
Definition MSGlobals.h:149
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition MSGlobals.h:81
The base class for an intersection.
Definition MSJunction.h:58
VehicleState
Definition of a vehicle state.
Definition MSNet.h:637
@ BUILT
The vehicle was built, but has not yet departed.
@ NEWROUTE
The vehicle got a new route.
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:201
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition MSNet.cpp:1385
A base class for constraints.
virtual void setActive(bool active)=0
virtual void write(OutputDevice &out, const std::string &tripId) const =0
A signal for rails.
void loadDeadlockRoute(const ConstMSEdgeVector &edges)
void notifyApproach(const MSLink *link)
switch rail signal to active
void addSignal(MSRailSignal *signal)
void vehicleStateChanged(const SUMOVehicle *const vehicle, MSNet::VehicleState to, const std::string &info="")
Called if a vehicle changes its state.
std::vector< Deadlock > myLoadedDeadlocks
void addDrivewayFollower(const MSDriveWay *dw, const MSDriveWay *dw2)
std::vector< MSRailSignal * > mySignals
list of all rail signals
void findDeadlockFoesFromRoutes(const MSDriveWay *dw, const Deadlock &dl, int signalIndex, std::vector< const MSDriveWay * > deadlockFoes)
MSRailSignalControl()
Constructor.
void loadDeadlockCheck(std::vector< const MSRailSignal * > signals)
void addWaitRelation(const SUMOVehicle *waits, const MSRailSignal *rs, const SUMOVehicle *reason, MSRailSignalConstraint *constraint=nullptr)
static MSRailSignalControl * myInstance
std::map< const SUMOVehicle *, WaitRelation > myWaitRelations
void addDWDeadlockChecks(const MSRailSignal *rs, MSDriveWay *dw)
check whether the given signal and driveway are part of a deadlock circle
static MSRailSignalControl & getInstance()
std::map< const MSDriveWay *, std::set< const MSDriveWay * > > myDriveWayPred
static SVCPermissions mySignalizedClasses
signalized classes
bool haveDeadlock(const SUMOVehicle *veh) const
whether there is a circle in the waiting-for relationships that contains the given vehicle
std::set< std::set< const SUMOVehicle * > > myWrittenDeadlocks
void updateSignals(SUMOTime t)
update active rail signals
std::set< MSRailSignal *, ComparatorNumericalIdLess > myActiveSignals
std::map< std::pair< int, int >, bool > myDriveWayCompatibility
static void clearState()
Perform resets events when quick-loading state.
static SVCPermissions myMBClasses
std::map< const MSDriveWay *, std::set< const MSDriveWay *, ComparatorNumericalIdLess > > myDriveWaySucc
std::map< const MSRailSignal *, std::vector< std::pair< int, int > > > mySignalDeadlocks
void findDeadlockFoes(const MSDriveWay *dw, const Deadlock &dl, int signalIndex, std::vector< const MSDriveWay * > deadlockFoes)
A signal for rails.
const MSJunction * getJunction() const
get the unique junction controlled by this signal
bool updateCurrentPhase()
returns the state of the signal that actually required
static void initDriveWays(const SUMOVehicle *ego, bool update)
MSRouteIterator end() const
Returns the end of the list of edges to pass.
Definition MSRoute.cpp:79
MSRouteIterator begin() const
Returns the begin of the list of edges to pass.
Definition MSRoute.cpp:73
const LinkVectorVector & getLinks() const
Returns the list of lists of all affected links.
bool isActive() const
whether this logic is the active program
bool setTrafficLightSignals(SUMOTime t) const
Applies the current signal states to controlled links.
Representation of a vehicle in the micro simulation.
Definition MSVehicle.h:77
const std::string & getID() const
Returns the id.
Definition Named.h:73
A storage for options typed value containers)
Definition OptionsCont.h:92
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
static OutputDevice & getDeviceByOption(const std::string &name)
Returns the device described by the option.
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
static OptionsCont & getOptions()
Retrieves the options.
Static storage of an output device and its base (abstract) implementation.
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.
OutputDevice & writeAttr(const ATTR_TYPE &attr, const T &val, const bool isNull=false, const bool escape=false)
writes a named attribute
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
virtual const std::string getParameter(const std::string &key, const std::string defaultValue="") const
Returns the value for a given key.
virtual const SUMOVehicleParameter & getParameter() const =0
Returns the vehicle's parameter (including departure definition)
virtual const MSEdge * getEdge() const =0
Returns the (normal) route edge the object is currently at.
Representation of a vehicle.
Definition SUMOVehicle.h:63
virtual bool isRail() const =0
virtual double getLength() const =0
Returns the vehicles's length.
virtual bool hasValidRoute(std::string &msg, ConstMSRoutePtr route=0) const =0
Validates the current or given route.
bool wasSet(long long int what) const
Returns whether the given parameter was set.
A scoped lock which only triggers on condition.
#define UNUSED_PARAMETER(x)
storage for loaded deadlocks
std::vector< const MSRailSignal * > signals
std::vector< ConstMSEdgeVector > edges