SUMO - Simulation of Urban MObility
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MSAgentbasedTrafficLightLogic.cpp
Go to the documentation of this file.
1 /****************************************************************************/
11 // An agentbased traffic light logic
12 /****************************************************************************/
13 // SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
14 // Copyright (C) 2001-2013 DLR (http://www.dlr.de/) and contributors
15 /****************************************************************************/
16 //
17 // This file is part of SUMO.
18 // SUMO is free software: you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation, either version 3 of the License, or
21 // (at your option) any later version.
22 //
23 /****************************************************************************/
24 
25 
26 // ===========================================================================
27 // included modules
28 // ===========================================================================
29 #ifdef _MSC_VER
30 #include <windows_config.h>
31 #else
32 #include <config.h>
33 #endif
34 
35 #include <cassert>
36 #include <utility>
37 #include <vector>
38 #include <bitset>
41 #include "MSTrafficLightLogic.h"
43 #include <microsim/MSLane.h>
44 #include <microsim/MSEdge.h>
45 
46 #ifdef CHECK_MEMORY_LEAKS
47 #include <foreign/nvwa/debug_new.h>
48 #endif // CHECK_MEMORY_LEAKS
49 
50 
51 // ===========================================================================
52 // parameter defaults definitions
53 // ===========================================================================
54 #define DEFAULT_T_DECIDE "1"
55 #define DEFAULT_LEARN_HORIZON "3"
56 #define DEFAULT_CYCLE_TIME "90"
57 #define DEFAULT_MIN_DIFF "1"
58 #define DEFAULT_DETECTOR_OFFSET "0"
59 
60 
61 // ===========================================================================
62 // member method definitions
63 // ===========================================================================
65  MSTLLogicControl& tlcontrol,
66  const std::string& id, const std::string& programID,
67  const Phases& phases, unsigned int step, SUMOTime delay,
68  const std::map<std::string, std::string>& parameter) :
69  MSSimpleTrafficLightLogic(tlcontrol, id, programID, phases, step, delay, parameter),
70  tSinceLastDecision(0), stepOfLastDecision(0) {
71 
72  tDecide = TplConvert::_2int(getParameter("decision-horizon", DEFAULT_T_DECIDE).c_str());
76 }
77 
78 
79 void
81  SUMOReal det_offset = TplConvert::_2SUMOReal(getParameter("detector_offset", DEFAULT_DETECTOR_OFFSET).c_str());
82  LaneVectorVector::const_iterator i2;
83  LaneVector::const_iterator i;
84  // build the detectors
85  for (i2 = myLanes.begin(); i2 != myLanes.end(); ++i2) {
86  const LaneVector& lanes = *i2;
87  for (i = lanes.begin(); i != lanes.end(); i++) {
88  MSLane* lane = (*i);
89  // Build the lane state detetcor and set it into the container
90  std::string id = "TL_" + myID + "_" + myProgramID + "_E2OverLanesDetectorStartingAt_" + lane->getID();
91 
92  if (myE2Detectors.find(lane) == myE2Detectors.end()) {
94  nb.buildMultiLaneE2Det(id,
95  DU_TL_CONTROL, lane, 0, det_offset,
96  /*haltingTimeThreshold!!!*/ 1,
97  /*haltingSpeedThreshold!!!*/(SUMOReal)(5.0 / 3.6),
98  /*jamDistThreshold!!!*/ 10);
99  myE2Detectors[lane] = static_cast<MS_E2_ZS_CollectorOverLanes*>(det);
100  }
101  }
102  }
103 
104 
105  // initialise the duration
106  unsigned int tCycleIst = 0; // the actual cycletime
107  unsigned int tCycleMin = 0; // the minimum cycle time
108  unsigned int tDeltaGreen = 0; // the difference between the actual cycle time and the required cycle time
109 
111  for (unsigned int actStep = 0; actStep != myPhases.size(); actStep++) {
112  unsigned int dur = (unsigned int) myPhases[actStep]->duration;
113  tCycleIst = tCycleIst + dur;
114  if (myPhases[actStep]->isGreenPhase()) {
115  unsigned int mindur = (unsigned int) myPhases[actStep]->minDuration;
116  tCycleMin = tCycleMin + mindur;
117  } else {
118  tCycleMin = tCycleMin + dur;
119  }
120  }
121  if (tCycle < tCycleMin) {
122  tCycle = tCycleMin;
123  }
124  if (tCycleIst < tCycle) {
125  tDeltaGreen = tCycle - tCycleIst;
126  lengthenCycleTime(tDeltaGreen);
127  }
128  if (tCycleIst > tCycle) {
129  tDeltaGreen = tCycleIst - tCycle;
130  cutCycleTime(tDeltaGreen);
131  }
132 }
133 
134 
136 
137 
138 // ------------ Switching and setting current rows
139 SUMOTime
141  assert(getCurrentPhaseDef().minDuration >= 0);
142  assert(getCurrentPhaseDef().minDuration <= getCurrentPhaseDef().duration);
143  if (myPhases[myStep]->isGreenPhase()) {
144  // collects the data for the signal control
145  collectData();
146  // decides wheter greentime shall distributed between phases
147  if (tDecide <= tSinceLastDecision) {
149  }
150  }
151  // increment the index to the current phase
152  nextStep();
153  // set the next event
154  while (getCurrentPhaseDef().duration == 0) {
155  nextStep();
156  }
157  assert(myPhases.size() > myStep);
158  return getCurrentPhaseDef().duration;
159 }
160 
161 
162 // ------------ "agentbased" algorithm methods
163 unsigned int
165  // increment the index to the current phase
166  myStep++;
167  assert(myStep <= myPhases.size());
168  if (myStep == myPhases.size()) {
169  myStep = 0;
170  }
171  // increment the number of cycles since last decision
172  if (myStep == stepOfLastDecision) {
174  }
175  return myStep;
176 }
177 
178 
179 void
181  const std::string& state = getCurrentPhaseDef().getState();
182  // finds the maximum QUEUE_LENGTH_AHEAD_OF_TRAFFIC_LIGHTS_IN_VEHICLES of one phase
183  SUMOReal maxPerPhase = 0;
184  for (unsigned int i = 0; i < (unsigned int) state.size(); i++) {
185  // finds the maximum QUEUE_LENGTH_AHEAD_OF_TRAFFIC_LIGHTS_IN_VEHICLES of all lanes that have green
186  if (state[i] == LINKSTATE_TL_GREEN_MAJOR || state[i] == LINKSTATE_TL_GREEN_MINOR) {
187  const std::vector<MSLane*>& lanes = getLanesAt(i);
188  if (lanes.empty()) {
189  break;
190  }
191  SUMOReal maxPerBit = 0;
192  for (LaneVector::const_iterator j = lanes.begin(); j != lanes.end(); j++) {
193  if ((*j)->getEdge().getPurpose() == MSEdge::EDGEFUNCTION_INTERNAL) {
194  continue;
195  }
204  }
205  if (maxPerPhase < maxPerBit) {
206  maxPerPhase = maxPerBit;
207  }
208  }
209  }
210  // if still no entry for the phase exists a new entry with an empty value is created
211  if (myRawDetectorData.find(myStep) == myRawDetectorData.end()) {
212  ValueType firstData;
213  myRawDetectorData[myStep] = firstData;
214  }
215  /* checks whether the number of values that are already in the dataqueue is
216  the same number of values taht shall be consideres in the traffic control
217  if both numbers are the same, the oldest value is deleted */
218  if (myRawDetectorData[myStep].size() == numberOfValues) {
219  myRawDetectorData[myStep].pop_back();
220  }
221  // adds the detectorvalue of the considered phase
222  myRawDetectorData[myStep].push_front(maxPerPhase);
223 }
224 
225 
226 void
228  for (PhaseValueMap::const_iterator i = myRawDetectorData.begin(); i != myRawDetectorData.end(); i++) {
229  SUMOReal sum = 0;
230  for (ValueType:: const_iterator it = myRawDetectorData[(*i).first].begin(); it != myRawDetectorData[(*i).first].end(); it ++) {
231  sum = sum + *it;
232  }
233  SUMOReal meanvalue = sum / myRawDetectorData[(*i).first].size();
234  myMeanDetectorData[(*i).first] = meanvalue;
235  }
236 }
237 
238 
239 void
242  unsigned int stepOfMaxValue = findStepOfMaxValue();
243  if (stepOfMaxValue == myPhases.size()) {
244  return;
245  }
246  unsigned int stepOfMinValue = findStepOfMinValue();
247  if (stepOfMinValue == myPhases.size()) {
248  return;
249  }
250  if (stepOfMinValue == stepOfMaxValue) {
251  return;
252  }
253  SUMOReal deltaIst = (myMeanDetectorData[stepOfMaxValue] - myMeanDetectorData[stepOfMinValue])
254  / myMeanDetectorData[stepOfMaxValue];
255  if (deltaIst > deltaLimit) {
256  myPhases[stepOfMaxValue]->duration = myPhases[stepOfMaxValue]->duration + 1;
257  myPhases[stepOfMinValue]->duration = myPhases[stepOfMinValue]->duration - 1;
258  tSinceLastDecision = 0;
260  }
261 }
262 
263 
264 void
266  typedef std::pair <unsigned int, unsigned int> contentType;
267  typedef std::vector< std::pair <unsigned int, unsigned int> > GreenPhasesVector;
268  GreenPhasesVector tmp_phases(myPhases.size());
269  tmp_phases.clear();
270  unsigned int maxLengthen = 0; // the sum of all times, that is possible to lengthen
271 
272  /* fills the vector tmp_phases with the difference between
273  duration and maxduration and the myStep of the phases.
274  only phases with duration < maxDuration are written in the vector.
275  sorts the vector after the difference. */
276  for (unsigned int i_Step = 0; i_Step != myPhases.size(); i_Step++) {
277  if (myPhases[i_Step]->isGreenPhase()) {
278  unsigned int dur = (unsigned int) myPhases[i_Step]->duration;
279  unsigned int maxdur = (unsigned int) myPhases[i_Step]->maxDuration;
280  if (dur < maxdur) {
281  contentType tmp;
282  tmp.second = i_Step;
283  tmp.first = maxdur - dur;
284  tmp_phases.push_back(tmp);
285  maxLengthen = maxLengthen + tmp.first;
286  }
287  }
288  }
289  sort(tmp_phases.begin(), tmp_phases.end());
290  //lengthens the phases acording to the difference between duration and maxDuration
291  for (GreenPhasesVector::iterator i = tmp_phases.begin(); i != tmp_phases.end(); i++) {
292  SUMOTime toLengthenPerPhase = 0;
293  SUMOReal tmpdb = ((*i).first * toLengthen / SUMOReal(maxLengthen)) + (SUMOReal) 0.5;
294  toLengthenPerPhase = static_cast<SUMOTime>(tmpdb);
295  toLengthen = toLengthen - (unsigned int) toLengthenPerPhase;
296  maxLengthen = maxLengthen - (*i).first;
297  SUMOTime newDur = myPhases[(*i).second]->duration + toLengthenPerPhase;
298  myPhases[(*i).second]->duration = newDur;
299  }
300 }
301 
302 
303 void
305  typedef std::pair <unsigned int, unsigned int> contentType;
306  typedef std::vector< std::pair <unsigned int, unsigned int> > GreenPhasesVector;
307  GreenPhasesVector tmp_phases(myPhases.size());
308  tmp_phases.clear();
309  unsigned maxCut = 0; // the sum of all times, that is possible to cut
310 
311  /* fills the vector tmp_phases with the difference between
312  duration and minduration and the myStep of the phases.
313  only phases with duration > minDuration are written in the vector.
314  sorts the vector after the difference. */
315  for (unsigned i_Step = 0; i_Step != myPhases.size(); i_Step++) {
316  if (myPhases[i_Step]->isGreenPhase()) {
317  unsigned int dur = (unsigned int) myPhases[i_Step]->duration;
318  unsigned int mindur = (unsigned int) myPhases[i_Step]->minDuration;
319  if (dur > mindur) {
320  contentType tmp;
321  tmp.second = i_Step;
322  tmp.first = dur - mindur;
323  tmp_phases.push_back(tmp);
324  maxCut = maxCut + tmp.first;
325  }
326  }
327  }
328  std::sort(tmp_phases.begin(), tmp_phases.end());
329  //cuts the phases acording to the difference between duration and minDuration
330  for (GreenPhasesVector::iterator i = tmp_phases.begin(); i != tmp_phases.end(); i++) {
331  SUMOTime toCutPerPhase = 0;
332  SUMOReal tmpdb = ((*i).first * toCut / SUMOReal(maxCut)) + (SUMOReal) 0.5;
333  toCutPerPhase = static_cast<SUMOTime>(tmpdb);
334  toCut = toCut - (unsigned int) toCutPerPhase;
335  maxCut = maxCut - (*i).first;
336  SUMOTime newDur = myPhases[(*i).second]->duration - toCutPerPhase;
337  myPhases[(*i).second]->duration = newDur;
338  }
339 }
340 
341 
342 unsigned int
344  unsigned int StepOfMaxValue = (unsigned int) myPhases.size();
345  SUMOReal MaxValue = -1;
346  for (MeanDataMap::const_iterator it = myMeanDetectorData.begin(); it != myMeanDetectorData.end(); it++) {
347  // checks whether the actual duruation is shorter than maxduration
348  // otherwise the phase can't be lenghten
349  unsigned int maxDur = (unsigned int) myPhases[(*it).first]->maxDuration;
350  unsigned int actDur = (unsigned int) myPhases[(*it).first]->duration;
351  if (actDur >= maxDur) {
352  continue;
353  }
354  if ((*it).second > MaxValue) {
355  MaxValue = (*it).second;
356  StepOfMaxValue = (*it).first;
357  }
358  }
359  return StepOfMaxValue;
360 }
361 
362 
363 unsigned int
365  unsigned int StepOfMinValue = (unsigned int) myPhases.size();
366  SUMOReal MinValue = 9999;
367  for (MeanDataMap::const_iterator it = myMeanDetectorData.begin(); it != myMeanDetectorData.end(); it++) {
368  // checks whether the actual duruation is longer than minduration
369  // otherwise the phase can't be cut
370  unsigned int minDur = (unsigned int) myPhases[(*it).first]->minDuration;
371  unsigned int actDur = (unsigned int) myPhases[(*it).first]->duration;
372  if (actDur <= minDur) {
373  continue;
374  }
375  if ((*it).second < MinValue) {
376  MinValue = (*it).second;
377  StepOfMinValue = (*it).first;
378  }
379  }
380  return StepOfMinValue;
381 }
382 
383 
384 /*
385 SUMOReal
386 MSAgentbasedTrafficLightLogic::currentForLane(E2::DetType what,
387  MSLane *lane) const
388 {
389 
390  E2DetectorMap::const_iterator i=myE2Detectors.find(lane);
391  return (*i).second->getCurrent(what);
392 }
393 */
394 
395 
396 /****************************************************************************/
397 
void init(NLDetectorBuilder &nb)
Initialises the tls with information about incoming lanes.
PhaseValueMap myRawDetectorData
A map of the step of the greenphases and their detectorvalues for several (mumberofValues) cycles...
#define DEFAULT_T_DECIDE
unsigned int numberOfValues
The number of detector values whivh is considered to make a decision.
The link has green light, may pass.
#define DEFAULT_DETECTOR_OFFSET
Builds detectors for microsim.
const std::string & getState() const
Returns the state within this phase.
unsigned int myStep
The current step.
std::string myProgramID
The id of the logic.
static SUMOReal _2SUMOReal(const E *const data)
Definition: TplConvert.h:223
A detector which joins E2Collectors over consecutive lanes (backward)
The link has green light, has to brake.
void lengthenCycleTime(unsigned int toLenghten)
lenghtens the actual cycle by an given value
Phases myPhases
The list of phases this logic uses.
void calculateDuration()
Calculates the duration for all real phases except intergreen phases.
MSDetectorFileOutput * buildMultiLaneE2Det(const std::string &id, DetectorUsage usage, MSLane *lane, SUMOReal pos, SUMOReal length, SUMOTime haltingTimeThreshold, SUMOReal haltingSpeedThreshold, SUMOReal jamDistThreshold)
Builds an e2 detector that continues on preceeding lanes.
const std::string & getParameter(const std::string &key, const std::string &defaultValue) const
Returns the value for a given key.
std::deque< SUMOReal > ValueType
Definition of a map which stores the detector values of one single phase.
unsigned int nextStep()
Returns the index of the phase next to the given phase.
MSAgentbasedTrafficLightLogic(MSTLLogicControl &tlcontrol, const std::string &id, const std::string &programID, const MSSimpleTrafficLightLogic::Phases &phases, unsigned int step, SUMOTime delay, const std::map< std::string, std::string > &parameter)
Constructor.
A fixed traffic light logic.
LaneVectorVector myLanes
The list of links which do participate in this traffic light.
A class that stores and controls tls and switching of their programs.
unsigned int findStepOfMaxValue() const
Returns the step of the phase with the longest Queue_Lengt_Ahead_Of_Traffic_Lights.
const std::string & getID() const
Returns the id.
Definition: Named.h:60
SUMOTime duration
The duration of the phase.
unsigned int tCycle
The cycletime of the trafficlight.
void aggregateRawData()
Aggregates the data of one phase, collected during different cycles.
MeanDataMap myMeanDetectorData
A map of the step of the greenphases and their aggregated detectordata.
#define DEFAULT_LEARN_HORIZON
#define DEFAULT_MIN_DIFF
const LaneVector & getLanesAt(unsigned int i) const
Returns the list of lanes that are controlled by the signals at the given position.
unsigned int tDecide
the interval in which the traffic light can make a decision
const MSPhaseDefinition & getCurrentPhaseDef() const
Returns the definition of the current phase.
SUMOTime trySwitch(bool isActive)
Switches to the next phase.
void collectData()
Collects the traffic data.
unsigned int tSinceLastDecision
The number of cycles, before the last decision was made.
E2DetectorMap myE2Detectors
A map from lanes to E2 detectors lying on them.
std::vector< MSPhaseDefinition * > Phases
Definition of a list of phases, being the junction logic.
static int _2int(const E *const data)
Definition: TplConvert.h:114
std::string myID
The name of the object.
Definition: Named.h:121
std::vector< MSLane * > LaneVector
Definition of the list of links that participate in this tl-light.
void cutCycleTime(unsigned int toCut)
cuts the actual cycle by an given value
int SUMOTime
Definition: SUMOTime.h:43
#define SUMOReal
Definition: config.h:221
The edge is an internal edge.
Definition: MSEdge.h:90
unsigned int findStepOfMinValue() const
Returns the step of the phase with the shortest Queue_Lengt_Ahead_Of_Traffic_Lights.
Representation of a lane in the micro simulation.
Definition: MSLane.h:73
#define DEFAULT_CYCLE_TIME
unsigned int stepOfLastDecision
Stores the step of the phase, when the last decision was made.
Base of value-generating classes (detectors)