LCOV - code coverage report
Current view: top level - src/microsim/traffic_lights - MSRailSignalControl.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 99.2 % 133 132
Test Date: 2025-12-06 15:35:27 Functions: 100.0 % 16 16

            Line data    Source code
       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    MSRailSignalControl.cpp
      15              : /// @author  Jakob Erdmann
      16              : /// @date    Sept 2020
      17              : ///
      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>
      27              : #include <microsim/MSRoute.h>
      28              : #include <microsim/MSEdge.h>
      29              : #include <microsim/MSLane.h>
      30              : #include "MSRailSignal.h"
      31              : #include "MSRailSignalConstraint.h"
      32              : #include "MSDriveWay.h"
      33              : #include "MSRailSignalControl.h"
      34              : 
      35              : 
      36              : //#define DEBUG_BUILD_DEADLOCK_CHECK
      37              : 
      38              : // ===========================================================================
      39              : // static value definitions
      40              : // ===========================================================================
      41              : MSRailSignalControl* MSRailSignalControl::myInstance(nullptr);
      42              : SVCPermissions MSRailSignalControl::mySignalizedClasses(SVC_UNSPECIFIED);
      43              : 
      44              : // ===========================================================================
      45              : // method definitions
      46              : // ===========================================================================
      47         1150 : MSRailSignalControl::MSRailSignalControl()
      48         1150 : {}
      49              : 
      50              : MSRailSignalControl&
      51     16787866 : MSRailSignalControl::getInstance() {
      52     16787866 :     if (myInstance == nullptr) {
      53         1150 :         myInstance = new MSRailSignalControl();
      54         1150 :         MSNet::getInstance()->addVehicleStateListener(myInstance);
      55              :     }
      56     16787866 :     return *myInstance;
      57              : }
      58              : 
      59              : void
      60        38777 : MSRailSignalControl::cleanup() {
      61        38777 :     delete myInstance;
      62        38777 :     myInstance = nullptr;
      63        38777 : }
      64              : 
      65              : void
      66          186 : MSRailSignalControl::clearState() {
      67          186 :     if (myInstance != nullptr) {
      68              :         myInstance->myDriveWayCompatibility.clear();
      69            9 :         myInstance->myDriveWaySucc.clear();
      70            9 :         myInstance->myDriveWayPred.clear();
      71            9 :         myInstance->myWrittenDeadlocks.clear();
      72            9 :         myInstance->myDeadlockChecks.clear();
      73              :         //myInstance->myActiveSignals.clear();
      74              :     }
      75          186 : }
      76              : 
      77              : 
      78         2298 : MSRailSignalControl::~MSRailSignalControl() {
      79         2298 : }
      80              : 
      81              : void
      82        16268 : MSRailSignalControl::vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& /*info*/) {
      83        16268 :     if (vehicle->isRail()) {
      84              :         std::string dummyMsg;
      85        17990 :         if ((to == MSNet::VehicleState::BUILT && (!vehicle->getParameter().wasSet(VEHPARS_FORCE_REROUTE) || vehicle->hasValidRoute(dummyMsg)))
      86        15924 :                 || to == MSNet::VehicleState::NEWROUTE) {
      87              :             // @note we could delay initialization until the departure time
      88         3534 :             if (vehicle->getEdge()->getFunction() != SumoXMLEdgeFunc::CONNECTOR && isRailwayOrShared(vehicle->getEdge()->getPermissions())) {
      89         3529 :                 MSRailSignal::initDriveWays(vehicle, to == MSNet::VehicleState::NEWROUTE);
      90              :             }
      91              :         }
      92              :     }
      93        16268 : }
      94              : 
      95              : 
      96              : void
      97         4597 : MSRailSignalControl::addSignal(MSRailSignal* signal) {
      98         4597 :     mySignals.push_back(signal);
      99        10416 :     for (const auto& links : signal->getLinks()) {
     100        11638 :         for (const MSLink* link : links) {
     101         5819 :             mySignalizedClasses |= link->getPermissions();
     102              :         }
     103              :     }
     104         4597 : }
     105              : 
     106              : 
     107              : void
     108       149113 : MSRailSignalControl::addWaitRelation(const SUMOVehicle* waits, const MSRailSignal* rs, const SUMOVehicle* reason, MSRailSignalConstraint* constraint) {
     109              :     //std::cout << time2string(SIMSTEP) << " addWaitRelation waits=" << waits->getID() << " foe=" << reason->getID() << "\n";
     110       149113 :     myWaitRelations[waits] = WaitRelation(rs, reason, constraint);
     111       149113 : }
     112              : 
     113              : 
     114              : bool
     115        13268 : MSRailSignalControl::haveDeadlock(const SUMOVehicle* veh) const {
     116              :     std::set<const SUMOVehicle*> seen;
     117              :     std::vector<WaitRelation> list;
     118        13268 :     const SUMOVehicle* cur = veh;
     119              :     std::vector<MSRailSignalConstraint*> constraints;
     120              :     std::vector<const SUMOVehicle*> constraintBlocked;
     121              :     std::vector<const MSRailSignal*> constraintSignals;
     122              :     //std::cout << time2string(SIMSTEP) << " haveDeadlock veh=" << veh->getID() << "\n";
     123              :     while (seen.count(cur) == 0) {
     124              :         auto it = myWaitRelations.find(cur);
     125        26158 :         if (it != myWaitRelations.end()) {
     126        12944 :             if (it->second.constraint != nullptr) {
     127           69 :                 constraints.push_back(it->second.constraint);
     128           69 :                 constraintBlocked.push_back(cur);
     129           69 :                 constraintSignals.push_back(it->second.railSignal);
     130              :             }
     131              :             seen.insert(cur);
     132        12944 :             list.push_back(it->second);
     133        12944 :             cur = it->second.foe;
     134              :         } else {
     135              :             return false;
     136              :         }
     137              :     }
     138           54 :     if (cur == veh) {
     139              :         const bool newDeadlock = myWrittenDeadlocks.count(seen) == 0;
     140              :         myWrittenDeadlocks.insert(seen);
     141           54 :         const OptionsCont& oc = OptionsCont::getOptions();
     142              :         MSRailSignalConstraint* resolved = nullptr;
     143              :         const SUMOVehicle* resolvedUnblocked = nullptr;
     144              :         const MSRailSignal* resolvedSignal = nullptr;
     145           90 :         if (!constraints.empty() && oc.getBool("time-to-teleport.remove-constraint")) {
     146           21 :             resolved = constraints.front();
     147           21 :             if (newDeadlock) {
     148              :                 std::vector<std::string> vehicles;
     149           54 :                 for (auto item : list) {
     150           36 :                     vehicles.push_back(item.foe->getID());
     151              :                 }
     152           36 :                 WRITE_WARNINGF("Deactivating constraint to resolve deadlock between vehicles % at time %.", toString(vehicles), time2string(SIMSTEP));
     153           18 :                 resolved->setActive(false);
     154           18 :                 resolvedUnblocked = constraintBlocked.front();
     155           18 :                 resolvedSignal = constraintSignals.front();
     156           18 :             }
     157              :         }
     158              : 
     159          108 :         if (oc.isSet("deadlock-output")) {
     160           54 :             if (newDeadlock) {
     161              :                 myWrittenDeadlocks.insert(seen);
     162              :                 std::vector<std::string> signals;
     163              :                 std::vector<std::string> vehicles;
     164              :                 std::vector<std::string> tripIDs;
     165          151 :                 for (auto item : list) {
     166          312 :                     signals.push_back(item.railSignal == nullptr ? "INSERTION" : item.railSignal->getID());
     167          108 :                     vehicles.push_back(item.foe->getID());
     168          324 :                     tripIDs.push_back(item.foe->getParameter().getParameter("tripId", item.foe->getID()));
     169              :                 }
     170           86 :                 OutputDevice& od = OutputDevice::getDeviceByOption("deadlock-output");
     171           43 :                 if (constraints.empty()) {
     172           10 :                     od.openTag(SUMO_TAG_DEADLOCK);
     173              :                 } else {
     174           66 :                     od.openTag("constraintDeadlock");
     175              :                 }
     176           43 :                 od.writeAttr(SUMO_ATTR_TIME, time2string(SIMSTEP));
     177           43 :                 od.writeAttr(SUMO_ATTR_SIGNALS, signals);
     178           86 :                 od.writeAttr("vehicles", vehicles);
     179           43 :                 if (!constraints.empty()) {
     180           66 :                     od.writeAttr("tripIds", tripIDs);
     181              :                 }
     182           43 :                 if (resolved != nullptr) {
     183           36 :                     od.openTag("resolvedConstraint");
     184           18 :                     od.writeAttr(SUMO_ATTR_ID, resolvedSignal->getID());
     185           54 :                     resolved->write(od, resolvedUnblocked->getParameter().getParameter("tripId", resolvedUnblocked->getID()));
     186           36 :                     od.closeTag();
     187              :                 }
     188           43 :                 od.closeTag();
     189              : 
     190           43 :             }
     191              :         }
     192           54 :         return resolved == nullptr;
     193              :     } else {
     194              :         // it's a deadlock but does not involve veh
     195              :         return false;
     196              :     }
     197        13268 : }
     198              : 
     199              : 
     200              : void
     201           15 : MSRailSignalControl::addDeadlockCheck(std::vector<const MSRailSignal*> signals) {
     202           15 :     if (MSDriveWay::haveDriveWays()) {
     203            0 :         WRITE_WARNING("Deadlocks should be loaded before any vehicles");
     204              :     }
     205           15 :     const int n = (int)signals.size();
     206           78 :     for (int i = 0; i < n; i++) {
     207              :         std::vector<const MSRailSignal*> others;
     208          342 :         for (int j = 0; j < n; j++) {
     209          279 :             others.push_back(signals[(i + j + 1) % n]);
     210              :         }
     211           63 :         myDeadlockChecks[signals[i]] = others;
     212           63 :     }
     213           15 : }
     214              : 
     215              : void
     216        35287 : MSRailSignalControl::addDrivewayFollower(const MSDriveWay* dw, const MSDriveWay* dw2) {
     217              :     //std::cout << " addDrivewayFollower " << dw->getID() << " " << dw2->getID() << "\n";
     218        35287 :     myDriveWaySucc[dw].insert(dw2);
     219        35287 :     myDriveWayPred[dw2].insert(dw);
     220        35287 : }
     221              : 
     222              : 
     223              : void
     224        35287 : MSRailSignalControl::addDWDeadlockChecks(const MSRailSignal* rs, MSDriveWay* dw) {
     225        35287 :     auto itDL = MSRailSignalControl::getInstance().getDeadlockChecks().find(rs);
     226        35287 :     if (itDL == MSRailSignalControl::getInstance().getDeadlockChecks().end()) {
     227        35167 :         return;
     228              :     }
     229          120 :     const std::vector<const MSRailSignal*>& others = itDL->second;
     230              :     // the driveway could be part of a deadlock. check whether it would be blocked by the next signal in the circle
     231              :     std::vector<const MSDriveWay*> deadlockFoes;
     232          120 :     findDeadlockFoes(dw, others, deadlockFoes);
     233          120 : }
     234              : 
     235              : 
     236              : void
     237          710 : MSRailSignalControl::findDeadlockFoes(const MSDriveWay* dw, const std::vector<const MSRailSignal*>& others, std::vector<const MSDriveWay*> deadlockFoes) {
     238              : #ifdef DEBUG_BUILD_DEADLOCK_CHECK
     239              :     //std::cout << " findDLfoes dw=" << dw->getID() << " dlFoes=" << toString(deadlockFoes) << "\n";
     240              : #endif
     241          710 :     int circleIndex = (int)deadlockFoes.size();
     242          710 :     if (circleIndex < (int)others.size()) {
     243          551 :         const MSRailSignal* other = others[circleIndex];
     244          551 :         deadlockFoes.push_back(dw);
     245         1047 :         for (const MSDriveWay* follower : myDriveWaySucc[dw]) {
     246         1986 :             for (MSDriveWay* foe : follower->getFoes()) {
     247         1490 :                 if (foe->getForward().back()->getEdge().getToJunction()->getID() == other->getID()) {
     248          590 :                     findDeadlockFoes(foe, others, deadlockFoes);
     249              :                 }
     250              :             }
     251              :         }
     252              :     } else {
     253              : #ifdef DEBUG_BUILD_DEADLOCK_CHECK
     254              :         std::cout << " add deadlock check foes=" << toString(deadlockFoes) << "\n";;
     255              : #endif
     256          784 :         for (const MSDriveWay* dldw : deadlockFoes) {
     257          625 :             if (dldw->isDepartDriveway()) {
     258          216 :                 const_cast<MSDriveWay*>(dldw)->addDWDeadlock(deadlockFoes);
     259              :             } else {
     260          844 :                 for (const MSDriveWay* pred : myDriveWayPred[dldw]) {
     261          435 :                     if (!pred->isDepartDriveway()) {
     262          144 :                         const MSRailSignal* predRS = dynamic_cast<const MSRailSignal*>(pred->getOrigin()->getTLLogic());
     263          144 :                         if (std::find(others.begin(), others.end(), predRS) != others.end()) {
     264              :                             // driveways that participate in the deadlock don't need to
     265              :                             // do checking since they cannot prevent the deadlock
     266              :                             // (unless they are departDriveways)
     267           86 :                             continue;
     268              :                         }
     269           58 :                         const_cast<MSDriveWay*>(pred)->addDWDeadlock(deadlockFoes);
     270              :                     }
     271              :                 }
     272              :             }
     273              :         }
     274              :     }
     275          710 : }
     276              : 
     277              : 
     278              : void
     279       622285 : MSRailSignalControl::notifyApproach(const MSLink* link) {
     280       622285 :     const MSRailSignal* rs = dynamic_cast<const MSRailSignal*>(link->getTLLogic());
     281              :     assert(rs != nullptr);
     282       622285 :     myActiveSignals.insert(const_cast<MSRailSignal*>(rs));
     283       622285 : }
     284              : 
     285              : 
     286              : void
     287      7928561 : MSRailSignalControl::updateSignals(SUMOTime t) {
     288              :     UNUSED_PARAMETER(t);
     289              :     // there are 4 states for a signal
     290              :     // 1. approached and green
     291              :     // 2. approached and red
     292              :     // 3. not approached and trains could pass
     293              :     // 4. not approached and trains coult not pass
     294              :     //
     295              :     // for understanding conflicts better in sumo-gui, we want to show (3) as green. This
     296              :     // means we have to keep updating signals in state (4) until they change to (3)
     297              : 
     298              :     //std::cout << SIMTIME << " activeSignals=" << myActiveSignals.size() << "\n";
     299     24115985 :     for (auto it = myActiveSignals.begin(); it != myActiveSignals.end();) {
     300     16187424 :         MSRailSignal* rs = *it;
     301              :         //std::cout << SIMTIME << " update " << rs->getID() << "\n";
     302     16187424 :         const bool keepActive = rs->updateCurrentPhase();
     303     16187424 :         if (rs->isActive()) {
     304     16187409 :             rs->setTrafficLightSignals(t);
     305              :         }
     306     16187424 :         if (!keepActive) {
     307              :             it = myActiveSignals.erase(it);
     308              :         } else {
     309              :             it++;
     310              :         }
     311              :     }
     312      7928561 : }
     313              : 
     314              : 
     315              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1