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