traci._trafficlight

  1# -*- coding: utf-8 -*-
  2# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
  3# Copyright (C) 2011-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
 14# @file    _trafficlight.py
 15# @author  Michael Behrisch
 16# @date    2011-03-16
 17
 18from __future__ import absolute_import
 19from sumolib.net import Phase
 20from .domain import Domain
 21from . import constants as tc
 22from .exceptions import TraCIException, deprecated, alias_param
 23
 24
 25class Logic:
 26
 27    def __init__(self, programID, type, currentPhaseIndex, phases=None, subParameter=None, offset=0.):
 28        """
 29        Constructs a new Logic object with the following arguments:
 30          programID (string) - arbitrary
 31          type (integer) - one of
 32             tc.TRAFFICLIGHT_TYPE_STATIC
 33             tc.TRAFFICLIGHT_TYPE_ACTUATED
 34             tc.TRAFFICLIGHT_TYPE_NEMA
 35             tc.TRAFFICLIGHT_TYPE_DELAYBASED
 36          currentPhaseIndex (integer) - must be in range [0, len(phases) - 1]
 37          phases (list of Phase objects)
 38          subParameter (dictl) - corresponds to generic <param> objects
 39          offset (float) - the program offset in seconds
 40        """
 41        self.programID = programID
 42        self.type = type
 43        self.currentPhaseIndex = currentPhaseIndex
 44        self.phases = phases if phases is not None else []
 45        self.subParameter = subParameter if subParameter is not None else {}
 46        self.offset = offset
 47
 48    def getPhases(self):
 49        return self.phases
 50
 51    def getSubID(self):
 52        return self.programID
 53
 54    def getType(self):
 55        return self.type
 56
 57    def getParameters(self):
 58        return self.subParameter
 59
 60    def getParameter(self, key, default=None):
 61        return self.subParameter.get(key, default)
 62
 63    def __repr__(self):
 64        return ("Logic(programID='%s', type=%s, currentPhaseIndex=%s, phases=%s, subParameter=%s)" %
 65                (self.programID, self.type, self.currentPhaseIndex, self.phases, self.subParameter))
 66
 67
 68def _readLogics(result):
 69    numLogics = result.readInt()
 70    logics = []
 71    for _ in range(numLogics):
 72        numElements = result.readCompound()
 73        programID = result.readTypedString()
 74        type = result.readTypedInt()
 75        currentPhaseIndex = result.readTypedInt()
 76        offset = result.readTypedDouble() if numElements == 6 else 0.
 77        numPhases = result.readCompound()
 78        phases = []
 79        for __ in range(numPhases):
 80            result.readCompound(6)
 81            duration = result.readTypedDouble()
 82            state = result.readTypedString()
 83            minDur = result.readTypedDouble()
 84            maxDur = result.readTypedDouble()
 85            numNext = result.readCompound()
 86            next = tuple([result.readTypedInt() for ___ in range(numNext)])
 87            name = result.readTypedString()
 88            phases.append(Phase(duration, state, minDur, maxDur, next, name))
 89        logic = Logic(programID, type, currentPhaseIndex, tuple(phases), offset=offset)
 90        numParams = result.readCompound()
 91        for __ in range(numParams):
 92            key, value = result.readTypedStringList()
 93            logic.subParameter[key] = value
 94        logics.append(logic)
 95    return tuple(logics)
 96
 97
 98class Constraint:
 99    def __init__(self, signalId, tripId, foeId, foeSignal, limit, type, mustWait, active=True, param={}):
100        self.signalId = signalId
101        self.tripId = tripId
102        self.foeId = foeId
103        self.foeSignal = foeSignal
104        self.limit = limit
105        self.type = type
106        self.mustWait = mustWait
107        self.active = active
108        self.param = param
109
110    def getParameters(self):
111        return self.param
112
113    def getParameter(self, key, default=None):
114        return self.param.get(key, default)
115
116    def __repr__(self):
117        param = ""
118        if self.param:
119            kvs = ["%s=%s" % (k, self.param[k]) for k in sorted(self.param.keys())]
120            param = " param=%s" % '|'.join(kvs)
121        return ("Constraint(signalId=%s tripId=%s, foeId=%s, foeSignal=%s, limit=%s, type=%s, mustWait=%s, active=%s%s)" %  # noqa
122                (self.signalId, self.tripId, self.foeId, self.foeSignal,
123                 self.limit, self.type, self.mustWait, self.active, param))
124
125
126def _readLinks(result):
127    result.readLength()
128    numSignals = result.readInt()  # Length
129    signals = []
130    for _ in range(numSignals):
131        # Type of Number of Controlled Links
132        result.read("!B")
133        # Number of Controlled Links
134        nbControlledLinks = result.read("!i")[0]
135        controlledLinks = []
136        for __ in range(nbControlledLinks):
137            result.read("!B")                       # Type of Link j
138            link = result.readStringList()          # Link j
139            controlledLinks.append(link)
140        signals.append(tuple(controlledLinks))
141    return tuple(signals)
142
143
144def _readConstraints(result):
145    result.readLength()
146    num = result.readInt()  # Length
147    constraints = []
148    for _ in range(num):
149        signalId = result.readTypedString()
150        tripId = result.readTypedString()
151        foeId = result.readTypedString()
152        foeSignal = result.readTypedString()
153        limit = result.readTypedInt()
154        type = result.readTypedInt()
155        mustWait = bool(result.readTypedByte())
156        active = bool(result.readTypedByte())
157        paramItems = result.readTypedStringList()
158        param = {}
159        for i in range(0, len(paramItems), 2):
160            param[paramItems[i]] = paramItems[i + 1]
161        constraints.append(Constraint(signalId, tripId, foeId, foeSignal, limit, type, mustWait, active, param))
162    return tuple(constraints)
163
164
165_RETURN_VALUE_FUNC = {tc.TL_COMPLETE_DEFINITION_RYG: _readLogics,
166                      tc.TL_CONTROLLED_LINKS: _readLinks,
167                      tc.TL_CONSTRAINT: _readConstraints,
168                      tc.TL_CONSTRAINT_BYFOE: _readConstraints,
169                      tc.TL_CONSTRAINT_SWAP: _readConstraints,
170                      }
171
172
173class TrafficLightDomain(Domain):
174
175    Phase = Phase
176    Logic = Logic
177
178    def __init__(self, name="trafficlight", deprecatedFor=None):
179        Domain.__init__(self, name, tc.CMD_GET_TL_VARIABLE, tc.CMD_SET_TL_VARIABLE,
180                        tc.CMD_SUBSCRIBE_TL_VARIABLE, tc.RESPONSE_SUBSCRIBE_TL_VARIABLE,
181                        tc.CMD_SUBSCRIBE_TL_CONTEXT, tc.RESPONSE_SUBSCRIBE_TL_CONTEXT,
182                        _RETURN_VALUE_FUNC, deprecatedFor)
183
184    def getRedYellowGreenState(self, tlsID):
185        """getRedYellowGreenState(string) -> string
186
187        Returns the named tl's state as a tuple of light definitions from
188        rugGyYoO, for red, yed-yellow, green, yellow, off, where lower case letters mean that the stream
189        has to decelerate.
190        """
191        return self._getUniversal(tc.TL_RED_YELLOW_GREEN_STATE, tlsID)
192
193    def getAllProgramLogics(self, tlsID):
194        """getAllProgramLogics(string) -> tuple(Logic)
195
196        Returns a tuple of Logic objects.
197        Each Logic encodes a traffic light program for the given tlsID.
198        """
199        return self._getUniversal(tc.TL_COMPLETE_DEFINITION_RYG, tlsID)
200
201    getCompleteRedYellowGreenDefinition = deprecated("getCompleteRedYellowGreenDefinition")(getAllProgramLogics)
202
203    def getControlledLanes(self, tlsID):
204        """getControlledLanes(string) -> tuple(string)
205
206        Returns the tuple of lanes which are controlled by the named traffic light.
207        """
208        return self._getUniversal(tc.TL_CONTROLLED_LANES, tlsID)
209
210    def getControlledLinks(self, tlsID):
211        """getControlledLinks(string) -> tuple(tuple(tuple(string)))
212
213        Returns the links controlled by the traffic light, sorted by the signal index and described by giving
214        the incoming, outgoing, and via lane.
215        """
216        return self._getUniversal(tc.TL_CONTROLLED_LINKS, tlsID)
217
218    def getProgram(self, tlsID):
219        """getProgram(string) -> string
220
221        Returns the id of the current program.
222        """
223        return self._getUniversal(tc.TL_CURRENT_PROGRAM, tlsID)
224
225    def getPhase(self, tlsID):
226        """getPhase(string) -> integer
227
228        Returns the index of the current phase within the list of all phases of
229        the current program.
230        """
231        return self._getUniversal(tc.TL_CURRENT_PHASE, tlsID)
232
233    def getPhaseName(self, tlsID):
234        """getPhaseName(string) -> string
235        Returns the name of the current phase.
236        """
237        return self._getUniversal(tc.VAR_NAME, tlsID)
238
239    def getNextSwitch(self, tlsID):
240        """getNextSwitch(string) -> double
241
242        Returns the absolute simulation time at which the traffic light is
243        schedule to switch to the next phase (in seconds).
244        """
245        return self._getUniversal(tc.TL_NEXT_SWITCH, tlsID)
246
247    def getSpentDuration(self, tlsID):
248        """getSpentDuration(string) -> double
249
250        Returns the time in seconds for which the current phase has been active
251        """
252        return self._getUniversal(tc.TL_SPENT_DURATION, tlsID)
253
254    def getPhaseDuration(self, tlsID):
255        """getPhaseDuration(string) -> double
256
257        Returns the total duration of the current phase (in seconds). This value
258        is not affected by the elapsed or remaining duration of the current phase.
259        """
260        return self._getUniversal(tc.TL_PHASE_DURATION, tlsID)
261
262    def getServedPersonCount(self, tlsID, index):
263        """getServedPersonCount(string, int) -> int
264        Returns the number of persons that would be served in the given phase
265        """
266        return self._getUniversal(tc.VAR_PERSON_NUMBER, tlsID, "i", index)
267
268    def getBlockingVehicles(self, tlsID, linkIndex):
269        """getBlockingVehicles(string, int) -> tuple(string)
270        Returns the tuple of vehicles that are blocking the subsequent block for
271        the given tls-linkIndex
272        """
273        return self._getUniversal(tc.TL_BLOCKING_VEHICLES, tlsID, "i", linkIndex)
274
275    def getRivalVehicles(self, tlsID, linkIndex):
276        """getRivalVehicles(string, int) -> tuple(string)
277        Returns the tuple of vehicles that also wish to enter the subsequent block for
278        the given tls-linkIndex (regardless of priority)
279        """
280        return self._getUniversal(tc.TL_RIVAL_VEHICLES, tlsID, "i", linkIndex)
281
282    def getPriorityVehicles(self, tlsID, linkIndex):
283        """getPriorityVehicles(string, int) -> tuple(string)
284        Returns the tuple of vehicles that also wish to enter the subsequent block for
285        the given tls-linkIndex (only those with higher priority)
286        """
287        return self._getUniversal(tc.TL_PRIORITY_VEHICLES, tlsID, "i", linkIndex)
288
289    def getConstraints(self, tlsID, tripId=""):
290        """getConstraints(string, string) -> tuple(Constraint)
291        Returns the tuple of rail signal constraints for the given rail signal.
292        If tripId is not "", only constraints with the given tripId are
293        returned. Otherwise, all constraints are returned
294        """
295        return self._getUniversal(tc.TL_CONSTRAINT, tlsID, "s", tripId)
296
297    def getConstraintsByFoe(self, foeSignal, foeId=""):
298        """getConstraintsByFoe(string, string) -> tuple(Constraint)
299        Returns the tuple of rail signal constraints that have the given rail
300        signal id as their foeSignal.
301        If foeId is not "", only constraints with the given foeId are
302        returned. Otherwise, all constraints are returned
303        """
304        return self._getUniversal(tc.TL_CONSTRAINT_BYFOE, foeSignal, "s", foeId)
305
306    def setRedYellowGreenState(self, tlsID, state):
307        """setRedYellowGreenState(string, string) -> None
308
309        Sets the named tl's state as a tuple of light definitions from
310        rugGyYuoO, for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has
311        to decelerate.
312        """
313        self._setCmd(tc.TL_RED_YELLOW_GREEN_STATE, tlsID, "s", state)
314
315    def setLinkState(self, tlsID, tlsLinkIndex, state):
316        """setLinkState(string, string, int, string) -> None
317        Sets the state for the given tls and link index. The state must be one
318        of rRgGyYoOu for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has
319        to decelerate.
320        The link index is shown in the GUI when setting the appropriate junction
321        visualization option.
322        """
323        fullState = list(self.getRedYellowGreenState(tlsID))
324        if tlsLinkIndex >= len(fullState):
325            raise TraCIException("Invalid tlsLinkIndex %s for tls '%s' with maximum index %s." % (
326                tlsLinkIndex, tlsID, len(fullState) - 1))
327        else:
328            fullState[tlsLinkIndex] = state
329            self.setRedYellowGreenState(tlsID, ''.join(fullState))
330
331    def setPhase(self, tlsID, index):
332        """setPhase(string, integer) -> None
333
334        Switches to the phase with the given index in the list of all phases for
335        the current program.
336        """
337        self._setCmd(tc.TL_PHASE_INDEX, tlsID, "i", index)
338
339    def setPhaseName(self, tlsID, name):
340        """setPhaseName(string, string) -> None
341
342        Sets the name of the current phase within the current program
343        """
344        self._setCmd(tc.VAR_NAME, tlsID, "s", name)
345
346    def setProgram(self, tlsID, programID):
347        """setProgram(string, string) -> None
348
349        Switches to the program with the given programID. The program must have
350        been loaded earlier. The special value 'off' can always be used to
351        switch off the traffic light.
352        """
353        self._setCmd(tc.TL_PROGRAM, tlsID, "s", programID)
354
355    def getNemaPhaseCalls(self, tlsID):
356        """getNemaPhaseCalls(string) -> tuple(string)
357        Get the vehicle calls for the phases.
358        The output is vehicle calls (coming from the detectors) for the phases.
359        """
360        vehCallStr = self.getParameter(tlsID, "NEMA.phaseCall")
361        return tuple(vehCallStr.split(","))
362
363    def setNemaSplits(self, tlsID, splits):
364        """setNemaSplits(string, list(string)) -> None
365        Set a new set of splits to the given NEMA-controller.
366        This function is only effective for NEMA type of controllers.
367        The new splits will be implemented in the next cycle of the control.
368        The value must be a space-separated list of 8 numbers with each number
369        being the time in seconds for NEMA-phases 1 to 8.
370        Time 0 must be used of the phase does not exists.
371        Example: “11.0 34.0 15.0 20.0 11.0 34.0 15.0 20.0" (gives total cycle length of 80s)
372        """
373        if isinstance(splits, list):
374            splits = ' '.join(map(str, splits))
375        self.setParameter(tlsID, "NEMA.splits", splits)
376
377    def setNemaMaxGreens(self, tlsID, maxGreens):
378        """setNemaMaxGreens(string, list(string)) -> None
379        Set a new set of splits to the given NEMA-controller.
380        This function is only effective for NEMA type of controllers.
381        The new max green will be implemented in the next cycle of the control.
382        The value must be a space-separated list of 8 numbers with each number
383        being the time in seconds for NEMA-phases 1 to 8.
384        Time 0 must be used of the phase does not exists.
385        Example: “11.0 34.0 15.0 20.0 11.0 34.0 15.0 20.0"
386        """
387        if isinstance(maxGreens, list):
388            maxGreens = ' '.join(map(str, maxGreens))
389        self.setParameter(tlsID, "NEMA.maxGreens", maxGreens)
390
391    def setNemaCycleLength(self, tlsID, cycleLength):
392        """setNemaCycleLength(string, double) -> None
393        Set a new cycle length to the given NEMA-controller.
394        This function is only effective for NEMA type of controllers.
395        The new cycle length will be implemented in the next cycle of the control.
396        This function should be used with setNemaSplits or setNemaMaxGreen.
397        """
398        self.setParameter(tlsID, "NEMA.cycleLength", str(cycleLength))
399
400    def setNemaOffset(self, tlsID, offset):
401        """setNemaOffset(string, double) -> None
402        Set a new offset to the given NEMA-controller.
403        This function is only effective for NEMA type controllers when operating under coordinated mode.
404        The new offset will be implemented in the next cycle of the control by adjusting
405        the actual green time of the coordinated phase.
406        There is no transition implemented in the NEMA-controller for changing the offset.
407        It’s expected that the users will control the change of the offset in each cycle
408        to implement their own transition algorithm.
409        """
410        self.setParameter(tlsID, "NEMA.offset", str(offset))
411
412    def setPhaseDuration(self, tlsID, phaseDuration):
413        """setPhaseDuration(string, double) -> None
414
415        Set the remaining phase duration of the current phase in seconds.
416        This value has no effect on subsquent repetitions of this phase.
417        """
418        self._setCmd(tc.TL_PHASE_DURATION, tlsID, "d", phaseDuration)
419
420    @alias_param("logic", "tls")
421    def setProgramLogic(self, tlsID, logic):
422        """setProgramLogic(string, Logic) -> None
423
424        Sets a new program for the given tlsID from a Logic object.
425        See getAllProgramLogics which returns a tuple of Logic objects.
426        """
427        withOffset = logic.offset != 0.
428        format = "tsiidt" if withOffset else "tsiit"
429        values = [6 if withOffset else 5, logic.programID, logic.type,
430                  logic.currentPhaseIndex]
431        if withOffset:
432            values.append(logic.offset)
433        values.append(len(logic.phases))
434        for p in logic.phases:
435            format += "tdsddt"
436            values += [6, p.duration, p.state, p.minDur, p.maxDur, len(p.next)]
437            for n in p.next:
438                format += "i"
439                values += [n]
440            format += "s"
441            values += [p.name]
442        # subparams
443        format += "t"
444        values += [len(logic.subParameter)]
445        for par in logic.subParameter.items():
446            format += "l"
447            values += [par]
448        self._setCmd(tc.TL_COMPLETE_PROGRAM_RYG, tlsID, format, *values)
449
450    setCompleteRedYellowGreenDefinition = deprecated("setCompleteRedYellowGreenDefinition")(setProgramLogic)
451
452    def addConstraint(self, tlsID, tripId, foeSignal, foeId, type=0, limit=0):
453        """addConstraint(string, string, string, string, int, int) -> None
454        Add the given constraint.
455        """
456        self._setCmd(tc.TL_CONSTRAINT_ADD, tlsID, "tsssii", 5, tripId, foeSignal, foeId, type, limit)
457
458    def swapConstraints(self, tlsID, tripId, foeSignal, foeId):
459        """swapConstraints(string, string, string, string) -> tuple(Constraint)
460        Reverse the given constraint and return a tuple of new constraints that
461        were created (by swapping) to avoid deadlock.
462        """
463        return self._getUniversal(tc.TL_CONSTRAINT_SWAP, tlsID, "tsss", 3, tripId, foeSignal, foeId)
464
465    def removeConstraints(self, tlsID, tripId, foeSignal, foeId):
466        """removeConstraints(string, string, string, string)
467        remove constraints with the given values. Any combination of inputs may
468        be set to "" to act as a wildcard filter """
469        self._setCmd(tc.TL_CONSTRAINT_REMOVE, tlsID, "tsss", 3, tripId, foeSignal, foeId)
470
471    def updateConstraints(self, vehID, tripId=""):
472        """getConstraints(string, string)
473        Removes all constraints that can no longer be met because the route of
474        vehID does not pass traffic light of the constraint with the given tripId.
475        This includes constraints on tripId as well as constraints where tripId
476        is the foeId.
477        If tripId is "", the current tripId of vehID is used.
478        """
479        self._setCmd(tc.TL_CONSTRAINT_UPDATE, vehID, "s", tripId)
class Logic:
26class Logic:
27
28    def __init__(self, programID, type, currentPhaseIndex, phases=None, subParameter=None, offset=0.):
29        """
30        Constructs a new Logic object with the following arguments:
31          programID (string) - arbitrary
32          type (integer) - one of
33             tc.TRAFFICLIGHT_TYPE_STATIC
34             tc.TRAFFICLIGHT_TYPE_ACTUATED
35             tc.TRAFFICLIGHT_TYPE_NEMA
36             tc.TRAFFICLIGHT_TYPE_DELAYBASED
37          currentPhaseIndex (integer) - must be in range [0, len(phases) - 1]
38          phases (list of Phase objects)
39          subParameter (dictl) - corresponds to generic <param> objects
40          offset (float) - the program offset in seconds
41        """
42        self.programID = programID
43        self.type = type
44        self.currentPhaseIndex = currentPhaseIndex
45        self.phases = phases if phases is not None else []
46        self.subParameter = subParameter if subParameter is not None else {}
47        self.offset = offset
48
49    def getPhases(self):
50        return self.phases
51
52    def getSubID(self):
53        return self.programID
54
55    def getType(self):
56        return self.type
57
58    def getParameters(self):
59        return self.subParameter
60
61    def getParameter(self, key, default=None):
62        return self.subParameter.get(key, default)
63
64    def __repr__(self):
65        return ("Logic(programID='%s', type=%s, currentPhaseIndex=%s, phases=%s, subParameter=%s)" %
66                (self.programID, self.type, self.currentPhaseIndex, self.phases, self.subParameter))
Logic( programID, type, currentPhaseIndex, phases=None, subParameter=None, offset=0.0)
28    def __init__(self, programID, type, currentPhaseIndex, phases=None, subParameter=None, offset=0.):
29        """
30        Constructs a new Logic object with the following arguments:
31          programID (string) - arbitrary
32          type (integer) - one of
33             tc.TRAFFICLIGHT_TYPE_STATIC
34             tc.TRAFFICLIGHT_TYPE_ACTUATED
35             tc.TRAFFICLIGHT_TYPE_NEMA
36             tc.TRAFFICLIGHT_TYPE_DELAYBASED
37          currentPhaseIndex (integer) - must be in range [0, len(phases) - 1]
38          phases (list of Phase objects)
39          subParameter (dictl) - corresponds to generic <param> objects
40          offset (float) - the program offset in seconds
41        """
42        self.programID = programID
43        self.type = type
44        self.currentPhaseIndex = currentPhaseIndex
45        self.phases = phases if phases is not None else []
46        self.subParameter = subParameter if subParameter is not None else {}
47        self.offset = offset

Constructs a new Logic object with the following arguments: programID (string) - arbitrary type (integer) - one of tc.TRAFFICLIGHT_TYPE_STATIC tc.TRAFFICLIGHT_TYPE_ACTUATED tc.TRAFFICLIGHT_TYPE_NEMA tc.TRAFFICLIGHT_TYPE_DELAYBASED currentPhaseIndex (integer) - must be in range [0, len(phases) - 1] phases (list of Phase objects) subParameter (dictl) - corresponds to generic objects offset (float) - the program offset in seconds

programID
type
currentPhaseIndex
phases
subParameter
offset
def getPhases(self):
49    def getPhases(self):
50        return self.phases
def getSubID(self):
52    def getSubID(self):
53        return self.programID
def getType(self):
55    def getType(self):
56        return self.type
def getParameters(self):
58    def getParameters(self):
59        return self.subParameter
def getParameter(self, key, default=None):
61    def getParameter(self, key, default=None):
62        return self.subParameter.get(key, default)
class Constraint:
 99class Constraint:
100    def __init__(self, signalId, tripId, foeId, foeSignal, limit, type, mustWait, active=True, param={}):
101        self.signalId = signalId
102        self.tripId = tripId
103        self.foeId = foeId
104        self.foeSignal = foeSignal
105        self.limit = limit
106        self.type = type
107        self.mustWait = mustWait
108        self.active = active
109        self.param = param
110
111    def getParameters(self):
112        return self.param
113
114    def getParameter(self, key, default=None):
115        return self.param.get(key, default)
116
117    def __repr__(self):
118        param = ""
119        if self.param:
120            kvs = ["%s=%s" % (k, self.param[k]) for k in sorted(self.param.keys())]
121            param = " param=%s" % '|'.join(kvs)
122        return ("Constraint(signalId=%s tripId=%s, foeId=%s, foeSignal=%s, limit=%s, type=%s, mustWait=%s, active=%s%s)" %  # noqa
123                (self.signalId, self.tripId, self.foeId, self.foeSignal,
124                 self.limit, self.type, self.mustWait, self.active, param))
Constraint( signalId, tripId, foeId, foeSignal, limit, type, mustWait, active=True, param={})
100    def __init__(self, signalId, tripId, foeId, foeSignal, limit, type, mustWait, active=True, param={}):
101        self.signalId = signalId
102        self.tripId = tripId
103        self.foeId = foeId
104        self.foeSignal = foeSignal
105        self.limit = limit
106        self.type = type
107        self.mustWait = mustWait
108        self.active = active
109        self.param = param
signalId
tripId
foeId
foeSignal
limit
type
mustWait
active
param
def getParameters(self):
111    def getParameters(self):
112        return self.param
def getParameter(self, key, default=None):
114    def getParameter(self, key, default=None):
115        return self.param.get(key, default)
class TrafficLightDomain(traci.domain.Domain):
174class TrafficLightDomain(Domain):
175
176    Phase = Phase
177    Logic = Logic
178
179    def __init__(self, name="trafficlight", deprecatedFor=None):
180        Domain.__init__(self, name, tc.CMD_GET_TL_VARIABLE, tc.CMD_SET_TL_VARIABLE,
181                        tc.CMD_SUBSCRIBE_TL_VARIABLE, tc.RESPONSE_SUBSCRIBE_TL_VARIABLE,
182                        tc.CMD_SUBSCRIBE_TL_CONTEXT, tc.RESPONSE_SUBSCRIBE_TL_CONTEXT,
183                        _RETURN_VALUE_FUNC, deprecatedFor)
184
185    def getRedYellowGreenState(self, tlsID):
186        """getRedYellowGreenState(string) -> string
187
188        Returns the named tl's state as a tuple of light definitions from
189        rugGyYoO, for red, yed-yellow, green, yellow, off, where lower case letters mean that the stream
190        has to decelerate.
191        """
192        return self._getUniversal(tc.TL_RED_YELLOW_GREEN_STATE, tlsID)
193
194    def getAllProgramLogics(self, tlsID):
195        """getAllProgramLogics(string) -> tuple(Logic)
196
197        Returns a tuple of Logic objects.
198        Each Logic encodes a traffic light program for the given tlsID.
199        """
200        return self._getUniversal(tc.TL_COMPLETE_DEFINITION_RYG, tlsID)
201
202    getCompleteRedYellowGreenDefinition = deprecated("getCompleteRedYellowGreenDefinition")(getAllProgramLogics)
203
204    def getControlledLanes(self, tlsID):
205        """getControlledLanes(string) -> tuple(string)
206
207        Returns the tuple of lanes which are controlled by the named traffic light.
208        """
209        return self._getUniversal(tc.TL_CONTROLLED_LANES, tlsID)
210
211    def getControlledLinks(self, tlsID):
212        """getControlledLinks(string) -> tuple(tuple(tuple(string)))
213
214        Returns the links controlled by the traffic light, sorted by the signal index and described by giving
215        the incoming, outgoing, and via lane.
216        """
217        return self._getUniversal(tc.TL_CONTROLLED_LINKS, tlsID)
218
219    def getProgram(self, tlsID):
220        """getProgram(string) -> string
221
222        Returns the id of the current program.
223        """
224        return self._getUniversal(tc.TL_CURRENT_PROGRAM, tlsID)
225
226    def getPhase(self, tlsID):
227        """getPhase(string) -> integer
228
229        Returns the index of the current phase within the list of all phases of
230        the current program.
231        """
232        return self._getUniversal(tc.TL_CURRENT_PHASE, tlsID)
233
234    def getPhaseName(self, tlsID):
235        """getPhaseName(string) -> string
236        Returns the name of the current phase.
237        """
238        return self._getUniversal(tc.VAR_NAME, tlsID)
239
240    def getNextSwitch(self, tlsID):
241        """getNextSwitch(string) -> double
242
243        Returns the absolute simulation time at which the traffic light is
244        schedule to switch to the next phase (in seconds).
245        """
246        return self._getUniversal(tc.TL_NEXT_SWITCH, tlsID)
247
248    def getSpentDuration(self, tlsID):
249        """getSpentDuration(string) -> double
250
251        Returns the time in seconds for which the current phase has been active
252        """
253        return self._getUniversal(tc.TL_SPENT_DURATION, tlsID)
254
255    def getPhaseDuration(self, tlsID):
256        """getPhaseDuration(string) -> double
257
258        Returns the total duration of the current phase (in seconds). This value
259        is not affected by the elapsed or remaining duration of the current phase.
260        """
261        return self._getUniversal(tc.TL_PHASE_DURATION, tlsID)
262
263    def getServedPersonCount(self, tlsID, index):
264        """getServedPersonCount(string, int) -> int
265        Returns the number of persons that would be served in the given phase
266        """
267        return self._getUniversal(tc.VAR_PERSON_NUMBER, tlsID, "i", index)
268
269    def getBlockingVehicles(self, tlsID, linkIndex):
270        """getBlockingVehicles(string, int) -> tuple(string)
271        Returns the tuple of vehicles that are blocking the subsequent block for
272        the given tls-linkIndex
273        """
274        return self._getUniversal(tc.TL_BLOCKING_VEHICLES, tlsID, "i", linkIndex)
275
276    def getRivalVehicles(self, tlsID, linkIndex):
277        """getRivalVehicles(string, int) -> tuple(string)
278        Returns the tuple of vehicles that also wish to enter the subsequent block for
279        the given tls-linkIndex (regardless of priority)
280        """
281        return self._getUniversal(tc.TL_RIVAL_VEHICLES, tlsID, "i", linkIndex)
282
283    def getPriorityVehicles(self, tlsID, linkIndex):
284        """getPriorityVehicles(string, int) -> tuple(string)
285        Returns the tuple of vehicles that also wish to enter the subsequent block for
286        the given tls-linkIndex (only those with higher priority)
287        """
288        return self._getUniversal(tc.TL_PRIORITY_VEHICLES, tlsID, "i", linkIndex)
289
290    def getConstraints(self, tlsID, tripId=""):
291        """getConstraints(string, string) -> tuple(Constraint)
292        Returns the tuple of rail signal constraints for the given rail signal.
293        If tripId is not "", only constraints with the given tripId are
294        returned. Otherwise, all constraints are returned
295        """
296        return self._getUniversal(tc.TL_CONSTRAINT, tlsID, "s", tripId)
297
298    def getConstraintsByFoe(self, foeSignal, foeId=""):
299        """getConstraintsByFoe(string, string) -> tuple(Constraint)
300        Returns the tuple of rail signal constraints that have the given rail
301        signal id as their foeSignal.
302        If foeId is not "", only constraints with the given foeId are
303        returned. Otherwise, all constraints are returned
304        """
305        return self._getUniversal(tc.TL_CONSTRAINT_BYFOE, foeSignal, "s", foeId)
306
307    def setRedYellowGreenState(self, tlsID, state):
308        """setRedYellowGreenState(string, string) -> None
309
310        Sets the named tl's state as a tuple of light definitions from
311        rugGyYuoO, for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has
312        to decelerate.
313        """
314        self._setCmd(tc.TL_RED_YELLOW_GREEN_STATE, tlsID, "s", state)
315
316    def setLinkState(self, tlsID, tlsLinkIndex, state):
317        """setLinkState(string, string, int, string) -> None
318        Sets the state for the given tls and link index. The state must be one
319        of rRgGyYoOu for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has
320        to decelerate.
321        The link index is shown in the GUI when setting the appropriate junction
322        visualization option.
323        """
324        fullState = list(self.getRedYellowGreenState(tlsID))
325        if tlsLinkIndex >= len(fullState):
326            raise TraCIException("Invalid tlsLinkIndex %s for tls '%s' with maximum index %s." % (
327                tlsLinkIndex, tlsID, len(fullState) - 1))
328        else:
329            fullState[tlsLinkIndex] = state
330            self.setRedYellowGreenState(tlsID, ''.join(fullState))
331
332    def setPhase(self, tlsID, index):
333        """setPhase(string, integer) -> None
334
335        Switches to the phase with the given index in the list of all phases for
336        the current program.
337        """
338        self._setCmd(tc.TL_PHASE_INDEX, tlsID, "i", index)
339
340    def setPhaseName(self, tlsID, name):
341        """setPhaseName(string, string) -> None
342
343        Sets the name of the current phase within the current program
344        """
345        self._setCmd(tc.VAR_NAME, tlsID, "s", name)
346
347    def setProgram(self, tlsID, programID):
348        """setProgram(string, string) -> None
349
350        Switches to the program with the given programID. The program must have
351        been loaded earlier. The special value 'off' can always be used to
352        switch off the traffic light.
353        """
354        self._setCmd(tc.TL_PROGRAM, tlsID, "s", programID)
355
356    def getNemaPhaseCalls(self, tlsID):
357        """getNemaPhaseCalls(string) -> tuple(string)
358        Get the vehicle calls for the phases.
359        The output is vehicle calls (coming from the detectors) for the phases.
360        """
361        vehCallStr = self.getParameter(tlsID, "NEMA.phaseCall")
362        return tuple(vehCallStr.split(","))
363
364    def setNemaSplits(self, tlsID, splits):
365        """setNemaSplits(string, list(string)) -> None
366        Set a new set of splits to the given NEMA-controller.
367        This function is only effective for NEMA type of controllers.
368        The new splits will be implemented in the next cycle of the control.
369        The value must be a space-separated list of 8 numbers with each number
370        being the time in seconds for NEMA-phases 1 to 8.
371        Time 0 must be used of the phase does not exists.
372        Example: “11.0 34.0 15.0 20.0 11.0 34.0 15.0 20.0" (gives total cycle length of 80s)
373        """
374        if isinstance(splits, list):
375            splits = ' '.join(map(str, splits))
376        self.setParameter(tlsID, "NEMA.splits", splits)
377
378    def setNemaMaxGreens(self, tlsID, maxGreens):
379        """setNemaMaxGreens(string, list(string)) -> None
380        Set a new set of splits to the given NEMA-controller.
381        This function is only effective for NEMA type of controllers.
382        The new max green will be implemented in the next cycle of the control.
383        The value must be a space-separated list of 8 numbers with each number
384        being the time in seconds for NEMA-phases 1 to 8.
385        Time 0 must be used of the phase does not exists.
386        Example: “11.0 34.0 15.0 20.0 11.0 34.0 15.0 20.0"
387        """
388        if isinstance(maxGreens, list):
389            maxGreens = ' '.join(map(str, maxGreens))
390        self.setParameter(tlsID, "NEMA.maxGreens", maxGreens)
391
392    def setNemaCycleLength(self, tlsID, cycleLength):
393        """setNemaCycleLength(string, double) -> None
394        Set a new cycle length to the given NEMA-controller.
395        This function is only effective for NEMA type of controllers.
396        The new cycle length will be implemented in the next cycle of the control.
397        This function should be used with setNemaSplits or setNemaMaxGreen.
398        """
399        self.setParameter(tlsID, "NEMA.cycleLength", str(cycleLength))
400
401    def setNemaOffset(self, tlsID, offset):
402        """setNemaOffset(string, double) -> None
403        Set a new offset to the given NEMA-controller.
404        This function is only effective for NEMA type controllers when operating under coordinated mode.
405        The new offset will be implemented in the next cycle of the control by adjusting
406        the actual green time of the coordinated phase.
407        There is no transition implemented in the NEMA-controller for changing the offset.
408        It’s expected that the users will control the change of the offset in each cycle
409        to implement their own transition algorithm.
410        """
411        self.setParameter(tlsID, "NEMA.offset", str(offset))
412
413    def setPhaseDuration(self, tlsID, phaseDuration):
414        """setPhaseDuration(string, double) -> None
415
416        Set the remaining phase duration of the current phase in seconds.
417        This value has no effect on subsquent repetitions of this phase.
418        """
419        self._setCmd(tc.TL_PHASE_DURATION, tlsID, "d", phaseDuration)
420
421    @alias_param("logic", "tls")
422    def setProgramLogic(self, tlsID, logic):
423        """setProgramLogic(string, Logic) -> None
424
425        Sets a new program for the given tlsID from a Logic object.
426        See getAllProgramLogics which returns a tuple of Logic objects.
427        """
428        withOffset = logic.offset != 0.
429        format = "tsiidt" if withOffset else "tsiit"
430        values = [6 if withOffset else 5, logic.programID, logic.type,
431                  logic.currentPhaseIndex]
432        if withOffset:
433            values.append(logic.offset)
434        values.append(len(logic.phases))
435        for p in logic.phases:
436            format += "tdsddt"
437            values += [6, p.duration, p.state, p.minDur, p.maxDur, len(p.next)]
438            for n in p.next:
439                format += "i"
440                values += [n]
441            format += "s"
442            values += [p.name]
443        # subparams
444        format += "t"
445        values += [len(logic.subParameter)]
446        for par in logic.subParameter.items():
447            format += "l"
448            values += [par]
449        self._setCmd(tc.TL_COMPLETE_PROGRAM_RYG, tlsID, format, *values)
450
451    setCompleteRedYellowGreenDefinition = deprecated("setCompleteRedYellowGreenDefinition")(setProgramLogic)
452
453    def addConstraint(self, tlsID, tripId, foeSignal, foeId, type=0, limit=0):
454        """addConstraint(string, string, string, string, int, int) -> None
455        Add the given constraint.
456        """
457        self._setCmd(tc.TL_CONSTRAINT_ADD, tlsID, "tsssii", 5, tripId, foeSignal, foeId, type, limit)
458
459    def swapConstraints(self, tlsID, tripId, foeSignal, foeId):
460        """swapConstraints(string, string, string, string) -> tuple(Constraint)
461        Reverse the given constraint and return a tuple of new constraints that
462        were created (by swapping) to avoid deadlock.
463        """
464        return self._getUniversal(tc.TL_CONSTRAINT_SWAP, tlsID, "tsss", 3, tripId, foeSignal, foeId)
465
466    def removeConstraints(self, tlsID, tripId, foeSignal, foeId):
467        """removeConstraints(string, string, string, string)
468        remove constraints with the given values. Any combination of inputs may
469        be set to "" to act as a wildcard filter """
470        self._setCmd(tc.TL_CONSTRAINT_REMOVE, tlsID, "tsss", 3, tripId, foeSignal, foeId)
471
472    def updateConstraints(self, vehID, tripId=""):
473        """getConstraints(string, string)
474        Removes all constraints that can no longer be met because the route of
475        vehID does not pass traffic light of the constraint with the given tripId.
476        This includes constraints on tripId as well as constraints where tripId
477        is the foeId.
478        If tripId is "", the current tripId of vehID is used.
479        """
480        self._setCmd(tc.TL_CONSTRAINT_UPDATE, vehID, "s", tripId)
TrafficLightDomain(name='trafficlight', deprecatedFor=None)
179    def __init__(self, name="trafficlight", deprecatedFor=None):
180        Domain.__init__(self, name, tc.CMD_GET_TL_VARIABLE, tc.CMD_SET_TL_VARIABLE,
181                        tc.CMD_SUBSCRIBE_TL_VARIABLE, tc.RESPONSE_SUBSCRIBE_TL_VARIABLE,
182                        tc.CMD_SUBSCRIBE_TL_CONTEXT, tc.RESPONSE_SUBSCRIBE_TL_CONTEXT,
183                        _RETURN_VALUE_FUNC, deprecatedFor)
def getRedYellowGreenState(self, tlsID):
185    def getRedYellowGreenState(self, tlsID):
186        """getRedYellowGreenState(string) -> string
187
188        Returns the named tl's state as a tuple of light definitions from
189        rugGyYoO, for red, yed-yellow, green, yellow, off, where lower case letters mean that the stream
190        has to decelerate.
191        """
192        return self._getUniversal(tc.TL_RED_YELLOW_GREEN_STATE, tlsID)

getRedYellowGreenState(string) -> string

Returns the named tl's state as a tuple of light definitions from rugGyYoO, for red, yed-yellow, green, yellow, off, where lower case letters mean that the stream has to decelerate.

def getAllProgramLogics(self, tlsID):
194    def getAllProgramLogics(self, tlsID):
195        """getAllProgramLogics(string) -> tuple(Logic)
196
197        Returns a tuple of Logic objects.
198        Each Logic encodes a traffic light program for the given tlsID.
199        """
200        return self._getUniversal(tc.TL_COMPLETE_DEFINITION_RYG, tlsID)

getAllProgramLogics(string) -> tuple(Logic)

Returns a tuple of Logic objects. Each Logic encodes a traffic light program for the given tlsID.

def getCompleteRedYellowGreenDefinition(self, tlsID):
194    def getAllProgramLogics(self, tlsID):
195        """getAllProgramLogics(string) -> tuple(Logic)
196
197        Returns a tuple of Logic objects.
198        Each Logic encodes a traffic light program for the given tlsID.
199        """
200        return self._getUniversal(tc.TL_COMPLETE_DEFINITION_RYG, tlsID)

getAllProgramLogics(string) -> tuple(Logic)

Returns a tuple of Logic objects. Each Logic encodes a traffic light program for the given tlsID.

def getControlledLanes(self, tlsID):
204    def getControlledLanes(self, tlsID):
205        """getControlledLanes(string) -> tuple(string)
206
207        Returns the tuple of lanes which are controlled by the named traffic light.
208        """
209        return self._getUniversal(tc.TL_CONTROLLED_LANES, tlsID)

getControlledLanes(string) -> tuple(string)

Returns the tuple of lanes which are controlled by the named traffic light.

def getProgram(self, tlsID):
219    def getProgram(self, tlsID):
220        """getProgram(string) -> string
221
222        Returns the id of the current program.
223        """
224        return self._getUniversal(tc.TL_CURRENT_PROGRAM, tlsID)

getProgram(string) -> string

Returns the id of the current program.

def getPhase(self, tlsID):
226    def getPhase(self, tlsID):
227        """getPhase(string) -> integer
228
229        Returns the index of the current phase within the list of all phases of
230        the current program.
231        """
232        return self._getUniversal(tc.TL_CURRENT_PHASE, tlsID)

getPhase(string) -> integer

Returns the index of the current phase within the list of all phases of the current program.

def getPhaseName(self, tlsID):
234    def getPhaseName(self, tlsID):
235        """getPhaseName(string) -> string
236        Returns the name of the current phase.
237        """
238        return self._getUniversal(tc.VAR_NAME, tlsID)

getPhaseName(string) -> string Returns the name of the current phase.

def getNextSwitch(self, tlsID):
240    def getNextSwitch(self, tlsID):
241        """getNextSwitch(string) -> double
242
243        Returns the absolute simulation time at which the traffic light is
244        schedule to switch to the next phase (in seconds).
245        """
246        return self._getUniversal(tc.TL_NEXT_SWITCH, tlsID)

getNextSwitch(string) -> double

Returns the absolute simulation time at which the traffic light is schedule to switch to the next phase (in seconds).

def getSpentDuration(self, tlsID):
248    def getSpentDuration(self, tlsID):
249        """getSpentDuration(string) -> double
250
251        Returns the time in seconds for which the current phase has been active
252        """
253        return self._getUniversal(tc.TL_SPENT_DURATION, tlsID)

getSpentDuration(string) -> double

Returns the time in seconds for which the current phase has been active

def getPhaseDuration(self, tlsID):
255    def getPhaseDuration(self, tlsID):
256        """getPhaseDuration(string) -> double
257
258        Returns the total duration of the current phase (in seconds). This value
259        is not affected by the elapsed or remaining duration of the current phase.
260        """
261        return self._getUniversal(tc.TL_PHASE_DURATION, tlsID)

getPhaseDuration(string) -> double

Returns the total duration of the current phase (in seconds). This value is not affected by the elapsed or remaining duration of the current phase.

def getServedPersonCount(self, tlsID, index):
263    def getServedPersonCount(self, tlsID, index):
264        """getServedPersonCount(string, int) -> int
265        Returns the number of persons that would be served in the given phase
266        """
267        return self._getUniversal(tc.VAR_PERSON_NUMBER, tlsID, "i", index)

getServedPersonCount(string, int) -> int Returns the number of persons that would be served in the given phase

def getBlockingVehicles(self, tlsID, linkIndex):
269    def getBlockingVehicles(self, tlsID, linkIndex):
270        """getBlockingVehicles(string, int) -> tuple(string)
271        Returns the tuple of vehicles that are blocking the subsequent block for
272        the given tls-linkIndex
273        """
274        return self._getUniversal(tc.TL_BLOCKING_VEHICLES, tlsID, "i", linkIndex)

getBlockingVehicles(string, int) -> tuple(string) Returns the tuple of vehicles that are blocking the subsequent block for the given tls-linkIndex

def getRivalVehicles(self, tlsID, linkIndex):
276    def getRivalVehicles(self, tlsID, linkIndex):
277        """getRivalVehicles(string, int) -> tuple(string)
278        Returns the tuple of vehicles that also wish to enter the subsequent block for
279        the given tls-linkIndex (regardless of priority)
280        """
281        return self._getUniversal(tc.TL_RIVAL_VEHICLES, tlsID, "i", linkIndex)

getRivalVehicles(string, int) -> tuple(string) Returns the tuple of vehicles that also wish to enter the subsequent block for the given tls-linkIndex (regardless of priority)

def getPriorityVehicles(self, tlsID, linkIndex):
283    def getPriorityVehicles(self, tlsID, linkIndex):
284        """getPriorityVehicles(string, int) -> tuple(string)
285        Returns the tuple of vehicles that also wish to enter the subsequent block for
286        the given tls-linkIndex (only those with higher priority)
287        """
288        return self._getUniversal(tc.TL_PRIORITY_VEHICLES, tlsID, "i", linkIndex)

getPriorityVehicles(string, int) -> tuple(string) Returns the tuple of vehicles that also wish to enter the subsequent block for the given tls-linkIndex (only those with higher priority)

def getConstraints(self, tlsID, tripId=''):
290    def getConstraints(self, tlsID, tripId=""):
291        """getConstraints(string, string) -> tuple(Constraint)
292        Returns the tuple of rail signal constraints for the given rail signal.
293        If tripId is not "", only constraints with the given tripId are
294        returned. Otherwise, all constraints are returned
295        """
296        return self._getUniversal(tc.TL_CONSTRAINT, tlsID, "s", tripId)

getConstraints(string, string) -> tuple(Constraint) Returns the tuple of rail signal constraints for the given rail signal. If tripId is not "", only constraints with the given tripId are returned. Otherwise, all constraints are returned

def getConstraintsByFoe(self, foeSignal, foeId=''):
298    def getConstraintsByFoe(self, foeSignal, foeId=""):
299        """getConstraintsByFoe(string, string) -> tuple(Constraint)
300        Returns the tuple of rail signal constraints that have the given rail
301        signal id as their foeSignal.
302        If foeId is not "", only constraints with the given foeId are
303        returned. Otherwise, all constraints are returned
304        """
305        return self._getUniversal(tc.TL_CONSTRAINT_BYFOE, foeSignal, "s", foeId)

getConstraintsByFoe(string, string) -> tuple(Constraint) Returns the tuple of rail signal constraints that have the given rail signal id as their foeSignal. If foeId is not "", only constraints with the given foeId are returned. Otherwise, all constraints are returned

def setRedYellowGreenState(self, tlsID, state):
307    def setRedYellowGreenState(self, tlsID, state):
308        """setRedYellowGreenState(string, string) -> None
309
310        Sets the named tl's state as a tuple of light definitions from
311        rugGyYuoO, for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has
312        to decelerate.
313        """
314        self._setCmd(tc.TL_RED_YELLOW_GREEN_STATE, tlsID, "s", state)

setRedYellowGreenState(string, string) -> None

Sets the named tl's state as a tuple of light definitions from rugGyYuoO, for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has to decelerate.

def setLinkState(self, tlsID, tlsLinkIndex, state):
316    def setLinkState(self, tlsID, tlsLinkIndex, state):
317        """setLinkState(string, string, int, string) -> None
318        Sets the state for the given tls and link index. The state must be one
319        of rRgGyYoOu for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has
320        to decelerate.
321        The link index is shown in the GUI when setting the appropriate junction
322        visualization option.
323        """
324        fullState = list(self.getRedYellowGreenState(tlsID))
325        if tlsLinkIndex >= len(fullState):
326            raise TraCIException("Invalid tlsLinkIndex %s for tls '%s' with maximum index %s." % (
327                tlsLinkIndex, tlsID, len(fullState) - 1))
328        else:
329            fullState[tlsLinkIndex] = state
330            self.setRedYellowGreenState(tlsID, ''.join(fullState))

setLinkState(string, string, int, string) -> None Sets the state for the given tls and link index. The state must be one of rRgGyYoOu for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has to decelerate. The link index is shown in the GUI when setting the appropriate junction visualization option.

def setPhase(self, tlsID, index):
332    def setPhase(self, tlsID, index):
333        """setPhase(string, integer) -> None
334
335        Switches to the phase with the given index in the list of all phases for
336        the current program.
337        """
338        self._setCmd(tc.TL_PHASE_INDEX, tlsID, "i", index)

setPhase(string, integer) -> None

Switches to the phase with the given index in the list of all phases for the current program.

def setPhaseName(self, tlsID, name):
340    def setPhaseName(self, tlsID, name):
341        """setPhaseName(string, string) -> None
342
343        Sets the name of the current phase within the current program
344        """
345        self._setCmd(tc.VAR_NAME, tlsID, "s", name)

setPhaseName(string, string) -> None

Sets the name of the current phase within the current program

def setProgram(self, tlsID, programID):
347    def setProgram(self, tlsID, programID):
348        """setProgram(string, string) -> None
349
350        Switches to the program with the given programID. The program must have
351        been loaded earlier. The special value 'off' can always be used to
352        switch off the traffic light.
353        """
354        self._setCmd(tc.TL_PROGRAM, tlsID, "s", programID)

setProgram(string, string) -> None

Switches to the program with the given programID. The program must have been loaded earlier. The special value 'off' can always be used to switch off the traffic light.

def getNemaPhaseCalls(self, tlsID):
356    def getNemaPhaseCalls(self, tlsID):
357        """getNemaPhaseCalls(string) -> tuple(string)
358        Get the vehicle calls for the phases.
359        The output is vehicle calls (coming from the detectors) for the phases.
360        """
361        vehCallStr = self.getParameter(tlsID, "NEMA.phaseCall")
362        return tuple(vehCallStr.split(","))

getNemaPhaseCalls(string) -> tuple(string) Get the vehicle calls for the phases. The output is vehicle calls (coming from the detectors) for the phases.

def setNemaSplits(self, tlsID, splits):
364    def setNemaSplits(self, tlsID, splits):
365        """setNemaSplits(string, list(string)) -> None
366        Set a new set of splits to the given NEMA-controller.
367        This function is only effective for NEMA type of controllers.
368        The new splits will be implemented in the next cycle of the control.
369        The value must be a space-separated list of 8 numbers with each number
370        being the time in seconds for NEMA-phases 1 to 8.
371        Time 0 must be used of the phase does not exists.
372        Example: “11.0 34.0 15.0 20.0 11.0 34.0 15.0 20.0" (gives total cycle length of 80s)
373        """
374        if isinstance(splits, list):
375            splits = ' '.join(map(str, splits))
376        self.setParameter(tlsID, "NEMA.splits", splits)

setNemaSplits(string, list(string)) -> None Set a new set of splits to the given NEMA-controller. This function is only effective for NEMA type of controllers. The new splits will be implemented in the next cycle of the control. The value must be a space-separated list of 8 numbers with each number being the time in seconds for NEMA-phases 1 to 8. Time 0 must be used of the phase does not exists. Example: “11.0 34.0 15.0 20.0 11.0 34.0 15.0 20.0" (gives total cycle length of 80s)

def setNemaMaxGreens(self, tlsID, maxGreens):
378    def setNemaMaxGreens(self, tlsID, maxGreens):
379        """setNemaMaxGreens(string, list(string)) -> None
380        Set a new set of splits to the given NEMA-controller.
381        This function is only effective for NEMA type of controllers.
382        The new max green will be implemented in the next cycle of the control.
383        The value must be a space-separated list of 8 numbers with each number
384        being the time in seconds for NEMA-phases 1 to 8.
385        Time 0 must be used of the phase does not exists.
386        Example: “11.0 34.0 15.0 20.0 11.0 34.0 15.0 20.0"
387        """
388        if isinstance(maxGreens, list):
389            maxGreens = ' '.join(map(str, maxGreens))
390        self.setParameter(tlsID, "NEMA.maxGreens", maxGreens)

setNemaMaxGreens(string, list(string)) -> None Set a new set of splits to the given NEMA-controller. This function is only effective for NEMA type of controllers. The new max green will be implemented in the next cycle of the control. The value must be a space-separated list of 8 numbers with each number being the time in seconds for NEMA-phases 1 to 8. Time 0 must be used of the phase does not exists. Example: “11.0 34.0 15.0 20.0 11.0 34.0 15.0 20.0"

def setNemaCycleLength(self, tlsID, cycleLength):
392    def setNemaCycleLength(self, tlsID, cycleLength):
393        """setNemaCycleLength(string, double) -> None
394        Set a new cycle length to the given NEMA-controller.
395        This function is only effective for NEMA type of controllers.
396        The new cycle length will be implemented in the next cycle of the control.
397        This function should be used with setNemaSplits or setNemaMaxGreen.
398        """
399        self.setParameter(tlsID, "NEMA.cycleLength", str(cycleLength))

setNemaCycleLength(string, double) -> None Set a new cycle length to the given NEMA-controller. This function is only effective for NEMA type of controllers. The new cycle length will be implemented in the next cycle of the control. This function should be used with setNemaSplits or setNemaMaxGreen.

def setNemaOffset(self, tlsID, offset):
401    def setNemaOffset(self, tlsID, offset):
402        """setNemaOffset(string, double) -> None
403        Set a new offset to the given NEMA-controller.
404        This function is only effective for NEMA type controllers when operating under coordinated mode.
405        The new offset will be implemented in the next cycle of the control by adjusting
406        the actual green time of the coordinated phase.
407        There is no transition implemented in the NEMA-controller for changing the offset.
408        It’s expected that the users will control the change of the offset in each cycle
409        to implement their own transition algorithm.
410        """
411        self.setParameter(tlsID, "NEMA.offset", str(offset))

setNemaOffset(string, double) -> None Set a new offset to the given NEMA-controller. This function is only effective for NEMA type controllers when operating under coordinated mode. The new offset will be implemented in the next cycle of the control by adjusting the actual green time of the coordinated phase. There is no transition implemented in the NEMA-controller for changing the offset. It’s expected that the users will control the change of the offset in each cycle to implement their own transition algorithm.

def setPhaseDuration(self, tlsID, phaseDuration):
413    def setPhaseDuration(self, tlsID, phaseDuration):
414        """setPhaseDuration(string, double) -> None
415
416        Set the remaining phase duration of the current phase in seconds.
417        This value has no effect on subsquent repetitions of this phase.
418        """
419        self._setCmd(tc.TL_PHASE_DURATION, tlsID, "d", phaseDuration)

setPhaseDuration(string, double) -> None

Set the remaining phase duration of the current phase in seconds. This value has no effect on subsquent repetitions of this phase.

@alias_param('logic', 'tls')
def setProgramLogic(self, tlsID, logic):
421    @alias_param("logic", "tls")
422    def setProgramLogic(self, tlsID, logic):
423        """setProgramLogic(string, Logic) -> None
424
425        Sets a new program for the given tlsID from a Logic object.
426        See getAllProgramLogics which returns a tuple of Logic objects.
427        """
428        withOffset = logic.offset != 0.
429        format = "tsiidt" if withOffset else "tsiit"
430        values = [6 if withOffset else 5, logic.programID, logic.type,
431                  logic.currentPhaseIndex]
432        if withOffset:
433            values.append(logic.offset)
434        values.append(len(logic.phases))
435        for p in logic.phases:
436            format += "tdsddt"
437            values += [6, p.duration, p.state, p.minDur, p.maxDur, len(p.next)]
438            for n in p.next:
439                format += "i"
440                values += [n]
441            format += "s"
442            values += [p.name]
443        # subparams
444        format += "t"
445        values += [len(logic.subParameter)]
446        for par in logic.subParameter.items():
447            format += "l"
448            values += [par]
449        self._setCmd(tc.TL_COMPLETE_PROGRAM_RYG, tlsID, format, *values)

setProgramLogic(string, Logic) -> None

Sets a new program for the given tlsID from a Logic object. See getAllProgramLogics which returns a tuple of Logic objects.

@alias_param('logic', 'tls')
def setCompleteRedYellowGreenDefinition(self, tlsID, logic):
421    @alias_param("logic", "tls")
422    def setProgramLogic(self, tlsID, logic):
423        """setProgramLogic(string, Logic) -> None
424
425        Sets a new program for the given tlsID from a Logic object.
426        See getAllProgramLogics which returns a tuple of Logic objects.
427        """
428        withOffset = logic.offset != 0.
429        format = "tsiidt" if withOffset else "tsiit"
430        values = [6 if withOffset else 5, logic.programID, logic.type,
431                  logic.currentPhaseIndex]
432        if withOffset:
433            values.append(logic.offset)
434        values.append(len(logic.phases))
435        for p in logic.phases:
436            format += "tdsddt"
437            values += [6, p.duration, p.state, p.minDur, p.maxDur, len(p.next)]
438            for n in p.next:
439                format += "i"
440                values += [n]
441            format += "s"
442            values += [p.name]
443        # subparams
444        format += "t"
445        values += [len(logic.subParameter)]
446        for par in logic.subParameter.items():
447            format += "l"
448            values += [par]
449        self._setCmd(tc.TL_COMPLETE_PROGRAM_RYG, tlsID, format, *values)

setProgramLogic(string, Logic) -> None

Sets a new program for the given tlsID from a Logic object. See getAllProgramLogics which returns a tuple of Logic objects.

def addConstraint(self, tlsID, tripId, foeSignal, foeId, type=0, limit=0):
453    def addConstraint(self, tlsID, tripId, foeSignal, foeId, type=0, limit=0):
454        """addConstraint(string, string, string, string, int, int) -> None
455        Add the given constraint.
456        """
457        self._setCmd(tc.TL_CONSTRAINT_ADD, tlsID, "tsssii", 5, tripId, foeSignal, foeId, type, limit)

addConstraint(string, string, string, string, int, int) -> None Add the given constraint.

def swapConstraints(self, tlsID, tripId, foeSignal, foeId):
459    def swapConstraints(self, tlsID, tripId, foeSignal, foeId):
460        """swapConstraints(string, string, string, string) -> tuple(Constraint)
461        Reverse the given constraint and return a tuple of new constraints that
462        were created (by swapping) to avoid deadlock.
463        """
464        return self._getUniversal(tc.TL_CONSTRAINT_SWAP, tlsID, "tsss", 3, tripId, foeSignal, foeId)

swapConstraints(string, string, string, string) -> tuple(Constraint) Reverse the given constraint and return a tuple of new constraints that were created (by swapping) to avoid deadlock.

def removeConstraints(self, tlsID, tripId, foeSignal, foeId):
466    def removeConstraints(self, tlsID, tripId, foeSignal, foeId):
467        """removeConstraints(string, string, string, string)
468        remove constraints with the given values. Any combination of inputs may
469        be set to "" to act as a wildcard filter """
470        self._setCmd(tc.TL_CONSTRAINT_REMOVE, tlsID, "tsss", 3, tripId, foeSignal, foeId)

removeConstraints(string, string, string, string) remove constraints with the given values. Any combination of inputs may be set to "" to act as a wildcard filter

def updateConstraints(self, vehID, tripId=''):
472    def updateConstraints(self, vehID, tripId=""):
473        """getConstraints(string, string)
474        Removes all constraints that can no longer be met because the route of
475        vehID does not pass traffic light of the constraint with the given tripId.
476        This includes constraints on tripId as well as constraints where tripId
477        is the foeId.
478        If tripId is "", the current tripId of vehID is used.
479        """
480        self._setCmd(tc.TL_CONSTRAINT_UPDATE, vehID, "s", tripId)

getConstraints(string, string) Removes all constraints that can no longer be met because the route of vehID does not pass traffic light of the constraint with the given tripId. This includes constraints on tripId as well as constraints where tripId is the foeId. If tripId is "", the current tripId of vehID is used.

class TrafficLightDomain.Phase:
118class Phase:
119
120    def __init__(self, duration, state, minDur=None, maxDur=None, next=tuple(), name="", earlyTarget=""):
121        """
122        Constructs a traffic light phase
123        duration (float): the duration of the phase in seconds
124        state (string): the state codes for each controlled link
125        minDur (float): the minimum duration (ignored by static tls)
126        maxDur (float): the maximum duration (ignored by static tls)
127        next (intList): possible succesor phase (optional)
128        name (string): the name of the phase
129        earlyTarget (string): early switching to phase with the given index(es)
130        """
131        self.duration = duration
132        self.state = state
133        # minimum and maximum duration (only for actuated tls)
134        self.minDur = minDur if minDur is not None else duration
135        self.maxDur = maxDur if maxDur is not None else duration
136        self.next = next
137        self.name = name
138        self.earlyTarget = earlyTarget
139
140    def __repr__(self):
141        name = (", name='%s'" % self.name) if self.name else ""
142        next = (", next='%s'" % str(self.next)) if self.next else ""
143        earlyTarget = (", earlyTarget='%s'" % self.earlyTarget) if self.earlyTarget else ""
144        return ("Phase(duration=%s, state='%s', minDur=%s, maxDur=%s%s%s%s)"
145                % (self.duration, self.state, self.minDur, self.maxDur, name, next, earlyTarget))
class TrafficLightDomain.Logic:
26class Logic:
27
28    def __init__(self, programID, type, currentPhaseIndex, phases=None, subParameter=None, offset=0.):
29        """
30        Constructs a new Logic object with the following arguments:
31          programID (string) - arbitrary
32          type (integer) - one of
33             tc.TRAFFICLIGHT_TYPE_STATIC
34             tc.TRAFFICLIGHT_TYPE_ACTUATED
35             tc.TRAFFICLIGHT_TYPE_NEMA
36             tc.TRAFFICLIGHT_TYPE_DELAYBASED
37          currentPhaseIndex (integer) - must be in range [0, len(phases) - 1]
38          phases (list of Phase objects)
39          subParameter (dictl) - corresponds to generic <param> objects
40          offset (float) - the program offset in seconds
41        """
42        self.programID = programID
43        self.type = type
44        self.currentPhaseIndex = currentPhaseIndex
45        self.phases = phases if phases is not None else []
46        self.subParameter = subParameter if subParameter is not None else {}
47        self.offset = offset
48
49    def getPhases(self):
50        return self.phases
51
52    def getSubID(self):
53        return self.programID
54
55    def getType(self):
56        return self.type
57
58    def getParameters(self):
59        return self.subParameter
60
61    def getParameter(self, key, default=None):
62        return self.subParameter.get(key, default)
63
64    def __repr__(self):
65        return ("Logic(programID='%s', type=%s, currentPhaseIndex=%s, phases=%s, subParameter=%s)" %
66                (self.programID, self.type, self.currentPhaseIndex, self.phases, self.subParameter))