Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
MSTLLogicControl.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/****************************************************************************/
24// A class that stores and controls tls and switching of their programs
25/****************************************************************************/
26#include <config.h>
27
28#include <vector>
29#include <algorithm>
30#include <cassert>
31#include <iterator>
32#include "MSTrafficLightLogic.h"
34#include "MSTLLogicControl.h"
37#include "MSDriveWay.h"
39#include <microsim/MSNet.h>
43
44#define TRACI_PROGRAM "online"
45
46// ===========================================================================
47// method definitions
48// ===========================================================================
49/* -------------------------------------------------------------------------
50 * MSTLLogicControl::TLSLogicVariants - methods
51 * ----------------------------------------------------------------------- */
53 myCurrentProgram(nullptr),
54 myDefaultProgram(nullptr) {
55}
56
57
59 std::map<std::string, MSTrafficLightLogic*>::const_iterator j;
60 for (const auto& var : myVariants) {
61 delete var.second;
62 }
63 for (OnSwitchAction* osa : mySwitchActions) {
64 delete osa;
65 }
66}
67
68
69bool
71 bool hadErrors = false;
72 for (std::map<std::string, MSTrafficLightLogic*>::const_iterator j = myVariants.begin(); j != myVariants.end(); ++j) {
73 const MSTrafficLightLogic::Phases& phases = (*j).second->getPhases();
74 int linkNo = (int)(*j).second->getLinks().size();
75 bool hadProgramErrors = false;
76 for (MSTrafficLightLogic::Phases::const_iterator i = phases.begin(); i != phases.end(); ++i) {
77 if ((int)(*i)->getState().length() < linkNo) {
78 hadProgramErrors = true;
79 }
80 }
81 if (hadProgramErrors) {
82 WRITE_ERRORF(TL("Mismatching phase size in tls '%', program '%'."), (*j).second->getID(), (*j).first);
83 hadErrors = true;
84 }
85 }
86 return !hadErrors;
87}
88
89
90void
92 myOriginalLinkStates = myCurrentProgram->collectLinkStates();
93}
94
95
96void
98 for (const auto& item : myVariants) {
99 item.second->saveState(out);
100 }
101}
102
103
104bool
106 MSTrafficLightLogic* logic, bool netWasLoaded, bool isNewDefault) {
107 if (myVariants.find(programID) != myVariants.end()) {
108 delete logic;
109 return false;
110 }
111 // assert the links are set
112 if (netWasLoaded) {
113 // this one has not yet its links set
114 if (myCurrentProgram == nullptr) {
115 const std::string id = logic->getID();
116 delete logic;
117 throw ProcessError(TLF("No initial signal plan loaded for tls '%'.", id));
118 }
119 logic->adaptLinkInformationFrom(*myCurrentProgram);
120 if (logic->getLinks().size() > logic->getPhase(0).getState().size()) {
121 const std::string id = logic->getID();
122 delete logic;
123 throw ProcessError(TLF("Mismatching phase size in tls '%', program '%'.", id, programID));
124 }
125 }
126 // add to the list of active
127 if (myVariants.size() == 0 || isNewDefault) {
128 if (myCurrentProgram != nullptr) {
129 myCurrentProgram->deactivateProgram();
130 }
131 myCurrentProgram = logic;
132 myCurrentProgram->activateProgram();
133 if (myVariants.size() == 0) {
134 myDefaultProgram = logic;
135 }
136 }
137 // add to the list of logic
138 myVariants[programID] = logic;
139 if (myVariants.size() == 1 || isNewDefault) {
140 logic->setTrafficLightSignals(MSNet::getInstance()->getCurrentTimeStep());
141 executeOnSwitchActions();
142 }
143 return true;
144}
145
146
148MSTLLogicControl::TLSLogicVariants::getLogic(const std::string& programID) const {
149 if (myVariants.find(programID) == myVariants.end()) {
150 return nullptr;
151 }
152 return myVariants.find(programID)->second;
153}
154
155
158 if (myVariants.find(programID) == myVariants.end()) {
159 if (programID == "off") {
160 // build an off-tll if this switch indicates it
161 MSTrafficLightLogic* tlLogic = new MSOffTrafficLightLogic(tlc, myCurrentProgram->getID());
162 if (!addLogic("off", tlLogic, true, true)) {
163 // inform the user if this fails
164 throw ProcessError(TLF("Could not build an off-state for tls '%'.", myCurrentProgram->getID()));
165 }
166 } else {
167 // inform the user about a missing logic
168 throw ProcessError(TLF("Can not switch tls '%' to program '%';\n The program is not known.", myCurrentProgram->getID(), programID));
169 }
170 }
171 return getLogic(programID);
172}
173
174
175void
177 const std::string& state) {
178 // build only once...
179 MSTrafficLightLogic* logic = getLogic(TRACI_PROGRAM);
180 if (logic == nullptr) {
182 phase->earliestEnd = SUMOTime_DAY; // prevent immediate switch
183 std::vector<MSPhaseDefinition*> phases;
184 phases.push_back(phase);
185 logic = new MSSimpleTrafficLightLogic(tlc, myCurrentProgram->getID(), TRACI_PROGRAM, 0, TrafficLightType::STATIC, phases, 0,
188 if (addLogic(TRACI_PROGRAM, logic, true, true)) {
190 }
191 } else {
192 MSPhaseDefinition nphase(SUMOTime_DAY, state);
193 *(dynamic_cast<MSSimpleTrafficLightLogic*>(logic)->getPhases()[0]) = nphase;
195 }
196}
197
198
199void
201 mySwitchActions.push_back(c);
202}
203
204
205std::vector<MSTrafficLightLogic*>
207 std::vector<MSTrafficLightLogic*> ret;
208 std::map<std::string, MSTrafficLightLogic*>::const_iterator i;
209 for (i = myVariants.begin(); i != myVariants.end(); ++i) {
210 ret.push_back((*i).second);
211 }
212 return ret;
213}
214
215
216bool
218 return tl == myCurrentProgram;
219}
220
221
224 return myCurrentProgram;
225}
226
229 return myDefaultProgram;
230}
231
232
233void
235 // set the found wished sub-program as this tls' current one
236 MSTrafficLightLogic* const previous = myCurrentProgram;
237 const std::string state = previous->getCurrentPhaseDef().getState();
238 MSTrafficLightLogic* const next = getLogicInstantiatingOff(tlc, programID);
239 // Creating the "off" program can already replace the active program.
240 if (myCurrentProgram == previous) {
241 previous->deactivateProgram();
242 }
243 myCurrentProgram = next;
244 myCurrentProgram->activateProgram();
245 myCurrentProgram->setTrafficLightSignals(MSNet::getInstance()->getCurrentTimeStep());
246 if (state != myCurrentProgram->getCurrentPhaseDef().getState()) {
247 myCurrentProgram->resetLastSwitch(SIMSTEP);
248 };
249 executeOnSwitchActions();
250}
251
252
253void
255 // setting tl as active and updating signal states happens on the calling side (MSTrafficLightLogic::loadState)
256 if (myCurrentProgram != tl) {
257 myCurrentProgram->deactivateProgram();
258 myCurrentProgram = tl;
259 }
260}
261
262
263void
265 for (std::vector<OnSwitchAction*>::const_iterator i = mySwitchActions.begin(); i != mySwitchActions.end(); ++i) {
266 (*i)->execute();
267 }
268}
269
270
271void
273 for (std::map<std::string, MSTrafficLightLogic*>::iterator i = myVariants.begin(); i != myVariants.end(); ++i) {
274 (*i).second->addLink(link, lane, pos);
275 }
276}
277
278void
280 for (std::map<std::string, MSTrafficLightLogic*>::iterator i = myVariants.begin(); i != myVariants.end(); ++i) {
281 (*i).second->ignoreLinkIndex(pos);
282 }
283}
284
285
286/* -------------------------------------------------------------------------
287 * method definitions for the Switching Procedures
288 * ----------------------------------------------------------------------- */
289/* -------------------------------------------------------------------------
290 * method definitions for WAUTSwitchProcedure
291 * ----------------------------------------------------------------------- */
292bool
294 // switch to the next programm if the GSP is reached
295 if (isPosAtGSP(step, *myFrom)) {
296 // adapt program's state
297 if (mySwitchSynchron) {
298 adaptLogic(step);
299 } else {
300 switchToPos(step, *myTo, getGSPTime(*myTo));
301 }
302 // switch to destination program
303 return true;
304 }
305 // do not switch, yet
306 return false;
307}
308
309
314
315
316bool
318 const SUMOTime gspTime = getGSPTime(logic) % logic.getDefaultCycleTime();
319 const SUMOTime programTime = logic.getOffsetFromIndex(logic.getCurrentPhaseIndex()) + logic.getSpentDuration(currentTime);
320 return gspTime == programTime;
321}
322
323
326 int stepOfMyPos = logic.getIndexFromOffset(toTime);
327 SUMOTime startOfPhase = logic.getOffsetFromIndex(stepOfMyPos);
328 assert(toTime >= startOfPhase);
329 return toTime - startOfPhase;
330}
331
332
333void
335 int stepTo = logic.getIndexFromOffset(toTime);
336 SUMOTime diff = getDiffToStartOfPhase(logic, toTime);
337 const MSPhaseDefinition& phase = logic.getPhase(stepTo);
338 SUMOTime leftDuration = phase.duration - diff;
339 logic.changeStepAndDuration(myControl, simStep, stepTo, leftDuration);
340}
341
342
343
344/* -------------------------------------------------------------------------
345 * method definitions for WAUTSwitchProcedure_JustSwitch
346 * ----------------------------------------------------------------------- */
351
352
354
355
356bool
360
361
362
363/* -------------------------------------------------------------------------
364 * method definitions for WAUTSwitchProcedure_GSP
365 * ----------------------------------------------------------------------- */
370
371
373
374
375void
377 const SUMOTime gspTo = getGSPTime(*myTo) % myTo->getDefaultCycleTime();
378 const SUMOTime currentPosTo = myTo->getOffsetFromIndex(myTo->getCurrentPhaseIndex()) + myTo->getSpentDuration(step);
379 SUMOTime deltaToStretch = gspTo - currentPosTo;
380 if (deltaToStretch < 0) {
381 deltaToStretch += myTo->getDefaultCycleTime();
382 }
383 const int stepTo = myTo->getIndexFromOffset(gspTo);
384 const SUMOTime newdur = myTo->getPhase(stepTo).duration - getDiffToStartOfPhase(*myTo, gspTo) + deltaToStretch;
385 myTo->changeStepAndDuration(myControl, step, stepTo, newdur);
386}
387
388
389
390/* -------------------------------------------------------------------------
391 * method definitions for WAUTSwitchProcedure_Stretch
392 * ----------------------------------------------------------------------- */
394 MSTLLogicControl& control, WAUT& waut,
395 MSTrafficLightLogic* from, MSTrafficLightLogic* to, bool synchron)
396 : MSTLLogicControl::WAUTSwitchProcedure(control, waut, from, to, synchron) {
397 int idx = 1;
398 while (myTo->hasParameter("B" + toString(idx) + ".begin")) {
399 StretchRange def;
400 def.begin = string2time(myTo->getParameter("B" + toString(idx) + ".begin"));
401 def.end = string2time(myTo->getParameter("B" + toString(idx) + ".end"));
402 def.fac = StringUtils::toDouble(myTo->getParameter("B" + toString(idx) + ".factor"));
403 myStretchRanges.emplace_back(def);
404 }
405
406}
407
408
410
411
412void
414 SUMOTime gspTo = getGSPTime(*myTo);
415 SUMOTime cycleTime = myTo->getDefaultCycleTime();
416 // the position, where the logic has to be after synchronisation
417 SUMOTime posAfterSyn = myTo->getPhaseIndexAtTime(step);
418 // calculate the difference, that has to be equalized
419 SUMOTime deltaToCut = 0;
420 if (posAfterSyn < gspTo) {
421 deltaToCut = posAfterSyn + cycleTime - gspTo;
422 } else {
423 deltaToCut = posAfterSyn - gspTo;
424 }
425 // test, wheter cutting of the Signalplan is possible
426 SUMOTime deltaPossible = 0;
427 for (const StretchRange& def : myStretchRanges) {
428 assert(def.end >= def.begin);
429 deltaPossible += def.end - def.begin;
430 }
431 int stretchUmlaufAnz = (int) StringUtils::toDouble(myTo->getParameter("StretchUmlaufAnz", ""));
432 deltaPossible = stretchUmlaufAnz * deltaPossible;
433 if ((deltaPossible > deltaToCut) && (deltaToCut < (cycleTime / 2))) {
434 cutLogic(step, gspTo, deltaToCut);
435 } else {
436 SUMOTime deltaToStretch = (cycleTime - deltaToCut) % cycleTime;
437 stretchLogic(step, gspTo, deltaToStretch);
438 }
439}
440
441
442void
444 int actStep = myTo->getIndexFromOffset(startPos);
445 // switches to startPos and cuts this phase, if there is a "Bereich"
446 SUMOTime toCut = 0;
447 for (const StretchRange& def : myStretchRanges) {
448 int stepOfBegin = myTo->getIndexFromOffset(def.begin);
449 if (stepOfBegin == actStep) {
450 if (def.begin < startPos) {
451 toCut = def.end - startPos;
452 } else {
453 toCut = def.end - def.begin;
454 }
455 toCut = MIN2(allCutTime, toCut);
456 allCutTime = allCutTime - toCut;
457 }
458 }
459 SUMOTime remainingDur = myTo->getPhase(actStep).duration - getDiffToStartOfPhase(*myTo, startPos);
460 SUMOTime newDur = remainingDur - toCut;
461 myTo->changeStepAndDuration(myControl, step, actStep, newDur);
462
463 // changes the duration of all other phases
464 int currStep = (actStep + 1) % (int)myTo->getPhases().size();
465 while (allCutTime > 0) {
466 for (int i = currStep; i < (int) myTo->getPhases().size(); i++) {
467 SUMOTime beginOfPhase = myTo->getOffsetFromIndex(i);
468 SUMOTime durOfPhase = myTo->getPhase(i).duration;
469 SUMOTime endOfPhase = beginOfPhase + durOfPhase;
470 for (const StretchRange& def : myStretchRanges) {
471 if ((beginOfPhase <= def.begin) && (endOfPhase >= def.end)) {
472 SUMOTime maxCutOfPhase = MIN2(def.end - def.begin, allCutTime);
473 allCutTime = allCutTime - maxCutOfPhase;
474 durOfPhase = durOfPhase - maxCutOfPhase;
475 }
476 }
477 myTo->addOverridingDuration(durOfPhase);
478 }
479 currStep = 0;
480 }
481}
482
483void
485 int currStep = myTo->getIndexFromOffset(startPos);
486 SUMOTime durOfPhase = myTo->getPhase(currStep).duration;
487 SUMOTime remainingStretchTime = allStretchTime;
488 SUMOTime StretchTimeOfPhase = 0;
489 int stretchUmlaufAnz = (int) StringUtils::toDouble(myTo->getParameter("StretchUmlaufAnz", ""));
490 double facSum = 0;
491 for (const StretchRange& def : myStretchRanges) {
492 facSum += def.fac;
493 }
494 facSum *= stretchUmlaufAnz;
495
496 //switch to startPos and stretch this phase, if there is a end of "bereich" between startpos and end of phase
497 SUMOTime diffToStart = getDiffToStartOfPhase(*myTo, startPos);
498 for (const StretchRange& def : myStretchRanges) {
499 SUMOTime endOfPhase = (startPos + durOfPhase - diffToStart);
500 if (def.end <= endOfPhase && def.end >= startPos) {
501 double actualfac = def.fac / facSum;
502 facSum = facSum - def.fac;
503 StretchTimeOfPhase = TIME2STEPS(int(STEPS2TIME(remainingStretchTime) * actualfac + 0.5));
504 remainingStretchTime = allStretchTime - StretchTimeOfPhase;
505 }
506 }
507 if (facSum == 0) {
508 WRITE_WARNINGF(TL("The computed factor sum in WAUT '%' at time '%' equals zero;\n assuming an error in WAUT definition."), myWAUT.id, toString(STEPS2TIME(step)));
509 return;
510 }
511 durOfPhase = durOfPhase - diffToStart + StretchTimeOfPhase;
512 myTo->changeStepAndDuration(myControl, step, currStep, durOfPhase);
513
514 currStep = (currStep + 1) % (int)myTo->getPhases().size();
515 // stretch all other phases, if there is a "bereich"
516 while (remainingStretchTime > 0) {
517 for (int i = currStep; i < (int)myTo->getPhases().size() && remainingStretchTime > 0; i++) {
518 durOfPhase = myTo->getPhase(i).duration;
519 SUMOTime beginOfPhase = myTo->getOffsetFromIndex(i);
520 SUMOTime endOfPhase = beginOfPhase + durOfPhase;
521 for (const StretchRange& def : myStretchRanges) {
522 if ((beginOfPhase <= def.end) && (endOfPhase >= def.end)) {
523 double actualfac = def.fac / facSum;
524 StretchTimeOfPhase = TIME2STEPS(int(STEPS2TIME(remainingStretchTime) * actualfac + 0.5));
525 facSum -= def.fac;
526 durOfPhase += StretchTimeOfPhase;
527 remainingStretchTime -= StretchTimeOfPhase;
528 }
529 }
530 myTo->addOverridingDuration(durOfPhase);
531 }
532 currStep = 0;
533 }
534}
535
536
537/* -------------------------------------------------------------------------
538 * method definitions for MSTLLogicControl
539 * ----------------------------------------------------------------------- */
542
543
545 // delete tls
546 for (std::map<std::string, TLSLogicVariants*>::const_iterator i = myLogics.begin(); i != myLogics.end(); ++i) {
547 delete (*i).second;
548 }
549 // delete WAUTs
550 for (std::map<std::string, WAUT*>::const_iterator i = myWAUTs.begin(); i != myWAUTs.end(); ++i) {
551 delete (*i).second;
552 }
553}
554
555
556void
558 for (std::map<std::string, TLSLogicVariants*>::const_iterator i = myLogics.begin(); i != myLogics.end(); ++i) {
559 (*i).second->getActive()->setTrafficLightSignals(t);
560 }
561}
562
563
564std::vector<MSTrafficLightLogic*>
566 std::vector<MSTrafficLightLogic*> ret;
567 std::map<std::string, TLSLogicVariants*>::const_iterator i;
568 for (i = myLogics.begin(); i != myLogics.end(); ++i) {
569 std::vector<MSTrafficLightLogic*> s = (*i).second->getAllLogics();
570 copy(s.begin(), s.end(), back_inserter(ret));
571 }
572 return ret;
573}
574
576MSTLLogicControl::get(const std::string& id) const {
577 std::map<std::string, TLSLogicVariants*>::const_iterator i = myLogics.find(id);
578 if (i == myLogics.end()) {
579 throw InvalidArgument("The tls '" + id + "' is not known.");
580 }
581 return *(*i).second;
582}
583
584
586MSTLLogicControl::get(const std::string& id, const std::string& programID) const {
587 std::map<std::string, TLSLogicVariants*>::const_iterator i = myLogics.find(id);
588 if (i == myLogics.end()) {
589 return nullptr;
590 }
591 return (*i).second->getLogic(programID);
592}
593
594
595std::vector<std::string>
597 std::vector<std::string> ret;
598 for (std::map<std::string, TLSLogicVariants*>::const_iterator i = myLogics.begin(); i != myLogics.end(); ++i) {
599 ret.push_back((*i).first);
600 }
601 return ret;
602}
603
604
605bool
606MSTLLogicControl::add(const std::string& id, const std::string& programID,
607 MSTrafficLightLogic* logic, bool newDefault) {
608 std::map<std::string, TLSLogicVariants*>::iterator it = myLogics.find(id);
609 TLSLogicVariants* tlmap;
610 if (it == myLogics.end()) {
611 tlmap = myLogics[id] = new TLSLogicVariants();
612 } else {
613 tlmap = it->second;
614 }
615 return tlmap->addLogic(programID, logic, myNetWasLoaded, newDefault);
616}
617
618
619bool
620MSTLLogicControl::knows(const std::string& id) const {
621 return myLogics.count(id) != 0;
622}
623
624
625bool
627 bool hadErrors = false;
628 for (const auto& it : myLogics) {
629 hadErrors |= !it.second->checkOriginalTLS();
630 it.second->saveInitialStates();
631 }
632 myNetWasLoaded = true;
633 return !hadErrors;
634}
635
636
637bool
639 std::map<std::string, TLSLogicVariants*>::const_iterator i = myLogics.find(tl->getID());
640 if (i == myLogics.end()) {
641 return false;
642 }
643 return (*i).second->isActive(tl);
644}
645
646
648MSTLLogicControl::getActive(const std::string& id) const {
649 std::map<std::string, TLSLogicVariants*>::const_iterator i = myLogics.find(id);
650 if (i == myLogics.end()) {
651 return nullptr;
652 }
653 return (*i).second->getActive();
654}
655
656
657void
658MSTLLogicControl::switchTo(const std::string& id, const std::string& programID) {
659 // try to get the tls program definitions
660 std::map<std::string, TLSLogicVariants*>::iterator i = myLogics.find(id);
661 // handle problems
662 if (i == myLogics.end()) {
663 throw ProcessError(TLF("Could not switch tls '%' to program '%': No such tls exists.", id, programID));
664 }
665 (*i).second->switchTo(*this, programID);
666}
667
668
669void
670MSTLLogicControl::addWAUT(SUMOTime refTime, const std::string& id,
671 const std::string& startProg, SUMOTime period) {
672 // check whether the waut was already defined
673 if (myWAUTs.find(id) != myWAUTs.end()) {
674 // report an error if so
675 throw InvalidArgument(TLF("Waut '%' was already defined.", id));
676 }
677 WAUT* w = new WAUT;
678 w->id = id;
679 w->refTime = refTime;
680 w->startProg = startProg;
681 w->period = period;
682 myWAUTs[id] = w;
683}
684
685
686void
687MSTLLogicControl::addWAUTSwitch(const std::string& wautid,
688 SUMOTime when, const std::string& to) {
689 // try to get the waut
690 if (myWAUTs.find(wautid) == myWAUTs.end()) {
691 // report an error if the waut is not known
692 throw InvalidArgument(TLF("Waut '%' was not yet defined.", wautid));
693 }
694 // build and save the waut switch definition
695 WAUT* waut = myWAUTs[wautid];
696 WAUTSwitch s;
697 s.to = to;
698 s.when = (waut->refTime + when);
699 if (waut->period > 0) {
700 s.when = s.when % waut->period;
701 }
702 myWAUTs[wautid]->switches.push_back(s);
703}
704
705
706void
707MSTLLogicControl::addWAUTJunction(const std::string& wautid,
708 const std::string& tls,
709 const std::string& proc,
710 bool synchron) {
711 // try to get the waut
712 if (myWAUTs.find(wautid) == myWAUTs.end()) {
713 // report an error if the waut is not known
714 throw InvalidArgument(TLF("Waut '%' was not yet defined.", wautid));
715 }
716 // try to get the tls to switch
717 if (myLogics.find(tls) == myLogics.end()) {
718 // report an error if the tls is not known
719 throw InvalidArgument(TLF("TLS '%' to switch in WAUT '%' was not yet defined.", tls, wautid));
720 }
721 WAUTJunction j;
722 j.junction = tls;
723 j.procedure = proc;
724 j.synchron = synchron;
725 myWAUTs[wautid]->junctions.push_back(j);
726
727 std::string initProg = myWAUTs[wautid]->startProg;
728 std::vector<WAUTSwitch>::const_iterator first = myWAUTs[wautid]->switches.end();
729 SUMOTime minExecTime = -1;
730 for (std::vector<WAUTSwitch>::const_iterator i = myWAUTs[wautid]->switches.begin(); i != myWAUTs[wautid]->switches.end(); ++i) {
731 if ((*i).when > MSNet::getInstance()->getCurrentTimeStep() && (minExecTime == -1 || (*i).when < minExecTime)) {
732 minExecTime = (*i).when;
733 first = i;
734 }
735 if (first != myWAUTs[wautid]->switches.begin()) {
736 initProg = (*(first - 1)).to;
737 }
738 }
739 // activate the first one
740 switchTo(tls, initProg);
741}
742
743
744void
745MSTLLogicControl::closeWAUT(const std::string& wautid) {
746 // try to get the waut
747 if (myWAUTs.find(wautid) == myWAUTs.end()) {
748 // report an error if the waut is not known
749 throw InvalidArgument(TLF("Waut '%' was not yet defined.", wautid));
750 }
751 WAUT* w = myWAUTs.find(wautid)->second;
752 std::string initProg = myWAUTs[wautid]->startProg;
753 // get the switch to be performed as first
754 SUMOTime minExecTime = SUMOTime_MAX;
755 int firstIndex = -1;
756 int i = 0;
757 for (const WAUTSwitch& s : w->switches) {
758 if (s.when >= SIMSTEP && s.when < minExecTime) {
759 minExecTime = s.when;
760 firstIndex = i;
761 }
762 i++;
763 }
764 // activate the first one
765 if (firstIndex >= 0) {
767 new SwitchInitCommand(*this, wautid, firstIndex), MAX2(SIMSTEP, minExecTime));
768 }
769 /*
770 // set the current program to all junctions
771 for(std::vector<WAUTJunction>::const_iterator i=w->junctions.begin(); i!=w->junctions.end(); ++i) {
772 switchTo((*i).junction, initProg);
773 }
774 */
775}
776
777
780 const std::string& wautid = cmd.getWAUTID();
781 int& index = cmd.getIndex();
782 WAUT* waut = myWAUTs[wautid];
783 WAUTSwitch s = waut->switches[index];
784 for (const WAUTJunction& j : waut->junctions) {
785 initSwitchProcess(*waut, j, s.to);
786 }
787 index++;
788 if (index == (int)waut->switches.size()) {
789 if (waut->period <= 0) {
790 return 0;
791 } else {
792 index = 0; // start over
793 for (WAUTSwitch& ws : waut->switches) {
794 ws.when += waut->period;
795 }
796 }
797 }
798 return myWAUTs[wautid]->switches[index].when - MSNet::getInstance()->getCurrentTimeStep();
799}
800
801
802void
803MSTLLogicControl::initSwitchProcess(WAUT& waut, const WAUTJunction& junction, const std::string& to) {
804 // get the current program and the one to instantiate
805 TLSLogicVariants* vars = myLogics.find(junction.junction)->second;
807 p.junction = junction.junction;
808 p.from = vars->getActive();
809 p.to = vars->getLogicInstantiatingOff(*this, to);
810 if (junction.procedure == "GSP") {
811 p.proc = new WAUTSwitchProcedure_GSP(*this, waut, p.from, p.to, junction.synchron);
812 } else if (junction.procedure == "Stretch") {
813 p.proc = new WAUTSwitchProcedure_Stretch(*this, waut, p.from, p.to, junction.synchron);
814 } else {
815 p.proc = new WAUTSwitchProcedure_JustSwitch(*this, waut, p.from, p.to, junction.synchron);
816 }
817 myCurrentlySwitched.push_back(p);
818}
819
820
821void
823 for (std::vector<WAUTSwitchProcess>::iterator i = myCurrentlySwitched.begin(); i != myCurrentlySwitched.end();) {
824 const WAUTSwitchProcess& proc = *i;
825 if (proc.proc->trySwitch(step)) {
826 delete proc.proc;
827 // do not switch away from TraCI control
828 if (getActive(proc.to->getID())->getProgramID() != TRACI_PROGRAM) {
829 switchTo(proc.to->getID(), proc.to->getProgramID());
830 }
831 i = myCurrentlySwitched.erase(i);
832 } else {
833 ++i;
834 }
835 }
836}
837
838
839std::pair<SUMOTime, MSPhaseDefinition>
840MSTLLogicControl::getPhaseDef(const std::string& tlid) const {
841 MSTrafficLightLogic* tl = getActive(tlid);
842 return std::make_pair(MSNet::getInstance()->getCurrentTimeStep(), tl->getCurrentPhaseDef());
843}
844
845
846void
848 for (const auto& logic : myLogics) {
849 if (logic.second->getActive()->getLogicType() == TrafficLightType::RAIL_SIGNAL) {
850 // there is no sensible fall-back behavior when switching of rail
851 // signals so they should ignore tls.all-off
852 continue;
853 }
854 logic.second->addLogic("off", new MSOffTrafficLightLogic(*this, logic.first), true, true);
855 }
856}
857
858
859void
861 MSRailSignalConstraint::saveState(out); // always saves vehicle tracker states
862 for (const auto& logic : myLogics) {
863 logic.second->saveState(out);
864 }
865 for (const WAUTSwitchProcess& p : myCurrentlySwitched) {
867 out.writeAttr(SUMO_ATTR_WAUT_ID, p.proc->getWAUTID());
868 out.writeAttr(SUMO_ATTR_JUNCTION_ID, p.junction);
869 out.writeAttr(SUMO_ATTR_TO, p.to->getProgramID());
870 out.closeTag();
871 }
873}
874
875
876void
877MSTLLogicControl::loadWAUTSwitch(const std::string& wautID, const std::string& junctionID, const std::string& to) {
878 auto it = myWAUTs.find(wautID);
879 if (it == myWAUTs.end()) {
880 throw ProcessError(TLF("Unknown WAUT '%' in loaded state.", wautID));
881 }
882 for (const WAUTJunction& j : it->second->junctions) {
883 if (j.junction == junctionID) {
884 initSwitchProcess(*it->second, j, to);
885 }
886 }
887}
888
889
890void
891MSTLLogicControl::clearState(SUMOTime time, bool quickReload) {
893 for (const WAUTSwitchProcess& p : myCurrentlySwitched) {
894 delete p.proc;
895 }
896 myCurrentlySwitched.clear();
897 if (quickReload) {
898 for (const auto& variants : myLogics) {
899 for (auto& logic : variants.second->getAllLogics()) {
900 if (logic->getLogicType() == TrafficLightType::OFF
901 || logic->getLogicType() == TrafficLightType::RAIL_SIGNAL
902 || logic->getLogicType() == TrafficLightType::RAIL_CROSSING) {
903 continue;
904 }
905 int step = 0;
906 const SUMOTime cycleTime = logic->getDefaultCycleTime();
907 auto& phases = logic->getPhases();
908 SUMOTime offset = logic->getOffset();
909 if (offset >= 0) {
910 offset = (time + cycleTime - (offset % cycleTime)) % cycleTime;
911 } else {
912 offset = (time + ((-offset) % cycleTime)) % cycleTime;
913 }
914
915 while (offset >= phases[step]->duration) {
916 offset -= phases[step]->duration;
917 step++;
918 }
919 SUMOTime nextSwitch = time + phases[step]->duration - offset;
920 SUMOTime timeInCycle = (time - offset) % logic->getDefaultCycleTime();
921 logic->loadState(*this, time, step, offset, nextSwitch, timeInCycle, logic->isActive());
922 }
923 }
924 }
925}
926
927
928/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
#define TRACI_PROGRAM
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_ERRORF(...)
Definition MsgHandler.h:308
#define TL(string)
Definition MsgHandler.h:316
#define TLF(string,...)
Definition MsgHandler.h:318
SUMOTime DELTA_T
Definition SUMOTime.cpp:39
SUMOTime string2time(const std::string &r)
convert string to SUMOTime
Definition SUMOTime.cpp:47
#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 SUMOTime_DAY
Definition SUMOTime.h:37
@ SUMO_TAG_WAUT_SWITCH
@ SUMO_ATTR_WAUT_ID
@ SUMO_ATTR_TO
@ SUMO_ATTR_JUNCTION_ID
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 void saveState(OutputDevice &out)
Save driveway occupancy into the given stream.
virtual void addEvent(Command *operation, SUMOTime execTimeStep=-1)
Adds an Event.
Representation of a lane in the micro simulation.
Definition MSLane.h:84
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
virtual void createTLWrapper(MSTrafficLightLogic *)
creates a wrapper for the given logic (see GUINet)
Definition MSNet.h:612
A traffic lights logic which represents a tls in an off-mode.
The definition of a single phase of a tls logic.
const std::string & getState() const
Returns the state within this phase.
SUMOTime duration
The duration of the phase.
SUMOTime earliestEnd
The minimum time within the cycle for switching (for coordinated actuation)
static void saveState(OutputDevice &out)
Saves the current constraint states into the given stream.
static void clearState()
Clear all constraint states before quick-loading state.
A fixed traffic light logic.
Base class for things to execute if a tls switches to a new phase.
This event-class is used to initialise a WAUT switch at a certain time.
const std::string & getWAUTID() const
Returns the WAUT-id.
int & getIndex()
Returns a reference to the index.
Storage for all programs of a single tls.
void addLink(MSLink *link, MSLane *lane, int pos)
void switchTo(MSTLLogicControl &tlc, const std::string &programID)
void addSwitchCommand(OnSwitchAction *c)
void setStateInstantiatingOnline(MSTLLogicControl &tlc, const std::string &state)
bool checkOriginalTLS() const
Verifies traffic lights loaded from the network.
std::vector< MSTrafficLightLogic * > getAllLogics() const
MSTrafficLightLogic * getLogic(const std::string &programID) const
bool addLogic(const std::string &programID, MSTrafficLightLogic *logic, bool netWasLoaded, bool isNewDefault=true)
Adds a logic (program). In case of an error the logic gets deleted.
void switchToLoaded(MSTrafficLightLogic *tl)
set current program upon loading saved state
MSTrafficLightLogic * getActive() const
MSTrafficLightLogic * getDefault() const
return the default program (that last used program except TRACI_PROGRAM)
MSTrafficLightLogic * getLogicInstantiatingOff(MSTLLogicControl &tlc, const std::string &programID)
bool isActive(const MSTrafficLightLogic *tl) const
This class switches using the GSP algorithm.
WAUTSwitchProcedure_GSP(MSTLLogicControl &control, WAUT &waut, MSTrafficLightLogic *from, MSTrafficLightLogic *to, bool synchron)
Constructor.
void adaptLogic(SUMOTime step)
Stretches the destination program's phase to which the tls was switched.
This class simply switches to the next program.
bool trySwitch(SUMOTime step)
Determines whether a switch is possible.
WAUTSwitchProcedure_JustSwitch(MSTLLogicControl &control, WAUT &waut, MSTrafficLightLogic *from, MSTrafficLightLogic *to, bool synchron)
Constructor.
This class switches using the Stretch algorithm.
void adaptLogic(SUMOTime step)
Determines the destination program's changes and applies them.
std::vector< StretchRange > myStretchRanges
the given Stretch-areas for the "to" program, this is 0-based indexed, while the input is 1-based
WAUTSwitchProcedure_Stretch(MSTLLogicControl &control, WAUT &waut, MSTrafficLightLogic *from, MSTrafficLightLogic *to, bool synchron)
Constructor.
void cutLogic(SUMOTime step, SUMOTime startPos, SUMOTime allCutTime)
Cuts the logic to synchronize.
void stretchLogic(SUMOTime step, SUMOTime startPos, SUMOTime allStretchTime)
Stretches the logic to synchronize.
This is the abstract base class for switching from one tls program to another.
virtual bool trySwitch(SUMOTime step)
Determines whether a switch is possible.
MSTrafficLightLogic * myTo
The program to switch the tls to.
bool isPosAtGSP(SUMOTime currentTime, const MSTrafficLightLogic &logic)
Checks, whether the position of a signal program is at the GSP ("Good Switching Point")
SUMOTime getGSPTime(const MSTrafficLightLogic &logic) const
Returns the GSP-value.
SUMOTime getDiffToStartOfPhase(MSTrafficLightLogic &logic, SUMOTime toTime)
Returns the difference between a given time and the start of the phase.
void switchToPos(SUMOTime simStep, MSTrafficLightLogic &logic, SUMOTime toTime)
switches the given logic directly to the given position
A class that stores and controls tls and switching of their programs.
void addWAUTJunction(const std::string &wautid, const std::string &tls, const std::string &proc, bool synchron)
Adds a tls to the list of tls to be switched by the named WAUT.
void clearState(SUMOTime time, bool quickReload=false)
Clear all tls states before quick-loading state.
std::vector< MSTrafficLightLogic * > getAllLogics() const
Returns a vector which contains all logics.
std::vector< WAUTSwitchProcess > myCurrentlySwitched
A list of currently running switching procedures.
std::pair< SUMOTime, MSPhaseDefinition > getPhaseDef(const std::string &tlid) const
return the complete phase definition for a named traffic lights logic
std::map< std::string, TLSLogicVariants * > myLogics
A map from ids to the corresponding variants.
void addWAUT(SUMOTime refTime, const std::string &id, const std::string &startProg, SUMOTime period)
Adds a WAUT definition.
std::vector< std::string > getAllTLIds() const
void switchTo(const std::string &id, const std::string &programID)
Switches the named (id) tls to the named (programID) program.
MSTrafficLightLogic * getActive(const std::string &id) const
Returns the active program of a named tls.
bool closeNetworkReading()
Lets MSTLLogicControl know that the network has been loaded.
void setTrafficLightSignals(SUMOTime t) const
Lets all running (current) tls programs apply their current signal states to links they control.
bool knows(const std::string &id) const
Returns the information whether the named tls is stored.
void saveState(OutputDevice &out)
Saves the current tls states into the given stream.
bool myNetWasLoaded
Information whether the net was completely loaded.
void switchOffAll()
switch all logic variants to 'off'
void addWAUTSwitch(const std::string &wautid, SUMOTime when, const std::string &to)
Adds a WAUT switch step to a previously built WAUT.
void loadWAUTSwitch(const std::string &wautID, const std::string &junctionID, const std::string &to)
Restores a WAUT switch that waited for its switching point when the state was saved.
TLSLogicVariants & get(const std::string &id) const
Returns the variants of a named tls.
MSTLLogicControl()
Constructor.
SUMOTime initWautSwitch(SwitchInitCommand &cmd)
Initialises switching a WAUT.
void initSwitchProcess(WAUT &waut, const WAUTJunction &junction, const std::string &to)
Starts switching a junction of the given WAUT to the given program.
~MSTLLogicControl()
Destructor.
void check2Switch(SUMOTime step)
Checks whether any WAUT is trying to switch a tls into another program.
std::map< std::string, WAUT * > myWAUTs
A map of ids to corresponding WAUTs.
bool isActive(const MSTrafficLightLogic *tl) const
Returns whether the given tls program is the currently active for his tls.
bool add(const std::string &id, const std::string &programID, MSTrafficLightLogic *logic, bool newDefault=true)
Adds a tls program to the container.
void closeWAUT(const std::string &wautid)
Closes loading of a WAUT.
The parent class for traffic light logics.
const LinkVectorVector & getLinks() const
Returns the list of lists of all affected links.
virtual void adaptLinkInformationFrom(const MSTrafficLightLogic &logic)
Applies information about controlled links and lanes from the given logic.
virtual const MSPhaseDefinition & getCurrentPhaseDef() const =0
Returns the definition of the current phase.
virtual int getCurrentPhaseIndex() const =0
Returns the current index within the program.
virtual SUMOTime getOffsetFromIndex(int index) const =0
Returns the position (start of a phase during a cycle) from of a given step.
virtual void changeStepAndDuration(MSTLLogicControl &tlcontrol, SUMOTime simStep, int step, SUMOTime stepDuration)=0
Changes the current phase and her duration.
virtual const MSPhaseDefinition & getPhase(int givenstep) const =0
Returns the definition of the phase from the given position within the plan.
const std::string & getProgramID() const
Returns this tl-logic's id.
virtual int getIndexFromOffset(SUMOTime offset) const =0
Returns the step (the phasenumber) of a given position of the cycle.
SUMOTime getDefaultCycleTime() const
Returns the cycle time (in ms)
virtual void activateProgram()
called when switching programs
SUMOTime getSpentDuration(SUMOTime simStep=-1) const
Returns the duration spent in the current phase.
bool setTrafficLightSignals(SUMOTime t) const
Applies the current signal states to controlled links.
virtual void addLink(MSLink *link, MSLane *lane, int pos)
Adds a link on building.
std::vector< MSPhaseDefinition * > Phases
Definition of a list of phases, being the junction logic.
const std::string & getID() const
Returns the id.
Definition Named.h:73
Static storage of an output device and its base (abstract) implementation.
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.
OutputDevice & writeAttr(const ATTR_TYPE &attr, const T &val, const bool isNull=false, const bool escape=false)
writes a named attribute
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
bool hasParameter(const std::string &key) const
Returns whether the parameter is set.
std::map< std::string, std::string > Map
parameters map
virtual const std::string getParameter(const std::string &key, const std::string defaultValue="") const
Returns the value for a given key.
static double toDouble(const std::string &sData)
converts a string into the double value described by it by calling the char-type converter
std::string startProg
The name of the start program.
std::vector< WAUTSwitch > switches
The list of switches to be done by the WAUT.
std::vector< WAUTJunction > junctions
The list of switches assigned to the WAUT.
SUMOTime period
The period with which to repeat switches.
std::string id
The id of the WAUT.
SUMOTime refTime
The reference time (offset to the switch times)
Storage for a junction assigned to a WAUT.
std::string procedure
The procedure to switch the junction with.
bool synchron
Information whether this junction shall be switched synchron.
std::string junction
The junction name.
Storage for a WAUTs switch point.
SUMOTime when
The time the WAUT shall switch the TLS.
std::string to
The program name the WAUT shall switch the TLS to.
double fac
The weight factor of a stretch/cut area.
An initialised switch process.
MSTrafficLightLogic * to
The program to switch the tls to.
std::string junction
The id of the junction to switch.
MSTrafficLightLogic * from
The current program of the tls.
WAUTSwitchProcedure * proc
The used procedure.