Path: blob/main/tests/complex/tutorial/traci_pedestrian_crossing/runner.py
169685 views
#!/usr/bin/env python1# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo2# Copyright (C) 2009-2025 German Aerospace Center (DLR) and others.3# This program and the accompanying materials are made available under the4# terms of the Eclipse Public License 2.0 which is available at5# https://www.eclipse.org/legal/epl-2.0/6# This Source Code may also be made available under the following Secondary7# Licenses when the conditions for such availability set forth in the Eclipse8# Public License 2.0 are satisfied: GNU General Public License, version 29# or later which is available at10# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html11# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later1213# @file runner.py14# @author Lena Kalleske15# @author Daniel Krajzewicz16# @author Michael Behrisch17# @author Jakob Erdmann18# @date 2009-03-261920"""21Tutorial for traffic light control via the TraCI interface.22This scenario models a pedestrian crossing which switches on demand.23"""24from __future__ import absolute_import25from __future__ import print_function2627import os28import sys29import optparse30import subprocess313233# the directory in which this script resides34THISDIR = os.path.dirname(__file__)353637# we need to import python modules from the $SUMO_HOME/tools directory38# If the environment variable SUMO_HOME is not set, try to locate the python39# modules relative to this script40if 'SUMO_HOME' in os.environ:41tools = os.path.join(os.environ['SUMO_HOME'], 'tools')42sys.path.append(tools)43else:44sys.exit("please declare environment variable 'SUMO_HOME'")45import traci # noqa46from sumolib import checkBinary # noqa47import randomTrips # noqa4849# minimum green time for the vehicles50MIN_GREEN_TIME = 1551# the first phase in tls plan. see 'pedcrossing.tll.xml'52VEHICLE_GREEN_PHASE = 053PEDESTRIAN_GREEN_PHASE = 254# the id of the traffic light (there is only one). This is identical to the55# id of the controlled intersection (by default)56TLSID = 'C'5758# pedestrian edges at the controlled intersection59WALKINGAREAS = [':C_w0', ':C_w1']60CROSSINGS = [':C_c0']616263def run():64"""execute the TraCI control loop"""65# track the duration for which the green phase of the vehicles has been66# active67greenTimeSoFar = 06869# whether the pedestrian button has been pressed70activeRequest = False7172# main loop. do something every simulation step until no more vehicles are73# loaded or running74while traci.simulation.getMinExpectedNumber() > 0:75traci.simulationStep()7677# decide wether there is a waiting pedestrian and switch if the green78# phase for the vehicles exceeds its minimum duration79if not activeRequest:80activeRequest = checkWaitingPersons()81if traci.trafficlight.getPhase(TLSID) == VEHICLE_GREEN_PHASE:82greenTimeSoFar += 183if greenTimeSoFar > MIN_GREEN_TIME:84# check whether someone has pushed the button8586if activeRequest:87# switch to the next phase88traci.trafficlight.setPhase(89TLSID, VEHICLE_GREEN_PHASE + 1)90# reset state91activeRequest = False92greenTimeSoFar = 09394sys.stdout.flush()95traci.close()969798def checkWaitingPersons():99"""check whether a person has requested to cross the street"""100101# check both sides of the crossing102for edge in WALKINGAREAS:103peds = traci.edge.getLastStepPersonIDs(edge)104# check who is waiting at the crossing105# we assume that pedestrians push the button upon106# standing still for 1s107for ped in peds:108if (traci.person.getWaitingTime(ped) == 1 and109traci.person.getNextEdge(ped) in CROSSINGS):110numWaiting = traci.trafficlight.getServedPersonCount(TLSID, PEDESTRIAN_GREEN_PHASE)111print("%s: pedestrian %s pushes the button (waiting: %s)" %112(traci.simulation.getTime(), ped, numWaiting))113return True114return False115116117def get_options():118"""define options for this script and interpret the command line"""119optParser = optparse.OptionParser()120optParser.add_option("--nogui", action="store_true",121default=False, help="run the commandline version of sumo")122options, args = optParser.parse_args()123return options124125126# this is the main entry point of this script127if __name__ == "__main__":128# load whether to run with or without GUI129options = get_options()130131# this script has been called from the command line. It will start sumo as a132# server, then connect and run133if options.nogui:134sumoBinary = checkBinary('sumo')135else:136sumoBinary = checkBinary('sumo-gui')137138net = 'pedcrossing.net.xml'139# build the multi-modal network from plain xml inputs140subprocess.call([checkBinary('netconvert'),141'-c', os.path.join('data', 'pedcrossing.netccfg'),142'--output-file', net],143stdout=sys.stdout, stderr=sys.stderr)144145# generate the pedestrians for this simulation146randomTrips.main(randomTrips.get_options([147'--net-file', net,148'--output-trip-file', 'pedestrians.trip.xml',149'--seed', '42', # make runs reproducible150'--pedestrians',151'--prefix', 'ped',152# prevent trips that start and end on the same edge153'--min-distance', '1',154'--trip-attributes', 'departPos="random" arrivalPos="random"',155'--binomial', '4',156'--period', '35']))157158# this is the normal way of using traci. sumo is started as a159# subprocess and then the python script connects and runs160traci.start([sumoBinary, '-c', os.path.join('data', 'run.sumocfg')])161run()162163164