Eclipse SUMO - Simulation of Urban MObility
MSDelayBasedTrafficLightLogic.cpp
Go to the documentation of this file.
1 /****************************************************************************/
2 // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
3 // Copyright (C) 2001-2020 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 // An actuated traffic light logic based on time delay of approaching vehicles
19 /****************************************************************************/
20 #include <config.h>
21 
22 #include <cassert>
23 #include <vector>
24 #include <microsim/MSGlobals.h>
25 #include <microsim/MSNet.h>
29 #include <microsim/MSLane.h>
32 
33 #define INVALID_POSITION std::numeric_limits<double>::max()
34 
35 // ===========================================================================
36 // parameter defaults definitions
37 // ===========================================================================
38 
39 //#define DEBUG_TIMELOSS_CONTROL
40 
41 // ===========================================================================
42 // method definitions
43 // ===========================================================================
45  const std::string& id, const std::string& programID,
46  const Phases& phases,
47  int step, SUMOTime delay,
48  const std::map<std::string, std::string>& parameter,
49  const std::string& basePath) :
50  MSSimpleTrafficLightLogic(tlcontrol, id, programID, TrafficLightType::DELAYBASED, phases, step, delay, parameter) {
51 #ifdef DEBUG_TIMELOSS_CONTROL
52  std::cout << "Building delay based tls logic '" << id << "'" << std::endl;
53 #endif
54  myShowDetectors = StringUtils::toBool(getParameter("show-detectors", "false"));
55  myDetectionRange = StringUtils::toDouble(getParameter("detectorRange", toString(OptionsCont::getOptions().getFloat("tls.delay_based.detector-range"))));
57  myFile = FileHelpers::checkForRelativity(getParameter("file", "NUL"), basePath);
59  myVehicleTypes = getParameter("vTypes", "");
60 #ifdef DEBUG_TIMELOSS_CONTROL
61  std::cout << "show-detectors: " << myShowDetectors
62  << " detectorRange: " << myDetectionRange
63  << " minTimeLoss: " << myTimeLossThreshold
64  << " file: " << myFile
65  << " freq: " << myFreq
66  << " vTypes: " << myVehicleTypes
67  << std::endl;
68 #endif
69 }
70 
71 
72 void
75  assert(myLanes.size() > 0);
76  LaneVectorVector::const_iterator i2;
77  LaneVector::const_iterator i;
78  // build the E2 detectors
79  for (i2 = myLanes.begin(); i2 != myLanes.end(); ++i2) {
80  const LaneVector& lanes = *i2;
81  for (i = lanes.begin(); i != lanes.end(); i++) {
82  MSLane* lane = (*i);
83  if (noVehicles(lane->getPermissions())) {
84  // do not build detectors on green verges or sidewalks
85  continue;
86  }
87  // Build the detectors and register them at the detector control
88  if (myLaneDetectors.find(lane) == myLaneDetectors.end()) {
89  MSE2Collector* det = nullptr;
90  const std::string customID = getParameter(lane->getID());
91  if (customID != "") {
93  if (det == nullptr) {
94  WRITE_ERROR("Unknown laneAreaDetector '" + customID + "' given as custom detector for delay_based tlLogic '" + getID() + "', program '" + getProgramID() + ".");
95  continue;
96  }
98  } else {
99  std::string id = "TLS" + myID + "_" + myProgramID + "_E2CollectorOn_" + lane->getID();
102  }
103  myLaneDetectors[lane] = det;
104  }
105  }
106  }
107 }
108 
109 
110 
112 
113 // ------------ Switching and setting current rows
114 
115 
116 SUMOTime
117 MSDelayBasedTrafficLightLogic::proposeProlongation(const SUMOTime actDuration, const SUMOTime maxDuration, bool& othersEmpty) {
118 #ifdef DEBUG_TIMELOSS_CONTROL
119  std::cout << "\n" << SIMTIME << " MSDelayBasedTrafficLightLogic::proposeProlongation() for TLS '" << this->getID() << "' (current phase = " << myStep << ")" << std::endl;
120 #endif
121  SUMOTime prolongation = 0;
122  const std::string& state = getCurrentPhaseDef().getState();
123  // iterate over green lanes, eventually increase the proposed prolongationTime to the estimated passing time for each lane.
124  for (int i = 0; i < (int) state.size(); i++) {
125  // this lane index corresponds to a non-green time
126  bool igreen = state[i] == LINKSTATE_TL_GREEN_MAJOR || state[i] == LINKSTATE_TL_GREEN_MINOR;
127  const std::vector<MSLane*>& lanes = getLanesAt(i);
128  for (LaneVector::const_iterator j = lanes.begin(); j != lanes.end(); j++) {
129  LaneDetectorMap::iterator i = myLaneDetectors.find(*j);
130  if (i == myLaneDetectors.end()) {
131 #ifdef DEBUG_TIMELOSS_CONTROL
132  // no detector for this lane!? maybe noVehicles allowed
133  std::cout << "no detector on lane '" << (*j)->getID() << std::endl;
134 #endif
135  continue;
136  }
137  MSE2Collector* detector = static_cast<MSE2Collector* >(i->second);
138  const std::vector<MSE2Collector::VehicleInfo*> vehInfos = detector->getCurrentVehicles();
139 #ifdef DEBUG_TIMELOSS_CONTROL
140  int nrVehs = 0; // count vehicles on detector
141 #endif
142  if (igreen) {
143  // green phase
144  for (std::vector<MSE2Collector::VehicleInfo*>::const_iterator ivp = vehInfos.begin(); ivp != vehInfos.end(); ++ivp) {
145  MSE2Collector::VehicleInfo* iv = *ivp;
147  const SUMOTime estimatedTimeToJunction = TIME2STEPS((iv->distToDetectorEnd) / (*j)->getSpeedLimit());
148  if (actDuration + estimatedTimeToJunction <= maxDuration) {
149  // only prolong if vehicle has a chance to pass until max duration is reached
150  prolongation = MAX2(prolongation, estimatedTimeToJunction);
151  }
152 #ifdef DEBUG_TIMELOSS_CONTROL
153  nrVehs++;
154 #endif
155 
156 #ifdef DEBUG_TIMELOSS_CONTROL
157  std::cout << "vehicle '" << iv->id << "' with accumulated timeloss: " << iv->accumulatedTimeLoss
158  << "\nestimated passing time: " << estimatedTimeToJunction << std::endl;
159  } else {
160  std::string reason = iv->accumulatedTimeLoss <= myTimeLossThreshold ? " (time loss below threshold)" : " (front already left detector)";
161  std::cout << "disregarded: (vehicle '" << iv->id << "' with accumulated timeloss " << iv->accumulatedTimeLoss << ")" << reason << std::endl;
162 #endif
163  }
164  }
165  } else {
166  // non-green phase
167  if (vehInfos.size() > 0) {
168  // here is a car on a non-green approach
169  othersEmpty = false;
170  if (actDuration >= getCurrentPhaseDef().maxDuration) {
171 #ifdef DEBUG_TIMELOSS_CONTROL
172  std::cout << "Actual duration exceeds maxDuration and a vehicle is on concurrent approach: " << nrVehs << std::endl;
173 #endif
174  // don't prolong
175  return 0;
176  }
177  break;
178  }
179 #ifdef DEBUG_TIMELOSS_CONTROL
180  std::cout << "Number of current vehicles on detector: " << nrVehs << std::endl;
181 #endif
182  }
183  }
184  }
185 #ifdef DEBUG_TIMELOSS_CONTROL
186  std::cout << "Proposed prolongation (maximal estimated passing time): " << prolongation << std::endl; // debug
187 #endif
188  return prolongation;
189 }
190 
191 
192 SUMOTime
194  /* check if the actual phase should be prolonged */
195  const MSPhaseDefinition& currentPhase = getCurrentPhaseDef();
196  // time since last switch
197  const SUMOTime actDuration = MSNet::getInstance()->getCurrentTimeStep() - currentPhase.myLastSwitch;
198 
199 #ifdef DEBUG_TIMELOSS_CONTROL
200  std::cout << "last switch = " << currentPhase.myLastSwitch
201  << "\nactDuration = " << actDuration
202  << "\nmaxDuration = " << currentPhase.maxDuration
203  << std::endl;
204 #endif
205 
206  // flag whether to prolong or not
207  if (currentPhase.isGreenPhase() && !MSGlobals::gUseMesoSim) {
208  bool othersEmpty = true; // whether no vehicles are present on concurrent approaches
209  SUMOTime proposedProlongation = proposeProlongation(actDuration, currentPhase.maxDuration, othersEmpty);
210 
211 #ifdef DEBUG_TIMELOSS_CONTROL
212  std::cout << "othersEmpty = " << othersEmpty
213  << std::endl;
214 #endif
215 
216  // keep this phase a little longer?
217  bool prolong = othersEmpty || actDuration < currentPhase.maxDuration;
218  // assure minimal duration
219  proposedProlongation = MAX3(SUMOTime(0), proposedProlongation, currentPhase.minDuration - actDuration);
220  if (othersEmpty) {
221  // prolong by one second if no vehicles on other approaches
222  proposedProlongation = MAX2(proposedProlongation, TIME2STEPS(1.));
223  } else {
224  // vehicles are present on other approaches -> prolong no further than the max green time
225  proposedProlongation = MIN2(proposedProlongation, MAX2(SUMOTime(0), currentPhase.maxDuration - actDuration));
226  }
227 
228 #ifdef DEBUG_TIMELOSS_CONTROL
229  std::cout << "Proposed prolongation = " << proposedProlongation << std::endl;
230 #endif
231 
232  prolong = proposedProlongation > 0;
233  if (prolong) {
234  // check again after the prolonged period (must be positive...)
235  // XXX: Can it be harmful not to return a duration of integer seconds?
236  return proposedProlongation;
237  }
238  }
239  // Don't prolong... switch to the next phase
240  myStep++;
241  assert(myStep <= (int)myPhases.size());
242  if (myStep == (int)myPhases.size()) {
243  myStep = 0;
244  }
245  MSPhaseDefinition* newPhase = myPhases[myStep];
246  //stores the time the phase started
248  // set the next event
249  return newPhase->minDuration;
250 }
251 
252 void
254  myShowDetectors = show;
255  for (auto& item : myLaneDetectors) {
256  item.second->setVisible(myShowDetectors);
257  }
258 }
259 
260 
261 
262 /****************************************************************************/
#define INVALID_POSITION
@ DU_TL_CONTROL
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:284
#define SIMTIME
Definition: SUMOTime.h:60
#define TIME2STEPS(x)
Definition: SUMOTime.h:55
long long int SUMOTime
Definition: SUMOTime.h:31
bool noVehicles(SVCPermissions permissions)
Returns whether an edge with the given permission forbids vehicles.
TrafficLightType
@ SUMO_TAG_LANE_AREA_DETECTOR
alternative tag for e2 detector
@ LINKSTATE_TL_GREEN_MAJOR
The link has green light, may pass.
@ LINKSTATE_TL_GREEN_MINOR
The link has green light, has to brake.
T MIN2(T a, T b)
Definition: StdDefs.h:73
T MAX2(T a, T b)
Definition: StdDefs.h:79
T MAX3(T a, T b, T c)
Definition: StdDefs.h:93
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition: ToString.h:44
static std::string checkForRelativity(const std::string &filename, const std::string &basePath)
Returns the path from a configuration so that it is accessable from the current working directory.
double myDetectionRange
Range of the connected detector, which provides the information on approaching vehicles.
MSDelayBasedTrafficLightLogic(MSTLLogicControl &tlcontrol, const std::string &id, const std::string &programID, const MSSimpleTrafficLightLogic::Phases &phases, int step, SUMOTime delay, const std::map< std::string, std::string > &parameter, const std::string &basePath)
Constructor.
std::string myVehicleTypes
Whether detector output separates by vType.
void init(NLDetectorBuilder &nb)
Initializes the tls with information about incoming lanes.
SUMOTime myFreq
The frequency for aggregating detector output.
LaneDetectorMap myLaneDetectors
A map from lanes to the corresponding lane detectors.
bool myShowDetectors
Whether the detectors shall be shown in the GUI.
std::string myFile
The output file for generated detectors.
SUMOTime proposeProlongation(const SUMOTime actDuration, const SUMOTime maxDuration, bool &othersEmpty)
The returned, proposed prolongation for the green phase is oriented on the largest estimated passing ...
SUMOTime trySwitch()
Switches to the next phase, if possible.
const NamedObjectCont< MSDetectorFileOutput * > & getTypedDetectors(SumoXMLTag type) const
Returns the list of detectors of the given type.
void add(SumoXMLTag type, MSDetectorFileOutput *d, const std::string &device, SUMOTime splInterval, SUMOTime begin=-1)
Adds a detector/output combination into the containers.
An areal detector corresponding to a sequence of consecutive lanes.
Definition: MSE2Collector.h:79
std::vector< VehicleInfo * > getCurrentVehicles() const
Returns the VehicleInfos for the vehicles currently on the detector.
virtual void setVisible(bool)
static bool gUseMesoSim
Definition: MSGlobals.h:88
Representation of a lane in the micro simulation.
Definition: MSLane.h:82
SVCPermissions getPermissions() const
Returns the vehicle class permissions for this lane.
Definition: MSLane.h:547
double getLength() const
Returns the lane's length.
Definition: MSLane.h:539
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition: MSNet.cpp:171
MSDetectorControl & getDetectorControl()
Returns the detector control.
Definition: MSNet.h:434
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition: MSNet.h:313
The definition of a single phase of a tls logic.
const std::string & getState() const
Returns the state within this phase.
SUMOTime maxDuration
The maximum duration of the phase.
SUMOTime minDuration
The minimum duration of the phase.
SUMOTime myLastSwitch
Stores the timestep of the last on-switched of the phase.
bool isGreenPhase() const
Returns whether this phase is a pure "green" phase.
A fixed traffic light logic.
Phases myPhases
The list of phases this logic uses.
const MSPhaseDefinition & getCurrentPhaseDef() const
Returns the definition of the current phase.
A class that stores and controls tls and switching of their programs.
std::vector< MSLane * > LaneVector
Definition of the list of arrival lanes subjected to this tls.
const std::string myProgramID
The id of the logic.
LaneVectorVector myLanes
The list of LaneVectors; each vector contains the incoming lanes that belong to the same link index.
const LaneVector & getLanesAt(int i) const
Returns the list of lanes that are controlled by the signals at the given position.
std::vector< MSPhaseDefinition * > Phases
Definition of a list of phases, being the junction logic.
virtual void init(NLDetectorBuilder &nb)
Initialises the tls with information about incoming lanes.
const std::string & getProgramID() const
Returns this tl-logic's id.
Builds detectors for microsim.
virtual MSE2Collector * createE2Detector(const std::string &id, DetectorUsage usage, MSLane *lane, double pos, double endPos, double length, SUMOTime haltingTimeThreshold, double haltingSpeedThreshold, double jamDistThreshold, const std::string &vTypes, bool showDetector=true)
Creates a MSE2Collector instance, overridden by GUIE2Collector::createE2Detector()
std::string myID
The name of the object.
Definition: Named.h:124
const std::string & getID() const
Returns the id.
Definition: Named.h:73
T get(const std::string &id) const
Retrieves an item.
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:58
const std::string getParameter(const std::string &key, const std::string defaultValue="") const
Returns the value for a given key.
static double toDouble(const std::string &sData)
converts a string into the double value described by it by calling the char-type converter
static bool toBool(const std::string &sData)
converts a string into the bool value described by it by calling the char-type converter
A VehicleInfo stores values that are tracked for the individual vehicles on the detector,...
Definition: MSE2Collector.h:85
double accumulatedTimeLoss
Accumulated time loss that this vehicle suffered since it entered the detector.
double distToDetectorEnd
Distance left till the detector end after the last integration step (may become negative if the vehic...
std::string id
vehicle's ID