SUMO - Simulation of Urban MObility
NBOwnTLDef.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-2018 German Aerospace Center (DLR) and others.
4 // This program and the accompanying materials
5 // are made available under the terms of the Eclipse Public License v2.0
6 // which accompanies this distribution, and is available at
7 // http://www.eclipse.org/legal/epl-v20.html
8 // SPDX-License-Identifier: EPL-2.0
9 /****************************************************************************/
18 // A traffic light logics which must be computed (only nodes/edges are given)
19 /****************************************************************************/
20 
21 
22 // ===========================================================================
23 // included modules
24 // ===========================================================================
25 #include <config.h>
26 
27 #include <vector>
28 #include <cassert>
29 #include <iterator>
31 #include "NBNode.h"
32 #include "NBOwnTLDef.h"
33 #include "NBTrafficLightLogic.h"
36 #include <utils/common/ToString.h>
38 #include <utils/options/Option.h>
39 
40 #define MIN_GREEN_TIME 5
41 
42 //#define DEBUG_STREAM_ORDERING
43 #define DEBUGCOND true
44 
45 // ===========================================================================
46 // member method definitions
47 // ===========================================================================
48 NBOwnTLDef::NBOwnTLDef(const std::string& id,
49  const std::vector<NBNode*>& junctions, SUMOTime offset,
50  TrafficLightType type) :
51  NBTrafficLightDefinition(id, junctions, DefaultProgramID, offset, type),
52  myHaveSinglePhase(false) {
53 }
54 
55 
56 NBOwnTLDef::NBOwnTLDef(const std::string& id, NBNode* junction, SUMOTime offset,
57  TrafficLightType type) :
58  NBTrafficLightDefinition(id, junction, DefaultProgramID, offset, type),
59  myHaveSinglePhase(false) {
60 }
61 
62 
63 NBOwnTLDef::NBOwnTLDef(const std::string& id, SUMOTime offset,
64  TrafficLightType type) :
65  NBTrafficLightDefinition(id, DefaultProgramID, offset, type),
66  myHaveSinglePhase(false) {
67 }
68 
69 
71 
72 
73 int
74 NBOwnTLDef::getToPrio(const NBEdge* const e) {
75  return e->getJunctionPriority(e->getToNode());
76 }
77 
78 
79 double
81  switch (dir) {
82  case LINKDIR_STRAIGHT:
83  case LINKDIR_PARTLEFT:
84  case LINKDIR_PARTRIGHT:
85  return 2.;
86  case LINKDIR_LEFT:
87  case LINKDIR_RIGHT:
88  return .5;
89  default:
90  break;
91  }
92  return 0;
93 }
94 
95 double
97  double val = 0;
98  for (int e1l = 0; e1l < e1->getNumLanes(); e1l++) {
99  std::vector<NBEdge::Connection> approached1 = e1->getConnectionsFromLane(e1l);
100  for (int e2l = 0; e2l < e2->getNumLanes(); e2l++) {
101  std::vector<NBEdge::Connection> approached2 = e2->getConnectionsFromLane(e2l);
102  for (std::vector<NBEdge::Connection>::iterator e1c = approached1.begin(); e1c != approached1.end(); ++e1c) {
103  if (e1->getTurnDestination() == (*e1c).toEdge) {
104  continue;
105  }
106  for (std::vector<NBEdge::Connection>::iterator e2c = approached2.begin(); e2c != approached2.end(); ++e2c) {
107  if (e2->getTurnDestination() == (*e2c).toEdge) {
108  continue;
109  }
110  if (!forbids(e1, (*e1c).toEdge, e2, (*e2c).toEdge, true)) {
111  val += getDirectionalWeight(e1->getToNode()->getDirection(e1, (*e1c).toEdge));
112  val += getDirectionalWeight(e2->getToNode()->getDirection(e2, (*e2c).toEdge));
113  }
114  }
115  }
116  }
117  }
118  return val;
119 }
120 
121 
122 std::pair<NBEdge*, NBEdge*>
124  std::pair<NBEdge*, NBEdge*> bestPair(static_cast<NBEdge*>(0), static_cast<NBEdge*>(0));
125  double bestValue = -1;
126  for (EdgeVector::const_iterator i = edges.begin(); i != edges.end(); ++i) {
127  for (EdgeVector::const_iterator j = i + 1; j != edges.end(); ++j) {
128  const double value = computeUnblockedWeightedStreamNumber(*i, *j);
129  if (value > bestValue) {
130  bestValue = value;
131  bestPair = std::pair<NBEdge*, NBEdge*>(*i, *j);
132  } else if (value == bestValue) {
133  const double ca = GeomHelper::getMinAngleDiff((*i)->getAngleAtNode((*i)->getToNode()), (*j)->getAngleAtNode((*j)->getToNode()));
134  const double oa = GeomHelper::getMinAngleDiff(bestPair.first->getAngleAtNode(bestPair.first->getToNode()), bestPair.second->getAngleAtNode(bestPair.second->getToNode()));
135  if (fabs(oa - ca) < NUMERICAL_EPS) { // break ties by id
136  if (bestPair.first->getID() < (*i)->getID()) {
137  bestPair = std::pair<NBEdge*, NBEdge*>(*i, *j);
138  }
139  } else if (oa < ca) {
140  bestPair = std::pair<NBEdge*, NBEdge*>(*i, *j);
141  }
142  }
143  }
144  }
145  return bestPair;
146 }
147 
148 
149 std::pair<NBEdge*, NBEdge*>
151  if (incoming.size() == 1) {
152  // only one there - return the one
153  std::pair<NBEdge*, NBEdge*> ret(*incoming.begin(), static_cast<NBEdge*>(0));
154  incoming.clear();
155  return ret;
156  }
157  // determine the best combination
158  // by priority, first
159  EdgeVector used;
160  std::sort(incoming.begin(), incoming.end(), edge_by_incoming_priority_sorter());
161  used.push_back(*incoming.begin()); // the first will definitely be used
162  // get the ones with the same priority
163  int prio = getToPrio(*used.begin());
164  for (EdgeVector::iterator i = incoming.begin() + 1; i != incoming.end() && prio == getToPrio(*i); ++i) {
165  used.push_back(*i);
166  }
167  // if there only lower priorised, use these, too
168  if (used.size() < 2) {
169  used = incoming;
170  }
171  std::pair<NBEdge*, NBEdge*> ret = getBestCombination(used);
172 #ifdef DEBUG_STREAM_ORDERING
173  if (DEBUGCOND) {
174  std::cout << "getBestPair tls=" << getID() << " incoming=" << toString(incoming) << " prio=" << prio << " used=" << toString(used) << " best=" << Named::getIDSecure(ret.first) << ", " << Named::getIDSecure(ret.second) << "\n";
175  }
176 #endif
177 
178  incoming.erase(find(incoming.begin(), incoming.end(), ret.first));
179  incoming.erase(find(incoming.begin(), incoming.end(), ret.second));
180  return ret;
181 }
182 
184 NBOwnTLDef::myCompute(int brakingTimeSeconds) {
185  return computeLogicAndConts(brakingTimeSeconds);
186 }
187 
189 NBOwnTLDef::computeLogicAndConts(int brakingTimeSeconds, bool onlyConts) {
190  myNeedsContRelation.clear();
191  myRightOnRedConflicts.clear();
192  const SUMOTime brakingTime = TIME2STEPS(brakingTimeSeconds);
193  const SUMOTime leftTurnTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.left-green.time"));
194  const SUMOTime minDur = myType == TLTYPE_STATIC ? UNSPECIFIED_DURATION : TIME2STEPS(OptionsCont::getOptions().getInt("tls.min-dur"));
195  const SUMOTime maxDur = myType == TLTYPE_STATIC ? UNSPECIFIED_DURATION : TIME2STEPS(OptionsCont::getOptions().getInt("tls.max-dur"));
196 
197  // build complete lists first
198  const EdgeVector& incoming = getIncomingEdges();
199  EdgeVector fromEdges, toEdges;
200  std::vector<bool> isTurnaround;
201  std::vector<bool> hasTurnLane;
202  std::vector<int> fromLanes;
203  int noLanesAll = 0;
204  int noLinksAll = 0;
205  for (int i1 = 0; i1 < (int)incoming.size(); i1++) {
206  int noLanes = incoming[i1]->getNumLanes();
207  noLanesAll += noLanes;
208  for (int i2 = 0; i2 < noLanes; i2++) {
209  NBEdge* fromEdge = incoming[i1];
210  std::vector<NBEdge::Connection> approached = fromEdge->getConnectionsFromLane(i2);
211  noLinksAll += (int) approached.size();
212  bool hasStraight = false;
213  for (int i3 = 0; i3 < (int)approached.size(); i3++) {
214  if (!fromEdge->mayBeTLSControlled(i2, approached[i3].toEdge, approached[i3].toLane)) {
215  --noLinksAll;
216  continue;
217  }
218  assert(i3 < (int)approached.size());
219  NBEdge* toEdge = approached[i3].toEdge;
220  fromEdges.push_back(fromEdge);
221  fromLanes.push_back((int)i2);
222  toEdges.push_back(toEdge);
223  if (toEdge != 0) {
224  isTurnaround.push_back(fromEdge->isTurningDirectionAt(toEdge));
225  } else {
226  isTurnaround.push_back(true);
227  }
228  if (fromEdge->getToNode()->getDirection(fromEdge, toEdge) == LINKDIR_STRAIGHT) {
229  hasStraight = true;
230  }
231  }
232  for (int i3 = 0; i3 < (int)approached.size(); i3++) {
233  hasTurnLane.push_back(!hasStraight);
234  }
235  }
236  }
237  // collect crossings
238  std::vector<NBNode::Crossing*> crossings;
239  for (std::vector<NBNode*>::iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) {
240  const std::vector<NBNode::Crossing*>& c = (*i)->getCrossings();
241  if (!onlyConts) {
242  // set tl indices for crossings
243  (*i)->setCrossingTLIndices(getID(), noLinksAll);
244  }
245  copy(c.begin(), c.end(), std::back_inserter(crossings));
246  noLinksAll += (int)c.size();
247  }
248 
249  NBTrafficLightLogic* logic = new NBTrafficLightLogic(getID(), getProgramID(), noLinksAll, myOffset, myType);
250  EdgeVector toProc = getConnectedOuterEdges(incoming);
251  const SUMOTime greenTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.green.time"));
252  const SUMOTime allRedTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.allred.time"));
253  const double minorLeftSpeedThreshold = OptionsCont::getOptions().getFloat("tls.minor-left.max-speed");
254  // build all phases
255  std::vector<int> greenPhases; // indices of green phases
256  std::vector<bool> hadGreenMajor(noLinksAll, false);
257  while (toProc.size() > 0) {
258  std::pair<NBEdge*, NBEdge*> chosen;
259  if (incoming.size() == 2) {
260  // if there are only 2 incoming edges we need to decide whether they are a crossing or a "continuation"
261  // @node: this heuristic could be extended to also check the number of outgoing edges
262  double angle = fabs(NBHelpers::relAngle(incoming[0]->getAngleAtNode(incoming[0]->getToNode()), incoming[1]->getAngleAtNode(incoming[1]->getToNode())));
263  // angle would be 180 for straight opposing incoming edges
264  if (angle < 135) {
265  chosen = std::pair<NBEdge*, NBEdge*>(toProc[0], static_cast<NBEdge*>(0));
266  toProc.erase(toProc.begin());
267  } else {
268  chosen = getBestPair(toProc);
269  }
270  } else {
271  chosen = getBestPair(toProc);
272  }
273  int pos = 0;
274  std::string state((int) noLinksAll, 'r');
275  //std::cout << " computing " << getID() << " prog=" << getProgramID() << " cho1=" << Named::getIDSecure(chosen.first) << " cho2=" << Named::getIDSecure(chosen.second) << " toProc=" << toString(toProc) << "\n";
276  // plain straight movers
277  for (int i1 = 0; i1 < (int) incoming.size(); ++i1) {
278  NBEdge* fromEdge = incoming[i1];
279  const bool inChosen = fromEdge == chosen.first || fromEdge == chosen.second; //chosen.find(fromEdge)!=chosen.end();
280  const int numLanes = fromEdge->getNumLanes();
281  for (int i2 = 0; i2 < numLanes; i2++) {
282  std::vector<NBEdge::Connection> approached = fromEdge->getConnectionsFromLane(i2);
283  for (int i3 = 0; i3 < (int)approached.size(); ++i3) {
284  if (!fromEdge->mayBeTLSControlled(i2, approached[i3].toEdge, approached[i3].toLane)) {
285  continue;
286  }
287  if (inChosen) {
288  state[pos] = 'G';
289  } else {
290  state[pos] = 'r';
291  }
292  ++pos;
293  }
294  }
295  }
296  //std::cout << " state after plain straight movers=" << state << "\n";
297  // correct behaviour for those that are not in chosen, but may drive, though
298  state = allowFollowersOfChosen(state, fromEdges, toEdges);
299  for (int i1 = 0; i1 < pos; ++i1) {
300  if (state[i1] == 'G') {
301  continue;
302  }
303  bool isForbidden = false;
304  for (int i2 = 0; i2 < pos && !isForbidden; ++i2) {
305  if (state[i2] == 'G' && !isTurnaround[i2] &&
306  (forbids(fromEdges[i2], toEdges[i2], fromEdges[i1], toEdges[i1], true) || forbids(fromEdges[i1], toEdges[i1], fromEdges[i2], toEdges[i2], true))) {
307  isForbidden = true;
308  }
309  }
310  if (!isForbidden && !hasCrossing(fromEdges[i1], toEdges[i1], crossings)) {
311  state[i1] = 'G';
312  }
313  }
314  //std::cout << " state after finding additional 'G's=" << state << "\n";
315  // correct behaviour for those that have to wait (mainly left-mover)
316  bool haveForbiddenLeftMover = false;
317  std::vector<bool> rightTurnConflicts(pos, false);
318  state = correctConflicting(state, fromEdges, toEdges, isTurnaround, fromLanes, hadGreenMajor, haveForbiddenLeftMover, rightTurnConflicts);
319  for (int i1 = 0; i1 < pos; ++i1) {
320  if (state[i1] == 'G') {
321  hadGreenMajor[i1] = true;
322  }
323  }
324  //std::cout << " state after correcting left movers=" << state << "\n";
325 
326  std::vector<bool> leftGreen(pos, false);
327  // check whether at least one left-turn lane exist
328  bool foundLeftTurnLane = false;
329  for (int i1 = 0; i1 < pos; ++i1) {
330  if (state[i1] == 'g' && !rightTurnConflicts[i1] && hasTurnLane[i1]) {
331  foundLeftTurnLane = true;
332  }
333  }
334  const bool buildLeftGreenPhase = haveForbiddenLeftMover && !myHaveSinglePhase && leftTurnTime > 0 && foundLeftTurnLane;
335 
336  // find indices for exclusive left green phase and apply option minor-left.max-speed
337  for (int i1 = 0; i1 < pos; ++i1) {
338  if (state[i1] == 'g' && !rightTurnConflicts[i1]) {
339  leftGreen[i1] = true;
340  if (fromEdges[i1]->getSpeed() > minorLeftSpeedThreshold) {
341  if (buildLeftGreenPhase) {
342  state[i1] = 'r';
343  } else if (!isTurnaround[i1]) {
344  WRITE_WARNING("Minor green from edge '" + fromEdges[i1]->getID() + "' to edge '" + toEdges[i1]->getID() + "' exceeds "
345  + toString(minorLeftSpeedThreshold) + "m/s. Maybe a left-turn lane is missing.");
346  }
347  }
348  }
349  }
350 
351  const std::string vehicleState = state; // backup state before pedestrian modifications
352  greenPhases.push_back((int)logic->getPhases().size());
353  state = addPedestrianPhases(logic, greenTime, minDur, maxDur, state, crossings, fromEdges, toEdges);
354  // pedestrians have 'r' from here on
355  for (int i1 = pos; i1 < pos + (int)crossings.size(); ++i1) {
356  state[i1] = 'r';
357  }
358  if (brakingTime > 0) {
359  // build yellow (straight)
360  for (int i1 = 0; i1 < pos; ++i1) {
361  if (state[i1] != 'G' && state[i1] != 'g') {
362  continue;
363  }
364  if ((vehicleState[i1] >= 'a' && vehicleState[i1] <= 'z') && buildLeftGreenPhase && !rightTurnConflicts[i1]) {
365  continue;
366  }
367  state[i1] = 'y';
368  }
369  // add step
370  logic->addStep(brakingTime, state);
371  // add optional all-red state
372  buildAllRedState(allRedTime, logic, state);
373  }
374 
375 
376  if (buildLeftGreenPhase) {
377  // build left green
378  for (int i1 = 0; i1 < pos; ++i1) {
379  if (state[i1] == 'Y' || state[i1] == 'y') {
380  state[i1] = 'r';
381  continue;
382  }
383  if (state[i1] == 'g' || leftGreen[i1]) {
384  state[i1] = 'G';
385  }
386  }
387  state = allowFollowersOfChosen(state, fromEdges, toEdges);
388  state = correctConflicting(state, fromEdges, toEdges, isTurnaround, fromLanes, hadGreenMajor, haveForbiddenLeftMover, rightTurnConflicts);
389 
390  // add step
391  logic->addStep(leftTurnTime, state, minDur, maxDur);
392 
393  // build left yellow
394  if (brakingTime > 0) {
395  for (int i1 = 0; i1 < pos; ++i1) {
396  if (state[i1] != 'G' && state[i1] != 'g') {
397  continue;
398  }
399  state[i1] = 'y';
400  }
401  // add step
402  logic->addStep(brakingTime, state);
403  // add optional all-red state
404  buildAllRedState(allRedTime, logic, state);
405  }
406  }
407  }
408  // fix pedestrian crossings that did not get the green light yet
409  if (crossings.size() > 0) {
410  addPedestrianScramble(logic, noLinksAll, TIME2STEPS(10), brakingTime, crossings, fromEdges, toEdges);
411  }
412  // add optional red phase if there where no foes
413  if (logic->getPhases().size() == 2 && brakingTime > 0
414  && OptionsCont::getOptions().getInt("tls.red.time") > 0) {
415  const SUMOTime redTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.red.time"));
416  logic->addStep(redTime, std::string(noLinksAll, 'r'));
417  }
418  // fix states to account for custom crossing link indices
419  if (crossings.size() > 0 && !onlyConts) {
421  }
422 
423  SUMOTime totalDuration = logic->getDuration();
424  if (OptionsCont::getOptions().isDefault("tls.green.time") || !OptionsCont::getOptions().isDefault("tls.cycle.time")) {
425  const SUMOTime cycleTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.cycle.time"));
426  // adapt to cycle time by changing the duration of the green phases
427  SUMOTime greenPhaseTime = 0;
428  SUMOTime minGreenDuration = SUMOTime_MAX;
429  for (std::vector<int>::const_iterator it = greenPhases.begin(); it != greenPhases.end(); ++it) {
430  const SUMOTime dur = logic->getPhases()[*it].duration;
431  greenPhaseTime += dur;
432  minGreenDuration = MIN2(minGreenDuration, dur);
433  }
434  const int patchSeconds = (int)(STEPS2TIME(cycleTime - totalDuration) / greenPhases.size());
435  const int patchSecondsRest = (int)(STEPS2TIME(cycleTime - totalDuration)) - patchSeconds * (int)greenPhases.size();
436  //std::cout << "cT=" << cycleTime << " td=" << totalDuration << " pS=" << patchSeconds << " pSR=" << patchSecondsRest << "\n";
437  if (STEPS2TIME(minGreenDuration) + patchSeconds < MIN_GREEN_TIME
438  || STEPS2TIME(minGreenDuration) + patchSeconds + patchSecondsRest < MIN_GREEN_TIME
439  || greenPhases.size() == 0) {
440  if (getID() != DummyID) {
441  WRITE_WARNING("The traffic light '" + getID() + "' cannot be adapted to a cycle time of " + time2string(cycleTime) + ".");
442  }
443  // @todo use a multiple of cycleTime ?
444  } else {
445  for (std::vector<int>::const_iterator it = greenPhases.begin(); it != greenPhases.end(); ++it) {
446  logic->setPhaseDuration(*it, logic->getPhases()[*it].duration + TIME2STEPS(patchSeconds));
447  }
448  if (greenPhases.size() > 0) {
449  logic->setPhaseDuration(greenPhases.front(), logic->getPhases()[greenPhases.front()].duration + TIME2STEPS(patchSecondsRest));
450  }
451  totalDuration = logic->getDuration();
452  }
453  }
454 
456  // this computation only makes sense for single nodes
458  if (totalDuration > 0) {
459  if (totalDuration > 3 * (greenTime + 2 * brakingTime + leftTurnTime)) {
460  WRITE_WARNING("The traffic light '" + getID() + "' has a high cycle time of " + time2string(totalDuration) + ".");
461  }
462  logic->closeBuilding();
463  return logic;
464  } else {
465  delete logic;
466  return 0;
467  }
468 }
469 
470 
471 bool
472 NBOwnTLDef::hasCrossing(const NBEdge* from, const NBEdge* to, const std::vector<NBNode::Crossing*>& crossings) {
473  assert(to != 0);
474  for (auto c : crossings) {
475  const NBNode::Crossing& cross = *c;
476  // only check connections at this crossings node
477  if (to->getFromNode() == cross.node) {
478  for (EdgeVector::const_iterator it_e = cross.edges.begin(); it_e != cross.edges.end(); ++it_e) {
479  const NBEdge* edge = *it_e;
480  if (edge == from || edge == to) {
481  return true;
482  }
483  }
484  }
485  }
486  return false;
487 }
488 
489 
490 std::string
492  SUMOTime minDur, SUMOTime maxDur,
493  std::string state, const std::vector<NBNode::Crossing*>& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges) {
494  // compute based on length of the crossing if not set by the user
495  const SUMOTime pedClearingTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.crossing-clearance.time"));
496  // compute if not set by user: must be able to reach the middle of the second "Richtungsfahrbahn"
497  const SUMOTime minPedTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.crossing-min.time"));
498  const std::string orig = state;
499  state = patchStateForCrossings(state, crossings, fromEdges, toEdges);
500  if (orig == state) {
501  // add step
502  logic->addStep(greenTime, state, minDur, maxDur);
503  } else {
504  const SUMOTime pedTime = greenTime - pedClearingTime;
505  if (pedTime >= minPedTime) {
506  // ensure clearing time for pedestrians
507  const int pedStates = (int)crossings.size();
508  logic->addStep(pedTime, state, minDur, maxDur);
509  state = state.substr(0, state.size() - pedStates) + std::string(pedStates, 'r');
510  logic->addStep(pedClearingTime, state);
511  } else {
512  state = orig;
513  // not safe for pedestrians.
514  logic->addStep(greenTime, state, minDur, maxDur);
515  }
516  }
517  return state;
518 }
519 
520 
521 std::string
522 NBOwnTLDef::patchStateForCrossings(const std::string& state, const std::vector<NBNode::Crossing*>& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges) {
523  std::string result = state;
524  const int pos = (int)(state.size() - crossings.size()); // number of controlled vehicle links
525  for (int ic = 0; ic < (int)crossings.size(); ++ic) {
526  const int i1 = pos + ic;
527  const NBNode::Crossing& cross = *crossings[ic];
528  bool isForbidden = false;
529  for (int i2 = 0; i2 < pos && !isForbidden; ++i2) {
530  // only check connections at this crossings node
531  if (fromEdges[i2] != 0 && toEdges[i2] != 0 && fromEdges[i2]->getToNode() == cross.node) {
532  for (EdgeVector::const_iterator it = cross.edges.begin(); it != cross.edges.end(); ++it) {
533  const NBEdge* edge = *it;
534  const LinkDirection i2dir = cross.node->getDirection(fromEdges[i2], toEdges[i2]);
535  if (state[i2] != 'r' && state[i2] != 's' && (edge == fromEdges[i2] ||
536  (edge == toEdges[i2] && (i2dir == LINKDIR_STRAIGHT || i2dir == LINKDIR_PARTLEFT || i2dir == LINKDIR_PARTRIGHT)))) {
537  isForbidden = true;
538  break;
539  }
540  }
541  }
542  }
543  if (!isForbidden) {
544  result[i1] = 'G';
545  } else {
546  result[i1] = 'r';
547  }
548  }
549 
550  // correct behaviour for roads that are in conflict with a pedestrian crossing
551  for (int i1 = 0; i1 < pos; ++i1) {
552  if (result[i1] == 'G') {
553  for (int ic = 0; ic < (int)crossings.size(); ++ic) {
554  const NBNode::Crossing& crossing = *crossings[ic];
555  if (fromEdges[i1] != 0 && toEdges[i1] != 0 && fromEdges[i1]->getToNode() == crossing.node) {
556  const int i2 = pos + ic;
557  if (result[i2] == 'G' && crossing.node->mustBrakeForCrossing(fromEdges[i1], toEdges[i1], crossing)) {
558  result[i1] = 'g';
559  break;
560  }
561  }
562  }
563  }
564  }
565  return result;
566 }
567 
568 
569 void
571  collectAllLinks();
572 }
573 
574 
575 void
577  // set the information about the link's positions within the tl into the
578  // edges the links are starting at, respectively
579  for (NBConnectionVector::const_iterator j = myControlledLinks.begin(); j != myControlledLinks.end(); ++j) {
580  const NBConnection& conn = *j;
581  NBEdge* edge = conn.getFrom();
582  edge->setControllingTLInformation(conn, getID());
583  }
584 }
585 
586 
587 void
588 NBOwnTLDef::remapRemoved(NBEdge* /*removed*/, const EdgeVector& /*incoming*/,
589  const EdgeVector& /*outgoing*/) {}
590 
591 
592 void
593 NBOwnTLDef::replaceRemoved(NBEdge* /*removed*/, int /*removedLane*/,
594  NBEdge* /*by*/, int /*byLane*/) {}
595 
596 
597 void
600  if (myControlledNodes.size() > 0) {
601  // we use a dummy node just to maintain const-correctness
602  myNeedsContRelation.clear();
605  NBTrafficLightLogic* tllDummy = dummy.computeLogicAndConts(0, true);
606  delete tllDummy;
608  for (std::vector<NBNode*>::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) {
609  (*i)->removeTrafficLight(&dummy);
610  }
611  }
613  }
614 }
615 
616 
619  EdgeVector result = incoming;
620  for (EdgeVector::iterator it = result.begin(); it != result.end();) {
621  if ((*it)->getConnections().size() == 0 || (*it)->isInnerEdge()) {
622  it = result.erase(it);
623  } else {
624  ++it;
625  }
626  }
627  return result;
628 }
629 
630 
631 std::string
632 NBOwnTLDef::allowFollowersOfChosen(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges) {
633  bool check = true;
634  while (check) {
635  check = false;
636  for (int i1 = 0; i1 < (int)fromEdges.size(); ++i1) {
637  if (state[i1] == 'G') {
638  continue;
639  }
640  bool followsChosen = false;
641  for (int i2 = 0; i2 < (int)fromEdges.size() && !followsChosen; ++i2) {
642  if (state[i2] == 'G' && fromEdges[i1] == toEdges[i2]) {
643  followsChosen = true;
644  }
645  }
646  if (followsChosen) {
647  state[i1] = 'G';
648  check = true;
649  }
650  }
651  }
652  return state;
653 }
654 
655 
656 std::string
657 NBOwnTLDef::correctConflicting(std::string state, const EdgeVector& fromEdges, const EdgeVector& toEdges,
658  const std::vector<bool>& isTurnaround,
659  const std::vector<int>& fromLanes,
660  const std::vector<bool>& hadGreenMajor,
661  bool& haveForbiddenLeftMover,
662  std::vector<bool>& rightTurnConflicts) {
663  const bool controlledWithin = !OptionsCont::getOptions().getBool("tls.uncontrolled-within");
664  for (int i1 = 0; i1 < (int)fromEdges.size(); ++i1) {
665  if (state[i1] == 'G') {
666  for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) {
667  if ((state[i2] == 'G' || state[i2] == 'g')) {
669  fromEdges[i1], toEdges[i1], fromLanes[i1], fromEdges[i2], toEdges[i2], fromLanes[i2])) {
670  rightTurnConflicts[i1] = true;
671  }
672  if (forbids(fromEdges[i2], toEdges[i2], fromEdges[i1], toEdges[i1], true, controlledWithin) || rightTurnConflicts[i1]) {
673  state[i1] = 'g';
674  myNeedsContRelation.insert(StreamPair(fromEdges[i1], toEdges[i1], fromEdges[i2], toEdges[i2]));
675  if (!isTurnaround[i1] && !hadGreenMajor[i1]) {
676  haveForbiddenLeftMover = true;
677  }
678  }
679  }
680  }
681  }
682  if (state[i1] == 'r') {
683  if (fromEdges[i1]->getToNode()->getType() == NODETYPE_TRAFFIC_LIGHT_RIGHT_ON_RED &&
684  fromEdges[i1]->getToNode()->getDirection(fromEdges[i1], toEdges[i1]) == LINKDIR_RIGHT) {
685  state[i1] = 's';
686  // do not allow right-on-red when in conflict with exclusive left-turn phase
687  for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) {
688  if (state[i2] == 'G' && !isTurnaround[i2] &&
689  (forbids(fromEdges[i2], toEdges[i2], fromEdges[i1], toEdges[i1], true) ||
690  forbids(fromEdges[i1], toEdges[i1], fromEdges[i2], toEdges[i2], true))) {
691  const LinkDirection foeDir = fromEdges[i2]->getToNode()->getDirection(fromEdges[i2], toEdges[i2]);
692  if (foeDir == LINKDIR_LEFT || foeDir == LINKDIR_PARTLEFT) {
693  state[i1] = 'r';
694  break;
695  }
696  }
697  }
698  if (state[i1] == 's') {
699  // handle right-on-red conflicts
700  for (int i2 = 0; i2 < (int)fromEdges.size(); ++i2) {
701  if (state[i2] == 'G' && !isTurnaround[i2] &&
702  (forbids(fromEdges[i2], toEdges[i2], fromEdges[i1], toEdges[i1], true) ||
703  forbids(fromEdges[i1], toEdges[i1], fromEdges[i2], toEdges[i2], true))) {
704  myRightOnRedConflicts.insert(std::make_pair(i1, i2));
705  }
706  }
707  }
708  }
709  }
710  }
711  return state;
712 }
713 
714 
715 void
716 NBOwnTLDef::addPedestrianScramble(NBTrafficLightLogic* logic, int noLinksAll, SUMOTime /* greenTime */, SUMOTime brakingTime,
717  const std::vector<NBNode::Crossing*>& crossings, const EdgeVector& fromEdges, const EdgeVector& toEdges) {
718  const int vehLinks = noLinksAll - (int)crossings.size();
719  std::vector<bool> foundGreen(crossings.size(), false);
720  const std::vector<NBTrafficLightLogic::PhaseDefinition>& phases = logic->getPhases();
721  for (int i = 0; i < (int)phases.size(); ++i) {
722  const std::string state = phases[i].state;
723  for (int j = 0; j < (int)crossings.size(); ++j) {
724  LinkState ls = (LinkState)state[vehLinks + j];
726  foundGreen[j] = true;
727  }
728  }
729  }
730  for (int j = 0; j < (int)foundGreen.size(); ++j) {
731  if (!foundGreen[j]) {
732 
733  // add a phase where all pedestrians may walk, (preceded by a yellow phase and followed by a clearing phase)
734  if (phases.size() > 0) {
735  bool needYellowPhase = false;
736  std::string state = phases.back().state;
737  for (int i1 = 0; i1 < vehLinks; ++i1) {
738  if (state[i1] == 'G' || state[i1] == 'g') {
739  state[i1] = 'y';
740  needYellowPhase = true;
741  }
742  }
743  // add yellow step
744  if (needYellowPhase && brakingTime > 0) {
745  logic->addStep(brakingTime, state);
746  }
747  }
748  const SUMOTime pedClearingTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.crossing-clearance.time"));
749  const SUMOTime scrambleTime = TIME2STEPS(OptionsCont::getOptions().getInt("tls.scramble.time"));
750  addPedestrianPhases(logic, scrambleTime + pedClearingTime, UNSPECIFIED_DURATION, UNSPECIFIED_DURATION, std::string(noLinksAll, 'r'), crossings, fromEdges, toEdges);
751  break;
752  }
753  }
754 }
755 
756 
757 void
758 NBOwnTLDef::buildAllRedState(SUMOTime allRedTime, NBTrafficLightLogic* logic, const std::string& state) {
759  if (allRedTime > 0) {
760  // build all-red phase
761  std::string allRedState = state;
762  for (int i1 = 0; i1 < (int)state.size(); ++i1) {
763  if (allRedState[i1] == 'Y' || allRedState[i1] == 'y') {
764  allRedState[i1] = 'r';
765  }
766  }
767  logic->addStep(allRedTime, allRedState);
768  }
769 }
770 
771 void
773  int minCustomIndex = -1;
774  int maxCustomIndex = -1;
775  // collect crossings
776  for (std::vector<NBNode*>::const_iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) {
777  const std::vector<NBNode::Crossing*>& c = (*i)->getCrossings();
778  for (auto crossing : c) {
779  minCustomIndex = MIN2(minCustomIndex, crossing->customTLIndex);
780  minCustomIndex = MIN2(minCustomIndex, crossing->customTLIndex2);
781  maxCustomIndex = MAX2(maxCustomIndex, crossing->customTLIndex);
782  maxCustomIndex = MAX2(maxCustomIndex, crossing->customTLIndex2);
783  }
784  }
785  // custom crossing linkIndex could lead to longer states. ensure that every index has a state
786  if (maxCustomIndex >= logic->getNumLinks()) {
787  logic->setStateLength(maxCustomIndex + 1);
788  }
789  // XXX shorter state vectors are possible as well
790  // XXX if the indices are shuffled the guessed crossing states should be shuffled correspondingly
791  // XXX initialize the backward index to the same state as the forward index
792 }
793 
794 
795 int
799  if (logic != 0) {
800  return logic->getNumLinks() - 1;
801  } else {
802  return -1;
803  }
804 }
805 /****************************************************************************/
static double relAngle(double angle1, double angle2)
computes the relative angle between the two angles
Definition: NBHelpers.cpp:47
bool mayBeTLSControlled(int fromLane, NBEdge *toEdge, int toLane) const
return true if certain connection must be controlled by TLS
Definition: NBEdge.cpp:2705
static double getMinAngleDiff(double angle1, double angle2)
Returns the minimum distance (clockwise/counter-clockwise) between both angles.
Definition: GeomHelper.cpp:161
#define MIN_GREEN_TIME
Definition: NBOwnTLDef.cpp:40
The link is a partial left direction.
The link has green light, may pass.
virtual void setParticipantsInformation()
Builds the list of participating nodes/edges/links.
bool setControllingTLInformation(const NBConnection &c, const std::string &tlID)
Returns if the link could be set as to be controlled.
Definition: NBEdge.cpp:2716
void setTLControllingInformation() const
Informs edges about being controlled by a tls.
Definition: NBOwnTLDef.cpp:576
TrafficLightType myType
The algorithm type for the traffic light.
long long int SUMOTime
Definition: SUMOTime.h:36
int getInt(const std::string &name) const
Returns the int-value of the named option (only for Option_Integer)
void collectAllLinks()
helper method for use in NBOwnTLDef and NBLoadedSUMOTLDef
static const std::string DummyID
id for temporary definitions
int getNumLinks()
Returns the number of participating links.
static bool hasCrossing(const NBEdge *from, const NBEdge *to, const std::vector< NBNode::Crossing *> &crossings)
compute whether the given connection is crossed by pedestrians
Definition: NBOwnTLDef.cpp:472
RightOnRedConflicts myRightOnRedConflicts
A SUMO-compliant built logic for a traffic light.
int getJunctionPriority(const NBNode *const node) const
Returns the junction priority (normalised for the node currently build)
Definition: NBEdge.cpp:1749
The link has green light, has to brake.
std::string correctConflicting(std::string state, const EdgeVector &fromEdges, const EdgeVector &toEdges, const std::vector< bool > &isTurnaround, const std::vector< int > &fromLanes, const std::vector< bool > &hadGreenMajor, bool &haveForbiddenLeftMover, std::vector< bool > &rightTurnConflicts)
change &#39;G&#39; to &#39;g&#39; for conflicting connections
Definition: NBOwnTLDef.cpp:657
The representation of a single edge during network building.
Definition: NBEdge.h:65
std::string allowFollowersOfChosen(std::string state, const EdgeVector &fromEdges, const EdgeVector &toEdges)
allow connections that follow on of the chosen edges
Definition: NBOwnTLDef.cpp:632
TrafficLightType getType() const
get the algorithm type (static etc..)
const std::vector< PhaseDefinition > & getPhases() const
Returns the phases.
std::string time2string(SUMOTime t)
Definition: SUMOTime.cpp:67
NBTrafficLightLogic * compute(OptionsCont &oc)
Computes the traffic light logic.
The base class for traffic light logic definitions.
T MAX2(T a, T b)
Definition: StdDefs.h:76
NBEdge * getTurnDestination(bool possibleDestination=false) const
Definition: NBEdge.cpp:2981
static const SUMOTime UNSPECIFIED_DURATION
static std::string getIDSecure(const T *obj, const std::string &fallBack="NULL")
get an identifier for Named-like object which may be Null
Definition: Named.h:62
NBEdge * getFrom() const
returns the from-edge (start of the connection)
bool isForbidden(SVCPermissions permissions)
Returns whether an edge with the given permission is a forbidden edge.
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
const std::string & getID() const
Returns the id.
Definition: Named.h:69
#define TIME2STEPS(x)
Definition: SUMOTime.h:60
static EdgeVector getConnectedOuterEdges(const EdgeVector &incoming)
get edges that have connections
Definition: NBOwnTLDef.cpp:618
SUMOTime myOffset
The offset in the program.
The link is a (hard) left direction.
#define WRITE_WARNING(msg)
Definition: MsgHandler.h:242
std::pair< NBEdge *, NBEdge * > getBestPair(EdgeVector &incoming)
Returns the combination of two edges from the given which has most unblocked streams.
Definition: NBOwnTLDef.cpp:150
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:58
static bool rightTurnConflict(const NBEdge *from, const NBEdge *to, int fromLane, const NBEdge *prohibitorFrom, const NBEdge *prohibitorTo, int prohibitorFromLane, bool lefthand=false)
return whether the given laneToLane connection is a right turn which must yield to a bicycle crossing...
Definition: NBNode.cpp:1486
LinkDirection
The different directions a link between two lanes may take (or a stream between two edges)...
The link is a straight direction.
std::vector< Connection > getConnectionsFromLane(int lane) const
Returns connections from a given lane.
Definition: NBEdge.cpp:1085
static void addPedestrianScramble(NBTrafficLightLogic *logic, int noLinksAll, SUMOTime greenTime, SUMOTime yellowTime, const std::vector< NBNode::Crossing *> &crossings, const EdgeVector &fromEdges, const EdgeVector &toEdges)
add an additional pedestrian phase if there are crossings that did not get green yet ...
Definition: NBOwnTLDef.cpp:716
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition: ToString.h:49
int getNumLanes() const
Returns the number of lanes.
Definition: NBEdge.h:418
void replaceRemoved(NBEdge *removed, int removedLane, NBEdge *by, int byLane)
Replaces a removed edge/lane.
Definition: NBOwnTLDef.cpp:593
double computeUnblockedWeightedStreamNumber(const NBEdge *const e1, const NBEdge *const e2)
Returns how many streams outgoing from the edges can pass the junction without being blocked...
Definition: NBOwnTLDef.cpp:96
std::pair< NBEdge *, NBEdge * > getBestCombination(const EdgeVector &edges)
Returns the combination of two edges from the given which has most unblocked streams.
Definition: NBOwnTLDef.cpp:123
bool myHaveSinglePhase
Whether left-mover should not have an additional phase.
Definition: NBOwnTLDef.h:261
void checkCustomCrossingIndices(NBTrafficLightLogic *logic) const
fix states in regard to custom crossing indices
Definition: NBOwnTLDef.cpp:772
#define STEPS2TIME(x)
Definition: SUMOTime.h:58
~NBOwnTLDef()
Destructor.
Definition: NBOwnTLDef.cpp:70
LinkState
The right-of-way state of a link between two lanes used when constructing a NBTrafficLightLogic, in MSLink and GNEInternalLane.
#define DEBUGCOND
Definition: NBOwnTLDef.cpp:43
NBOwnTLDef(const std::string &id, const std::vector< NBNode *> &junctions, SUMOTime offset, TrafficLightType type)
Constructor.
Definition: NBOwnTLDef.cpp:48
T MIN2(T a, T b)
Definition: StdDefs.h:70
The link is a (hard) right direction.
static const std::string DefaultProgramID
const std::string & getProgramID() const
Returns the ProgramID.
The link is a partial right direction.
double getFloat(const std::string &name) const
Returns the double-value of the named option (only for Option_Float)
void buildAllRedState(SUMOTime allRedTime, NBTrafficLightLogic *logic, const std::string &state)
Definition: NBOwnTLDef.cpp:758
int getMaxIndex()
Returns the maximum index controlled by this traffic light.
Definition: NBOwnTLDef.cpp:796
SUMOTime getDuration() const
Returns the duration of the complete cycle.
LinkDirection getDirection(const NBEdge *const incoming, const NBEdge *const outgoing, bool leftHand=false) const
Returns the representation of the described stream&#39;s direction.
Definition: NBNode.cpp:1696
const EdgeVector & getIncomingEdges() const
Returns the list of incoming edges (must be build first)
static std::string patchStateForCrossings(const std::string &state, const std::vector< NBNode::Crossing *> &crossings, const EdgeVector &fromEdges, const EdgeVector &toEdges)
compute phase state in regard to pedestrian crossings
Definition: NBOwnTLDef.cpp:522
void closeBuilding(bool checkVarDurations=true)
closes the building process
NBTrafficLightLogic * myCompute(int brakingTimeSeconds)
Computes the traffic light logic finally in dependence to the type.
Definition: NBOwnTLDef.cpp:184
#define SUMOTime_MAX
Definition: SUMOTime.h:37
NBTrafficLightLogic * computeLogicAndConts(int brakingTimeSeconds, bool onlyConts=false)
helper function for myCompute
Definition: NBOwnTLDef.cpp:189
void collectLinks()
Collects the links participating in this traffic light.
Definition: NBOwnTLDef.cpp:570
static std::string addPedestrianPhases(NBTrafficLightLogic *logic, SUMOTime greenTime, SUMOTime minDur, SUMOTime maxDur, std::string state, const std::vector< NBNode::Crossing *> &crossings, const EdgeVector &fromEdges, const EdgeVector &toEdges)
add 1 or 2 phases depending on the presence of pedestrian crossings
Definition: NBOwnTLDef.cpp:491
bool forbids(const NBEdge *const possProhibitorFrom, const NBEdge *const possProhibitorTo, const NBEdge *const possProhibitedFrom, const NBEdge *const possProhibitedTo, bool regardNonSignalisedLowerPriority, bool sameNodeOnly=false) const
Returns the information whether "prohibited" flow must let "prohibitor" flow pass.
std::vector< NBEdge * > EdgeVector
container for (sorted) edges
Definition: NBCont.h:34
const NBNode * node
The parent node of this crossing.
Definition: NBNode.h:129
void setPhaseDuration(int phaseIndex, SUMOTime duration)
Modifies the duration for an existing phase (used by NETEDIT)
bool isTurningDirectionAt(const NBEdge *const edge) const
Returns whether the given edge is the opposite direction to this edge.
Definition: NBEdge.cpp:2652
double getDirectionalWeight(LinkDirection dir)
Returns the weight of a stream given its direction.
Definition: NBOwnTLDef.cpp:80
EdgeVector edges
The edges being crossed.
Definition: NBNode.h:131
Represents a single node (junction) during network building.
Definition: NBNode.h:68
A definition of a pedestrian crossing.
Definition: NBNode.h:125
bool mustBrakeForCrossing(const NBEdge *const from, const NBEdge *const to, const Crossing &crossing) const
Returns the information whether the described flow must brake for the given crossing.
Definition: NBNode.cpp:1480
void setStateLength(int numLinks, LinkState fill=LINKSTATE_TL_RED)
#define NUMERICAL_EPS
Definition: config.h:148
data structure for caching needsCont information
std::vector< NBNode * > myControlledNodes
The container with participating nodes.
NBNode * getFromNode() const
Returns the origin node of the edge.
Definition: NBEdge.h:432
A traffic light logics which must be computed (only nodes/edges are given)
Definition: NBOwnTLDef.h:47
void addStep(SUMOTime duration, const std::string &state, int index=-1)
Adds a phase to the logic.
void initNeedsContRelation() const
Definition: NBOwnTLDef.cpp:598
Sorts edges by their priority within the node they end at.
Definition: NBOwnTLDef.h:244
NBConnectionVector myControlledLinks
The list of controlled links.
NBNode * getToNode() const
Returns the destination node of the edge.
Definition: NBEdge.h:439
int getToPrio(const NBEdge *const e)
Returns this edge&#39;s priority at the node it ends at.
Definition: NBOwnTLDef.cpp:74
TrafficLightType
void remapRemoved(NBEdge *removed, const EdgeVector &incoming, const EdgeVector &outgoing)
Replaces occurences of the removed edge in incoming/outgoing edges of all definitions.
Definition: NBOwnTLDef.cpp:588