Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
NEMAController.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/****************************************************************************/
20// An actuated NEMA-phase-compliant traffic light logic
21/****************************************************************************/
22#include <config.h>
23
24#include <cassert>
25#include <utility>
26#include <vector>
27#include <bitset>
28#include <sstream>
29#include <iostream>
34#include <microsim/MSGlobals.h>
35#include <microsim/MSNet.h>
36#include <microsim/MSLane.h>
37#include <microsim/MSEdge.h>
42#include "NEMAController.h"
43
44
45// ===========================================================================
46// parameter defaults definitions
47// ===========================================================================
48#define INVALID_POSITION std::numeric_limits<double>::max() // tl added
49
50// #define DEBUG_NEMA
51// #define FUZZ_TESTING
52// #define DEBUG_NEMA_SWITCH
53
54// ===========================================================================
55// method definitions
56// ===========================================================================
58 const std::string& id, const std::string& programID,
59 const SUMOTime _offset,
60 const Phases& phases,
61 int step, SUMOTime delay,
62 const std::map<std::string, std::string>& parameter,
63 const std::string& basePath) :
64 MSSimpleTrafficLightLogic(tlcontrol, id, programID, _offset, TrafficLightType::NEMA, phases, step, delay, parameter),
65 myPhase(phases[0]->duration, phases[0]->getState()) {
66 myDetectorLength = StringUtils::toDouble(getParameter("detector-length", "20"));
67 myDetectorLengthLeftTurnLane = StringUtils::toDouble(getParameter("detector-length-leftTurnLane", "20"));
71 myShowDetectors = StringUtils::toBool(getParameter("show-detectors", toString(OptionsCont::getOptions().getBool("tls.actuated.show-detectors"))));
72 myFile = FileHelpers::checkForRelativity(getParameter("file", "NUL"), basePath);
74 myVehicleTypes = getParameter("vTypes", "");
75 myControllerType = parseControllerType(getParameter("controllerType", "TS2"));
76 ignoreErrors = StringUtils::toBool(getParameter("ignore-errors", "false"));
77 // This should be extended in the future.
78 myNumberRings = 2;
79}
80
82 // delete the phase objects
83 for (auto p : myPhaseObjs) {
84 delete p;
85 }
86}
87
88void
89NEMALogic::constructTimingAndPhaseDefs(std::string& barriers, std::string& coordinates, std::string& ring1, std::string& ring2) {
90
91 // read in the barrier and coordinated phases from the XML
92 std::vector<int> barrierPhases = readParaFromString(barriers);
93 std::vector<int> coordinatePhases = readParaFromString(coordinates);
94 // both parameters need one phase per ring (#18514)
95 if (barrierPhases.size() != 2) {
96 throw ProcessError(TLF("At NEMA tlLogic '%', barrierPhases needs one phase per ring (2 values), got '%'.", getID(), barriers));
97 }
98 if (coordinatePhases.size() != 2) {
99 throw ProcessError(TLF("At NEMA tlLogic '%', coordinatePhases (or barrier2Phases) needs one phase per ring (2 values), got '%'.", getID(), coordinates));
100 }
101
102 // create a {{}, {}} vector of phases
103 rings.push_back(readParaFromString(ring1));
104 rings.push_back(readParaFromString(ring2));
105
106#ifdef DEBUG_NEMA
107 //print to check
108 for (int i = 0; i < (int)rings.size(); i++) {
109 int count = 0;
110 std::cout << "Ring" << i + 1 << " includes phases: \t";
111 for (auto j : rings[i]) {
112 count++;
113 std::cout << j << " ";
114 if (count == 2 || count == 4) {
115 std::cout << " | ";
116 }
117 }
118 std::cout << std::endl;
119 }
120#endif
121
122 // load the recalls, if they exist
123 std::vector<int> VecMinRecall = readParaFromString(getParameter("minRecall", "1,2,3,4,5,6,7,8"));
124 std::vector<int> VecMaxRecall = readParaFromString(getParameter("maxRecall", ""));
125
126#ifdef DEBUG_NEMA
127 std::cout << "minRecall: ";
128 for (int i = 0; i < 8; i++) {
129 std::cout << vectorContainsPhase(VecMinRecall, i + 1) << '\t';
130 }
131 std::cout << std::endl;
132
133 std::cout << "maxRecall: ";
134 for (int i = 0; i < 8; i++) {
135 std::cout << vectorContainsPhase(VecMaxRecall, i + 1) << '\t';
136 }
137 std::cout << std::endl;
138#endif
139
140 // loop through the rings and construct NEMAPhases.
141 // This relies on the phase being in order in the rings parameter in the configuration file
142 int ringNum = 0;
143 int lastPhaseIter = 0;
144 int phaseIter = 0;
145 for (const auto& r : rings) {
146 int ringIter = 0;
147 lastPhaseIter = phaseIter;
148 phaseIter = 0;
149 for (const auto& p : r) {
150 if (p != 0) {
151 // find the phase definition matching the phase integer
152 MSPhaseDefinition* tempPhase = nullptr;
153 for (const auto& pDef : myPhases) {
154 if (string2int(pDef->getName()) == p) {
155 tempPhase = pDef;
156 break;
157 }
158 }
159 // there must be a matching MSPhaseDefinition
160 if (tempPhase == nullptr) {
161 throw ProcessError("At traffic signal '" + myID + "' program '" + myProgramID + "' no phase named '" + toString(p) + "' was found");
162 }
163
164 // create lane specific objects
165 std::string state = tempPhase->getState();
166
167 // check that all phases have the same length. myPhaseStrLen is initially set to -1.
168 if (myPhaseStrLen < 0) {
169 myPhaseStrLen = (int)state.size();
170 } else if (myPhaseStrLen != (int)state.size()) {
171 throw ProcessError(TLF("At NEMA tlLogic '%', different sizes of NEMA phase states. Please check the NEMA XML", getID()));
172 }
173
174 // get the lane-based info
175 StringVector laneIDs;
176 IntVector controlledStateIndexes;
177 getLaneInfoFromNEMAState(state, laneIDs, controlledStateIndexes);
178
179 std::vector<std::string> laneIDs_vector;
180 for (std::string laneID : laneIDs) {
181 laneIDs_vector.push_back(laneID);
182 myLanePhaseMap[laneID] = p;
183 }
184 phase2ControllerLanesMap[p] = laneIDs_vector;
185
186 // Create the Phase Object
187 // find if it is at a barrier, i.e. the last phase on its side of the barrier in this ring.
188 // This is taken from the ring order, so that a coordinated phase followed by a lagging phase is not a barrier phase
189 bool barrierPhase = true;
190 for (int i = ringIter + 1; i < (int)r.size() && i / 2 == ringIter / 2; i++) {
191 if (r[i] != 0) {
192 barrierPhase = false;
193 }
194 }
195 // is it a coordinate phase
196 bool coordinatePhase = vectorContainsPhase(coordinatePhases, p) && coordinateMode;
197 // is there a minimum or max recall
198 bool minRecall = vectorContainsPhase(VecMinRecall, p);
199 bool maxRecall = vectorContainsPhase(VecMaxRecall, p);
200 // A phase can "green rest" only if it has a recall and no other phases on that ring do OR if NO phases have a recall (unique case)
201 bool phaseGreenRest = ((VecMaxRecall.size() + VecMinRecall.size()) < 1);
202 if (!phaseGreenRest) {
203 bool recallActive = minRecall || maxRecall;
204 if (recallActive) {
205 for (const auto& pO : r) {
206 if (pO != p) {
207 if (vectorContainsPhase(VecMinRecall, pO)
208 || vectorContainsPhase(VecMaxRecall, pO)) {
209 recallActive = false;
210 break;
211 }
212 }
213 }
214 // only set the green rest to true if I am the only phase on my ring with a recall
215 phaseGreenRest = recallActive;
216 }
217 }
218 // could add per-phase fixforceoff here
219 // barrierNum is either 0 or 1, depending on mainline side or sidestreet
220 int barrierNum = ringIter / 2;
221
222 // now ready to create the phase
223 myPhaseObjs.push_back(
224 new NEMAPhase(p, barrierPhase, phaseGreenRest, coordinatePhase, minRecall, maxRecall, fixForceOff, barrierNum, ringNum, controlledStateIndexes, tempPhase)
225 );
226
227 // Add a reference to the sequentially prior phase
228 if (phaseIter > 0) {
229 myPhaseObjs.back()->setSequentialPriorPhase(myPhaseObjs[lastPhaseIter + (phaseIter - 1)]);
230 }
231 phaseIter++;
232 }
233 ringIter++;
234 }
235 if (lastPhaseIter >= (int)myPhaseObjs.size()) {
236 throw ProcessError("At traffic signal '" + myID + "', ring " + toString(ringNum + 1) + " contains only '0'");
237 }
238 // Set the first to point to the last, wrapping around the ring.
239 myPhaseObjs[lastPhaseIter]->setSequentialPriorPhase(myPhaseObjs[lastPhaseIter + phaseIter - 1]);
240 // index the ring counter
241 ringNum++;
242 }
243
244 //TODO: set the default phases. This could also be set using dual entry in future
245 bool barrierMismatch = false;
246 for (int i = 0; i < 2; i++) {
247 // create the coordinate phase ptr
248 coordinatePhaseObjs[i] = getPhaseObj(coordinatePhases[i], i);
250 // create the other barrier phase ptr
251 PhasePtr b = getPhaseObj(barrierPhases[i], i);
253 // the barrier 1 and barrier 0 default phase must not have the same barrier number
255 throw ProcessError("At traffic signal " + myID + " the barrier and coordinated phases " +
256 std::to_string(b->phaseName) + ", " + std::to_string(coordinatePhaseObjs[i]->barrierNum) +
257 " are located on the same side of a barrier." +
258 " Please check your configuration file");
259 }
260 // the barrier phases must be last on their side of the barrier. In coordinated mode, the coordinated phase may be followed by a lagging phase
262 barrierMismatch = true;
263 }
264 }
265 if (barrierMismatch) {
266 WRITE_WARNINGF(TL("At NEMA tlLogic '%', barrierPhases or barrier2Phases name a phase that is not the last on its side of the barrier. Ring order decides which phase ends at the barrier, while these parameters still choose the default phase entered after a crossing."), getID());
267 }
268
269 // coordinated phases that are served again in the same cycle when their lagging phase gaps out
270 for (int p : readParaFromString(getParameter("reservicePhases", ""))) {
271 bool valid = false;
272 for (auto& phase : myPhaseObjs) {
273 if (phase->phaseName == p && phase->coordinatePhase && !phase->isAtBarrier) {
274 phase->reservice = true;
275 valid = true;
276 }
277 }
278 if (!valid) {
279 WRITE_WARNINGF(TL("At NEMA tlLogic '%', reservicePhases names phase %, which is not a coordinated phase followed by a lagging phase; it is ignored."), getID(), toString(p));
280 }
281 }
282
283 // Create the PhaseDetectorInfo for each of the phases (needs knowledge of other phases to create)
284 IntVector latchingDetectors = readParaFromString(getParameter("latchingDetectors", ""));
285 std::vector<std::pair<int, int>> cp;
286 for (auto& p : myPhaseObjs) {
287 std::string cps = "crossPhaseSwitching:";
288 int crossPhase = StringUtils::toInt(getParameter(cps.append(std::to_string(p->phaseName)), "0"));
289 if (crossPhase > 0) {
290 cp.push_back({ p->phaseName, crossPhase });
291 }
292 }
293
294 // Knowing the cross phase info, we can add that to the phase
295 for (auto& p : myPhaseObjs) {
296 bool latching = vectorContainsPhase(latchingDetectors, p->phaseName);
297 int cpTarget = 0;
298 int cpSource = 0;
299 for (auto& cp_pair : cp) {
300 if (cp_pair.first == p->phaseName || cp_pair.second == p->phaseName) {
301 cpTarget = cp_pair.first;
302 cpSource = cp_pair.second;
303 }
304 }
305 p->init(this, cpTarget, cpSource, latching);
306 }
307
308 // Calculate Force offs Based on Timing
310
311 if (coordinateMode) {
312 // Calculate the Initial Phases in coordinated operation only.
313 // Otherwise they have already been calculated above
315 } else {
316 // Fall back being the barrier 0 default phases
317 // NEMAPhase* defaultP[2] = {defaultBarrierPhases[0][0], defaultBarrierPhases[1][0]};
318 NEMAPhase* defaultP[2] = { getPhasesByRing(0).front(), getPhasesByRing(1).front() };
319 defaultP[0]->forceEnter(this);
320 defaultP[1]->forceEnter(this);
321 }
322
323
324#ifdef DEBUG_NEMA
325 //print to check the rings and barriers active phase
326 std::cout << "After init, active ring1 phase is " << myActivePhaseObjs[0]->phaseName << std::endl;
327 std::cout << "After init, active ring2 phase is " << myActivePhaseObjs[1]->phaseName << std::endl;
328
329
330 //print to check the phase definition is correct
331 std::cout << "Print to check NEMA phase definitions\n";
332 for (auto& p : myPhaseObjs) {
333 std::cout << "index = " << p->phaseName << "; ";
334 std::cout << "minDur = " << std::to_string(p->minDuration) << "; ";
335 std::cout << "maxDur = " << std::to_string(p->maxDuration) << "; ";
336 std::cout << "vehext = " << std::to_string(p->vehExt) << "; ";
337 std::cout << "yellow = " << std::to_string(p->yellow) << "; ";
338 std::cout << "red = " << std::to_string(p->red) << "; ";
339 std::cout << "state = " << std::to_string((int)p->getCurrentState()) << std::endl;
340 }
341#endif
342
343
344#ifdef DEBUG_NEMA
345 std::cout << "After init, r1/r2 barrier phase = " << defaultBarrierPhases[0][1]->phaseName << " and " << defaultBarrierPhases[1][1]->phaseName << std::endl;
346 std::cout << "After init, r1/r2 coordinate phase = " << defaultBarrierPhases[0][0]->phaseName << " and " << defaultBarrierPhases[1][0]->phaseName << std::endl;
347#endif
348
349
350#ifdef DEBUG_NEMA
351 std::cout << "R1State = " << myActivePhaseObjs[0]->phaseName << " and its state = " << std::to_string((int)myActivePhaseObjs[0]->getCurrentState()) << std::endl;
352 std::cout << "R2State = " << myActivePhaseObjs[1]->phaseName << " and its state = " << std::to_string((int)myActivePhaseObjs[0]->getCurrentState()) << std::endl;
353#endif
354
355 // Set the initial light state
357 myPhase.setName(toString(myActivePhaseObjs[0]->phaseName) + "+" + toString(myActivePhaseObjs[1]->phaseName));
359 myStep = 0;
360
361 //validating timing
363}
364
365bool
366NEMALogic::vectorContainsPhase(std::vector<int> v, int phaseNum) {
367 if (std::find(v.begin(), v.end(), phaseNum) != v.end()) {
368 return true;
369 }
370 return false;
371}
372
373void
375
376 // TODO: Create a parameter for this
378
379 std::string barriers = getParameter("barrierPhases", "");
380 std::string coordinates = getParameter("coordinatePhases", getParameter("barrier2Phases", ""));
381 std::string ring1 = getParameter("ring1", "");
382 std::string ring2 = getParameter("ring2", "");
383
384 fixForceOff = StringUtils::toBool(getParameter("fixForceOff", "false"));
387 whetherOutputState = StringUtils::toBool(getParameter("whetherOutputState", "false"));
388 coordinateMode = StringUtils::toBool(getParameter("coordinate-mode", "false"));
389
390 // set the queued traci changes to false
391 queuedTraciChanges = false;
392
393 //missing parameter error
394 error_handle_not_set(ring1, "ring1");
395 error_handle_not_set(ring2, "ring2");
396 error_handle_not_set(barriers, "barrierPhases");
397 error_handle_not_set(coordinates, "barrier2Phases or coordinatePhases");
398
399 //print to check
400#ifdef DEBUG_NEMA
401 std::cout << "JunctionID = " << myID << std::endl;
402 std::cout << "All parameters after calling constructor are: " << std::endl;
403 std::cout << "myDetectorLength = " << myDetectorLength << std::endl;
404 std::cout << "cycleLength = " << STEPS2TIME(myCycleLength) << std::endl;
405 std::cout << "ring1 = " << ring1 << std::endl;
406 std::cout << "ring2 = " << ring2 << std::endl;
407 std::cout << "barriers = " << barriers << std::endl;
408 std::cout << "coordinates = " << coordinates << std::endl;
409 std::cout << "offset = " << offset << std::endl;
410 std::cout << "cycleSecond = " << getTimeInCycle() << std::endl;
411 std::cout << "whetherOutputState = " << whetherOutputState << std::endl;
412 std::cout << "myShowDetectors = " << myShowDetectors << std::endl;
413 std::cout << "coordinateMode = " << coordinateMode << std::endl;
414 std::cout << "fixForceOff = " << fixForceOff << std::endl;
415 std::cout << "You reach the end of constructor" << std::endl;
416 std::cout << "****************************************\n";
417#endif
418 // Construct the NEMA specific timing data types and initial phases
419 constructTimingAndPhaseDefs(barriers, coordinates, ring1, ring2);
420
421 //init the traffic light
423 assert(myLanes.size() > 0);
424 //iterate through the lanes and build one E2 detector for each lane associated with the traffic light control junction
425 for (const LaneVector& lanes : myLanes) {
426 for (MSLane* const lane : lanes) {
427 //decide the detector length
428 double detector_length = 0;
429 if (isLeftTurnLane(lane)) {
430 detector_length = myDetectorLengthLeftTurnLane;
431 } else {
432 detector_length = myDetectorLength;
433 }
434 if (noVehicles(lane->getPermissions())) {
435 // do not build detectors on green verges or sidewalks
436 continue;
437 }
438 // Build detector and register them in the detector control
439 if (myLaneDetectorMap.find(lane) == myLaneDetectorMap.end()) {
440 MSE2Collector* det = nullptr;
441 const std::string customID = getParameter(lane->getID());
442 if (customID != "") {
444 if (det == nullptr) {
445 throw ProcessError("Unknown laneAreaDetector '" + customID + "' given as custom detector for NEMA tlLogic '" + getID() + "', program '" + getProgramID() + ".");
446 }
447 //set the detector to be visible in gui
449 } else {
450 int phaseNumber = 0;
451 if (myLanePhaseMap.find(lane->getID()) != myLanePhaseMap.end()) {
452 phaseNumber = myLanePhaseMap.find(lane->getID())->second;
453 }
454 int index = lane->getIndex();
455 std::string id = myID + "_" + myProgramID + "_D" + toString(phaseNumber) + "." + toString(index);
456 while (MSNet::getInstance()->getDetectorControl().getTypedDetectors(SUMO_TAG_LANE_AREA_DETECTOR).get(id) != nullptr) {
457 index++;
458 id = myID + "_" + myProgramID + "_D" + toString(phaseNumber) + "." + toString(index);
459 }
460 //createE2Detector() method will lead to bad detector showing in sumo-gui
461 //so it is better to use build2Detector() rather than createE2Detector()
462 nb.buildE2Detector(id, //detectorID
463 lane, //lane to build this detector
464 INVALID_POSITION, // set the detector location by end point and length, so this one is set to invalue value so this parameter can be passed
465 lane->getLength(), // set the end position of the detector at the end of the lane, which is right at the position of stop bar of a junction
466 detector_length, //detector length
467 myFile, // detector information output file
468 myFreq, // detector reading interval
469 0, // time-based threshold that describes how much time has to pass until a vehicle is considered as halting
470 0, // speed threshold as halting
471 0, // minimum dist to the next standing vehicle to make this vehicle count as a participant to the jam
472 "",
473 myVehicleTypes, //vehicle types to consider, if it is empty, meaning consider all types of vehicles
474 "", // nextEdges (no filtering by vehicle route)
475 (int)PersonMode::NONE, // detector vehicles, not persons
476 true, // whether to give some slack on positioning
477 myShowDetectors, // whether to show detectors in sumo-gui
478 nullptr, //traffic light that triggers aggregation when switching
479 nullptr); // outgoing lane that associated with the traffic light
480
481 //get the detector to be used in the lane detector map loading
483 }
484
485 //map the detector to lane and lane to detector
486 myLaneDetectorMap[lane] = det;
487 myDetectorLaneMap[det] = lane;
488 myDetectorInfoVector.push_back(DetectorInfo(det, (int)myPhases.size()));
489
490 }
491 }
492 }
493 for (auto item : phase2ControllerLanesMap) {
494 int NEMAPhaseIndex = item.first;
495 std::vector<std::string> laneIDs = item.second;
496 std::vector<MSE2Collector*> detectors;
497 MSE2Collector* detector = nullptr;
498 for (std::string laneID : laneIDs) {
499 MSLane* lane = MSLane::dictionary(laneID);
500 detector = myLaneDetectorMap[lane];
501 detectors.push_back(detector);
502 }
503 // have to try this on both rings, because of the case where both rings have the same phase
504 // See Basic NEMA test
505 for (int i = 0; i < 2; i++) {
506 if (vectorContainsPhase(rings[i], NEMAPhaseIndex)) {
507 getPhaseObj(NEMAPhaseIndex, i)->setDetectors(detectors);
508 }
509 }
510 }
511
512 //Do not delete. SUMO traffic logic check.
513 //SUMO check begin
514 const SVCPermissions motorized = ~(SVC_PEDESTRIAN | SVC_BICYCLE);
515 std::map<int, std::set<MSE2Collector*>> linkToDetectors;
516 std::set<int> actuatedLinks;
517
518 const int numLinks = (int)myLinks.size();
519 std::vector<bool> neverMajor(numLinks, true);
520 for (const MSPhaseDefinition* phase : myPhases) {
521 const std::string& state = phase->getState();
522 for (int i = 0; i < numLinks; i++) {
523 if (state[i] == LINKSTATE_TL_GREEN_MAJOR) {
524 neverMajor[i] = false;
525 }
526 }
527 }
528 std::vector<bool> oneLane(numLinks, false);
529 for (int i = 0; i < numLinks; i++) {
530 for (MSLane* lane : getLanesAt(i)) {
531 int numMotorized = 0;
532 for (MSLane* l : lane->getEdge().getLanes()) {
533 if ((l->getPermissions() & motorized) != 0) {
534 numMotorized++;
535 }
536 }
537 if (numMotorized == 1) {
538 oneLane[i] = true;
539 break;
540 }
541 }
542 }
543
544 for (const MSPhaseDefinition* phase : myPhases) {
545 const int phaseIndex = (int)myDetectorForPhase.size();
546 std::set<MSE2Collector*> detectors;
547 if (phase->isActuated()) {
548 const std::string& state = phase->getState();
549 std::set<int> greenLinks;
550 std::map<MSE2Collector*, std::set<int>> detectorLinks;
551
552 for (int i = 0; i < numLinks; i++) {
553 if (state[i] == LINKSTATE_TL_GREEN_MAJOR
554 || (state[i] == LINKSTATE_TL_GREEN_MINOR
555 && ((neverMajor[i] // check1a
556 && hasMajor(state, getLanesAt(i))) // check1b
557 || oneLane[i])) // check1c
558 ) {
559 greenLinks.insert(i);
560 actuatedLinks.insert(i);
561 }
562
563 for (MSLane* lane : getLanesAt(i)) {
564 if (myLaneDetectorMap.count(lane) != 0) {
565 detectorLinks[myLaneDetectorMap[lane]].insert(i);
566 }
567 }
568 }
569 for (auto& item : detectorLinks) {
570 MSE2Collector* det = item.first;
571 MSLane* detectorLane = myDetectorLaneMap[det];
572 bool usable = true;
573 // check 1
574 for (int j : item.second) {
575 if (greenLinks.count(j) == 0) {
576 usable = false;
577 }
578 }
579
580 //check 2
581 if (usable) {
582 for (MSLink* link : detectorLane->getLinkCont()) {
583 MSLane* next = link->getLane();
584 if (myLaneDetectorMap.count(next) != 0) {
585 MSE2Collector* nextDet = myLaneDetectorMap[next];
586 for (int j : detectorLinks[nextDet]) {
587 if (greenLinks.count(j) == 0) {
588 usable = false;
589 break;
590 }
591 }
592 }
593 }
594 }
595
596 if (usable) {
597 detectors.insert(item.first);
598 for (int j : item.second) {
599 linkToDetectors[j].insert(item.first);
600 }
601 }
602 }
603 if (detectors.size() == 0) {
604 WRITE_WARNINGF(TL("At NEMA tlLogic '%', actuated phase % has no controlling detector"), getID(), toString(phaseIndex));
605 }
606 }
607 std::vector<DetectorInfo*> detectorInfos;
608 myDetectorForPhase.push_back(detectorInfos);
609 for (MSE2Collector* det : detectors) {
610 for (DetectorInfo& detInfo : myDetectorInfoVector) {
611 if (detInfo.det == det) {
612 myDetectorForPhase.back().push_back(&detInfo);
613 detInfo.servedPhase[phaseIndex] = true;
614 }
615 }
616 }
617 }
618
619 for (int i : actuatedLinks) {
620 if (linkToDetectors[i].size() == 0 && myLinks[i].size() > 0
621 && (myLinks[i].front()->getLaneBefore()->getPermissions() & motorized) != 0) {
622 WRITE_WARNINGF(TL("At NEMA tlLogic '%, linkIndex % has no controlling detector"), getID(), toString(i));
623 }
624 }
625}
626
627void
629 // check that the cycle length for each ring adds up to the specified cycle length
630 for (int ringIndex = 0; ringIndex < 2; ringIndex++) {
631 SUMOTime cycleLengthCalculated = 0;
632 for (auto& p : getPhasesByRing(ringIndex)) {
633 cycleLengthCalculated += (p->maxDuration + p->yellow + p->red);
634 }
635 if (coordinateMode && (cycleLengthCalculated != myCycleLength)) {
636 int ringNumber = ringIndex + 1;
637 const std::string error = "At NEMA tlLogic '" + getID() + "', Ring " + toString(ringNumber) + " does not add to cycle length.";
638 if (ignoreErrors) {
639 WRITE_WARNING(error);
640 } else {
641 throw ProcessError(error);
642 }
643 }
644 }
645 // check that the barriers sum together
646 SUMOTime cycleLengths[2][2] = { {0, 0}, {0, 0} };
647 for (int ringIndex = 0; ringIndex < 2; ringIndex++) {
648 // TS2 Force Offs don't go in order, so using a different method to check cycle time
649 for (const auto p : getPhasesByRing(ringIndex)) {
650 cycleLengths[ringIndex][p->barrierNum] += p->maxDuration + p->yellow + p->red;
651 }
652 }
653 // Write warnings if the barriers do not sum
654 for (int barrierNum = 0; barrierNum < 2; barrierNum++) {
655 if (cycleLengths[0][barrierNum] != cycleLengths[1][barrierNum]) {
656 const std::string error = "At NEMA tlLogic '" + getID() + "', the phases before barrier " + toString(barrierNum + 1) + " from both rings do not add up. (ring1="
657 + toString(STEPS2TIME(cycleLengths[0][barrierNum])) + ", ring2=" + toString(STEPS2TIME(cycleLengths[1][barrierNum])) + ")";
659 throw ProcessError(error);
660 } else {
661 WRITE_WARNING(error);
662 }
663 }
664 }
665
666 // no offset for non coordinated
667 if (!coordinateMode && offset != 0) {
668 WRITE_WARNINGF(TL("NEMA tlLogic '%' is not coordinated but an offset was set."), getID());
669 }
670}
671
672void
673NEMALogic::setNewSplits(std::vector<double> newSplits) {
674 assert(newSplits.size() == 8);
675 for (auto& p : myPhaseObjs) {
676 if (newSplits[p->phaseName - 1] > 0) {
677 // set the phase's nextMaxDuration. This will be implemented when implementTraciChanges is called
678 p->nextMaxDuration = TIME2STEPS(newSplits[p->phaseName - 1]) - p->yellow - p->red;
679 }
680 }
681}
682
683
684void
685NEMALogic::setNewMaxGreens(std::vector<double> newMaxGreens) {
686 for (auto& p : myPhaseObjs) {
687 if (newMaxGreens[p->phaseName - 1] > 0) {
688 // set the phase's nextMaxDuration. This will be implemented when implementTraciChanges is called
689 p->nextMaxDuration = TIME2STEPS(newMaxGreens[p->phaseName - 1]);
690 }
691 }
692}
693
694
695void
696NEMALogic::setNewCycleLength(double newCycleLength) {
697 // set the controller's next cycle length. This will be implemented when implementTraciChanges is called
698 myNextCycleLength = TIME2STEPS(newCycleLength);
699}
700
701
702void
703NEMALogic::setNewOffset(double newOffset) {
704 // set the controller's offset. This will be implemented when implementTraciChanges is called
705 myNextOffset = TIME2STEPS(newOffset);
706}
707
708
709std::vector<int> NEMALogic::readParaFromString(std::string s) {
710 std::vector<int> output;
711 for (char c : s) {
712 if (c >= '0' && c <= '9') {
713 int temp = c - '0';
714 output.push_back(temp);
715 }
716 }
717 return output;
718}
719
722 return myPhase;
723}
724
725
726void
730
731
732int NEMALogic::measureRingDistance(int p1, int p2, int ringNum) {
733 int length = (int)rings[ringNum].size();
734 int d = 0;
735 bool found = false;
736 // Loop around the ring and keep track of the distance from p1 to p2
737 for (int i = 0; i < (length * 2); i++) {
738 if (rings[ringNum][i % length] > 0) {
739 if (found) {
740 d++;
741 if (rings[ringNum][i % length] == p2) {
742 break;
743 }
744 } else if (rings[ringNum][i % length] == p1) {
745 found = true;
746 }
747 }
748 }
749 assert(d > 0);
750 return d;
751}
752
753
756 SUMOTime c = a - b;
757 while (c >= b) {
758 c = c - b;
759 }
760 while (c < 0) {
761 c += b;
762 }
763 return c;
764}
765
766
767void
768NEMALogic::getLaneInfoFromNEMAState(std::string state, StringVector& laneIDs, IntVector& stateIndex) {
769 std::set<std::string> output;
770 for (int i = 0; i < (int)myLinks.size(); i++) {
771 if (myLinks[i].empty()) {
772 // unused index
773 continue;
774 }
775 char ch = state[i];
776 // if the ch is 'G', it means that the phase is controlling this lane
777 if (ch == 'G') {
778 stateIndex.push_back(i);
779 for (auto link : myLinks[i]) {
780 const MSLane* incoming = link->getLaneBefore();
781 if (incoming->isNormal()) {
782 laneIDs.push_back(incoming->getID());
783 }
784 }
785 }
786 }
787}
788
789bool NEMALogic::isLeftTurnLane(const MSLane* const lane) const {
790 const std::vector<MSLink*> links = lane->getLinkCont();
791 if (links.size() == 1 && links.front()->getDirection() == LinkDirection::LEFT) {
792 return true;
793 }
794 return false;
795}
796
797bool
798NEMALogic::hasMajor(const std::string& state, const LaneVector& lanes) const {
799 for (int i = 0; i < (int)state.size(); i++) {
800 if (state[i] == LINKSTATE_TL_GREEN_MAJOR) {
801 for (MSLane* cand : getLanesAt(i)) {
802 for (MSLane* lane : lanes) {
803 if (lane == cand) {
804 return true;
805 }
806 }
807 }
808 }
809 }
810 return false;
811}
812
813
814void
817 for (auto& item : myLaneDetectorMap) {
818 item.second->setVisible(true);
819 }
820}
821
822void
825 for (auto& item : myLaneDetectorMap) {
826 item.second->setVisible(false);
827 }
828}
829
830void
832 myShowDetectors = show;
833 for (auto& item : myLaneDetectorMap) {
834 item.second->setVisible(myShowDetectors);
835 }
836}
837
838int NEMALogic::string2int(std::string s) {
839 std::stringstream ss(s);
840 int ret = 0;
841 ss >> ret;
842 return ret;
843}
844
845
846const std::string
847NEMALogic::getParameter(const std::string& key, const std::string defaultValue) const {
848 if (StringUtils::startsWith(key, "NEMA.")) {
849 if (key == "NEMA.phaseCall") {
850 int activeCalls[8] = { 0 };
851 for (const auto p : myPhaseObjs) {
852 // This handles the case when the controller has multiple of the same phase call
853 if (!activeCalls[p->phaseName - 1]) {
854 activeCalls[p->phaseName - 1] = 1 * p->lastDetectActive;
855 }
856 }
857 std::string outStr = "";
858 for (int i = 0; i < 8; i++) {
859 outStr += std::to_string(activeCalls[i]);
860 if (i < 7) {
861 outStr += ",";
862 }
863 }
864 return outStr;
865 } else {
866 throw InvalidArgument("Unsupported parameter '" + key + "' for NEMA controller '" + getID() + "'");
867 }
868 } else {
869 return Parameterised::getParameter(key, defaultValue);
870 }
871}
872
873
874void
875NEMALogic::setParameter(const std::string& key, const std::string& value) {
876 queuedTraciChanges = true;
877 if (StringUtils::startsWith(key, "NEMA.")) {
878 if (key == "NEMA.splits" || key == "NEMA.maxGreens") {
879 //splits="2.0 3.0 4.0 5.0 2.0 3.0 4.0 5.0"
880 const std::vector<std::string>& tmp = StringTokenizer(value).getVector();
881 if (tmp.size() != 8) {
882 queuedTraciChanges = false;
883 throw InvalidArgument("Parameter '" + key + "' for NEMA controller '" + getID() + "' requires 8 space or comma separated values");
884 }
885 std::vector<double> timing;
886 for (const std::string& s : tmp) {
887 timing.push_back(StringUtils::toDouble(s));
888 }
889 if (key == "NEMA.maxGreens") {
890 setNewMaxGreens(timing);
891 } else {
892 setNewSplits(timing);
893 }
894 } else if (key == "NEMA.cycleLength") {
896 } else if (key == "NEMA.offset") {
898 } else {
899 queuedTraciChanges = false;
900 throw InvalidArgument("Unsupported parameter '" + key + "' for NEMA controller '" + getID() + "'");
901 }
902 }
903 Parameterised::setParameter(key, value);
904}
905
906void
907NEMALogic::error_handle_not_set(std::string param_variable, std::string param_name) {
908 if (param_variable == "") {
909 throw InvalidArgument("Please set " + param_name + " for NEMA tlLogic '" + getID() + "'");
910 }
911}
912
913void
915 SUMOTime zeroTime[2] = { TIME2STEPS(0), TIME2STEPS(0) };
916 for (int i = 0; i < 2; i++) {
917 SUMOTime runningTime = 0;
918 // loop through the phases for ring 0 and then 1
919 for (auto& p : getPhasesByRing(i)) {
920 runningTime += p->maxDuration + p->getTransitionTimeStateless();
921 // in 170, the cycle "starts" when the coordinated phase goes to yellow.
922 // See https://ops.fhwa.dot.gov/publications/fhwahop08024/chapter6.html
923 if (p->coordinatePhase) {
924 zeroTime[i] = runningTime;
925 }
926 p->forceOffTime = runningTime - p->getTransitionTimeStateless();
927 p->greatestStartTime = p->forceOffTime - p->minDuration;
928 }
929 }
930 // find the minimum offset time and then subtract from everything, modecycling where negative
931 // This sets the 0 cycle time as start of yellow on earliest ending coordinated phase
932 SUMOTime minCoordYellow = MIN2(zeroTime[0], zeroTime[1]);
933 for (auto& p : myPhaseObjs) {
934 p->forceOffTime = ModeCycle(p->forceOffTime - minCoordYellow, myCycleLength);
935 p->greatestStartTime = ModeCycle(p->greatestStartTime - minCoordYellow, myCycleLength);
936 }
937
938#ifdef DEBUG_NEMA
939 std::ios_base::fmtflags oldflags = std::cout.flags();
940 std::streamsize oldprecision = std::cout.precision();
941 for (int i = 0; i < 2; i++) {
942 std::cout << "Ring" << i + 1 << " force offs: \t";
943 for (auto& p : rings[i]) {
944 if (p > 0) {
945 PhasePtr pObj = getPhaseObj(p, i);
946 std::cout << std::fixed << std::setprecision(2) << STEPS2TIME(pObj->forceOffTime) << "\t";
947 } else {
948 std::cout << std::to_string(0) << "\t";
949 }
950 }
951 std::cout << std::endl;
952 }
953 std::cout.flags(oldflags);
954 std::cout.precision(oldprecision);
955#endif
956}
957
958void
960 // TS2 "0" cycle time is the start of the "first" coordinated phases.
961 // We can find this "0" point by first constructing the forceOffs in sequential order via the 170 method
963
964 // Switch the Force Off Times to align with TS2 Cycle, which is the *start* of the earliest coordinated phase
965 // The coordinate phases will always be the defaultBarrierPhases[i][0]
968 };
969 // When a coordinated phase is followed by a lagging phase, the coordinated phases do not end together at the 170 "0",
970 // so one of them may start before it. Wrap the starts into the cycle to find the one that comes first.
971 // Without a lagging phase the wrap is a no-op as long as the barriers line up; the condition leaves timings that do not
972 // fit the cycle (e.g. after NEMA.maxGreens via TraCI) with the unwrapped starts, which they rely on
973 if (!coordinatePhaseObjs[0]->isAtBarrier || !coordinatePhaseObjs[1]->isAtBarrier) {
974 coordStart[0] = ModeCycle(coordStart[0], myCycleLength);
975 coordStart[1] = ModeCycle(coordStart[1], myCycleLength);
976 }
977 SUMOTime minCoordTime = MIN2(coordStart[0], coordStart[1]);
978
979 // loop through all the phases and subtract this minCoordTime to move the 0 point to the start of the first coordinated phase
980 for (auto& p : myPhaseObjs) {
981 if ((p->forceOffTime - minCoordTime) >= 0) {
982 p->forceOffTime -= (minCoordTime);
983 } else {
984 p->forceOffTime = (myCycleLength + (p->forceOffTime - (minCoordTime)));
985 }
986 p->greatestStartTime = ModeCycle(p->greatestStartTime - minCoordTime, myCycleLength);
987 }
988}
989
990void
992 // get the time in the cycle
994 NEMAPhase* activePhases[2];
995 for (int i = 0; i < 2; i++) {
996 std::vector<NEMAPhase*> ringCopy = getPhasesByRing(i);
997 // sort by the minimum start time in the cycle.
998 std::sort(ringCopy.begin(), ringCopy.end(),
999 [](NEMAPhase * p, NEMAPhase * p1) {
1000 return p->greatestStartTime <= p1->greatestStartTime;
1001 }
1002 );
1003 bool found = false;
1004 // loop through the sorted phases by time and try to find the phase that should be active given the time in the cycle
1005 for (auto& p : ringCopy) {
1006 // This handles the wrap around. Checks if the prior phases start time should have already happened.
1007 // If it should have happened and it's not to the start time of me yet, start in my phase ( will have to be in my phase longer than max time likely )
1008 SUMOTime syntheticPriorStart = p->getSequentialPriorPhase()->greatestStartTime < p->greatestStartTime ?
1010 if (cycleTime <= ModeCycle(p->greatestStartTime, myCycleLength) && cycleTime > ModeCycle(syntheticPriorStart, myCycleLength)) {
1011 found = true;
1012 activePhases[i] = p;
1013 break;
1014 }
1015 }
1016 if (!found) {
1017#ifdef DEBUG_NEMA
1018 const std::string error = "I can't find the correct phase for NEMA tlLogic '" + getID() + "' Ring " + toString(i) + " to start in.";
1019 WRITE_WARNING(error);
1020 WRITE_WARNING(TL("I am starting in the coordinated phases"));
1021#endif
1022 activePhases[0] = defaultBarrierPhases[0][0];
1023 activePhases[1] = defaultBarrierPhases[1][0];
1024 }
1025 }
1026
1027 // ensure that the two found phases are on the same side of the barrier. If they aren't, just override with the default barrier phases
1028 if (activePhases[0]->barrierNum != activePhases[1]->barrierNum) {
1029 // give preference to whatever is on the coordinate side of the barrier, one must be if they aren't equal to each other
1030 activePhases[0] = activePhases[0]->barrierNum == 0 ? activePhases[0] : defaultBarrierPhases[0][0];
1031 activePhases[1] = activePhases[1]->barrierNum == 0 ? activePhases[1] : defaultBarrierPhases[1][0];
1032 }
1033
1034 // force enter the phases and update their expected duration to last until the forceOff
1035 activePhases[0]->forceEnter(this);
1036 activePhases[1]->forceEnter(this);
1037}
1038
1039void
1041 // Modifications where made to 170 algorithm so that it works with both.
1043}
1044
1046NEMALogic::parseControllerType(std::string inputType) {
1047 std::string cleanString;
1048 for (const char& c : inputType) {
1049 if (isalpha(c) || isdigit(c)) {
1050 cleanString += (char)::tolower(c);
1051 }
1052 }
1053 if (cleanString == "type170") {
1054 return Type170;
1055 } else if (cleanString == "ts2") {
1056 return TS2;
1057 } else {
1058 throw InvalidArgument("Please set controllerType for NEMA tlLogic " + myID + " to either Type170 or TS2");
1059 }
1060}
1061
1062std::vector<NEMAPhase*>
1064 std::vector<NEMAPhase*> phases;
1065 for (auto& p : myPhaseObjs) {
1066 if (p->ringNum == ringNum) {
1067 phases.push_back(p);
1068 }
1069 }
1070 return phases;
1071}
1072
1073void
1077
1078std::map<std::string, double>
1080 std::map<std::string, double> result;
1081 for (auto item : myDetectorLaneMap) {
1082 result[item.first->getID()] = item.first->getCurrentVehicleNumber();
1083 }
1084 return result;
1085}
1086
1089 // return a pointer to the other active phase
1090 return myActivePhaseObjs[!p->ringNum];
1091}
1092
1093NEMAPhase*
1094NEMALogic::getPhaseObj(int phaseNum, int ringNum) {
1095 // This satisfies the case where there is a "duplicate" phase on both ring
1096 std::vector<PhasePtr> iterRing = ringNum >= 0 ? getPhasesByRing(ringNum) : myPhaseObjs;
1097 for (auto& p : iterRing) {
1098 if (p->phaseName == phaseNum) {
1099 return p;
1100 }
1101 }
1102 // the phase must always be found
1103 throw ProcessError("At traffic signal '" + myID + "' program '" + myProgramID + "' phase '" + toString(phaseNum) + "' not found in ring '" + toString(ringNum) + "'.");
1104}
1105
1106bool
1110
1113 NEMAPhase* p = t->getFromPhase();
1114 // if the current phase is not ready to switch or a barrier cross is desired by the other transition
1115 // and t fromPhase is not ready to switch, the default transition is back to myself
1116 // a coordinated phase holding through its unserved lagging phase's split is not pulled across the barrier early either
1117 if (!p->readyToSwitch ||
1119 p->holdsForLag(this)) {
1120 return p->getTransition(p->phaseName);
1121 }
1122 // otherwise the default transition is to the default phase on whatever barrier ot wants to transition to
1124 // with a lagging phase, a coordinated or lagging phase is pulled across the barrier only if the other side fits for its own
1125 // yellow and red too (the other ring's fit test does not cover them), and never after the other side's force off
1126 if (target->barrierNum != p->barrierNum && hasLaggingPhase() && (p->coordinatePhase || p->lagWindowLeft(this) >= 0)
1127 && !p->crossFits(this, target)) {
1128 return p->getTransition(p->phaseName);
1129 }
1130 return p->getTransition(target->phaseName);
1131}
1132
1133void
1135 std::vector<std::vector<PhaseTransitionLogic* >> potentialPhases;
1136
1137 // Get a vector of each phases' potential transitions
1138 for (const auto& p : myActivePhaseObjs) {
1139 potentialPhases.push_back(p->trySwitch(this));
1140 }
1141
1142 // Loop through all combination of transitions, keeping only the valid ones and filling in the gaps where necessary
1143 for (const auto& r1_t : potentialPhases[0]) {
1144 for (const auto& r2_t : potentialPhases[1]) {
1145 // if both transitions go to the same barrier then we are good
1146 if (r1_t->getToPhase()->barrierNum == r2_t->getToPhase()->barrierNum) {
1147 transitions.push_back({ r1_t, r2_t, (float)(r1_t->getDistance(r2_t) + r2_t->getDistance(r1_t)) / 2 });
1148 } else {
1149 // If the rings are different, add a choice where one of them is the default choice for whatever ring it is
1150 // create two choices, one for each of the phase as they are on different rings
1151 if (r1_t->getFromPhase()->readyToSwitch) {
1152 // get the r2 default
1153 PhaseTransitionLogic* r2_t_temp = getDefaultTransition(r2_t, r1_t);
1154 // only add it if it does not cross a barrier!
1155 if (r2_t_temp->getToPhase()->barrierNum == r1_t->getToPhase()->barrierNum) {
1156 transitions.push_back({ r1_t, r2_t_temp, (float)(r2_t_temp->getDistance(r1_t) + r1_t->getDistance(r2_t_temp)) / 2 });
1157 }
1158 }
1159 if (r2_t->getFromPhase()->readyToSwitch) {
1160 // R1 default
1161 PhaseTransitionLogic* r1_t_temp = getDefaultTransition(r1_t, r2_t);
1162 // only add it if it does not cross a barrier!
1163 if (r1_t_temp->getToPhase()->barrierNum == r2_t->getToPhase()->barrierNum) {
1164 transitions.push_back({ r1_t_temp, r2_t, (float)(r2_t->getDistance(r1_t_temp) + r1_t_temp->getDistance(r2_t)) / 2 });
1165 }
1166 }
1167 // If the distances are <= 1, this means that this is the shortest transition possible
1168 // and we can return early without considering any other options
1169 if (!transitions.empty()) {
1170 if (transitions.back().distance < 1) {
1171 return;
1172 }
1173 }
1174 }
1175 }
1176 }
1177}
1178
1179
1180std::string
1182 // FIX with plan to support #10742
1183 std::string out(myPhaseStrLen, 'r');
1184 for (int i = 0; i < myPhaseStrLen; i++) {
1185 bool controlled = false;
1186 std::string phaseChars = "";
1187 for (auto& p : myActivePhaseObjs) {
1188 phaseChars += p->getNEMAChar(i);
1189 if (p->controlledIndex(i)) {
1190 out[i] = p->getNEMAChar(i);
1191 controlled = true;
1192 }
1193 }
1194 // if the index wasn't a controlled one, the prior priority order still stands
1195 if (!controlled) {
1196 for (auto priority_char : lightHeadPriority) {
1197 if (std::count(phaseChars.begin(), phaseChars.end(), priority_char)) {
1198 out[i] = priority_char;
1199 break;
1200 }
1201 }
1202 }
1203 }
1204 return out;
1205}
1206
1207
1210#ifdef DEBUG_NEMA_SWITCH
1211 std::cout << SIMTIME << " trySwitch tls=" << getID() << "\n";
1212#endif
1213 PhaseTransitionLogic* nextPhases[2] = { nullptr, nullptr };
1214
1215 // update the internal time. This is a must. Could have just used a reference to the time
1217
1218 // Check the Detectors
1219 for (auto& p : myPhaseObjs) {
1220 p->checkMyDetectors();
1221 }
1222
1223 // Update the timing parameters
1224 for (const auto& p : myActivePhaseObjs) {
1225 p->update(this);
1226 }
1227
1228 // Calculate the Next Phases, but only if atleast one of them is ready to transition
1229 if (myActivePhaseObjs[0]->readyToSwitch || myActivePhaseObjs[1]->readyToSwitch) {
1230 TransitionPairs transitions;
1231 // set the next phases by reference
1232 getNextPhases(transitions);
1233
1234 // Sort the next phases by distance and select the closest.
1235 // TODO: Is there a way to avoid this sort? The transitions are already sorted by distance prior
1236 // to picking the valid ones
1237 if (transitions.size() > 1) {
1238 std::sort(transitions.begin(), transitions.end(),
1239 [](const transitionInfo & i, const transitionInfo & j) {
1240 return i.distance < j.distance;
1241 });
1242 }
1243
1244 // Set the Next Phases = to the transition with least combined distance
1245 nextPhases[0] = transitions.front().p1;
1246 nextPhases[1] = transitions.front().p2;
1247
1248 // Try the exit logic. This doesn't necessarily mean that the phase will exit,
1249 // as it could go into green rest or green transfer, but this is considered an "exit"
1250 for (const auto& p : myActivePhaseObjs) {
1251 if (p->readyToSwitch) {
1252 p->exit(this, nextPhases);
1253 }
1254 }
1255
1256 // This is the only time when something might have happened, so we update the phase strings here
1257 std::string newState = composeLightString();
1258 if (newState != myPhase.getState()) {
1259 myPhase.setState(newState);
1260 myPhase.setName(toString(myActivePhaseObjs[0]->phaseName) + "+" + toString(myActivePhaseObjs[1]->phaseName));
1261 // ensure that SwitchCommand::execute notices a change
1262 myStep = 1 - myStep;
1263
1264 }
1265 }
1266
1267 // clear the phases' detectors
1268 for (auto& p : myPhaseObjs) {
1269 p->clearMyDetectors();
1270 }
1271
1272
1273#ifdef FUZZ_TESTING
1274 // Basic Assertion to ensure that the Barrier is not crossed
1275 assert(myActivePhaseObjs[0]->barrierNum == myActivePhaseObjs[1]->barrierNum);
1276#endif
1277
1278 // return the simulation timestep, as this controller must be checked every simulation step
1279 return DELTA_T;
1280}
1281
1282
1283void
1285 // Implement Traci Updates on the start of ring1 coordinated phase (rising edge of it turning green)
1286 if (queuedTraciChanges) {
1287 for (auto& p : myPhaseObjs) {
1288 p->maxDuration = p->nextMaxDuration;
1289 }
1292 // now that we have set the cycle length, offset and max duration, we need to update force off times
1294 queuedTraciChanges = false;
1295 }
1296}
1297
1298
1299// ===========================================================================
1300// NEMAPhase Definitions
1301// ===========================================================================
1302NEMAPhase::NEMAPhase(int phaseName, bool isBarrier, bool isGreenRest, bool isCoordinated,
1303 bool minRecall, bool maxRecall, bool fixForceOff, int barrierNum, int ringNum,
1304 IntVector phaseStringInds,
1305 MSPhaseDefinition* phase) :
1306 phaseName(phaseName),
1307 isAtBarrier(isBarrier),
1308 isGreenRest(isGreenRest),
1309 barrierNum(barrierNum),
1310 coordinatePhase(isCoordinated),
1311 minRecall(minRecall),
1312 maxRecall(maxRecall),
1313 fixForceOff(fixForceOff),
1314 ringNum(ringNum),
1315 myCorePhase(phase),
1316 myPhaseStringInds(phaseStringInds) {
1317 // Public
1318 readyToSwitch = false;
1319 reservice = false;
1320 greenRestTimer = 0;
1321 forceOffTime = 0;
1322 lastDetectActive = false;
1323
1324 // Private
1325 myInstance = this;
1326 myLastPhaseInstance = nullptr;
1327 sequentialPriorPhase = nullptr;
1329 transitionActive = false;
1330 myReserviced = false;
1331
1332 // Timing Parameters
1334 myStartTime = TIME2STEPS(0.);
1336 myLastEnd = TIME2STEPS(0.);
1337
1338 // set the phase colors
1340}
1341
1343 // Delete the transitions from their alloc
1344 for (auto t : myTransitions) {
1345 delete t;
1346 }
1347}
1348
1349void
1350NEMAPhase::init(NEMALogic* controller, int crossPhaseTarget, int crossPhaseSource, bool latching) {
1351 // switch the durations from steps2time
1353
1354 for (auto p : controller->getPhasesByRing(ringNum)) {
1355 // construct transitions for all potential movements, including back to myself
1356 myTransitions.push_back(new PhaseTransitionLogic(this, p));
1357 myTransitions.back()->setDistance(controller->measureRingDistance(phaseName, p->phaseName, ringNum));
1358 }
1359
1360 // sort the transitions by distance for speed later. Using plain distance here
1361 std::sort(myTransitions.begin(), myTransitions.end(), [&](const PhaseTransitionLogic * i, const PhaseTransitionLogic * j) {
1362 return i->distance < j->distance;
1363 });
1364
1365 // create the phase detector info
1367 crossPhaseSource > 0 ? controller->getPhaseObj(crossPhaseSource) : nullptr,
1368 crossPhaseTarget > 0 ? controller->getPhaseObj(crossPhaseTarget) : nullptr
1369 );
1370}
1371
1372void
1374 // This could be extended in the future to allow for traci manipulation
1376 red = myCorePhase->red;
1382}
1383
1384
1385// TODO: this can be computed once.
1386char
1389 return myGreenString[i];
1390 } else if (myLightState <= LightState::Red) {
1391 return myRedString[i];
1392 } else {
1393 return myYellowString[i];
1394 }
1395}
1396
1397void
1400 myRedString = "";
1401 myYellowString = "";
1402 for (char ch : myGreenString) {
1403 myRedString += 'r';
1404 if (ch == 'G' || ch == 'g') {
1405 myYellowString += 'y';
1406 } else {
1407 myYellowString += ch;
1408 }
1409 }
1410}
1411
1412void
1415 // remove the active flag on the detector if the detector is not latching or if it is green
1418 }
1419}
1420
1421void
1423 // Check my Detectors, only necessary if it isn't currently marked as on
1425 // If I have a cross phase target and it is active and I am not, save my detector as not active
1426 if (myDetectorInfo.cpdTarget != nullptr) {
1430 return;
1431 }
1432 }
1433 }
1434 // If we make it to this point, check my detector like normal.
1435 for (auto& d : myDetectorInfo.detectors) {
1436 if (d->getCurrentVehicleNumber() > 0) {
1438 return;
1439 }
1440 }
1441 // If my detector is not active, check my cross phase
1442 if ((myDetectorInfo.cpdSource != nullptr) && (myLightState >= LightState::Green)) {
1444 for (auto& d : myDetectorInfo.cpdSource->getDetectors()) {
1445 if (d->getCurrentVehicleNumber() > 0) {
1447 return;
1448 }
1449 }
1450 }
1451 }
1452 }
1453}
1454
1455void
1456NEMAPhase::enter(NEMALogic* controller, NEMAPhase* lastPhase) {
1457#ifdef DEBUG_NEMA_SWITCH
1458 std::cout << SIMTIME << " enter tls=" << controller->getID() << " phase=" << phaseName << "\n";
1459#endif
1460
1461 // set the last phase instance to inactive
1462 lastPhase->cleanupExit();
1463
1464 // Enter the phase
1465 myStartTime = controller->getCurrentTime();
1467 myLastPhaseInstance = lastPhase;
1468 readyToSwitch = false;
1469
1470 // implement the new timing parameters on the first coordinated phase to appear
1471 if (phaseName == controller->coordinatePhaseObjs[ringNum]->phaseName) {
1472 controller->implementTraciChanges();
1473 }
1474
1475 // a coordinated phase with reservice that is entered from its lagging phase between its force off and its next start
1476 // is served again in this cycle: it times its minimum green only, so that a later call on the other side of the barrier
1477 // can still cross, and it is timed to its force off at its next start (see update)
1478 const SUMOTime cycle = controller->getCurrentCycleLength();
1479 myReserviced = reservice && lastPhase != this && lastPhase->barrierNum == barrierNum
1480 && controller->ModeCycle(controller->getTimeInCycle() - forceOffTime, cycle) < controller->ModeCycle(-maxDuration, cycle);
1481
1482 // Handle Green Rest Peculiarities
1483 if (!controller->coordinateMode && isGreenRest) {
1484 // If the controller is in free mode and the phase is a green rest phase, then it should enter as "green rest"
1486 // if the phase has "green rest" capabilities, set its timer to the dynamic maxGreen
1488 }
1489
1490 // clear the last transition decision
1491 lastTransitionDecision = nullptr;
1492
1493 // Calculate the Max Green Time & Expected Duration here:
1494 if (controller->coordinateMode) {
1495 if (myReserviced) {
1497 } else if (coordinatePhase) {
1498 myExpectedDuration = controller->ModeCycle(forceOffTime - controller->getTimeInCycle(), controller->getCurrentCycleLength());
1499 // with a lagging phase, the other ring may pull me across the barrier as soon as I am ready to switch: entered
1500 // shortly before my force off (e.g. back from a leading phase served late), I still time my minimum green
1501 if (controller->hasLaggingPhase()) {
1503 }
1504 } else {
1505 maxGreenDynamic = controller->ModeCycle(forceOffTime - controller->getTimeInCycle(), controller->getCurrentCycleLength());
1506 if (!fixForceOff) {
1508 }
1510 }
1511 } else {
1512 // in free mode, the current max green (which may have been changed via TraCI) applies (#18513)
1515 }
1516 // Implements the maxRecall functionality
1517 if (maxRecall && !coordinatePhase) {
1519 }
1520 // Set the controller's active phase
1521 controller->setActivePhase(this);
1522}
1523
1524void NEMAPhase::exit(NEMALogic* controller, PhaseTransitionLogic* nextPhases[2]) {
1525 if (nextPhases[ringNum]->getToPhase() != this) {
1526 // if the next phase is not me, then I need to go into a transition
1527 lastTransitionDecision = nextPhases[ringNum];
1529 // if I am in green, then I need to enter yellow
1530 enterYellow(controller);
1531 return;
1532 }
1533
1534 if (controller->getCurrentTime() - myLastEnd < (yellow + red)) {
1535 if (controller->getCurrentTime() - myLastEnd >= yellow) {
1536 // if I am in yellow, then I need to enter red
1538 }
1539 // I am currently in the Red state but haven't reached max
1540 return;
1541 }
1542
1543 handleRedXferOrNextPhase(controller, nextPhases);
1544 return;
1545 }
1546
1547 handleGreenRestOrTransfer(controller, nextPhases);
1548}
1549
1551 myLastEnd = controller->getCurrentTime();
1553 transitionActive = true;
1554}
1555
1557 PhasePtr otherPhase = controller->getOtherPhase(this);
1558 bool barrierCross = nextPhases[ringNum]->getToPhase()->barrierNum != barrierNum;
1559 bool barrierCrossButOkay = barrierCross && (
1560 nextPhases[ringNum]->getToPhase()->barrierNum == nextPhases[otherPhase->ringNum]->getToPhase()->barrierNum
1561 ) && otherPhase->okay2ForceSwitch(controller);
1562
1563 if (!barrierCross) {
1564 nextPhases[ringNum]->getToPhase()->enter(controller, this);
1565 return;
1566 }
1567
1568 if (barrierCrossButOkay) {
1569 // if the barrier is crossed, but the other phase is going to the same barrier, then I can enter red transfer
1570 // enter the next phase
1571 nextPhases[ringNum]->getToPhase()->enter(controller, this);
1572 // trigger the other phase to enter red transfer
1573 nextPhases[otherPhase->ringNum]->getToPhase()->enter(controller, this);
1574 return;
1575 }
1576
1578 readyToSwitch = true;
1579 transitionActive = false;
1580}
1581
1583 NEMAPhase* otherPhase = controller->getOtherPhase(this);
1584 readyToSwitch = false;
1585 bool isOtherPhaseReady = nextPhases[!ringNum]->getToPhase() == otherPhase && otherPhase->readyToSwitch;
1586 bool isOtherPhaseInGreenRest = otherPhase->greenRestTimer >= otherPhase->maxDuration && otherPhase->getCurrentState() == LightState::GreenRest;
1587
1588 // holding through the lagging phase's split is not resting: it ends at the barrier
1589 if ((isOtherPhaseReady || isOtherPhaseInGreenRest) && !holdsForLag(controller)) {
1591 myStartTime = controller->getCurrentTime() - minDuration;
1594 } else {
1596 if (isAtBarrier) {
1597 myExpectedDuration = (otherPhase->myExpectedDuration + otherPhase->myStartTime) - myStartTime;
1598 // a lagging phase that keeps its green must still be ready to go back to its coordinated phase in time for that
1599 // phase's next start, even if the other ring's phase was timed past it (e.g. a coordinated phase re-entered from
1600 // green rest early in a Type 170 cycle)
1601 const SUMOTime windowLeft = lagWindowLeft(controller);
1602 if (windowLeft > 0) {
1603 myExpectedDuration = MIN2(myExpectedDuration, controller->getCurrentTime() - myStartTime + windowLeft);
1604 }
1605 }
1606 }
1607}
1608
1612 // if in red xfer, I am ready to switch whenevery
1613 return TIME2STEPS(0);
1614 }
1615 if (!transitionActive) {
1616 // if a transition is not active, the transition is just yellow + red time
1618 }
1619 // if a transition is active, then return the time left in the transition
1620 return MAX2(TIME2STEPS(0), ((yellow + red) - (controller->getCurrentTime() - myLastEnd)));
1621}
1622
1626 // add the vehicle extension timer if the detector is active.
1627 // capped by the minimum and maximum duration
1628 return MIN2(MAX2(duration + vehExt, minDuration), maxGreenDynamic);
1629 }
1630 return myExpectedDuration;
1631}
1632
1633void
1635 // If I am in a transition, the rest of the update logic does not matter
1637 // return early
1638 readyToSwitch = true;
1639 return;
1640 }
1641
1642 // a reserviced coordinated phase that is still green at its next start is timed to its force off from there
1643 if (myReserviced && controller->ModeCycle(controller->getTimeInCycle() - (forceOffTime - maxDuration), controller->getCurrentCycleLength()) < DELTA_T) {
1644 enter(controller, this);
1645 }
1646
1647 // Continuation Logic
1648 SUMOTime duration = controller->getCurrentTime() - myStartTime;
1649 // Check the vehicle extension timer as long as not in green transfer and not a coordinated phase
1652 }
1653 // Special Logic for Green Rest, which behaves uniquely
1655 // check all other detectors and see if anything else is active. If so,
1656 // start the green rest timer countdown, which is == to the max duration of the phase
1657 bool vehicleActive = false;
1658 for (auto& p : controller->getPhaseObjs()) {
1659 if ((p->phaseName != phaseName)
1660 && (p->phaseName != controller->getOtherPhase(this)->phaseName)
1661 && p->callActive()) {
1663 vehicleActive = true;
1664 break;
1665 }
1666 }
1667 // catch the rising edge of the sidestreet detection and calculate the maximum timer
1668 if (vehicleActive && (greenRestTimer + DELTA_T >= maxDuration)) {
1670 }
1671
1672 // if there are no other vehicles slide the startTime along
1673 if (!vehicleActive) {
1675 if (duration >= minDuration) {
1676 myStartTime = controller->getCurrentTime() - minDuration;
1679 }
1680 }
1681
1682 // if the green rest timer is exhausted, set ready to switch
1683 if (greenRestTimer < DELTA_T) {
1684 readyToSwitch = true;
1685 // force the counterpart to be ready to switch too. This needs to be latching....
1686 NEMAPhase* otherPhase = controller->getOtherPhase(this);
1687 if (otherPhase->getCurrentState() > LightState::Green) {
1688 otherPhase->readyToSwitch = true;
1689 }
1690 }
1691
1692 // Special Behavior when the Green Rest Circles all the way around in coordinated mode
1693 // (not for a reserviced phase: this check holds from the cycle's zero up to my start, which in the Type 170 frame is
1694 // more than one step, and re-entering early would time me to my next force off. It is retimed above instead)
1695 if (coordinatePhase && !myReserviced) {
1696 // This means that we have green rested until I should "start" again. Just call my entry function again.
1697 if (controller->getTimeInCycle() <= ((forceOffTime - maxDuration) + DELTA_T / 2)) {
1698 enter(controller, this);
1699 }
1700 }
1701 }
1702 // Check to see if a switch is desired
1703 if (duration >= myExpectedDuration) {
1704 readyToSwitch = true;
1705 }
1706}
1707
1708bool
1710 if (!coordinatePhase || isAtBarrier) {
1711 return false;
1712 }
1713 for (auto& p : controller->getPhasesByRing(ringNum)) {
1714 if (p->isAtBarrier && p->barrierNum == barrierNum) {
1715 // the barrier is where the lagging phase would end its red. My green ends my own yellow + red before it
1716 SUMOTime barrierTime = p->forceOffTime + p->getTransitionTimeStateless() - getTransitionTimeStateless();
1717 SUMOTime timeTillBarrier = controller->ModeCycle(barrierTime - controller->getTimeInCycle(), controller->getCurrentCycleLength());
1718 // hold between my force off and the barrier
1719 return timeTillBarrier > 0 && timeTillBarrier <= controller->ModeCycle(barrierTime - forceOffTime, controller->getCurrentCycleLength());
1720 }
1721 }
1722 return false;
1723}
1724
1725bool
1727 const SUMOTime cycle = controller->getCurrentCycleLength();
1728 const SUMOTime timeTillForceOff = controller->ModeCycle(toPhase->forceOffTime - controller->getTimeInCycle(), cycle);
1729 const SUMOTime windowLeft = lagWindowLeft(controller);
1730 const bool inWindow = windowLeft >= 0 ? windowLeft > 0
1731 : timeTillForceOff <= controller->ModeCycle(toPhase->forceOffTime - forceOffTime, cycle);
1732 return inWindow && toPhase->minDuration + getTransitionTime(controller) <= timeTillForceOff;
1733}
1734
1737 if (!isAtBarrier || coordinatePhase) {
1738 return -1;
1739 }
1740 for (auto& p : controller->getPhasesByRing(ringNum)) {
1741 if (p->coordinatePhase && !p->isAtBarrier && p->barrierNum == barrierNum) {
1742 // from the coordinated phase's force off until my yellow and red would end at its next start
1743 const SUMOTime cycle = controller->getCurrentCycleLength();
1744 const SUMOTime sinceForceOff = controller->ModeCycle(controller->getTimeInCycle() - p->forceOffTime, cycle);
1745 const SUMOTime windowLength = controller->ModeCycle(-p->maxDuration - getTransitionTimeStateless(), cycle);
1746 return sinceForceOff < windowLength ? windowLength - sinceForceOff : 0;
1747 }
1748 }
1749 return -1;
1750}
1751
1754 for (auto t : myTransitions) {
1755 if (t->getToPhase()->phaseName == toPhase) {
1756 return t;
1757 }
1758 }
1759 // This point should never be reached
1760 assert(0);
1761 // To satisfy the compiler and return value from all control paths
1762 return myTransitions.front();
1763}
1764
1765std::vector<PhaseTransitionLogic*>
1767 // this function returns the preferred valid transition for the phase
1768 std::vector<PhaseTransitionLogic*> nextTransitions;
1769 if (readyToSwitch) {
1770 // only try to switch if I am ready to switch
1771 for (auto& t : myTransitions) {
1772 // for the transitions check if it is okay
1773 if (t->okay(controller)) {
1774 // if there was already a transition decision, it can be overriden but only if the new transition
1775 // is on the same side of a barrier
1776 if (lastTransitionDecision != nullptr) {
1777 if (t->getToPhase()->barrierNum == lastTransitionDecision->getToPhase()->barrierNum) {
1778 nextTransitions.push_back(t);
1779 break;
1780 }
1781 } else {
1782 nextTransitions.push_back(t);
1783 // break once there is a valid option (they have already been sorted)
1784 break;
1785 }
1786 }
1787 }
1788 }
1789 // Add in the last transition decision if it hasn't been added in yet
1790 if (lastTransitionDecision != nullptr) {
1791 bool found = false;
1792 bool sameBarrier = false;
1793 for (auto& t : nextTransitions) {
1794 if (t == lastTransitionDecision) {
1795 found = true;
1796 break;
1797 }
1798 if (t->getToPhase()->barrierNum == lastTransitionDecision->getToPhase()->barrierNum) {
1799 sameBarrier = true;
1800 break;
1801 }
1802 }
1803 // but only need to add it if it is not in the list AND if nothing in the list is the same barrier as it was.
1804 if (!found && !sameBarrier) {
1805 nextTransitions.push_back(lastTransitionDecision);
1806 }
1807 }
1808 // Add the transition back to myself, but only in the case when no others have been added
1809 if (nextTransitions.size() < 1) {
1810 nextTransitions.push_back(myTransitions.back());
1811 }
1812
1813 return nextTransitions;
1814}
1815
1816// ===========================================================================
1817// PhaseTransitionLogic Definitions
1818// ===========================================================================
1820 NEMAPhase* fromPhase, NEMAPhase* toPhase) :
1821 distance(0),
1822 fromPhase(fromPhase),
1823 toPhase(toPhase)
1824{}
1825
1826bool
1828 // Picking the correct transition logic to use
1829 // #TODO this could be a case of using function as variable and setting it at PhaseTransitionLogic
1830 // creation time
1831 if (fromPhase == toPhase) {
1832 // for green rest or green transfer, it cannot return to itself if a transition is active
1834 } else if (fromPhase->coordinatePhase) {
1835 // if the from phase is a coordinated phase i.e. {2, 6} in a standard setup
1836 return fromCoord(controller);
1837 } else if (fromPhase->isAtBarrier) {
1838 // if the phase is at a barrier i.e. {2, 6, 4, 8} in a standard setup
1839 return fromBarrier(controller);
1840 } else if (controller->coordinateMode) {
1841 // typical coordinate mode transition,
1842 return coordBase(controller);
1843 } else {
1844 // base transition logic
1845 return freeBase(controller);
1846 }
1847}
1848
1849bool
1851 // Simplest transition logic. Just check if a detector (or recall) is active on that phase and
1852 bool okay = false;
1853 // is a call active on the toPhase?
1854 if (toPhase->callActive()) {
1855 // would the transition be a barrier cross?
1857 PhasePtr otherPhase = controller->getOtherPhase(fromPhase);
1858 // If it is a barrier cross, then the other phase must also be ready to switch
1859 // or have a transition time that is lower than mine currently. DELTA_T is critical here
1860 if (otherPhase->readyToSwitch) {
1861 // #&& otherPhase->getTransitionTime(controller) <= fromPhase->getTransitionTime(controller)) {
1862 okay = true;
1863 }
1864 } else {
1865 okay = true;
1866 }
1867 }
1868 return okay;
1869}
1870
1871bool
1873 if (toPhase->coordinatePhase &&
1875 // transitions TO the coordinated phase may always happen, as long as the other phase is okay to switch too
1876 return true;
1877 }
1878 // first check if the free logic is upheld
1879 else if (freeBase(controller)) {
1880 // Then check if the "to phase" can fit, which means that there is enough time to fit the current transition + the minimum time of the next phase
1881 SUMOTime transitionTime = fromPhase->getTransitionTime(controller);
1882 SUMOTime timeTillForceOff = controller->ModeCycle(toPhase->forceOffTime - controller->getTimeInCycle(), controller->getCurrentCycleLength());
1883 if (toPhase->minDuration + transitionTime <= timeTillForceOff) {
1884 return true;
1885 }
1886 }
1887 return false;
1888}
1889
1890
1891bool
1893 if (freeBase(controller)) {
1895 // a lagging phase that gaps out does not go back to its coordinated phase while that one is past its force off
1896 // in this cycle (unless reservicePhases names it): entered there, the coordinated phase would keep its green until
1897 // its force off in the next cycle and lock out the other side of the barrier. The lagging phase keeps its green
1898 // instead, until the other side is called or its yellow and red end at the coordinated phase's next start. Only a
1899 // coordinated phase that is followed by a lagging phase matches, so lead-lead and free mode are not affected
1901 // once the window is over, it is the coordinated phase's time: go back even if the other side is called
1902 if (fromPhase->lagWindowLeft(controller) == 0) {
1903 return true;
1904 }
1905 // inside the window, only a coordinated phase with reservice is served again (if the other side is not called)
1906 if (!toPhase->reservice) {
1907 return false;
1908 }
1909 }
1910 // same barrier side so we are good.
1911 // Check if green transfer is active. If so, we need to make sure that there are no calls on the other side of the barrier
1912 // (in either ring for a reserviced coordinated phase: it would delay a side street call of the other ring too)
1914 const bool reservice = toPhase->coordinatePhase && !toPhase->isAtBarrier;
1915 for (auto& p : reservice ? controller->getPhaseObjs() : controller->getPhasesByRing(fromPhase->ringNum)) {
1916 if (p->barrierNum != fromPhase->barrierNum && p->callActive()) {
1917 return false;
1918 }
1919 }
1920 }
1921 return true;
1922 } else {
1923 // This is now a barrier cross and we need to make sure that the other phase is also ready to transition
1925 // a lagging phase crosses only inside its window, and only if the other side still fits before its force off
1926 // (the fit test coordBase applies to the other ring), so that a late call does not delay the coordinated
1927 // phase's next start
1928 if (fromPhase->lagWindowLeft(controller) >= 0) {
1929 return fromPhase->crossFits(controller, toPhase);
1930 }
1931 return true;
1932 }
1933 }
1934 }
1935 return false;
1936}
1937
1938
1939bool
1941 if (coordBase(controller)) {
1942 // A coordinated phase that is not at the barrier is followed by a lagging phase on its side of the barrier
1943 if (!fromPhase->isAtBarrier) {
1945 // moving on to the lagging phase is a same side transition, so there is no need to wait for the other ring.
1946 // The lagging phase runs only between the coordinated phase's force off and its own. coordBase's fit test wraps
1947 // around the cycle, so on its own it would also serve the lagging phase as a leading phase while the coordinated
1948 // phase is green before its force off, or after the lagging phase's force off (e.g. a coordinated phase entered
1949 // late at the start of the simulation), cutting into the other side of the barrier. Such a call waits for the
1950 // next cycle. A coordinated phase that is served again after its lagging phase does not yield to it a second time
1951 // in the same cycle either
1952 if (fromPhase->isReserviced()) {
1953 return false;
1954 }
1955 const SUMOTime cycle = controller->getCurrentCycleLength();
1956 return controller->ModeCycle(toPhase->forceOffTime - controller->getTimeInCycle(), cycle)
1957 <= controller->ModeCycle(toPhase->forceOffTime - fromPhase->forceOffTime, cycle);
1958 }
1959 // the lagging phase is not served, so the coordinated phase keeps its green until the barrier
1960 if (fromPhase->holdsForLag(controller)) {
1961 return false;
1962 }
1963 }
1964 // with a lagging phase, the coordinated phases do not end together. One at the barrier goes back to the leading phase on its
1965 // side only after its own force off, and only while the other side of the barrier is not called: otherwise the leading
1966 // phase would cut its coordinated green short (served while the other ring still holds for or serves its lagging phase)
1967 // or delay the other side
1969 const SUMOTime tillForceOff = controller->ModeCycle(fromPhase->forceOffTime - controller->getTimeInCycle(), controller->getCurrentCycleLength());
1970 if (tillForceOff > 0 && tillForceOff < fromPhase->maxDuration) {
1971 return false;
1972 }
1973 for (auto& p : controller->getPhaseObjs()) {
1974 if (p->barrierNum != fromPhase->barrierNum && p->callActive()) {
1975 return false;
1976 }
1977 }
1978 }
1979 // with a lagging phase, a coordinated phase crosses only while the other side's force off is still ahead in this cycle
1980 // and the other side fits: coordBase's fit test wraps around the cycle and would let a late call cross into the
1981 // coordinated phases' time
1982 if (fromPhase->barrierNum != toPhase->barrierNum && controller->hasLaggingPhase()
1983 && !fromPhase->crossFits(controller, toPhase)) {
1984 return false;
1985 }
1986 // Determine if the other phase is also ready to switch
1987 if (controller->getOtherPhase(fromPhase)->readyToSwitch) {
1988 // Dr. Wang had the Type-170 code setup in a way that it could transition whenever - meaning that it didn't matter if the prior phase could fit or not
1989 if (controller->isType170()) {
1990 return true;
1991 }
1992 // If the transition is already active, then report that the movement is possible
1994 return true;
1995 }
1996 // now determine if there my prior phase can fit or not. We already know that I can fit.
1997 NEMAPhase* priorPhase = toPhase->getSequentialPriorPhase();
1998 SUMOTime timeTillForceOff = controller->ModeCycle(priorPhase->forceOffTime - controller->getTimeInCycle(), controller->getCurrentCycleLength());
1999 SUMOTime transitionTime = fromPhase->getTransitionTime(controller);
2000 // if the time till the force off is less than the min duration ||
2001 // if it is greater than the cycle length minus the length of the coordinate phase (which the fromPhase automatically is)
2002 if ((priorPhase->minDuration + transitionTime) > timeTillForceOff || timeTillForceOff > (controller->getCurrentCycleLength() - fromPhase->minDuration)) {
2003 return true;
2004 }
2005 }
2006 }
2007 return false;
2008}
2009
2010int
2012 // Returns the other transitions distance in green transfer situations
2013 if ((toPhase == fromPhase) && (otherTrans->toPhase->barrierNum == toPhase->barrierNum)) {
2015 return otherTrans->distance;
2016 }
2017 }
2018 return distance;
2019}
long long int SUMOTime
Definition GUI.h:36
#define INVALID_POSITION
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
#define TL(string)
Definition MsgHandler.h:316
#define TLF(string,...)
Definition MsgHandler.h:318
std::vector< std::string > StringVector
Definition of a vector of strings.
Definition Option.h:42
std::vector< int > IntVector
Definition of a vector of ints.
Definition Option.h:37
SUMOTime DELTA_T
Definition SUMOTime.cpp:39
#define STEPS2TIME(x)
Definition SUMOTime.h:58
#define SIMSTEP
Definition SUMOTime.h:69
constexpr SUMOTime TIME2STEPS(double x)
Definition SUMOTime.h:60
#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
@ SVC_BICYCLE
vehicle is a bicycle
@ SVC_PEDESTRIAN
pedestrian
@ SUMO_TAG_LANE_AREA_DETECTOR
alternative tag for e2 detector
@ LEFT
The link is a (hard) left direction.
@ LINKSTATE_TL_GREEN_MAJOR
The link has green light, may pass.
@ LINKSTATE_TL_GREEN_MINOR
The link has green light, has to brake.
@ SUMO_ATTR_CYCLETIME
T MIN2(T a, T b)
Definition StdDefs.h:80
T MAX2(T a, T b)
Definition StdDefs.h:86
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.
const NamedObjectCont< MSDetectorFileOutput * > & getTypedDetectors(SumoXMLTag type) const
Returns the list of detectors of the given type.
An areal detector corresponding to a sequence of consecutive lanes.
virtual void setVisible(bool)
Representation of a lane in the micro simulation.
Definition MSLane.h:84
bool isNormal() const
Definition MSLane.cpp:2675
static bool dictionary(const std::string &id, MSLane *lane)
Static (sic!) container methods {.
Definition MSLane.cpp:2538
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
The definition of a single phase of a tls logic.
SUMOTime maxDuration
The maximum duration of the phase.
SUMOTime vehext
for NEMA phase
SUMOTime minDuration
The minimum duration of the phase.
SUMOTime yellow
for NEMA phase
SUMOTime red
for NEMA phase
SUMOTime myLastSwitch
Stores the timestep of the last on-switched of the phase.
const std::string & getState() const
Returns the state within this phase.
void setState(const std::string &_state)
void setName(const std::string &_name)
A fixed traffic light logic.
Phases myPhases
The list of phases this logic uses.
A class that stores and controls tls and switching of their programs.
SUMOTime myOffset
the offset parameter of the current program
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 myDefaultCycleTime
The cycle time (without changes)
const std::string & getProgramID() const
Returns this tl-logic's id.
const std::string myProgramID
The id of the logic.
LaneVectorVector myLanes
The list of LaneVectors; each vector contains the incoming lanes that belong to the same link index.
virtual void activateProgram()
called when switching programs
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.
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.
A NEMA (adaptive) traffic light logic based on E2Detector.
SUMOTime cycleRefPoint
std::map< std::string, double > getDetectorStates() const override
retrieve all detectors used by this program
int measureRingDistance(int p1, int p2, int ringNum)
return the ring distance between two phases
SUMOTime getTimeInCycle() const
override Function to Simplify Accessing Offset Cycle Time
void getLaneInfoFromNEMAState(std::string state, StringVector &laneIDs, IntVector &stateIndex)
returns the IDs of the phase's controlled lanes. Found by looking for the "G" in the light state stri...
void getNextPhases(TransitionPairs &transitions)
extends the transitions vector with valid Transitions given the current traffic light state
void setNewMaxGreens(std::vector< double > newMaxGreens)
Set the max green of all phases.
void calculateForceOffs170()
calculate the forceOffs for a Type 170 style offset From https://ops.fhwa.dot.gov/publications/fhwaho...
void calculateInitialPhases()
directs the controller to the correct calculate phases function
const std::string lightHeadPriority
constant for storing the priority order for light heads. Iterates left to right and stops when finds ...
const std::string getParameter(const std::string &key, const std::string defaultValue="") const override
try to get the value of the given parameter. Parameters prefixed with 'NEMA.' control functionality
std::vector< DetectorInfo > myDetectorInfoVector
storing the detector info in a vector
SUMOTime myNextCycleLength
the next cycle length (set by traci)
void init(NLDetectorBuilder &nb) override
Initialises the tls with information about incoming lanes.
void resetLastSwitch(SUMOTime t) override
void calculateInitialPhasesTS2()
calculate the initial phases for the TS2 style controller to start in
std::string myVehicleTypes
Whether detector output separates by vType.
std::string myFile
The output file for generated detectors.
double myDetectorLength
store the generated detector length
SUMOTime getCurrentCycleLength()
Get the current cycle length.
std::vector< std::vector< int > > rings
SUMOTime myFreq
The frequency for aggregating detector output.
DetectorLaneMap myDetectorLaneMap
A map from detectors to lanes.
SUMOTime trySwitch() override
overrides the MSSimpleTrafficLightLogic trySwitch method
bool isType170(void) const
checks if the controller is of type170
void validate_timing()
validates the NEMA timing. Writes warnings if ignoreError set to true else throws ProcessError
bool queuedTraciChanges
flag to keep track of whether a timing change has been requested via traci
NEMALogic(MSTLLogicControl &tlcontrol, const std::string &id, const std::string &programID, const SUMOTime offset, const MSSimpleTrafficLightLogic::Phases &phases, int step, SUMOTime delay, const std::map< std::string, std::string > &parameter, const std::string &basePath)
Constructor.
void activateProgram() override
called when switching programs
void setShowDetectors(bool show)
bool whetherOutputState
void constructTimingAndPhaseDefs(std::string &barriers, std::string &coordinates, std::string &ring1, std::string &ring2)
constructs phase using the configuration file
int myPhaseStrLen
stores the length of phase string for the controller "GGrrrrs" = 6. Must be the same length for all p...
int myNumberRings
stores controllers # of rings
PhasePtr defaultBarrierPhases[2][2]
an array to store the phases located at a barrier for each ring
bool hasLaggingPhase() const
whether the controller is in coordinated mode and a coordinated phase is followed by a lagging phase
SUMOTime getCurrentTime(void) const
Wrapper Function to Simplify Accessing Time.
std::vector< PhasePtr > myPhaseObjs
a vector that stores a pointer to the instantiated NEMAPhase objects
void setParameter(const std::string &key, const std::string &value) override
try to set the given parameter. Parameters prefixed with 'NEMA.' control functionality
void error_handle_not_set(std::string param_variable, std::string param_name)
throw an InvalidArgument error if the param_name is not set
void implementTraciChanges(void)
implement any pending traci changes This function is called once per cycle
PhasePtr getPhaseObj(int phaseNum, int ringNum=-1)
get the phase object matching the phaseNum If ringNum is passed, it will only search for the phase in...
void setNewOffset(double newOffset)
Set the new offset for the controller.
std::vector< PhasePtr > getPhasesByRing(int ringNum)
get all phases for a given ring
controllerType parseControllerType(std::string inputType)
parse the controllerType from the tllogic description
SUMOTime myCycleLength
the coordinated cycle length
SUMOTime offset
the controller's offset
void calculateInitialPhases170()
calculate the initial phases for Type 170
SUMOTime myNextOffset
the next offset to implement
SUMOTime ModeCycle(SUMOTime a, SUMOTime b)
Calculates the modulus a / b, normally used to calculate the cycle time between two times....
void calculateForceOffs()
directs the code to the correct force off function accorifing to its cabinet type
std::vector< int > readParaFromString(std::string s)
converts a comma separated string into a integer vector "1,2,3,4" -> {1,2,3,4}
std::vector< PhasePtr > getPhaseObjs(void)
get a vector of all phase objects
bool myShowDetectors
Whether the detectors shall be shown in the GUI.
detectorMap myDetectorForPhase
int string2int(std::string s)
convert a string to an integer
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
bool coordinateMode
whether the controller is in coordinated mode or not
PhasePtr myActivePhaseObjs[2]
variable to store the active phases
void deactivateProgram() override
void setCurrentTime(void)
Set the simTime.
~NEMALogic()
Destructor.
MSPhaseDefinition myPhase
virtual phase that holds the current state
PhaseTransitionLogic * getDefaultTransition(PhaseTransitionLogic *t, PhaseTransitionLogic *ot)
return the default transition for t give its and the ot's state
bool vectorContainsPhase(std::vector< int > v, int phaseNum)
check if a vector contains an element
void calculateForceOffsTS2()
calculate the forceOffs for a TS2 style offset From https://ops.fhwa.dot.gov/publications/fhwahop0802...
PhasePtr getOtherPhase(PhasePtr p)
Get the opposite active phase.
double myDetectorLengthLeftTurnLane
store the left turn lane detestor length
controllerType myControllerType
bool isLeftTurnLane(const MSLane *const lane) const
decide whether the detector is for left turn lane if it is, use the detector length for left turn lan...
LaneDetectorMap myLaneDetectorMap
A map from lanes to detectors.
PhasePtr coordinatePhaseObjs[2]
a store of the coordinated phase objects. Only used meaningfully when the controller is in coordinate...
std::map< std::string, int > myLanePhaseMap
A map from lanes names to phases.
std::string composeLightString()
iterates over the two active phases (myActivePhaseObjs) and merges the two active phases
void setNewCycleLength(double newCycleLength)
set the new cycle length for the controller
void setActivePhase(PhasePtr phase)
set the active phase
std::vector< transitionInfo > TransitionPairs
const MSPhaseDefinition & getCurrentPhaseDef() const override
Returns myPhase, which doesn't correspond to a NEMA phase, but rather the composite light string.
std::map< int, std::vector< std::string > > phase2ControllerLanesMap
void setNewSplits(std::vector< double > newSplits)
Set the new splits of all phases.
One phase in the NEMAController.
bool lastDetectActive
store the last detect check for traci purposes
std::string myYellowString
bool myReserviced
whether this coordinated phase was entered from its lagging phase past its force off (served again in...
void setDetectors(std::vector< MSE2Collector * > detectors)
sets the detectors for the phase
SUMOTime myLastEnd
SUMOTime vehExt
SUMOTime nextMaxDuration
NEMAPhase(int phaseName, bool isBarrier, bool isGreenRest, bool isCoordinated, bool minRecall, bool maxRecall, bool fixForceOff, int barrierNum, int ringNum, IntVector phaseStringInds, MSPhaseDefinition *phase)
Construct a new NEMAPhase object.
void cleanupExit(void)
public method to set whether phase is active or not
bool holdsForLag(NEMALogic *controller)
whether a coordinated phase that is followed by a lagging phase is past its force off but has not rea...
MSPhaseDefinition * myCorePhase
A reference to the core phase of which NEMAPhase wraps.
LightState myLightState
std::string myGreenString
LightState getCurrentState() const
gets the current light state
SUMOTime myExpectedDuration
void setMyNEMAStates(void)
this function replaces getNEMAStates calculation at every call It sets my myGreenString,...
~NEMAPhase()
Destructor.
PhasePtr getSequentialPriorPhase(void)
get the prior phase
bool coordinatePhase
SUMOTime greenRestTimer
a count down timer to track green rest transition time
void clearMyDetectors(void)
Clear My Detectors. Called on all phases at every step.
void checkMyDetectors(void)
Check Detectors. Called on all phases at every step.
bool reservice
whether this coordinated phase is served again in the same cycle when its lagging phase gaps out (res...
SUMOTime yellow
SUMOTime minDuration
PhaseDetectorInfo myDetectorInfo
PhasePtr sequentialPriorPhase
SUMOTime greatestStartTime
bool isReserviced() const
whether this coordinated phase is being served again in this cycle after its lagging phase gapped out
std::vector< PhaseTransitionLogic * > trySwitch(NEMALogic *controller)
calculate a vector of potention next phases
std::vector< MSE2Collector * > getDetectors() const
returns a vector of the phases detectors
char getNEMAChar(int i)
Return the ryg light string for the phase.
SUMOTime forceOffTime
stores the force off time in coordinated mode
SUMOTime red
void recalculateTiming(void)
accessory function to recalculate timing
void handleRedXferOrNextPhase(NEMALogic *controller, PhaseTransitionLogic *nextPhases[2])
handles the transition into a red xfer state, which is roughly the same as green rest
SUMOTime getTransitionTimeStateless(void)
Get the Transition time given.
SUMOTime calcVehicleExtension(SUMOTime duration)
}
bool okay2ForceSwitch(NEMALogic *controller)
simple internal check to see if done okay to transition
void init(NEMALogic *controller, int crossPhaseTarget, int crossPhaseSource, bool latching)
initializes the object
PhasePtr myInstance
bool isTransitionActive() const
check if a transition is active
void enterYellow(NEMALogic *controller)
handles the transition into yellow
PhaseTransitionLogic * getTransition(int toPhase)
return the PhaseTransitionLogic matching the toPhase
SUMOTime maxDuration
void handleGreenRestOrTransfer(NEMALogic *controller, PhaseTransitionLogic *nextPhases[2])
handles the transition into a green rest state
bool readyToSwitch
flag to for the supervisory controller to denote whether phase is ready to switch or not.
bool transitionActive
variable to store whether a transition is active or not
std::vector< PhaseTransitionLogic * > myTransitions
stores a sorted list of potential transitions
SUMOTime myStartTime
bool crossFits(NEMALogic *controller, NEMAPhase *toPhase)
for a coordinated or lagging phase in a plan with a lagging phase: whether this ring may cross the ba...
SUMOTime lagWindowLeft(NEMALogic *controller)
for a lagging phase (the barrier phase after a coordinated phase on its side of the barrier): the tim...
void forceEnter(NEMALogic *controller)
Force Enter. This Should only be called at initialization time.
PhasePtr myLastPhaseInstance
bool callActive(void)
simple method to check if there is either a recall or an active detector
std::string myRedString
void update(NEMALogic *controller)
update is called on the active phases by the NEMAController at every time step
SUMOTime getTransitionTime(NEMALogic *controller)
Get the Transition Time.
PhaseTransitionLogic * lastTransitionDecision
pointer to save the last transition
void enter(NEMALogic *controller, PhasePtr lastPhase)
handles entry to the phase during simulation Sets the color to green and determines maximum duration
SUMOTime maxGreenDynamic
void exit(NEMALogic *controller, PhaseTransitionLogic *nextPhases[2])
handles the transition out of a phase into the next (puts the phase through (G -> Y -> R) transition
Builds detectors for microsim.
Parameterised * buildE2Detector(const std::string &id, MSLane *lane, double pos, double endPos, double length, const std::string &device, SUMOTime frequency, SUMOTime haltingTimeThreshold, double haltingSpeedThreshold, double jamDistThreshold, const std::string name, const std::string &vTypes, const std::string &nextEdges, int detectPersons, bool friendlyPos, bool showDetector, MSTLLogicControl::TLSLogicVariants *tlls=0, MSLane *toLane=0)
Builds a new E2 detector and adds it to the net's detector control. Also performs some consistency ch...
std::string myID
The name of the object.
Definition Named.h:124
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.
virtual const std::string getParameter(const std::string &key, const std::string defaultValue="") const
Returns the value for a given key.
virtual void setParameter(const std::string &key, const std::string &value)
Sets a parameter.
This class handles the transition logic between two phases.
int getDistance(PhaseTransitionLogic *otherTrans)
return the ring distance that this transition represents
bool okay(NEMALogic *controller)
This function is the main PhaseTransitionLogic function It is called by the fromPhase to check if a t...
bool freeBase(NEMALogic *controller)
this represents the bare minimum logic, that the toPhase has an active detector and that the fromPhas...
bool coordBase(NEMALogic *controller)
represents the bare minimum coordinate mode logic. Requires that the toPhase can fit its minimum gree...
bool fromBarrier(NEMALogic *controller)
If the fromPhase is at a barrier, then this function will be called to check whether the transition i...
bool fromCoord(NEMALogic *controller)
if the fromPhase is a coordinated phase, then this logic will be checked
PhaseTransitionLogic(PhasePtr fromPhase, PhasePtr toPhase)
Construct a new Phase Transition Logic object.
PhasePtr getFromPhase(void) const
get the from phase
PhasePtr getToPhase(void) const
get the to phase
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
stores information about the phase's detector(s)
bool detectActive
where any of my detectors are active or not
std::vector< MSE2Collector * > detectors
a vector of pointers to the phase's detectors
PhasePtr cpdSource
the cross-phase switching source for myself (1 if 6 should check 1 if 6 is green and I am phase 6)
PhasePtr cpdTarget
the cross-phase switching target for myself (6 if 6 should check 1 if 6 is green and I am phase 1)
bool latching
whether the detectors are latching or not