Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
eclipse
GitHub Repository: eclipse/sumo
Path: blob/main/tests/complex/tutorial/traci_pedestrian_crossing/runner.py
169685 views
1
#!/usr/bin/env python
2
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3
# Copyright (C) 2009-2025 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 runner.py
15
# @author Lena Kalleske
16
# @author Daniel Krajzewicz
17
# @author Michael Behrisch
18
# @author Jakob Erdmann
19
# @date 2009-03-26
20
21
"""
22
Tutorial for traffic light control via the TraCI interface.
23
This scenario models a pedestrian crossing which switches on demand.
24
"""
25
from __future__ import absolute_import
26
from __future__ import print_function
27
28
import os
29
import sys
30
import optparse
31
import subprocess
32
33
34
# the directory in which this script resides
35
THISDIR = os.path.dirname(__file__)
36
37
38
# we need to import python modules from the $SUMO_HOME/tools directory
39
# If the environment variable SUMO_HOME is not set, try to locate the python
40
# modules relative to this script
41
if 'SUMO_HOME' in os.environ:
42
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
43
sys.path.append(tools)
44
else:
45
sys.exit("please declare environment variable 'SUMO_HOME'")
46
import traci # noqa
47
from sumolib import checkBinary # noqa
48
import randomTrips # noqa
49
50
# minimum green time for the vehicles
51
MIN_GREEN_TIME = 15
52
# the first phase in tls plan. see 'pedcrossing.tll.xml'
53
VEHICLE_GREEN_PHASE = 0
54
PEDESTRIAN_GREEN_PHASE = 2
55
# the id of the traffic light (there is only one). This is identical to the
56
# id of the controlled intersection (by default)
57
TLSID = 'C'
58
59
# pedestrian edges at the controlled intersection
60
WALKINGAREAS = [':C_w0', ':C_w1']
61
CROSSINGS = [':C_c0']
62
63
64
def run():
65
"""execute the TraCI control loop"""
66
# track the duration for which the green phase of the vehicles has been
67
# active
68
greenTimeSoFar = 0
69
70
# whether the pedestrian button has been pressed
71
activeRequest = False
72
73
# main loop. do something every simulation step until no more vehicles are
74
# loaded or running
75
while traci.simulation.getMinExpectedNumber() > 0:
76
traci.simulationStep()
77
78
# decide wether there is a waiting pedestrian and switch if the green
79
# phase for the vehicles exceeds its minimum duration
80
if not activeRequest:
81
activeRequest = checkWaitingPersons()
82
if traci.trafficlight.getPhase(TLSID) == VEHICLE_GREEN_PHASE:
83
greenTimeSoFar += 1
84
if greenTimeSoFar > MIN_GREEN_TIME:
85
# check whether someone has pushed the button
86
87
if activeRequest:
88
# switch to the next phase
89
traci.trafficlight.setPhase(
90
TLSID, VEHICLE_GREEN_PHASE + 1)
91
# reset state
92
activeRequest = False
93
greenTimeSoFar = 0
94
95
sys.stdout.flush()
96
traci.close()
97
98
99
def checkWaitingPersons():
100
"""check whether a person has requested to cross the street"""
101
102
# check both sides of the crossing
103
for edge in WALKINGAREAS:
104
peds = traci.edge.getLastStepPersonIDs(edge)
105
# check who is waiting at the crossing
106
# we assume that pedestrians push the button upon
107
# standing still for 1s
108
for ped in peds:
109
if (traci.person.getWaitingTime(ped) == 1 and
110
traci.person.getNextEdge(ped) in CROSSINGS):
111
numWaiting = traci.trafficlight.getServedPersonCount(TLSID, PEDESTRIAN_GREEN_PHASE)
112
print("%s: pedestrian %s pushes the button (waiting: %s)" %
113
(traci.simulation.getTime(), ped, numWaiting))
114
return True
115
return False
116
117
118
def get_options():
119
"""define options for this script and interpret the command line"""
120
optParser = optparse.OptionParser()
121
optParser.add_option("--nogui", action="store_true",
122
default=False, help="run the commandline version of sumo")
123
options, args = optParser.parse_args()
124
return options
125
126
127
# this is the main entry point of this script
128
if __name__ == "__main__":
129
# load whether to run with or without GUI
130
options = get_options()
131
132
# this script has been called from the command line. It will start sumo as a
133
# server, then connect and run
134
if options.nogui:
135
sumoBinary = checkBinary('sumo')
136
else:
137
sumoBinary = checkBinary('sumo-gui')
138
139
net = 'pedcrossing.net.xml'
140
# build the multi-modal network from plain xml inputs
141
subprocess.call([checkBinary('netconvert'),
142
'-c', os.path.join('data', 'pedcrossing.netccfg'),
143
'--output-file', net],
144
stdout=sys.stdout, stderr=sys.stderr)
145
146
# generate the pedestrians for this simulation
147
randomTrips.main(randomTrips.get_options([
148
'--net-file', net,
149
'--output-trip-file', 'pedestrians.trip.xml',
150
'--seed', '42', # make runs reproducible
151
'--pedestrians',
152
'--prefix', 'ped',
153
# prevent trips that start and end on the same edge
154
'--min-distance', '1',
155
'--trip-attributes', 'departPos="random" arrivalPos="random"',
156
'--binomial', '4',
157
'--period', '35']))
158
159
# this is the normal way of using traci. sumo is started as a
160
# subprocess and then the python script connects and runs
161
traci.start([sumoBinary, '-c', os.path.join('data', 'run.sumocfg')])
162
run()
163
164