交通

  

#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2009-2018 German Aerospace Center (DLR) and others.
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v2.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v20.html
# SPDX-License-Identifier: EPL-2.0

# @file    runner.py
# @author  Lena Kalleske
# @author  Daniel Krajzewicz
# @author  Michael Behrisch
# @author  Jakob Erdmann
# @date    2009-03-26
# @version $Id$

from __future__ import absolute_import
from __future__ import print_function

import os
import sys
import optparse
import random

# we need to import python modules from the $SUMO_HOME/tools directory
if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")

from sumolib import checkBinary  # noqa
import traci  # noqa


def generate_routefile():
    random.seed(42)  # make tests reproducible
    N = 3600  # number of time steps,ʵ���ʱ�䳤��.
    # demand per second from different directions
    '''
    加入方向pSN    1/n  表示1s来几个车.1/10表示 1小时来360个车
    '''
    pWE = 1. / 10
    pEW = 1. / 10
    pNS = 1. / 10
    pSN = 1. / 10
    with open("data/cross.rou.xml", "w") as routes:
        #开始写的是车辆信息,之后<route>这行写的是车流信息,其中sigma参数表示车辆的不确定性.一般0.5会波动一下模拟更真实.如果是0表示完全定死的车辆运动,不包含任何随机.其中参数length表示车头到车尾,车本身的长度,minGap表示排队时(standing in a jam)前车的屁股跟后车的车头之间的距离.


        #下面路线里面写个字母o和i是什么意思?是路线的名字.写路线名字,不要写node名字
        # depart:
        # Determines the time at which the vehicle enters the network (for <flow the value of begin is used instead). If there is not enough space in the network, the actual depart time may be later.
        #下面print里面参数写的是file所以就不会在python终端输出字符.而直接写入文件.
        print("""<routes>
        <vType id="typeWE" accel="0.8" decel="4.5" sigma="0.5" length="5" minGap="2.5" maxSpeed="16.67" \
guiShape="passenger"/>
        <vType id="typeNS" accel="0.8" decel="4.5" sigma="0.5" length="5" minGap="2.5" maxSpeed="16.67" guiShape="passenger"/>



        <route id="right" edges="51o 1i 2o 52i" />
        <route id="left" edges="52o 2i 1o 51i" />
        <route id="down" edges="54o 4i 3o 53i" />
        <route id="up" edges="53o 3i 4o 54i" />""", file=routes)
        vehNr = 0
        for i in range(N):
            if random.uniform(0, 1) < pWE:
                print('    <vehicle id="right_%i" type="typeWE" route="right" depart="%i" />' % (
                    vehNr, i), file=routes)
                vehNr += 1
            if random.uniform(0, 1) < pEW:
                print('    <vehicle id="left_%i" type="typeWE" route="left" depart="%i" />' % (
                    vehNr, i), file=routes)
                vehNr += 1
            if random.uniform(0, 1) < pNS:
                print('    <vehicle id="down_%i" type="typeNS" route="down" depart="%i" color="1,0,0"/>' % (
                    vehNr, i), file=routes)
                vehNr += 1
            if random.uniform(0, 1) < pSN:
                print('    <vehicle id="up_%i" type="typeNS" route="up" depart="%i" color="1,0,0"/>' % (
                    vehNr, i), file=routes)
                vehNr += 1
        print("</routes>", file=routes)

# The program looks like this
#    <tlLogic id="0" type="static" programID="0" offset="0">
# the locations of the tls are      NESW
#        <phase duration="31" state="GrGr"/>
#        <phase duration="6"  state="yryr"/>
#        <phase duration="31" state="rGrG"/>
#        <phase duration="6"  state="ryry"/>
#    </tlLogic>


def run():
    '''
    这个模型交通灯的id是"0",traci.trafficlight.setPhase("0", 2)
    里面的参数是第一个是id这里就锁定是0了,第二个是index
    '''
    """execute the TraCI control loop"""
    step = 0#表示的是时间
    # we start with phase 2 where EW has green
    traci.trafficlight.setPhase("0", 2)
    print('开始')
    #print((traci.inductionloop.getIDList()))  只有一个元素'0' 类型tuple
    #print((traci.inductionloop.getPosition('0')))  

    '''
    模型里面中间的圆圈叫'0',是感应圈.
    '''
 







    while traci.simulation.getMinExpectedNumber() > 0:
        #循环体写这个while里面.
        '''
        traci.simulation.getMinExpectedNumber:
        Returns the number of vehicles which are in the net plus the
        ones still waiting to start.
        '''
        traci.simulationStep()
        #print((traci.inductionloop.getPosition('0'))) 
        
        #move 1s for stimulation
        #print(traci.trafficlight.getPhase("0"))#在python终端会输出.0,1,2,3表示信号灯4种信号
        '''
        0状态表示左右通行,--------上下绿 
        1状态表示左右黄灯,---------上下变黄
        2状态表示上下通行,     -------左右绿
        3状态表示上下黄灯,
        
        '''
        print((traci.trafficlight.getPhase('0')))
        if traci.trafficlight.getPhase("0") == 2:#if 信号灯状态在2
            # we are not already switching
            '''
            getLastStepVehicleNumber:
            Returns the number of vehicles that were on the named induction loop within the last simulation step.
            也就是返回传递参数这个id这个induction loop中上一个step中的汽车数量.


所以induction loop只识别
 On the approach in the north we have an induction loop to recognize entering vehicles.
            下行表示,如果


            induction loop只识别从上到下的车辆.
            '''
            #print(traci.inductionloop.getLastStepVehicleNumber("0")) 这行打印之后都是0和1的数字,
            #如果是1就表示当前时间这1s正好感应圈中有一个车.
            '''
            
            '''
            if traci.inductionloop.getLastStepVehicleNumber("0") > 0:#??????????why?表示当上一秒是否有车辆通过,如果有车辆通过,那么就设置为状态3:上下黄灯.
                # there is a vehicle from the north, switch
                traci.trafficlight.setPhase("0", 3)
            else:
                # otherwise try to keep green for EW
                traci.trafficlight.setPhase("0", 2)
        step += 1
    
    print(step)
    traci.close()
    sys.stdout.flush()


def get_options():
    optParser = optparse.OptionParser()
    optParser.add_option("--nogui", action="store_true",
                         default=False, help="run the commandline version of sumo")
    options, args = optParser.parse_args()
    return options


# this is the main entry point of this script
if __name__ == "__main__":
    options = get_options()

    # this script has been called from the command line. It will start sumo as a
    # server, then connect and run
    if options.nogui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    # first, generate the route file for this simulation
    generate_routefile()

    # this is the normal way of using traci. sumo is started as a
    # subprocess and then the python script connects and runs
    traci.start([sumoBinary, "-c", "data/cross.sumocfg",
                             "--tripinfo-output", "tripinfo.xml"])
    run()

 

posted on 2018-12-03 20:10  张博的博客  阅读(595)  评论(0编辑  收藏  举报

导航