SUMO - Simulation of Urban MObility
MSSOTLTrafficLightLogic.cpp
Go to the documentation of this file.
1 /****************************************************************************/
9 // The base abstract class for SOTL logics
10 /****************************************************************************/
11 // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
12 // Copyright (C) 2013-2017 DLR (http://www.dlr.de/) and contributors
13 /****************************************************************************/
14 //
15 // This file is part of SUMO.
16 // SUMO is free software: you can redistribute it and/or modify
17 // it under the terms of the GNU General Public License as published by
18 // the Free Software Foundation, either version 3 of the License, or
19 // (at your option) any later version.
20 //
21 /****************************************************************************/
22 
24 #include "../MSLane.h"
25 #include "../MSEdge.h"
26 #include "MSPushButton.h"
27 
28 #if 1
29 #define ANALYSIS_DBG(X) {X}
30 #else
31 #define ANALYSIS_DBG(X) DBG(X)
32 #endif
33 // ===========================================================================
34 // member method definitions
35 // ===========================================================================
37  MSTLLogicControl& tlcontrol,
38  const std::string& id,
39  const std::string& subid,
40  const Phases& phases,
41  int step,
42  SUMOTime delay,
43  const std::map<std::string, std::string>& parameters)
44  : MSPhasedTrafficLightLogic(tlcontrol, id, subid, phases, step, delay, parameters) {
45  this->mySensors = NULL;
46  this->myCountSensors = NULL;
47  sensorsSelfBuilt = true;
48  checkPhases();
49  setupCTS();
51 }
52 
54  MSTLLogicControl& tlcontrol,
55  const std::string& id,
56  const std::string& subid,
57  const Phases& phases,
58  int step,
59  SUMOTime delay,
60  const std::map<std::string, std::string>& parameters,
61  MSSOTLSensors* sensors)
62  : MSPhasedTrafficLightLogic(tlcontrol, id, subid, phases, step, delay, parameters) {
63  this->mySensors = sensors;
64  sensorsSelfBuilt = false;
65  checkPhases();
66  setupCTS();
68 }
69 
71  for (PhasePushButtons::iterator mapIt = m_pushButtons.begin(); mapIt != m_pushButtons.end(); ++mapIt)
72  for (std::vector<MSPushButton*>::iterator vIt = mapIt->second.begin(); vIt != mapIt->second.end(); ++vIt) {
73  delete *vIt;
74  }
75  m_pushButtons.clear();
76  for (int i = 0; i < (int)myPhases.size(); i++) {
77  delete myPhases[i];
78  }
79  if (sensorsSelfBuilt) {
80  delete mySensors;
81 // delete myCountSensors;
82  }
83 }
84 
86 
87 }
88 
89 void
91  for (int step = 0; step < (int)getPhases().size(); step++) {
92  if (getPhase(step).isUndefined()) {
93  MsgHandler::getErrorInstance()->inform("Step " + toString(step) + " of traffic light logic " + myID + " phases declaration has its type undeclared!");
94  }
95  }
96 }
97 
98 void
100  for (int phaseStep = 0; phaseStep < (int)getPhases().size(); phaseStep++) {
101  if (getPhase(phaseStep).isTarget()) {
102  targetPhasesCTS[phaseStep] = 0;
104  targetPhasesLastSelection[phaseStep] = 0;
105  }
106  }
107 }
108 
109 void
111  for (int step = 0; step < (int)getPhases().size(); step++) {
112  if (getPhase(step).isTarget()) {
113  setStep(step);
114  lastChain = step;
115  return;
116  }
117  }
118  MsgHandler::getErrorInstance()->inform("No phase of type target found for traffic light logic " + myID + " The logic could malfunction. Check phases declaration.");
119 }
120 
121 
122 void
124 
126 
128  decayThreshold = 1;
129  }
130  if (sensorsSelfBuilt) {
131  //Building SOTLSensors
132  switch (SENSORS_TYPE) {
133  case SENSORS_TYPE_E1:
134  assert(0); // Throw exception because TLS can only handle E2 sensors
135  case SENSORS_TYPE_E2:
136 
137  //Adding Sensors to the ingoing Lanes
138 
140 
141  DBG(
142  WRITE_MESSAGE("Listing lanes for TLS " + getID());
143 
144  for (int i = 0; i < lvv.size(); i++) {
145  LaneVector lv = lvv[i];
146 
147  for (int j = 0; j < lv.size(); j++) {
148  MSLane* lane = lv[j];
149  WRITE_MESSAGE(lane ->getID());
150  }
151  }
152  )
153 
156  mySensors->stepChanged(getCurrentPhaseIndex());
157  if (getParameter("USE_VEHICLE_TYPES_WEIGHTS", "0") == "1") {
158  ((MSSOTLE2Sensors*) mySensors)->setVehicleWeigths(getParameter("VEHICLE_TYPES_WEIGHTS", ""));
159  }
160 
161  //threshold speed param for tuning with irace
162  ((MSSOTLE2Sensors*)mySensors)->setSpeedThresholdParam(getSpeedThreshold());
163 
164  myCountSensors = new MSSOTLE2Sensors(myID + "Count", &(getPhases()));
167 
168  //Adding Sensors to the outgoing Lanes
169 
171 
172 
173  DBG(
174  WRITE_MESSAGE("Listing output lanes");
175  for (int i = 0; i < myLinks.size(); i++) {
176  LinkVector oneLink = getLinksAt(i);
177 
178  for (int j = 0; j < oneLink.size(); j++) {
179 
180  MSLane* lane = oneLink[j]->getLane();
181  WRITE_MESSAGE(lane ->getID());
182 
183  }
184  }
185  )
186 
187 
188  LaneVectorVector myLaneVector;
189 
190  LaneVector outLanes;
191  LinkVectorVector myoutLinks = getLinks();
192 
193  for (int i = 0; i < (int)myLinks.size(); i++) {
194  LinkVector oneLink = getLinksAt(i);
195  for (int j = 0; j < (int)oneLink.size(); j++) {
196  MSLane* lane = oneLink[j]->getLane();
197  outLanes.push_back(lane);
198  }
199  }
200 
201  if (outLanes.size() > 0) {
202  myLaneVector.push_back(outLanes);
203  }
204  if (myLaneVector.size() > 0) {
205  ((MSSOTLE2Sensors*)mySensors)->buildOutSensors(myLaneVector, nb, getOutputSensorsLength());
206  myCountSensors->buildCountOutSensors(myLaneVector, nb);
207  }
208 
209  }
210  }
211 }
212 
213 
214 void
216  std::map<int, SUMOTime>::iterator phaseIterator = targetPhasesCTS.find(phaseStep);
217  if (phaseIterator != targetPhasesCTS.end()) {
218  phaseIterator->second = 0;
220  }
221 }
222 
223 void
225  SUMOTime elapsedTimeSteps = 0;
227  //Iterate over the target phase map and update CTS value for every target phase except for the one belonging to the current steps chain
228  for (std::map<int, SUMOTime>::iterator mapIterator = targetPhasesCTS.begin();
229  mapIterator != targetPhasesCTS.end();
230  mapIterator++) {
231  int chain = mapIterator->first;
232  SUMOTime oldVal = mapIterator->second;
233  if (chain != lastChain) {
234  //Get the number of timesteps since the last check for that phase
235  elapsedTimeSteps = now - lastCheckForTargetPhase[chain];
236  //Update the last check time
237  lastCheckForTargetPhase[chain] = now;
238  //Increment the CTS
239  //SWITCH between 3 counting vehicles function
240  switch (getMode()) {
241  case (0):
242  mapIterator->second += elapsedTimeSteps
243  * countVehicles(getPhase(chain)); //SUMO
244  break;
245  case (1):
246  mapIterator->second += elapsedTimeSteps
247  * countVehicles(getPhase(chain)); //COMPLEX
248  break;
249  case (2):
250  mapIterator->second = countVehicles(getPhase(chain)); //QUEUE
251  break;
252  default:
253  WRITE_ERROR("Unrecognized traffic threshold calculation mode");
254  }
255  std::ostringstream oss;
256  oss << "MSSOTLTrafficLightLogic::updateCTS->TLC " << getID() << " chain " << chain << " oldVal " << oldVal << " newVal " << mapIterator->second;
257  WRITE_MESSAGE(oss.str());
258  }
261  }
262  }
263 }
264 
265 int
267 
268  if (!phase.isTarget()) {
269  return 0;
270  }
271 
272  int accumulator = 0;
273  //Iterate over the target lanes for the current target phase to get the number of approaching vehicles
275  for (MSPhaseDefinition::LaneIdVector::const_iterator laneIterator = targetLanes.begin(); laneIterator != targetLanes.end(); laneIterator++) {
276  //SWITCH between 3 counting vehicles function
277  switch (getMode()) {
278  case (0):
279  accumulator += mySensors->countVehicles((*laneIterator)); //SUMO
280  break;
281  case (1):
282  accumulator += ((MSSOTLE2Sensors*)mySensors)->estimateVehicles((*laneIterator)); //COMPLEX
283  break;
284  case (2):
285  accumulator = MAX2((int)((MSSOTLE2Sensors*)mySensors)->getEstimateQueueLength((*laneIterator)), accumulator); //QUEUE
286  break;
287  default:
288  WRITE_ERROR("Unrecognized traffic threshold calculation mode");
289  }
290  }
291  return accumulator;
292 }
293 
294 void
296  if (getCurrentPhaseDef().isGreenPhase()) {
298  }
299 // ANALYSIS_DBG(
300  DBG(
301  std::stringstream out;
302  out << decayThreshold;
303  WRITE_MESSAGE("\n" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + "\tMSSOTLTrafficLightLogic::updateDecayThreshold():: " + out.str());
304  )
305 }
306 bool
308 
309  DBG(
310  // WRITE_MESSAGE("\n" +time2string(MSNet::getInstance()->getCurrentTimeStep()) +"\tMSSOTLTrafficLightLogic::isThresholdPassed():: " + " tlsid=" + getID());
311 
312  std::ostringstream threshold_str;
313  // threshold_str << "tlsid=" << getID() << " targetPhaseCTS size=" << targetPhasesCTS.size();
314 // threshold_str << "\n";
315  WRITE_MESSAGE(threshold_str.str());
316  )
317  /*
318  * if a dynamic threshold based on the exponential decrease, if passed we force the phase change
319  */
320 // double random = ((double) RandHelper::rand(RAND_MAX) / (RAND_MAX));
321  double random = RandHelper::rand();
322 // ANALYSIS_DBG(
323  DBG(
325  std::ostringstream str;
326  str << time2string(MSNet::getInstance()->getCurrentTimeStep()) << "\tMSSOTLTrafficLightLogic::isThresholdPassed():: "
327  << " tlsid=" << getID() << " decayThreshold=" << decayThreshold << " random=" << random << ">" << (1 - decayThreshold)
328  << (random > (1 - decayThreshold) ? " true" : " false");
329 
330  WRITE_MESSAGE(str.str());
331  }
332  )
333  if (!isDecayThresholdActivated() || (isDecayThresholdActivated() && random > (1 - decayThreshold))) {
334  for (std::map<int, SUMOTime>::const_iterator iterator =
335  targetPhasesCTS.begin(); iterator != targetPhasesCTS.end();
336  iterator++) {
337  DBG(
338  SUMOTime step = MSNet::getInstance()->getCurrentTimeStep();
339  std::ostringstream threshold_str;
340  // threshold_str <<"\tTL " +getID()<<" time " +time2string(step)<< "(getThreshold()= " << getThreshold()
341  // << ", targetPhaseCTS= " << iterator->second << " )" << " phase="<<getPhase(iterator->first).getState();
342  threshold_str << getCurrentPhaseDef().getState() << ";" << time2string(step) << ";" << getThreshold()
343  << ";" << iterator->second << ";" << getPhase(iterator->first).getState() << ";"
344  << iterator->first << "!=" << lastChain;
345  WRITE_MESSAGE(threshold_str.str());
346  );
347  //Note that the current chain is not eligible to be directly targeted again, it would be unfair
348  if ((iterator->first != lastChain) && (getThreshold() <= iterator->second)) {
349  return true;
350  }
351  }
352  return false;
353  } else {
354  return true;
355  }
356 }
357 
358 
359 SUMOTime
361  MSPhaseDefinition currentPhase = getCurrentPhaseDef();
362 
364  SUMOTime elapsed = now - currentPhase.myLastSwitch;
365 
366  return elapsed;
367 }
368 
369 
370 int
372  SUMOTime maxCTS = 0;
373  int maxLastStep = getTargetPhaseMaxLastSelection();
374  bool usedMaxCTS = false;
375  std::vector<int> equalIndexes;
376  for (std::map<int, int>::const_iterator it = targetPhasesLastSelection.begin();
377  it != targetPhasesLastSelection.end(); ++it) {
378  if (it->first != lastChain) {
379  if (maxLastStep < it->second) {
380  maxLastStep = it->second;
381  equalIndexes.clear();
382  equalIndexes.push_back(it->first);
383  } else if (maxLastStep == it->second) {
384  equalIndexes.push_back(it->first);
385  }
386  }
387  }
388  if (equalIndexes.size() == 0) {
389  usedMaxCTS = true;
390  for (std::map<int, SUMOTime>::const_iterator iterator = targetPhasesCTS.begin();
391  iterator != targetPhasesCTS.end(); ++iterator) {
392  if (iterator->first != lastChain) {
393  if (maxCTS < iterator->second) {
394  maxCTS = iterator->second;
395  equalIndexes.clear();
396  equalIndexes.push_back(iterator->first);
397  } else if (maxCTS == iterator->second) {
398  equalIndexes.push_back(iterator->first);
399  }
400  }
401  }
402  }
403 
404  std::ostringstream oss;
405  oss << "MSSOTLTrafficLightLogic::getPhaseIndexWithMaxCTS-> TLC " << getID();
406  if (usedMaxCTS) {
407  oss << " maxCTS " << maxCTS;
408  } else {
409  oss << " forcing selection since not selected for " << maxLastStep;
410  }
411  if (equalIndexes.size() == 1) {
412  oss << " phase " << equalIndexes[0];
413  WRITE_MESSAGE(oss.str());
414  return equalIndexes[0];
415  } else {
416  const int index = RandHelper::getRandomFrom(equalIndexes);
417  oss << " phases [";
418  for (std::vector<int>::const_iterator it = equalIndexes.begin(); it != equalIndexes.end(); ++it) {
419  oss << *it << ", ";
420  }
421  oss << "]. Random select " << index;
422  WRITE_MESSAGE(oss.str());
423  return index;
424  }
425 }
426 
427 int
429  MSPhaseDefinition currentPhase = getCurrentPhaseDef();
430  //If the junction was in a commit step
431  //=> go to the target step that gives green to the set with the current highest CTS
432  // and return computeReturnTime()
433  if (currentPhase.isCommit()) {
434  // decide which chain to activate. Gotta work on this
435  return getPhaseIndexWithMaxCTS();
436  }
437  if (currentPhase.isTransient()) {
438  //If the junction was in a transient step
439  //=> go to the next step and return computeReturnTime()
440  return getCurrentPhaseIndex() + 1;
441  }
442 
443  if (currentPhase.isDecisional()) {
444 
445  if (canRelease()) {
446  return getCurrentPhaseIndex() + 1;
447  }
448  }
449 
450  return getCurrentPhaseIndex();
451 }
452 
453 SUMOTime
455  if (MSNet::getInstance()->getCurrentTimeStep() % 1000 == 0) {
456  WRITE_MESSAGE("MSSOTLTrafficLightLogic::trySwitch()")
457  // To check if decideNextPhase changes the step
458  int previousStep = getCurrentPhaseIndex() ;
459  SUMOTime elapsed = getCurrentPhaseElapsed();
460  // Update CTS according to sensors
461  updateCTS();
462 
463  // Invoking the function member, specialized for each SOTL logic
465  MSPhaseDefinition currentPhase = getCurrentPhaseDef();
466 
467  //At the end, check if new step started
468  if (getCurrentPhaseIndex() != previousStep) {
469  //Check if a new steps chain started
470  if (currentPhase.isTarget()) {
471  //Reset CTS for the ending steps chain
473  //Update lastTargetPhase
475  for (std::map<int, int>::iterator it = targetPhasesLastSelection.begin(); it != targetPhasesLastSelection.end(); ++ it) {
476  if (it->first == lastChain) {
477  if (it->second >= getTargetPhaseMaxLastSelection()) {
478  std::ostringstream oss;
479  oss << "Forced selection of the phase " << lastChain << " since its last selection was " << it->second << " changes ago";
480  WRITE_MESSAGE(oss.str())
481  }
482  it->second = 0;
483  } else if (it->first != previousStep) {
484  ++it->second;
485  }
486  }
488  decayThreshold = 1;
489  }
490  }
491  //Inform the sensors logic
493  //Store the time the new phase started
496  decayThreshold = 1;
497  }
498  ANALYSIS_DBG(
499  std::ostringstream oss;
500  oss << getID() << " from " << getPhase(previousStep).getState() << " to " << currentPhase.getState() << " after " << time2string(elapsed);
501  WRITE_MESSAGE(time2string(MSNet::getInstance()->getCurrentTimeStep()) + "\tMSSOTLTrafficLightLogic::trySwitch " + oss.str());
502  )
503  }
504  }
505  return computeReturnTime();
506 }
507 
509  if (getParameter("USE_PUSH_BUTTON", "0") == "0") {
510  return false;
511  }
512  const MSPhaseDefinition currentPhase = getCurrentPhaseDef();
513  if (m_pushButtons.find(currentPhase.getState()) == m_pushButtons.end()) {
514  m_pushButtons[currentPhase.getState()] = MSPedestrianPushButton::loadPushButtons(&currentPhase);
515  }
516  return MSPushButton::anyActive(m_pushButtons[currentPhase.getState()]);
517 }
518 
static const T & getRandomFrom(const std::vector< T > &v)
Returns a random element from the given vector.
Definition: RandHelper.h:114
const std::string & getState() const
Returns the state within this phase.
static MsgHandler * getErrorInstance()
Returns the instance to add errors to.
Definition: MsgHandler.cpp:76
Builds detectors for microsim.
void init(NLDetectorBuilder &nb)
Initialises the tls with sensors on incoming and outgoing lanes Sensors are built in the simulation a...
#define ANALYSIS_DBG(X)
const LaneVectorVector & getLaneVectors() const
Returns the list of lists of all lanes controlled by this tls.
std::string time2string(SUMOTime t)
Definition: SUMOTime.cpp:60
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition: MSNet.cpp:158
T MAX2(T a, T b)
Definition: StdDefs.h:70
const MSPhaseDefinition & getPhase(int givenstep) const
Returns the definition of the phase from the given position within the plan.
std::map< int, SUMOTime > lastCheckForTargetPhase
const std::string & getID() const
Returns the id.
Definition: Named.h:66
void buildCountOutSensors(MSTrafficLightLogic::LaneVectorVector controlledLanes, NLDetectorBuilder &nb)
const LinkVectorVector & getLinks() const
Returns the list of lists of all affected links.
const LinkVector & getLinksAt(int i) const
Returns the list of links that are controlled by the signals at the given position.
LaneVectorVector myLanes
The list of LaneVectors; each vector contains the incoming lanes that belong to the same link index...
A class that stores and controls tls and switching of their programs.
std::vector< LinkVector > LinkVectorVector
Definition of a list that holds lists of links that do have the same attribute.
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition: ToString.h:56
SUMOTime myLastSwitch
Stores the timestep of the last on-switched of the phase.
Phases myPhases
The list of phases this logic uses.
virtual void init(NLDetectorBuilder &nb)
Initialises the tls with information about incoming lanes.
std::map< int, SUMOTime > targetPhasesCTS
void buildCountSensors(MSTrafficLightLogic::LaneVectorVector controlledLanes, NLDetectorBuilder &nb)
bool isTransient() const
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition: MSNet.h:257
static double rand()
Returns a random real number in [0, 1)
Definition: RandHelper.h:62
#define DBG(X)
Definition: SwarmDebug.h:30
virtual int countVehicles(MSLane *lane)=0
std::vector< MSLink * > LinkVector
Definition of the list of links that are subjected to this tls.
bool isUndefined() const
std::vector< MSPhaseDefinition * > Phases
Definition of a list of phases, being the junction logic.
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:206
const std::string & getParameter(const std::string &key, const std::string &defaultValue) const
Returns the value for a given key.
#define SENSORS_TYPE
LinkVectorVector myLinks
The list of LinkVectors; each vector contains the links that belong to the same link index...
MSSOTLTrafficLightLogic(MSTLLogicControl &tlcontrol, const std::string &id, const std::string &subid, const Phases &phases, int step, SUMOTime delay, const std::map< std::string, std::string > &parameters)
Constructor without sensors passed.
std::string myID
The name of the object.
Definition: Named.h:136
std::vector< MSLane * > LaneVector
Definition of the list of arrival lanes subjected to this tls.
std::vector< LaneVector > LaneVectorVector
Definition of a list that holds lists of lanes that do have the same attribute.
std::vector< std::string > LaneIdVector
const MSPhaseDefinition & getCurrentPhaseDef() const
Returns the definition of the current phase.
int getCurrentPhaseIndex() const
Returns the current index within the program.
void buildSensors(MSTrafficLightLogic::LaneVectorVector controlledLanes, NLDetectorBuilder &nb)
This function member has to be extended to properly build sensors for the input lanes Sensors has to ...
SUMOTime trySwitch()
Switches to the next phase.
const Phases & getPhases() const
Returns the phases of this tls program.
void inform(std::string msg, bool addType=true)
adds a new error to the list
Definition: MsgHandler.cpp:85
static std::vector< MSPushButton * > loadPushButtons(const MSPhaseDefinition *)
Loads all the pushbuttons for all the controlled lanes of a stage.
virtual SUMOTime computeReturnTime()
#define SENSORS_TYPE_E2
virtual bool canRelease()=0
long long int SUMOTime
Definition: TraCIDefs.h:52
const LaneIdVector & getTargetLaneSet() const
virtual void stepChanged(int newStep)
A fixed traffic light logic.
#define WRITE_MESSAGE(msg)
Definition: MsgHandler.h:201
static bool anyActive(const std::vector< MSPushButton *> &)
Checks if any pushbutton in the vector is active.
The definition of a single phase of a tls logic.
Representation of a lane in the micro simulation.
Definition: MSLane.h:79
#define SENSORS_TYPE_E1
void setStep(int step)
Forces a specific step.
bool isDecisional() const
std::map< int, int > targetPhasesLastSelection
int countVehicles(MSPhaseDefinition phase)