Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
MSActuatedTrafficLightLogic.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2001-2026 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
22// An actuated (adaptive) traffic light logic
23/****************************************************************************/
24#include <config.h>
25
26#include <cassert>
27#include <utility>
28#include <vector>
29#include <bitset>
34#include <microsim/MSGlobals.h>
35#include <microsim/MSNet.h>
36#include <microsim/MSLane.h>
37#include <microsim/MSEdge.h>
41
42//#define DEBUG_DETECTORS
43//#define DEBUG_PHASE_SELECTION
44//#define DEBUG_PHASE_SELECTION_CUSTOM
45#define DEBUG_COND (getID()=="C")
46
47// ===========================================================================
48// static members
49// ===========================================================================
50const std::vector<std::string> MSActuatedTrafficLightLogic::OPERATOR_PRECEDENCE({
51 "**", "^", "*", "/", "+", "-", "%",
52 "=", "==", "!=", "<", ">", "<=", ">=",
53 "and", "&&", "or", "||",
54});
55
56// ===========================================================================
57// parameter defaults definitions
58// ===========================================================================
59#define DEFAULT_MAX_GAP "3.0"
60#define DEFAULT_PASSING_TIME "1.9"
61#define DEFAULT_DETECTOR_GAP "2.0"
62#define DEFAULT_INACTIVE_THRESHOLD "180"
63#define DEFAULT_CURRENT_PRIORITY 10
64#define DEFAULT_CROSSING_PRIORITY 100
65
66#define DEFAULT_LENGTH_WITH_GAP 7.5
67#define DEFAULT_BIKE_LENGTH_WITH_GAP (getDefaultVehicleLength(SVC_BICYCLE) + 0.5)
68#define DEFAULT_STATIC_MINDUR TIME2STEPS(0) // loop position for non-stretchable phases
69
70#define NO_DETECTOR "NO_DETECTOR"
71#define DEFAULT_CONDITION "DEFAULT"
72
73// ===========================================================================
74// method definitions
75// ===========================================================================
77 const std::string& id, const std::string& programID,
78 const SUMOTime offset,
79 const Phases& phases,
80 int step, SUMOTime delay,
81 const Parameterised::Map& parameter,
82 const std::string& basePath,
83 const ConditionMap& conditions,
84 const AssignmentMap& assignments,
85 const FunctionMap& functions) :
86 MSSimpleTrafficLightLogic(tlcontrol, id, programID, offset, TrafficLightType::ACTUATED, phases, step, delay, parameter),
87 myHasMultiTarget(false),
88 myLastTrySwitchTime(0),
89 myConditions(conditions),
90 myAssignments(assignments),
91 myFunctions(functions),
92 myTraCISwitch(false),
93 myDetectorPrefix(id + "_" + programID + "_") {
95 myJamThreshold = StringUtils::toDouble(getParameter("jam-threshold", OptionsCont::getOptions().getValueString("tls.actuated.jam-threshold")));
99 myShowDetectors = StringUtils::toBool(getParameter("show-detectors", toString(OptionsCont::getOptions().getBool("tls.actuated.show-detectors"))));
100 myBuildAllDetectors = StringUtils::toBool(getParameter("build-all-detectors", "false"));
101 myFile = FileHelpers::checkForRelativity(getParameter("file", "NUL"), basePath);
103 myVehicleTypes = getParameter("vTypes", "");
104
105 if (hasParameter("hide-conditions")) {
106 std::vector<std::string> hidden = StringTokenizer(getParameter("hide-conditions", "")).getVector();
107 std::set<std::string> hiddenSet(hidden.begin(), hidden.end());
108 for (auto item : myConditions) {
109 if (hiddenSet.count(item.first) == 0) {
110 myListedConditions.insert(item.first);
111 }
112 }
113 } else {
114 const bool showAll = getParameter("show-conditions", "") == "";
115 std::vector<std::string> shown = StringTokenizer(getParameter("show-conditions", "")).getVector();
116 std::set<std::string> shownSet(shown.begin(), shown.end());
117 for (auto item : myConditions) {
118 if (showAll || shownSet.count(item.first) != 0) {
119 myListedConditions.insert(item.first);
120 }
121 }
122 }
123 if (hasParameter("extra-detectors")) {
124 const std::string extraIDs = getParameter("extra-detectors", "");
125 for (std::string customID : StringTokenizer(extraIDs).getVector()) {
126 try {
127 myExtraLoops.push_back(retrieveDetExpression<MSInductLoop, SUMO_TAG_INDUCTION_LOOP>(customID, extraIDs, true));
128 } catch (ProcessError&) {
129 myExtraE2.push_back(retrieveDetExpression<MSE2Collector, SUMO_TAG_LANE_AREA_DETECTOR>(customID, extraIDs, true));
130 }
131 }
132 }
133 myStack.push_back(std::map<std::string, double>());
134}
135
136
138
139void
144 // myTargets is computed lazily in decideNextPhase(): it is only needed for phases with multiple 'next' entries that
145 // use the default switching algorithm
146 if (myLanes.size() == 0) {
147 // must be an older network
148 WRITE_WARNINGF(TL("Traffic light '%' does not control any links"), getID());
149 }
150 bool warn = true; // warn only once
151 const int numLinks = (int)myLinks.size();
152
153 // Detector position should be computed based on road speed. If the position
154 // is quite far away and the minDur is short this may cause the following
155 // problems:
156 //
157 // 1) high flow failure:
158 // In a standing queue, no vehicle touches the detector.
159 // By the time the queue advances, the detector gap has been exceeded and the phase terminates prematurely
160 //
161 // 2) low flow failure
162 // The standing queue is fully between stop line and detector and there are no further vehicles.
163 // The minDur is too short to let all vehicles pass
164 //
165 // Problem 2) is not so critical because there is less potential for
166 // jamming in a low-flow situation. In contrast, problem 1) should be
167 // avoided as it has big jamming potential. We compute an upper bound for the
168 // detector distance to avoid it
169
170
171 std::set<int> multiNextTargets = getMultiNextTargets();
172 // change values for setting the loops and lanestate-detectors, here
173 //SUMOTime inductLoopInterval = 1; //
174 // build the induct loops
175 std::map<const MSLane*, MSInductLoop*> laneInductLoopMap;
176 std::map<MSInductLoop*, int> inductLoopInfoMap; // retrieve junction entry lane in case loops are placed further upstream (and other properties)
177 int detEdgeIndex = -1;
178 int detLaneIndex = 0;
179 const double detDefaultLength = StringUtils::toDouble(getParameter("detector-length",
180 OptionsCont::getOptions().getValueString("tls.actuated.detector-length")));
181 MSEdge* prevDetEdge = nullptr;
182 for (LaneVector& lanes : myLanes) {
183 for (MSLane* lane : lanes) {
184 const std::string customID = getParameter(lane->getID());
185 if (noVehicles(lane->getPermissions()) && customID == "") {
186 // do not build detectors on green verges or sidewalks
187 continue;
188 }
189 if (laneInductLoopMap.find(lane) != laneInductLoopMap.end()) {
190 // only build one detector per lane
191 continue;
192 }
193 const SUMOTime minDur = getMinimumMinDuration(lane, multiNextTargets);
194 if (minDur == std::numeric_limits<SUMOTime>::max() && customID == "" && !myBuildAllDetectors) {
195 // only build detector if this lane is relevant for an actuated phase
196 continue;
197 }
198 double length = lane->getLength();
199 double ilpos;
200 double inductLoopPosition;
201 MSInductLoop* loop = nullptr;
202 if (&lane->getEdge() != prevDetEdge) {
203 detEdgeIndex++;
204 detLaneIndex = 0;
205 prevDetEdge = &lane->getEdge();
206 } else {
207 detLaneIndex++;
208 }
209 const bool isBikeLane = (lane->getPermissions() & ~SVC_PEDESTRIAN) == SVC_BICYCLE;
210 const double defaultLength = isBikeLane ? DEFAULT_BIKE_LENGTH_WITH_GAP : DEFAULT_LENGTH_WITH_GAP;
211 if (customID == "") {
212 const double speed = isBikeLane ? DEFAULT_BICYCLE_SPEED : lane->getSpeedLimit();
213 inductLoopPosition = MIN2(
214 myDetectorGap * speed,
215 (STEPS2TIME(minDur) / myPassingTime + 0.5) * defaultLength);
216
217 // check whether the lane is long enough
218 ilpos = length - inductLoopPosition;
219 MSLane* placementLane = lane;
220 while (ilpos < 0 && placementLane->getIncomingLanes().size() == 1
221 && placementLane->getLogicalPredecessorLane() != nullptr
222 && placementLane->getIncomingLanes().front().viaLink->getCorrespondingEntryLink()->getTLLogic() == nullptr) {
223 placementLane = placementLane->getLogicalPredecessorLane();
224 ilpos += placementLane->getLength();
225 }
226 if (ilpos < 0) {
227 ilpos = 0;
228 }
229 // Build the induct loop and set it into the container
230 const double detLength = getDouble("detector-length:" + lane->getID(), detDefaultLength);
231 std::string id = myDetectorPrefix + "D" + toString(detEdgeIndex) + "." + toString(detLaneIndex);
232 loop = static_cast<MSInductLoop*>(nb.createInductLoop(id, placementLane, ilpos, detLength, "", myVehicleTypes, "", (int)PersonMode::NONE, myShowDetectors, true));
234 } else if (customID == NO_DETECTOR) {
235 continue;
236 } else {
238 if (loop == nullptr) {
239 throw ProcessError(TLF("Unknown inductionLoop '%' given as custom detector for actuated tlLogic '%', program '%.", customID, getID(), getProgramID()));
240 }
241 ilpos = loop->getPosition();
242 inductLoopPosition = length - ilpos;
243 }
244 const double maxGap = getDouble("max-gap:" + lane->getID(), myMaxGap);
245 const double jamThreshold = getDouble("jam-threshold:" + lane->getID(), myJamThreshold);
246 laneInductLoopMap[lane] = loop;
247 inductLoopInfoMap[loop] = (int)myInductLoops.size();
248 myInductLoops.push_back(InductLoopInfo(loop, lane, (int)myPhases.size(), maxGap, jamThreshold));
249
250 if (warn && floor(floor(inductLoopPosition / defaultLength) * myPassingTime) > STEPS2TIME(minDur)) {
251 // warn if the minGap is insufficient to clear vehicles between stop line and detector
252 WRITE_WARNINGF(TL("At actuated tlLogic '%', minDur % is too short for a detector gap of %m."), getID(), time2string(minDur), toString(inductLoopPosition));
253 warn = false;
254 }
255 }
256 }
257 // assign loops to phase index (myInductLoopsForPhase)
258 // check1: loops may not be used for a phase if there are other connections from the same lane that may not drive in that phase
259 // greenMinor is ambiguous as vehicles may not be able to drive
260 // Under the following condition we allow actuation from minor link:
261 // check1a : the minor link is minor in all phases
262 // check1b : there is another major link from the same lane in the current phase
263 // check1e : the conflict is only with bikes/pedestrians (i.e. for a right turn, also left turn with no oncoming traffic)
264 // check1f : the conflict is only with a link from the same edge
265 // (Under these conditions we assume that the minor link is unimportant and traffic is mostly for the major link)
266 //
267 // check1c: when the edge has only one lane, we treat greenMinor as green as there would be no actuation otherwise
268 // check1d: for turnarounds 1b is sufficient and we do not require 1a
269 //
270 // check2: if there are two loops on subsequent lanes (joined tls) and the second one has a red link, the first loop may not be used
271 //
272 // if a jamThreshold is specificed for the loop, all checks are ignored
273
274 // also assign loops to link index for validation:
275 // check if all links from actuated phases (minDur != maxDur) have an inductionloop in at least one phase
276 const SVCPermissions motorized = ~(SVC_PEDESTRIAN | SVC_BICYCLE);
277 std::map<int, std::set<MSInductLoop*> > linkToLoops;
278 std::set<int> actuatedLinks;
279
280 std::vector<bool> neverMajor(numLinks, true);
281 for (const MSPhaseDefinition* phase : myPhases) {
282 const std::string& state = phase->getState();
283 for (int i = 0; i < numLinks; i++) {
284 if (state[i] == LINKSTATE_TL_GREEN_MAJOR) {
285 neverMajor[i] = false;
286 }
287 }
288 }
289 std::vector<bool> oneLane(numLinks, false);
290 std::vector<bool> turnaround(numLinks, true);
291 for (int i = 0; i < numLinks; i++) {
292 for (MSLane* lane : getLanesAt(i)) {
293 // only count motorized vehicle lanes
294 int numMotorized = 0;
295 for (MSLane* l : lane->getEdge().getLanes()) {
296 if ((l->getPermissions() & motorized) != 0) {
297 numMotorized++;
298 }
299 }
300 if (numMotorized == 1) {
301 oneLane[i] = true;
302 break;
303 }
304 }
305 for (MSLink* link : getLinksAt(i)) {
306 if (!link->isTurnaround()) {
307 turnaround[i] = false;
308 break;
309 }
310 }
311 }
312
313 for (const MSPhaseDefinition* phase : myPhases) {
314 const int phaseIndex = (int)myInductLoopsForPhase.size();
315 std::set<MSInductLoop*> loops;
316 if (phase->isActuated() || multiNextTargets.count(phaseIndex) != 0) {
317 const std::string& state = phase->getState();
318 // collect indices of all green links for the phase
319 std::set<int> greenLinks;
320 // green links that could jam
321 std::set<int> greenLinksPermissive;
322 // collect green links for each induction loops (in this phase)
323 std::map<MSInductLoop*, std::set<int> > loopLinks;
324
325 for (int i = 0; i < numLinks; i++) {
326 if (state[i] == LINKSTATE_TL_GREEN_MAJOR) {
327 greenLinks.insert(i);
328 if (phase->isActuated()) {
329 actuatedLinks.insert(i);
330 }
331
332 for (MSLink* link : getLinksAt(i)) {
333 if (link->getLane()->isCrossing()) {
334 while (myCrossingsForPhase.size() < myPhases.size()) {
335 myCrossingsForPhase.push_back(std::vector<const MSLink*>());
336 }
337 myCrossingsForPhase[phaseIndex].push_back(link);
338 }
339 }
340
341 } else if (state[i] == LINKSTATE_TL_GREEN_MINOR) {
342 if (((neverMajor[i] || turnaround[i]) // check1a, 1d
343 && hasMajor(state, getLanesAt(i))) // check1b
344 || oneLane[i] // check1c
345 || weakConflict(i, state)) { // check1e, check1f
346 greenLinks.insert(i);
347 if (!turnaround[i]) {
348 if (phase->isActuated()) {
349 actuatedLinks.insert(i);
350 }
351 }
352 } else {
353 greenLinksPermissive.insert(i);
354 }
355 }
356#ifdef DEBUG_DETECTORS
357 if (DEBUG_COND) {
358 std::cout << " phase=" << phaseIndex << " i=" << i << " state=" << state[i] << " green=" << greenLinks.count(i) << " oneLane=" << oneLane[i]
359 << " turn=" << turnaround[i] << " loopLanes=";
360 for (MSLane* lane : getLanesAt(i)) {
361 if (laneInductLoopMap.count(lane) != 0) {
362 std::cout << lane->getID() << " ";
363 }
364 }
365 std::cout << "\n";
366 }
367#endif
368 for (MSLane* lane : getLanesAt(i)) {
369 if (laneInductLoopMap.count(lane) != 0) {
370 loopLinks[laneInductLoopMap[lane]].insert(i);
371 }
372 }
373 }
374 for (auto& item : loopLinks) {
375 MSInductLoop* loop = item.first;
376 const InductLoopInfo& info = myInductLoops[inductLoopInfoMap[loop]];
377 const MSLane* loopLane = info.lane;
378 bool usable = true;
379 bool foundUsable = false;
380 // check1
381 for (int j : item.second) {
382 if (greenLinks.count(j) == 0 && (info.jamThreshold <= 0 || greenLinksPermissive.count(j) == 0)) {
383 usable = false;
384#ifdef DEBUG_DETECTORS
385 if (DEBUG_COND) {
386 std::cout << " phase=" << phaseIndex << " check1: loopLane=" << loopLane->getID() << " notGreen=" << j << " oneLane[j]=" << oneLane[j] << "\n";
387 }
388#endif
389 } else {
390 foundUsable = true;
391 }
392 }
393 if (!usable && foundUsable && info.jamThreshold > 0) {
394 // permit green even when the same lane has green and red links (if we have jamDetection)
395 usable = true;
396 }
397 // check2 (skip if we have jam detection)
398 if (usable && info.jamThreshold <= 0) {
399 for (MSLink* link : loopLane->getLinkCont()) {
400 if (link->isTurnaround()) {
401 continue;
402 }
403 const MSLane* next = link->getLane();
404 if (laneInductLoopMap.count(next) != 0) {
405 MSInductLoop* nextLoop = laneInductLoopMap[next];
406 for (int j : loopLinks[nextLoop]) {
407 if (greenLinks.count(j) == 0) {
408 usable = false;
409#ifdef DEBUG_DETECTORS
410 if (DEBUG_COND) std::cout << " phase=" << phaseIndex << " check2: loopLane=" << loopLane->getID()
411 << " nextLane=" << next->getID() << " nextLink=" << j << " nextState=" << state[j] << "\n";
412#endif
413 break;
414 }
415 }
416 }
417 }
418 }
419
420 if (usable) {
421 loops.insert(item.first);
422#ifdef DEBUG_DETECTORS
423 if (DEBUG_COND) {
424 std::cout << " phase=" << phaseIndex << " usableLoops=" << item.first->getID() << " links=" << joinToString(item.second, " ") << "\n";
425 }
426#endif
427 for (int j : item.second) {
428 linkToLoops[j].insert(item.first);
429 }
430 }
431 }
432 if (loops.size() == 0 && phase->isActuated()) {
433 WRITE_WARNINGF(TL("At actuated tlLogic '%', actuated phase % has no controlling detector."), getID(), toString(phaseIndex));
434 }
435 }
436#ifdef DEBUG_DETECTORS
437 if (DEBUG_COND) {
438 std::cout << " phase=" << phaseIndex << " loops=" << joinNamedToString(loops, " ") << "\n";
439 }
440 if (DEBUG_COND) {
441 std::cout << " linkToLoops:\n";
442 for (auto item : linkToLoops) {
443 std::cout << " link=" << item.first << " loops=" << joinNamedToString(item.second, " ") << "\n";
444 }
445 }
446#endif
447 std::vector<InductLoopInfo*> loopInfos;
448 myInductLoopsForPhase.push_back(loopInfos);
449 for (MSInductLoop* loop : loops) {
450 for (InductLoopInfo& loopInfo : myInductLoops) {
451 if (loopInfo.loop == loop) {
452 myInductLoopsForPhase.back().push_back(&loopInfo);
453 loopInfo.servedPhase[phaseIndex] = true;
454 }
455 }
456 }
457 }
458#ifdef DEBUG_DETECTORS
459 if (DEBUG_COND) {
460 std::cout << "final linkToLoops:\n";
461 for (auto item : linkToLoops) {
462 std::cout << " link=" << item.first << " loops=" << joinNamedToString(item.second, " ") << "\n";
463 }
464 }
465#endif
466 std::vector<int> warnLinks;
467 for (int i : actuatedLinks) {
468 if (linkToLoops[i].size() == 0 && myLinks[i].size() > 0
469 && (myLinks[i].front()->getLaneBefore()->getPermissions() & motorized) != 0) {
470 if (getParameter(myLinks[i].front()->getLaneBefore()->getID()) != NO_DETECTOR) {
471 warnLinks.push_back(i);
472 }
473 }
474 }
475 if (warnLinks.size() > 0) {
476 WRITE_WARNINGF(TL("At actuated tlLogic '%', linkIndex % has no controlling detector."), getID(), joinToString(warnLinks, ","));
477 }
478 // parse maximum green times for each link (optional)
479 for (const auto& kv : getParametersMap()) {
480 if (StringUtils::startsWith(kv.first, "linkMaxDur:")) {
481 int link = StringUtils::toInt(kv.first.substr(11));
482 if (link < 0 || link >= myNumLinks) {
483 WRITE_ERRORF(TL("Invalid link '%' given as linkMaxDur parameter for actuated tlLogic '%', program '%."), kv.first.substr(11), getID(), getProgramID());
484 continue;
485 }
486 if (myLinkMaxGreenTimes.empty()) {
487 myLinkMaxGreenTimes = std::vector<SUMOTime>(myNumLinks, std::numeric_limits<SUMOTime>::max());
488 }
489 myLinkMaxGreenTimes[link] = string2time(kv.second);
490 } else if (StringUtils::startsWith(kv.first, "linkMinDur:")) {
491 int link = StringUtils::toInt(kv.first.substr(11));
492 if (link < 0 || link >= myNumLinks) {
493 WRITE_ERRORF(TL("Invalid link '%' given as linkMinDur parameter for actuated tlLogic '%', program '%."), kv.first.substr(11), getID(), getProgramID());
494 continue;
495 }
496 if (myLinkMinGreenTimes.empty()) {
497 myLinkMinGreenTimes = std::vector<SUMOTime>(myNumLinks, 0);
498 }
499 myLinkMinGreenTimes[link] = string2time(kv.second);
500 }
501 }
502 bool haveSwitchingRules = myConditions.size() > 0 || myAssignments.size() > 0 || myFunctions.size() > 0;
503 for (auto sr : mySwitchingRules) {
504 if (sr.enabled) {
505 haveSwitchingRules = true;
506 break;
507 }
508 }
509 if (myLinkMaxGreenTimes.size() > 0 || myLinkMinGreenTimes.size() > 0 || haveSwitchingRules) {
510 myLinkGreenTimes = std::vector<SUMOTime>(myNumLinks, 0);
511 myLinkRedTimes = std::vector<SUMOTime>(myNumLinks, 0);
512 }
513 //std::cout << SIMTIME << " linkMaxGreenTimes=" << toString(myLinkMaxGreenTimes) << "\n";
514}
515
516
517bool
518MSActuatedTrafficLightLogic::weakConflict(int tlIndex, const std::string& state) const {
519 for (MSLink* link : getLinksAt(tlIndex)) {
520 int linkIndex = link->getIndex();
521 const MSJunction* junction = link->getJunction();
522 for (int i = 0; i < (int)myLinks.size(); i++) {
523 if (i == tlIndex) {
524 continue;
525 }
526 if (state[i] == LINKSTATE_TL_GREEN_MAJOR || state[i] == LINKSTATE_TL_GREEN_MINOR) {
527 for (MSLink* foe : getLinksAt(i)) {
528 // junction logic is based on junction link index rather than tl index
529 int foeIndex = foe->getIndex();
530 const MSJunction* junction2 = foe->getJunction();
531 if (junction == junction2) {
532 const MSJunctionLogic* logic = junction->getLogic();
533 //std::cout << " greenLink=" << i << " isFoe=" << logic->getFoesFor(linkIndex).test(foeIndex) << "\n";
534 if (logic->getFoesFor(linkIndex).test(foeIndex)
535 && (foe->getPermissions() & ~SVC_VULNERABLE) != 0 // check1e
536 && &foe->getLaneBefore()->getEdge() != &link->getLaneBefore()->getEdge()) { // check1f
537 //std::cout << " strongConflict " << tlIndex << " in phase " << state << " with link " << foe->getTLIndex() << "\n";
538 return false;
539 }
540 }
541 }
542
543 }
544 }
545 }
546 //std::cout << " weakConflict " << tlIndex << " in phase " << state << "\n";
547 return true;
548}
549
550
553 step = step < 0 ? myStep : step;
554 const MSPhaseDefinition* p = myPhases[step];
556 ? p->minDuration
557 : TIME2STEPS(evalExpression(myConditions.find("minDur:" + toString(step))->second));
558}
559
562 step = step < 0 ? myStep : step;
563 const MSPhaseDefinition* p = myPhases[step];
565 ? p->maxDuration
566 : TIME2STEPS(evalExpression(myConditions.find("maxDur:" + toString(step))->second));
567}
568
571 step = step < 0 ? myStep : step;
572 const MSPhaseDefinition* p = myPhases[step];
574 ? p->earliestEnd
575 : TIME2STEPS(evalExpression(myConditions.find("earliestEnd:" + toString(step))->second));
576}
577
580 step = step < 0 ? myStep : step;
581 const MSPhaseDefinition* p = myPhases[step];
583 ? p->latestEnd
584 : TIME2STEPS(evalExpression(myConditions.find("latestEnd:" + toString(step))->second));
585}
586
587
588void
591 for (int i = 0; i < (int)myPhases.size(); i++) {
592 MSPhaseDefinition* phase = myPhases[i];
593 const std::string errorSuffix = "' for overriding attribute in phase " + toString(i) + " of tlLogic '" + getID() + "' in program '" + getProgramID() + "'.";
594 if (phase->minDuration == ovrd) {
595 const std::string cond = "minDur:" + toString(i);
596 if (myConditions.count(cond) == 0) {
597 throw ProcessError("Missing condition '" + cond + errorSuffix);
598 }
599 }
600 if (phase->maxDuration == ovrd) {
601 const std::string cond = "maxDur:" + toString(i);
602 if (myConditions.count(cond) == 0) {
603 throw ProcessError("Missing condition '" + cond + errorSuffix);
604 }
605 }
606 if (phase->earliestEnd == ovrd) {
607 const std::string cond = "earliestEnd:" + toString(i);
608 if (myConditions.count(cond) == 0) {
609 throw ProcessError("Missing condition '" + cond + errorSuffix);
610 }
611 }
612 if (phase->latestEnd == ovrd) {
613 const std::string cond = "latestEnd:" + toString(i);
614 if (myConditions.count(cond) == 0) {
615 throw ProcessError("Missing condition '" + cond + errorSuffix);
616 }
617 }
618 }
619}
620
621
622void
624 for (int i = 0; i < (int)myPhases.size(); i++) {
626 MSPhaseDefinition* phase = myPhases[i];
627 std::vector<int> nextPhases = phase->nextPhases;
628 if (nextPhases.size() == 0) {
629 nextPhases.push_back((i + 1) % (int)myPhases.size());
630 } else if (nextPhases.size() > 1) {
631 myHasMultiTarget = true;
632 }
633 for (int next : nextPhases) {
634 if (next >= 0 && next < (int)myPhases.size()) {
635 const MSPhaseDefinition* nextPhase = myPhases[next];
636 if (nextPhase->earlyTarget != "" || nextPhase->finalTarget != "") {
637 sr.enabled = true;
638 }
639 }
640 }
641 // simplifies later code
642 phase->nextPhases = nextPhases;
643 mySwitchingRules.push_back(sr);
644 }
645}
646
647
648void
650 // next -> target -> transitionTime starting from step
651 std::map<int, std::map<int, SUMOTime> > reached;
652 const std::vector<int>& next = myPhases[step]->nextPhases;
653 // also marks step as computed if no target is found
654 std::map<int, std::vector<int> >& targets = myTargets[step];
655 for (int n : next) {
656 findTargets(step, n, 0, reached[n]);
657 }
658 for (int target = 0; target < (int)myPhases.size(); target++) {
659 int bestNext = next[0];
660 SUMOTime bestTime = SUMOTime_MAX;
661 for (const auto& item : reached) {
662 auto it = item.second.find(target);
663 if (it != item.second.end()) {
664 SUMOTime transitionTime = it->second;
665 if (transitionTime < bestTime) {
666 bestTime = transitionTime;
667 bestNext = item.first;
668 }
669 }
670 }
671 if (bestTime != SUMOTime_MAX) {
672 targets[bestNext].push_back(target);
673 //std::cout << " myTargets step=" << step << " bestNext=" << bestNext << " target=" << target << "\n";
674 }
675 }
676}
677
678
679void
680MSActuatedTrafficLightLogic::findTargets(int origStep, int n, SUMOTime priorTransition, std::map<int, SUMOTime>& found) {
681 std::pair<int, SUMOTime> tDur = getTarget(n);
682 int target = tDur.first;
683 SUMOTime transitionTime = tDur.second + priorTransition;
684 //std::cout << " findTargets origStep=" << origStep << " n=" << n << " ptt=" << priorTransition << " target=" << target << " tt=" << transitionTime << "\n";
685 if (target == origStep) {
686 // full circle
687 //std::cout << " foundCircle\n";
688 return;
689 }
690 auto it = found.find(target);
691 if (it != found.end()) {
692 if (it->second <= transitionTime) {
693 //std::cout << " oldShorterTime=" << it->second << "\n";
694 // found the same target again
695 return;
696 } else {
697 //std::cout << " newShorterTime=" << it->second << "\n";
698 }
699 } else {
700 //std::cout << " newTarget\n";
701 }
702 found[target] = transitionTime;
703 //std::cout << " targetNext=" << toString(myPhases[target]->nextPhases) << "\n";
704 for (int n2 : myPhases[target]->nextPhases) {
705 findTargets(origStep, n2, transitionTime, found);
706 }
707}
708
709
710std::set<int>
712 std::set<int> result;
713 if (myHasMultiTarget) {
714 // find all phase that are the target green phase of a 'next' attribute
715 for (const MSPhaseDefinition* p : myPhases) {
716 for (int next : p->nextPhases) {
717 result.insert(getTarget(next).first);
718 }
719 }
720 }
721 return result;
722}
723
724
726MSActuatedTrafficLightLogic::getMinimumMinDuration(MSLane* lane, const std::set<int>& multiNextTargets) const {
727 SUMOTime result = std::numeric_limits<SUMOTime>::max();
728 for (int pI = 0; pI < (int)myPhases.size(); pI++) {
729 const MSPhaseDefinition* phase = myPhases[pI];
730 const std::string& state = phase->getState();
731 for (int i = 0; i < (int)state.size(); i++) {
732 if (state[i] == LINKSTATE_TL_GREEN_MAJOR || state[i] == LINKSTATE_TL_GREEN_MINOR) {
733 for (MSLane* cand : getLanesAt(i)) {
734 if (lane == cand) {
735 if (phase->isActuated()) {
736 result = MIN2(result, getMinDur(pI));
737 } else if (multiNextTargets.count(pI) != 0) {
738 result = MIN2(result, DEFAULT_STATIC_MINDUR);
739 }
740 }
741 }
742 }
743 }
744 }
745 return result;
746}
747
748bool
749MSActuatedTrafficLightLogic::hasMajor(const std::string& state, const LaneVector& lanes) const {
750 for (int i = 0; i < (int)state.size(); i++) {
751 if (state[i] == LINKSTATE_TL_GREEN_MAJOR) {
752 for (MSLane* cand : getLanesAt(i)) {
753 for (MSLane* lane : lanes) {
754 if (lane == cand) {
755 return true;
756 }
757 }
758 }
759 }
760 }
761 return false;
762}
763
764
765// ------------ Switching and setting current rows
766void
773
774
775void
778 for (InductLoopInfo& loopInfo : myInductLoops) {
779 loopInfo.loop->setVisible(false);
780 }
781}
782
783void
785 SUMOTime simStep, int step, SUMOTime stepDuration) {
786 // do not change timing if the phase changes
787 if (step >= 0 && step != myStep) {
788 myStep = step;
790 setTrafficLightSignals(simStep);
791 tlcontrol.get(getID()).executeOnSwitchActions();
792 } else if (step < 0) {
793 // TraCI requested new timing
795 mySwitchCommand = new SwitchCommand(tlcontrol, this, stepDuration + simStep);
797 mySwitchCommand, stepDuration + simStep);
798 myTraCISwitch = true;
799 }
800}
801
802
803void
804MSActuatedTrafficLightLogic::loadState(MSTLLogicControl& tlcontrol, SUMOTime t, int step, SUMOTime spentDuration, SUMOTime nextSwitch, SUMOTime timeInCycle, bool active) {
805 myAmActive = active;
806 const SUMOTime lastSwitch = t - spentDuration;
807 myStep = step;
808 myPhases[myStep]->myLastSwitch = lastSwitch;
809 if (!myCoordinated && myStep != 0) {
810 // the time in cycle counts from the last start of phase 0
811 myPhases[0]->myLastSwitch = t - timeInCycle;
812 }
814 mySwitchCommand = new SwitchCommand(tlcontrol, this, nextSwitch);
816 if (myAmActive) {
817 setTrafficLightSignals(lastSwitch);
818 }
819 tlcontrol.get(getID()).executeOnSwitchActions();
820}
821
822
825 // checks if the actual phase should be continued
826 // @note any vehicles which arrived during the previous phases which are now waiting between the detector and the stop line are not
827 // considere here. RiLSA recommends to set minDuration in a way that lets all vehicles pass the detector
830
831 if (myLinkGreenTimes.size() > 0) {
832 // constraints exist, record green time durations for each link
833 const std::string& state = getCurrentPhaseDef().getState();
834 SUMOTime lastDuration = SIMSTEP - myLastTrySwitchTime;
835 for (int i = 0; i < myNumLinks; i++) {
836 if (state[i] == 'G' || state[i] == 'g') {
837 myLinkGreenTimes[i] += lastDuration;
838 } else {
839 myLinkGreenTimes[i] = 0;
840 }
841 if (state[i] == 'r' || state[i] == 'u') {
842 myLinkRedTimes[i] += lastDuration;
843 } else {
844 myLinkRedTimes[i] = 0;
845 }
846 }
847 }
849 // decide the next phase
850 const bool multiTarget = myPhases[myStep]->nextPhases.size() > 1 && myPhases[myStep]->nextPhases.front() >= 0;
851 const int origStep = myStep;
852 int nextStep = myStep;
853 SUMOTime actDuration = now - myPhases[myStep]->myLastSwitch;
854
855 if (mySwitchingRules[myStep].enabled) {
856 const bool mustSwitch = MIN2(getMaxDur() - actDuration, getLatest()) <= 0;
857 nextStep = decideNextPhaseCustom(mustSwitch);
858 } else {
859 // default algorithm
860 const double detectionGap = gapControl();
861#ifdef DEBUG_PHASE_SELECTION
862 if (DEBUG_COND) {
863 std::cout << SIMTIME << " p=" << myStep
864 << " trySwitch dGap=" << (detectionGap == std::numeric_limits<double>::max() ? "inf" : toString(detectionGap))
865 << " multi=" << multiTarget << "\n";
866 }
867#endif
868 if (detectionGap < std::numeric_limits<double>::max() && !multiTarget && !myTraCISwitch) {
869 return duration(detectionGap);
870 }
871 if (multiTarget) {
872 nextStep = decideNextPhase();
873 } else {
874 if (myPhases[myStep]->nextPhases.size() == 1 && myPhases[myStep]->nextPhases.front() >= 0) {
875 nextStep = myPhases[myStep]->nextPhases.front();
876 } else {
877 nextStep = (myStep + 1) % (int)myPhases.size();
878 }
879 }
880 }
881
882 myTraCISwitch = false;
883 if (myLinkMinGreenTimes.size() > 0) {
884 SUMOTime linkMinDur = getLinkMinDuration(getTarget(nextStep).first);
885 if (linkMinDur > 0) {
886 // for multiTarget, the current phase must be extended but if another
887 // targer is chosen, earlier switching than linkMinDur is possible
888 return multiTarget ? TIME2STEPS(1) : linkMinDur;
889 }
890 }
891 myStep = nextStep;
892 assert(myStep <= (int)myPhases.size());
893 assert(myStep >= 0);
894 //stores the time the phase started
895 const SUMOTime prevStart = myPhases[myStep]->myLastSwitch;
896 if (myStep != origStep) {
897 myPhases[origStep]->myLastEnd = now;
898 myPhases[myStep]->myLastSwitch = now;
899 actDuration = 0;
900 }
901 // activate coloring
902 if ((myShowDetectors || myHasMultiTarget) && getCurrentPhaseDef().isGreenPhase()) {
903 for (InductLoopInfo* loopInfo : myInductLoopsForPhase[myStep]) {
904 //std::cout << SIMTIME << " p=" << myStep << " loopinfo=" << loopInfo->loop->getID() << " set lastGreen=" << STEPS2TIME(now) << "\n";
905 if (loopInfo->isJammed()) {
906 loopInfo->loop->setSpecialColor(&RGBColor::ORANGE);
907 } else {
908 loopInfo->loop->setSpecialColor(&RGBColor::GREEN);
909 }
910 loopInfo->lastGreenTime = now;
911 }
912 }
913 // set the next event
914#ifdef DEBUG_PHASE_SELECTION
915 if (DEBUG_COND) {
916 std::cout << SIMTIME << " tl=" << getID() << " p=" << myStep
917 << " nextTryMinDur=" << STEPS2TIME(getMinDur() - actDuration)
918 << " nextTryEarliest=" << STEPS2TIME(getEarliest(prevStart)) << "\n";
919 }
920#endif
921 SUMOTime minRetry = myStep != origStep ? 0 : TIME2STEPS(1);
922 return MAX3(minRetry, getMinDur() - actDuration, getEarliest(prevStart));
923}
924
925
926// ------------ "actuated" algorithm methods
928MSActuatedTrafficLightLogic::duration(const double detectionGap) const {
929 assert(getCurrentPhaseDef().isGreenPhase());
930 assert((int)myPhases.size() > myStep);
931 const SUMOTime actDuration = MSNet::getInstance()->getCurrentTimeStep() - myPhases[myStep]->myLastSwitch;
932 // ensure that minimum duration is kept
933 SUMOTime newDuration = getMinDur() - actDuration;
934 // try to let the last detected vehicle pass the intersection (duration must be positive)
935 newDuration = MAX3(newDuration, TIME2STEPS(myDetectorGap - detectionGap), SUMOTime(1));
936 // cut the decimal places to ensure that phases always have integer duration
937 if (newDuration % 1000 != 0) {
938 const SUMOTime totalDur = newDuration + actDuration;
939 newDuration = (totalDur / 1000 + 1) * 1000 - actDuration;
940 }
941 // ensure that the maximum duration is not exceeded
942 newDuration = MIN3(newDuration, getMaxDur() - actDuration, getLatest());
943 return newDuration;
944}
945
946
947double
949 //intergreen times should not be lengthend
950 assert((int)myPhases.size() > myStep);
951 double result = std::numeric_limits<double>::max();
952 // switch off active colors
953 if (myShowDetectors) {
954 for (InductLoopInfo& loopInfo : myInductLoops) {
955 if (loopInfo.lastGreenTime < loopInfo.loop->getLastDetectionTime()) {
956 loopInfo.loop->setSpecialColor(&RGBColor::RED);
957 } else {
958 loopInfo.loop->setSpecialColor(nullptr);
959 }
960 }
961 }
963 return result; // end current phase
964 }
965
966 // Checks, if the maxDuration is kept. No phase should last longer than maxDuration.
967 SUMOTime actDuration = MSNet::getInstance()->getCurrentTimeStep() - myPhases[myStep]->myLastSwitch;
968 if (actDuration >= getCurrentPhaseDef().maxDuration || maxLinkDurationReached() || getLatest() == 0) {
969#ifdef DEBUG_PHASE_SELECTION
970 if (DEBUG_COND) {
971 std::cout << SIMTIME << " actDuration=" << STEPS2TIME(actDuration) << " maxDur=" << STEPS2TIME(getCurrentPhaseDef().maxDuration)
972 << " maxLinkDurationReached=" << maxLinkDurationReached() << " latest=" << STEPS2TIME(getLatest()) << "\n";
973 }
974#endif
975 return result; // end current phase
976 }
977
978 // now the gapcontrol starts
979 for (InductLoopInfo* loopInfo : myInductLoopsForPhase[myStep]) {
980 MSInductLoop* loop = loopInfo->loop;
981 if (loopInfo->isJammed()) {
982 loopInfo->loop->setSpecialColor(&RGBColor::ORANGE);
983 } else {
984 loopInfo->loop->setSpecialColor(&RGBColor::GREEN);
985 }
986 const double actualGap = loop->getTimeSinceLastDetection();
987 if (actualGap < loopInfo->maxGap && !loopInfo->isJammed()) {
988 result = MIN2(result, actualGap);
989 }
990 }
991 return result;
992}
993
994int
996 const auto& cands = myPhases[myStep]->nextPhases;
997 // decide by priority
998 // first target is the default when there is no traffic
999 // @note: to keep the current phase, even when there is no traffic, it must be added to 'next' explicitly
1000 int result = cands.front();
1001 int maxPrio = 0;
1002 SUMOTime actDuration = MSNet::getInstance()->getCurrentTimeStep() - myPhases[myStep]->myLastSwitch;
1003 const bool canExtend = actDuration < getCurrentPhaseDef().maxDuration && !maxLinkDurationReached() && getLatest() > 0;
1004 if (canExtend) {
1005 // consider keeping the current phase until maxDur is reached
1006 // (only when there is still traffic in that phase)
1007 int currentPrio = getPhasePriority(myStep);
1008#ifdef DEBUG_PHASE_SELECTION
1009 std::cout << SIMTIME << " p=" << myStep << " loops=" << myInductLoopsForPhase[myStep].size() << " currentPrio=" << currentPrio << "\n";
1010#endif
1011 if (currentPrio > maxPrio) {
1012 result = myStep;
1013 maxPrio = currentPrio;
1014 }
1015 }
1016 if (myTargets.count(myStep) == 0) {
1018 }
1019 for (int step : cands) {
1020 int prio = 0;
1021 for (int target : myTargets[myStep][step]) {
1022 prio += getPhasePriority(target);
1023#ifdef DEBUG_PHASE_SELECTION
1024 if (DEBUG_COND) {
1025 std::cout << SIMTIME << " p=" << myStep << " step=" << step << " target=" << target << " loops=" << myInductLoopsForPhase[target].size() << " prio=" << prio << "\n";
1026 }
1027#endif
1028 }
1029 if (prio > maxPrio && canExtendLinkGreen(getTarget(step).first)) {
1030 maxPrio = prio;
1031 result = step;
1032 }
1033 }
1034 return result;
1035}
1036
1037
1038std::pair<int, SUMOTime>
1040 int seen = 0;
1041 int origStep = step;
1042 SUMOTime dur = 0;
1043
1044 // if step is a transition, find the upcoming green phase
1045 while (!myPhases[step]->isGreenPhase()) {
1046 seen += 1;
1047 dur += myPhases[step]->duration;
1048 if (myPhases[step]->nextPhases.size() > 0 && myPhases[step]->nextPhases.front() >= 0) {
1049 for (int next : myPhases[step]->nextPhases) {
1050 if (next != step) {
1051 step = next;
1052 break;
1053 }
1054 }
1055 } else {
1056 step = (step + 1) % (int)myPhases.size();
1057 }
1058 if (step == origStep || seen > (int)myPhases.size()) {
1059 WRITE_WARNING("At actuated tlLogic '" + getID() + "', infinite transition loop from phase " + toString(origStep));
1060 return std::make_pair(0, 0);
1061 }
1062 }
1063 return std::make_pair(step, dur);
1064}
1065
1066int
1068 MSInductLoop* loop = loopInfo.loop;
1069 const double actualGap = loop->getTimeSinceLastDetection();
1070 if ((actualGap < loopInfo.maxGap && !loopInfo.isJammed())
1071 || loopInfo.lastGreenTime < loop->getLastDetectionTime()) {
1072 SUMOTime inactiveTime = MSNet::getInstance()->getCurrentTimeStep() - loopInfo.lastGreenTime;
1073 // @note. Inactive time could also be tracked regardless of current activity (to increase robustness in case of detection failure
1074 if (inactiveTime > myInactiveThreshold) {
1075#ifdef DEBUG_PHASE_SELECTION
1076 if (DEBUG_COND) {
1077 std::cout << " loop=" << loop->getID() << " gap=" << loop->getTimeSinceLastDetection() << " lastGreen=" << STEPS2TIME(loopInfo.lastGreenTime)
1078 << " lastDetection=" << STEPS2TIME(loop->getLastDetectionTime()) << " inactive=" << STEPS2TIME(inactiveTime) << "\n";
1079 }
1080#endif
1081 return (int)STEPS2TIME(inactiveTime);
1082 } else {
1083 // give bonus to detectors that are currently served (if that phase can stil be extended)
1084 if (loopInfo.servedPhase[myStep]) {
1085 SUMOTime actDuration = MSNet::getInstance()->getCurrentTimeStep() - myPhases[myStep]->myLastSwitch;
1086 const bool canExtend = actDuration < getCurrentPhaseDef().maxDuration && getLatest() > 0;
1087#ifdef DEBUG_PHASE_SELECTION
1088 if (DEBUG_COND) {
1089 std::cout << " loop=" << loop->getID()
1090 << " actDuration=" << STEPS2TIME(actDuration)
1091 << " maxDur=" << STEPS2TIME(getCurrentPhaseDef().maxDuration)
1092 << " getLatest=" << STEPS2TIME(getLatest())
1093 << " canExtend=" << canExtend
1094 << "\n";
1095 }
1096#endif
1097 if (canExtend) {
1099 } else {
1100 return 0;
1101 }
1102 }
1103 return 1;
1104 }
1105 }
1106 return 0;
1107}
1108
1109int
1111 int result = 0;
1112 for (const InductLoopInfo* loopInfo : myInductLoopsForPhase[step]) {
1113 result += getDetectorPriority(*loopInfo);
1114 }
1115 if (myCrossingsForPhase.size() > 0) {
1116 for (const MSLink* crossingEntry : myCrossingsForPhase[step]) {
1117 auto* aPersons = crossingEntry->getApproachingPersons();
1118 if (aPersons != nullptr && aPersons->size() > 0) {
1119 result += DEFAULT_CROSSING_PRIORITY;
1120 }
1121 }
1122 }
1123 return result;
1124}
1125
1126
1127void
1129 myShowDetectors = show;
1130 for (InductLoopInfo& loopInfo : myInductLoops) {
1131 loopInfo.loop->setVisible(myShowDetectors);
1132 }
1133}
1134
1135
1136bool
1138 if (myLinkMaxGreenTimes.empty()) {
1139 return false;
1140 }
1141 for (int i = 0; i < myNumLinks; i++) {
1143 //std::cout << SIMTIME << " maxLinkDurationReached i=" << i << "\n";
1144 return true;
1145 }
1146 }
1147 return false;
1148}
1149
1150bool
1152 if (myLinkMaxGreenTimes.empty()) {
1153 return true;
1154 }
1155 const std::string& targetState = myPhases[target]->getState();
1156 for (int i = 0; i < myNumLinks; i++) {
1157 if (myLinkGreenTimes[i] >= myLinkMaxGreenTimes[i] && (
1158 targetState[i] == 'G' || targetState[i] == 'g')) {
1159 //std::cout << SIMTIME << " cannotExtendLinkGreen target=" << target << " i=" << i << "\n";
1160 return false;
1161 }
1162 }
1163 return true;
1164}
1165
1168 SUMOTime result = 0;
1169 if (target != myStep && myLinkMinGreenTimes.size() > 0) {
1170 const std::string& state = myPhases[myStep]->getState();
1171 const std::string& targetState = myPhases[target]->getState();
1172 for (int i = 0; i < myNumLinks; i++) {
1174 && (state[i] == 'G' || state[i] == 'g')
1175 && !(targetState[i] == 'G' || targetState[i] == 'g')) {
1176 result = MAX2(result, myLinkMinGreenTimes[i] - myLinkGreenTimes[i]);
1177 //std::cout << SIMTIME << " getLinkMinDuration myStep=" << myStep << " target=" << target << " i=" << i
1178 // << " greenTime=" << STEPS2TIME(myLinkGreenTimes[i]) << " min=" << STEPS2TIME(myLinkMinGreenTimes[i]) << " result=" << STEPS2TIME(result) << "\n";
1179 }
1180 }
1181 }
1182 return result;
1183}
1184
1185int
1187 for (int next : getCurrentPhaseDef().nextPhases) {
1188 const MSPhaseDefinition* phase = myPhases[next];
1189 const std::string& condition = mustSwitch ? phase->finalTarget : phase->earlyTarget;
1190#ifdef DEBUG_PHASE_SELECTION_CUSTOM
1191 if (DEBUG_COND) {
1192 std::cout << SIMTIME << " mustSwitch=" << mustSwitch << " cur=" << myStep << " next=" << next << " condition=" << condition
1193 << " eval=" << (condition == "" ? NAN : evalExpression(condition)) << "\n";
1194 }
1195#endif
1196 if (condition != "") {
1197 // backward compatibility if a user redefined DEFAULT_CONDITION
1198 if (condition == DEFAULT_CONDITION && myConditions.count(DEFAULT_CONDITION) == 0) {
1199 if (gapControl() == std::numeric_limits<double>::max()) {
1200 return next;
1201 }
1202 } else if (evalExpression(condition)) {
1203 return next;
1204 }
1205 }
1206 }
1207 return mustSwitch ? getCurrentPhaseDef().nextPhases.back() : myStep;
1208}
1209
1210
1211double
1212MSActuatedTrafficLightLogic::evalExpression(const std::string& condition) const {
1213 const size_t bracketOpen = condition.find('(');
1214 if (bracketOpen != std::string::npos) {
1215 // find matching closing bracket
1216 size_t bracketClose = std::string::npos;
1217 int open = 1;
1218 for (size_t i = bracketOpen + 1; i < condition.size(); i++) {
1219 if (condition[i] == '(') {
1220 open++;
1221 } else if (condition[i] == ')') {
1222 open--;
1223 if (open == 0) {
1224 bracketClose = i;
1225 break;
1226 }
1227 }
1228 }
1229 if (bracketClose == std::string::npos) {
1230 throw ProcessError(TLF("Unmatched parentheses in condition %'", condition));
1231 }
1232 std::string cond2 = condition;
1233 const std::string inBracket = condition.substr(bracketOpen + 1, bracketClose - bracketOpen - 1);
1234 double bracketVal = evalExpression(inBracket);
1235 cond2.replace(bracketOpen, bracketClose - bracketOpen + 1, toString(bracketVal));
1236 try {
1237 return evalExpression(cond2);
1238 } catch (ProcessError& e) {
1239 throw ProcessError(TLF("Error when evaluating expression '%':\n %", condition, e.what()));
1240 }
1241 }
1242 std::vector<std::string> tokens = StringTokenizer(condition).getVector();
1243 //std::cout << SIMTIME << " tokens(" << tokens.size() << ")=" << toString(tokens) << "\n";
1244 if (tokens.size() == 0) {
1245 throw ProcessError(TLF("Invalid empty condition '%'", condition));
1246 } else if (tokens.size() == 1) {
1247 try {
1248 return evalAtomicExpression(tokens[0]);
1249 } catch (ProcessError& e) {
1250 throw ProcessError(TLF("Error when evaluating expression '%':\n %", condition, e.what()));
1251 }
1252 } else if (tokens.size() == 2) {
1253 if (tokens[0] == "not") {
1254 try {
1255 return evalAtomicExpression(tokens[1]) == 0. ? 1. : 0.;
1256 } catch (ProcessError& e) {
1257 throw ProcessError(TLF("Error when evaluating expression '%':\n %", condition, e.what()));
1258 }
1259 } else {
1260 throw ProcessError(TLF("Unsupported condition '%'", condition));
1261 }
1262 } else if (tokens.size() == 3) {
1263 // infix expression
1264 const double a = evalAtomicExpression(tokens[0]);
1265 const double b = evalAtomicExpression(tokens[2]);
1266 const std::string& o = tokens[1];
1267 //std::cout << SIMTIME << " o=" << o << " a=" << a << " b=" << b << "\n";
1268 try {
1269 return evalTernaryExpression(a, o, b, condition);
1270 } catch (ProcessError& e) {
1271 throw ProcessError(TLF("Error when evaluating expression '%':\n %", condition, e.what()));
1272 }
1273 } else {
1274 const int iEnd = (int)tokens.size() - 1;
1275 for (const std::string& o : OPERATOR_PRECEDENCE) {
1276 for (int i = 1; i < iEnd; i++) {
1277 if (tokens[i] == o) {
1278 try {
1279 const double val = evalTernaryExpression(
1280 evalAtomicExpression(tokens[i - 1]), o,
1281 evalAtomicExpression(tokens[i + 1]), condition);
1282 std::vector<std::string> newTokens(tokens.begin(), tokens.begin() + (i - 1));
1283 newTokens.push_back(toString(val));
1284 newTokens.insert(newTokens.end(), tokens.begin() + (i + 2), tokens.end());
1285 return evalExpression(toString(newTokens));
1286 } catch (ProcessError& e) {
1287 throw ProcessError(TLF("Error when evaluating expression '%':\n %", condition, e.what()));
1288 }
1289 }
1290 }
1291 }
1292 throw ProcessError(TLF("Parsing expressions with % elements ('%') is not supported", toString(tokens.size()), condition));
1293 }
1294 return true;
1295}
1296
1297double
1298MSActuatedTrafficLightLogic::evalTernaryExpression(double a, const std::string& o, double b, const std::string& condition) const {
1299 if (o == "=" || o == "==") {
1300 return (double)(a == b);
1301 } else if (o == "<") {
1302 return (double)(a < b);
1303 } else if (o == ">") {
1304 return (double)(a > b);
1305 } else if (o == "<=") {
1306 return (double)(a <= b);
1307 } else if (o == ">=") {
1308 return (double)(a >= b);
1309 } else if (o == "!=") {
1310 return (double)(a != b);
1311 } else if (o == "or" || o == "||") {
1312 return (double)(a || b);
1313 } else if (o == "and" || o == "&&") {
1314 return (double)(a && b);
1315 } else if (o == "+") {
1316 return a + b;
1317 } else if (o == "-") {
1318 return a - b;
1319 } else if (o == "*") {
1320 return a * b;
1321 } else if (o == "/") {
1322 if (b == 0) {
1323 WRITE_ERRORF(TL("Division by 0 in condition '%'"), condition);
1324 return 0;
1325 }
1326 return a / b;
1327 } else if (o == "%") {
1328 return fmod(a, b);
1329 } else if (o == "**" || o == "^") {
1330 return pow(a, b);
1331 } else {
1332 throw ProcessError(TLF("Unsupported operator '%' in condition '%'", o, condition));
1333 }
1334}
1335
1336double
1337MSActuatedTrafficLightLogic::evalCustomFunction(const std::string& fun, const std::string& arg) const {
1338 std::vector<std::string> args = StringTokenizer(arg, ",").getVector();
1339 const Function& f = myFunctions.find(fun)->second;
1340 if ((int)args.size() != f.nArgs) {
1341 throw ProcessError(TLF("Function '%' requires % arguments but % were given", fun, toString(f.nArgs), toString(args.size())));
1342 }
1343 std::vector<double> args2;
1344 for (auto a : args) {
1345 args2.push_back(evalExpression(a));
1346 }
1347 myStack.push_back(myStack.back());
1348 myStack.back()["$0"] = 0;
1349 for (int i = 0; i < (int)args2.size(); i++) {
1350 myStack.back()["$" + toString(i + 1)] = args2[i];
1351 }
1352 try {
1353 ConditionMap empty;
1355 } catch (ProcessError& e) {
1356 throw ProcessError(TLF("Error when evaluating function '%' with args '%' (%)", fun, joinToString(args2, ","), e.what()));
1357 }
1358 double result = myStack.back()["$0"];
1359 myStack.pop_back();
1360 return result;
1361}
1362
1363
1364void
1365MSActuatedTrafficLightLogic::executeAssignments(const AssignmentMap& assignments, ConditionMap& conditions, const ConditionMap& forbidden) const {
1366 for (const auto& assignment : assignments) {
1367 if (evalExpression(std::get<1>(assignment))) {
1368 const std::string& id = std::get<0>(assignment);
1369 const double val = evalExpression(std::get<2>(assignment));
1370 ConditionMap::iterator it = conditions.find(id);
1371 if (it != conditions.end()) {
1372 it->second = toString(val);
1373 } else if (forbidden.find(id) != forbidden.end()) {
1374 throw ProcessError(TLF("Modifying global condition '%' is forbidden", id));
1375 } else {
1376 myStack.back()[id] = val;
1377 }
1378 }
1379 }
1380}
1381
1382
1383double
1385 if (expr.size() == 0) {
1386 throw ProcessError(TL("Invalid empty expression"));
1387 } else if (expr[0] == '!') {
1388 return evalAtomicExpression(expr.substr(1)) == 0. ? 1. : 0.;
1389 } else if (expr[0] == '-') {
1390 return -evalAtomicExpression(expr.substr(1));
1391 } else {
1392 // check for 'operator:'
1393 const size_t pos = expr.find(':');
1394 if (pos == std::string::npos) {
1395 auto it = myConditions.find(expr);
1396 if (it != myConditions.end()) {
1397 // symbol lookup
1398 return evalExpression(it->second);
1399 } else {
1400 // look at stack
1401 auto it2 = myStack.back().find(expr);
1402 if (it2 != myStack.back().end()) {
1403 return it2->second;
1404 }
1405 // must be a number
1406 return StringUtils::toDouble(expr);
1407 }
1408 } else {
1409 const std::string fun = expr.substr(0, pos);
1410 const std::string arg = expr.substr(pos + 1);
1411 if (fun == "z") {
1412 return retrieveDetExpression<MSInductLoop, SUMO_TAG_INDUCTION_LOOP>(arg, expr, true)->getTimeSinceLastDetection();
1413 } else if (fun == "a") {
1414 try {
1415 return retrieveDetExpression<MSInductLoop, SUMO_TAG_INDUCTION_LOOP>(arg, expr, true)->getTimeSinceLastDetection() == 0;
1416 } catch (ProcessError&) {
1417 return retrieveDetExpression<MSE2Collector, SUMO_TAG_LANE_AREA_DETECTOR>(arg, expr, true)->getCurrentVehicleNumber();
1418 }
1419 } else if (fun == "w") {
1420 try {
1421 return retrieveDetExpression<MSInductLoop, SUMO_TAG_INDUCTION_LOOP>(arg, expr, true)->getOccupancyTime();
1422 } catch (ProcessError&) {
1423 return retrieveDetExpression<MSE2Collector, SUMO_TAG_LANE_AREA_DETECTOR>(arg, expr, true)->getCurrentJamDuration();
1424 }
1425 } else if (fun == "d") {
1426 try {
1427 return retrieveDetExpression<MSInductLoop, SUMO_TAG_INDUCTION_LOOP>(arg, expr, true)->getArrivalDelay();
1428 } catch (ProcessError&) {
1429 return retrieveDetExpression<MSE2Collector, SUMO_TAG_LANE_AREA_DETECTOR>(arg, expr, true)->getArrivalDelay();
1430 }
1431 } else if (fun == "g" || fun == "r") {
1432 try {
1433 int linkIndex = StringUtils::toInt(arg);
1434 if (linkIndex >= 0 && linkIndex < myNumLinks) {
1435 const std::vector<SUMOTime>& times = fun == "g" ? myLinkGreenTimes : myLinkRedTimes;
1436 if (times.empty()) {
1437 return 0;
1438 }
1440 // times are only updated at the start of a phase where
1441 // switching is possible (i.e. not during minDur).
1442 // If somebody is looking at those values in the tracker
1443 // this would be confusing
1444 const LinkState ls = getCurrentPhaseDef().getSignalState(linkIndex);
1445 if ((fun == "g" && (ls == LINKSTATE_TL_GREEN_MAJOR || ls == LINKSTATE_TL_GREEN_MINOR))
1446 || (fun == "r" && (ls == LINKSTATE_TL_RED || ls == LINKSTATE_TL_REDYELLOW))) {
1447 const SUMOTime currentGreen = SIMSTEP - myLastTrySwitchTime;
1448 return STEPS2TIME(times[linkIndex] + currentGreen);
1449 } else {
1450 return 0;
1451 }
1452 } else {
1453 return STEPS2TIME(times[linkIndex]);
1454 }
1455 }
1456 } catch (NumberFormatException&) { }
1457 throw ProcessError(TLF("Invalid link index '%' in expression '%'", arg, expr));
1458 } else if (fun == "p") {
1459 try {
1460 int linkIndex = StringUtils::toInt(arg);
1461 if (linkIndex >= 0 && linkIndex < myNumLinks) {
1462 double approachingPersons = 0;
1463 for (const MSLink* link : getLinksAt(linkIndex)) {
1464 auto* aPersons = link->getApproachingPersons();
1465 if (aPersons != nullptr) {
1466 approachingPersons += (double)aPersons->size();
1467 }
1468 }
1469 return approachingPersons;
1470 }
1471 } catch (NumberFormatException&) { }
1472 throw ProcessError(TLF("Invalid link index '%' in expression '%'", arg, expr));
1473 } else if (fun == "c") {
1474 return STEPS2TIME(getTimeInCycle());
1475 } else {
1476 if (myFunctions.find(fun) == myFunctions.end()) {
1477 throw ProcessError(TLF("Unsupported function '%' in expression '%'", fun, expr));
1478 }
1479 return evalCustomFunction(fun, arg);
1480 }
1481 }
1482 }
1483}
1484
1485
1486std::map<std::string, double>
1488 std::map<std::string, double> result;
1489 for (auto li : myInductLoops) {
1490 result[li.loop->getID()] = li.loop->getOccupancy() > 0 ? 1 : 0;
1491 }
1492 for (auto loop : myExtraLoops) {
1493 result[loop->getID()] = loop->getOccupancy() > 0 ? 1 : 0;
1494 }
1495 for (auto loop : myExtraE2) {
1496 result[loop->getID()] = loop->getCurrentVehicleNumber();
1497 }
1498 return result;
1499}
1500
1501double
1502MSActuatedTrafficLightLogic::getDetectorState(const std::string laneID) const {
1503 double result = 0.0;
1504 for (auto li : myInductLoops) {
1505 if (li.lane->getID() == laneID) {
1506 result = li.loop->getOccupancy() > 0 ? 1 : 0;
1507 break;
1508 }
1509 }
1510 return result;
1511}
1512
1513std::map<std::string, double>
1515 std::map<std::string, double> result;
1516 for (auto item : myConditions) {
1517 if (myListedConditions.count(item.first) != 0) {
1518 try {
1519 result[item.first] = evalExpression(item.second);
1520 } catch (ProcessError& e) {
1521 WRITE_ERRORF(TL("Error when retrieving conditions '%' for tlLogic '%' (%)"), item.first, getID(), e.what());
1522 }
1523 }
1524 }
1525 return result;
1526}
1527
1528const std::string
1529MSActuatedTrafficLightLogic::getParameter(const std::string& key, const std::string defaultValue) const {
1530 if (StringUtils::startsWith(key, "condition.")) {
1531 const std::string cond = key.substr(10);
1532 auto it = myConditions.find(cond);
1533 if (it != myConditions.end()) {
1534 return toString(evalExpression(it->second));
1535 } else {
1536 throw InvalidArgument(TLF("Unknown condition '%' for actuated traffic light '%'", cond, getID()));
1537 }
1538 } else {
1539 return MSSimpleTrafficLightLogic::getParameter(key, defaultValue);
1540 }
1541}
1542
1543void
1544MSActuatedTrafficLightLogic::setParameter(const std::string& key, const std::string& value) {
1545 // some pre-defined parameters can be updated at runtime
1546 if (key == "detector-gap" || key == "passing-time" || key == "file" || key == "freq" || key == "vTypes"
1547 || key == "build-all-detectors"
1548 || StringUtils::startsWith(key, "linkMaxDur")
1549 || StringUtils::startsWith(key, "linkMinDur")) {
1550 throw InvalidArgument(key + " cannot be changed dynamically for actuated traffic light '" + getID() + "'");
1551 } else if (key == "max-gap") {
1553 // overwrite custom values
1554 for (InductLoopInfo& loopInfo : myInductLoops) {
1555 loopInfo.maxGap = myMaxGap;
1556 }
1557 Parameterised::setParameter(key, value);
1558 } else if (StringUtils::startsWith(key, "max-gap:")) {
1559 const std::string laneID = key.substr(8);
1560 for (InductLoopInfo& loopInfo : myInductLoops) {
1561 if (loopInfo.lane->getID() == laneID) {
1562 loopInfo.maxGap = StringUtils::toDouble(value);
1563 Parameterised::setParameter(key, value);
1564 return;
1565 }
1566 }
1567 throw InvalidArgument(TLF("Invalid lane '%' in key '%' for actuated traffic light '%'", laneID, key, getID()));
1568 } else if (key == "jam-threshold") {
1570 // overwrite custom values
1571 for (InductLoopInfo& loopInfo : myInductLoops) {
1572 loopInfo.jamThreshold = myJamThreshold;
1573 }
1574 Parameterised::setParameter(key, value);
1575 } else if (StringUtils::startsWith(key, "jam-threshold:")) {
1576 const std::string laneID = key.substr(14);
1577 for (InductLoopInfo& loopInfo : myInductLoops) {
1578 if (loopInfo.lane->getID() == laneID) {
1579 loopInfo.jamThreshold = StringUtils::toDouble(value);
1580 Parameterised::setParameter(key, value);
1581 return;
1582 }
1583 }
1584 throw InvalidArgument(TLF("Invalid lane '%' in key '%' for actuated traffic light '%'", laneID, key, getID()));
1585 } else if (key == "show-detectors") {
1587 Parameterised::setParameter(key, value);
1588 for (InductLoopInfo& loopInfo : myInductLoops) {
1589 loopInfo.loop->setVisible(myShowDetectors);
1590 }
1591 } else if (key == "inactive-threshold") {
1593 Parameterised::setParameter(key, value);
1594 } else {
1596 }
1597}
1598
1599
1600/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
#define DEFAULT_DETECTOR_GAP
#define DEFAULT_MAX_GAP
#define DEFAULT_STATIC_MINDUR
#define DEFAULT_PASSING_TIME
#define DEFAULT_BIKE_LENGTH_WITH_GAP
#define DEFAULT_LENGTH_WITH_GAP
#define NO_DETECTOR
#define DEFAULT_INACTIVE_THRESHOLD
#define DEFAULT_CROSSING_PRIORITY
#define DEFAULT_CONDITION
#define DEFAULT_CURRENT_PRIORITY
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_ERRORF(...)
Definition MsgHandler.h:308
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
#define TL(string)
Definition MsgHandler.h:316
#define TLF(string,...)
Definition MsgHandler.h:318
SUMOTime string2time(const std::string &r)
convert string to SUMOTime
Definition SUMOTime.cpp:47
std::string time2string(SUMOTime t, bool humanReadable)
convert SUMOTime to string (independently of global format setting)
Definition SUMOTime.cpp:107
#define STEPS2TIME(x)
Definition SUMOTime.h:58
#define SIMSTEP
Definition SUMOTime.h:69
constexpr SUMOTime TIME2STEPS(double x)
Definition SUMOTime.h:60
#define SUMOTime_MAX
Definition SUMOTime.h:34
#define SIMTIME
Definition SUMOTime.h:70
bool noVehicles(SVCPermissions permissions)
Returns whether an edge with the given permissions forbids vehicles.
long long int SVCPermissions
bitset where each bit declares whether a certain SVC may use this edge/lane
const double DEFAULT_BICYCLE_SPEED
@ SVC_BICYCLE
vehicle is a bicycle
@ SVC_PEDESTRIAN
pedestrian
@ SUMO_TAG_INDUCTION_LOOP
alternative tag for e1 detector
LinkState
The right-of-way state of a link between two lanes used when constructing a NBTrafficLightLogic,...
@ LINKSTATE_TL_REDYELLOW
The link has red light (must brake) but indicates upcoming green.
@ LINKSTATE_TL_GREEN_MAJOR
The link has green light, may pass.
@ LINKSTATE_TL_RED
The link has red light (must brake)
@ LINKSTATE_TL_GREEN_MINOR
The link has green light, has to brake.
T MIN3(T a, T b, T c)
Definition StdDefs.h:93
T MIN2(T a, T b)
Definition StdDefs.h:80
T MAX2(T a, T b)
Definition StdDefs.h:86
T MAX3(T a, T b, T c)
Definition StdDefs.h:100
std::string joinNamedToString(const std::set< T *, C > &ns, const T_BETWEEN &between)
Definition ToString.h:374
std::string joinToString(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=gPrecision)
Definition ToString.h:322
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:57
static std::string checkForRelativity(const std::string &filename, const std::string &basePath)
Returns the path from a configuration so that it is accessible from the current working directory.
double myDetectorGap
The detector distance in seconds.
void findTargets(int origStep, int n, SUMOTime priorTransition, std::map< int, SUMOTime > &found)
FunctionMap myFunctions
The loaded functions.
double myJamThreshold
The minimum continuous occupancy time to mark a detector as jammed.
bool myBuildAllDetectors
Whether all detectors shall be built.
double myMaxGap
The maximum gap to check in seconds.
const std::string getParameter(const std::string &key, const std::string defaultValue="") const override
try to get the value of the given parameter (including prefixed parameters)
std::map< int, std::map< int, std::vector< int > > > myTargets
std::vector< SwitchingRules > mySwitchingRules
std::vector< std::map< std::string, double > > myStack
The function call stack;.
double evalAtomicExpression(const std::string &expr) const
evaluate atomic expression
SUMOTime trySwitch() override
Switches to the next phase.
std::set< int > getMultiNextTargets() const
find green phases target by a next attribute
SUMOTime myLastTrySwitchTime
last time trySwitch was called
int getDetectorPriority(const InductLoopInfo &loopInfo) const
SUMOTime myFreq
The frequency for aggregating detector output.
std::vector< const MSInductLoop * > myExtraLoops
extra loops for output/tracking
bool myShowDetectors
Whether the detectors shall be shown in the GUI.
std::vector< SUMOTime > myLinkMaxGreenTimes
maximum consecutive time that the given link may remain green
MSActuatedTrafficLightLogic(MSTLLogicControl &tlcontrol, const std::string &id, const std::string &programID, const SUMOTime offset, const MSSimpleTrafficLightLogic::Phases &phases, int step, SUMOTime delay, const Parameterised::Map &parameter, const std::string &basePath, const ConditionMap &conditions=ConditionMap(), const AssignmentMap &assignments=AssignmentMap(), const FunctionMap &functions=FunctionMap())
Constructor.
SUMOTime getMaxDur(int step=-1) const override
std::vector< std::vector< const MSLink * > > myCrossingsForPhase
AssignmentMap myAssignments
The condition assignments.
std::string myVehicleTypes
Whether detector output separates by vType.
double gapControl()
Return the minimum detection gap of all detectors if the current phase should be extended and double:...
std::vector< std::tuple< std::string, std::string, std::string > > AssignmentMap
std::set< std::string > myListedConditions
the conditions which shall be listed in GUITLLogicPhasesTrackerWindow
double evalExpression(const std::string &condition) const
evaluate custom switching condition
std::vector< SUMOTime > myLinkMinGreenTimes
minimum consecutive time that the given link must remain green
void changeStepAndDuration(MSTLLogicControl &tlcontrol, SUMOTime simStep, int step, SUMOTime stepDuration) override
Changes the current phase and her duration.
bool weakConflict(int linkIndex, const std::string &state) const
whether a given link has only weak mode foes that are green in the given state
static const std::vector< std::string > OPERATOR_PRECEDENCE
bool myHasMultiTarget
Whether any of the phases has multiple targets.
double myPassingTime
The passing time used in seconds.
SUMOTime getLinkMinDuration(int target) const
the minimum duratin for keeping the current phase due to linkMinDur constraints
SUMOTime getMinDur(int step=-1) const override
bool canExtendLinkGreen(int target)
whether the target phase is acceptable in light of linkMaxDur constraints
InductLoopMap myInductLoopsForPhase
A map from phase to induction loops to be used for gap control.
SUMOTime getMinimumMinDuration(MSLane *lane, const std::set< int > &multiNextTargets) const
get the minimum min duration for all stretchable phases that affect the given lane
int decideNextPhaseCustom(bool mustSwitch)
select among candidate phases based on detector states and custom switching rules
double evalTernaryExpression(double a, const std::string &o, double b, const std::string &condition) const
evaluate atomic expression
void executeAssignments(const AssignmentMap &assignments, ConditionMap &conditions, const ConditionMap &forbidden=ConditionMap()) const
execute assignemnts of the logic or a custom function
bool myTraCISwitch
whether the next switch time was requested via TraCI
int getPhasePriority(int step) const
count the number of active detectors for the given step
SUMOTime duration(const double detectionGap) const
Returns the minimum duration of the current phase.
void activateProgram() override
called when switching programs
std::vector< InductLoopInfo > myInductLoops
bool maxLinkDurationReached()
whether the current phase cannot be continued due to linkMaxDur constraints
double evalCustomFunction(const std::string &fun, const std::string &arg) const
evaluate function expression
void initAttributeOverride()
initialize custom switching rules
std::map< std::string, double > getConditions() const override
return all named conditions defined for this traffic light
bool hasMajor(const std::string &state, const LaneVector &lanes) const
return whether there is a major link from the given lane in the given phase
std::vector< const MSE2Collector * > myExtraE2
SUMOTime getEarliestEnd(int step=-1) const override
std::map< std::string, Function > FunctionMap
std::map< std::string, double > getDetectorStates() const override
retrieve all detectors used by this program
double getDetectorState(const std::string laneID) const override
retrieve a specific detector used by this program
void setParameter(const std::string &key, const std::string &value) override
Sets a parameter and updates internal constants.
std::vector< SUMOTime > myLinkGreenTimes
consecutive time that the given link index has been green
SUMOTime getLatestEnd(int step=-1) const override
std::string myFile
The output file for generated detectors.
std::pair< int, SUMOTime > getTarget(int step) const
get the green phase following step and the transition time
ConditionMap myConditions
The custom switching conditions.
void loadState(MSTLLogicControl &tlcontrol, SUMOTime t, int step, SUMOTime spentDuration, SUMOTime nextSwitch, SUMOTime timeInCycle, bool active) override
restores the tls state, including the start of the current phase
void init(NLDetectorBuilder &nb) override
Initialises the tls with information about incoming lanes.
int decideNextPhase()
select among candidate phases based on detector states
SUMOTime myInactiveThreshold
The time threshold to avoid starved phases.
const NamedObjectCont< MSDetectorFileOutput * > & getTypedDetectors(SumoXMLTag type) const
Returns the list of detectors of the given type.
void add(SumoXMLTag type, MSDetectorFileOutput *d, const std::string &device, SUMOTime interval, SUMOTime begin=-1)
Adds a detector/output combination into the containers.
A road/street connecting two junctions.
Definition MSEdge.h:78
double getSpeedLimit() const
Returns the speed limit of the edge @caution The speed limit of the first lane is returned; should pr...
Definition MSEdge.cpp:1235
virtual void addEvent(Command *operation, SUMOTime execTimeStep=-1)
Adds an Event.
An unextended detector measuring at a fixed position on a fixed lane.
double getPosition() const
Returns the position of the detector on the lane.
virtual void setSpecialColor(const RGBColor *)
allows for special color in the gui version
double getTimeSinceLastDetection() const
Returns the time since the last vehicle left the detector.
SUMOTime getLastDetectionTime() const
return last time a vehicle was on the detector
The base class for an intersection.
Definition MSJunction.h:58
virtual const MSJunctionLogic * getLogic() const
Definition MSJunction.h:141
virtual const MSLogicJunction::LinkBits & getFoesFor(int linkIndex) const
Returns the foes for the given link.
Representation of a lane in the micro simulation.
Definition MSLane.h:84
const std::vector< IncomingLaneInfo > & getIncomingLanes() const
Definition MSLane.h:984
double getLength() const
Returns the lane's length.
Definition MSLane.h:632
MSLane * getLogicalPredecessorLane() const
get the most likely predecessor lane (sorted using by_connections_to_sorter). The result is cached in...
Definition MSLane.cpp:3271
const std::vector< MSLink * > & getLinkCont() const
returns the container with all links !!!
Definition MSLane.h:750
MSDetectorControl & getDetectorControl()
Returns the detector control.
Definition MSNet.h:466
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:201
MSEventControl * getBeginOfTimestepEvents()
Returns the event control for events executed at the begin of a time step.
Definition MSNet.h:496
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:335
The definition of a single phase of a tls logic.
SUMOTime maxDuration
The maximum duration of the phase.
LinkState getSignalState(int pos) const
Returns the state of the tls signal at the given position.
static const SUMOTime OVERRIDE_DURATION
SUMOTime latestEnd
The maximum time within the cycle for switching (for coordinated actuation)
SUMOTime minDuration
The minimum duration of the phase.
const std::string & getState() const
Returns the state within this phase.
bool isGreenPhase() const
Returns whether this phase is a pure "green" phase.
std::vector< int > nextPhases
The index of the phase that suceeds this one (or -1)
std::string finalTarget
The condition expression for switching into this phase when the active phase must end.
std::string earlyTarget
The condition expression for an early switch into this phase.
SUMOTime earliestEnd
The minimum time within the cycle for switching (for coordinated actuation)
A fixed traffic light logic.
SUMOTime getLatest() const
the maximum duration for keeping the current phase when considering 'latestEnd'
Phases myPhases
The list of phases this logic uses.
SUMOTime getEarliest(SUMOTime prevStart) const
the minimum duration for keeping the current phase when considering 'earliestEnd'
bool myCoordinated
whether coordination parameters earliestEnd, latestEnd are
virtual const std::string getParameter(const std::string &key, const std::string defaultValue="") const override
gets a parameter
virtual void setParameter(const std::string &key, const std::string &value) override
Sets a parameter and updates internal constants.
const MSPhaseDefinition & getCurrentPhaseDef() const override
Returns the definition of the current phase.
A class that stores and controls tls and switching of their programs.
TLSLogicVariants & get(const std::string &id) const
Returns the variants of a named tls.
Class realising the switch between the traffic light phases.
void deschedule(MSTrafficLightLogic *tlLogic)
Marks this swicth as invalid (if the phase duration has changed, f.e.)
const LaneVector & getLanesAt(int i) const
Returns the list of lanes that are controlled by the signals at the given position.
std::vector< MSLane * > LaneVector
Definition of the list of arrival lanes subjected to this tls.
SUMOTime getTimeInCycle() const
return time within the current cycle
const std::string & getProgramID() const
Returns this tl-logic's id.
LaneVectorVector myLanes
The list of LaneVectors; each vector contains the incoming lanes that belong to the same link index.
SwitchCommand * mySwitchCommand
The current switch command.
int myNumLinks
number of controlled links
virtual void activateProgram()
called when switching programs
bool myAmActive
whether the current program is active
bool setTrafficLightSignals(SUMOTime t) const
Applies the current signal states to controlled links.
std::vector< MSPhaseDefinition * > Phases
Definition of a list of phases, being the junction logic.
const LinkVector & getLinksAt(int i) const
Returns the list of links that are controlled by the signals at the given position.
LinkVectorVector myLinks
The list of LinkVectors; each vector contains the links that belong to the same link index.
virtual void init(NLDetectorBuilder &nb)
Initialises the tls with information about incoming lanes.
Builds detectors for microsim.
virtual MSDetectorFileOutput * createInductLoop(const std::string &id, MSLane *lane, double pos, double length, const std::string name, const std::string &vTypes, const std::string &nextEdges, int detectPersons, bool show, bool forceMicro=false)
Creates an instance of an e1 detector using the given values.
const std::string & getID() const
Returns the id.
Definition Named.h:73
T get(const std::string &id) const
Retrieves an item.
static OptionsCont & getOptions()
Retrieves the options.
bool hasParameter(const std::string &key) const
Returns whether the parameter is set.
std::map< std::string, std::string > Map
parameters map
double getDouble(const std::string &key, const double defaultValue) const
Returns the value for a given key converted to a double.
const Parameterised::Map & getParametersMap() const
Returns the inner key/value map.
virtual void setParameter(const std::string &key, const std::string &value)
Sets a parameter.
static const RGBColor ORANGE
Definition RGBColor.h:210
static const RGBColor GREEN
Definition RGBColor.h:205
static const RGBColor RED
named colors
Definition RGBColor.h:204
std::vector< std::string > getVector()
return vector of strings
static double toDouble(const std::string &sData)
converts a string into the double value described by it by calling the char-type converter
static bool startsWith(const std::string &str, const std::string prefix)
Checks whether a given string starts with the prefix.
static int toInt(const std::string &sData)
converts a string into the integer value described by it by calling the char-type converter,...
static bool toBool(const std::string &sData)
converts a string into the bool value described by it by calling the char-type converter
#define DEBUG_COND