Sumo学习日记

之前经常使用sumo,但是网络上相关教程较少,且并没有行成系统的教学。官方文档教育效果很棒,但是对于想学习sumo这个软件的萌新来说好像有点不友好,所以在这里开一个专题 主要介绍sumo和traci的相关使用 同时也是自己学习的一个过程 如果有问题 欢迎交流。


文章目录

  • Sumo学习日记
  • 写在前面
  • 一、最简单的traci接口使用
  • 二、第一个traci程序
  • 三、仿真运行结果

写在前面

这个专题是假设你大致了解了sumo仿真的基本文件结构,如sumocfg 文件、rou.xml文件等。还需要知道xml文件的大致结构。


一、最简单的traci接口使用

traci是sumo基于java和python的一个接口,你可以使用pip install traci命令在你的python或者anaconda环境中添加traci。

如果你要使用traci,你需要在你的电脑环境变量中配置sumo的路径,配置环境变量不用多说,官方文档建议将变量名命名为SUMO_HOME ,最好按照官方文档配置变量名。

二、第一个traci程序

你可以在 sumo安装路径:\Sumo\doc\tutorial\traci_tls中找到一个名为runner.py的文件 详细代码如下:

#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2009-2021 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0/
# This Source Code may also be made available under the following Secondary
# Licenses when the conditions for such availability set forth in the Eclipse
# Public License 2.0 are satisfied: GNU General Public License, version 2
# or later which is available at
# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later# @file    runner.py
# @author  Lena Kalleske
# @author  Daniel Krajzewicz
# @author  Michael Behrisch
# @author  Jakob Erdmann
# @date    2009-03-26from __future__ import absolute_import
from __future__ import print_functionimport 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  # noqadef generate_routefile():random.seed(42)  # make tests reproducibleN = 3600  # number of time steps# demand per second from different directionspWE = 1. / 10pEW = 1. / 11pNS = 1. / 30with open(r"D:\Sumo\doc\tutorial\traci_tls\data\cross.rou.xml", "w") as routes: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="7" minGap="3" maxSpeed="25" guiShape="bus"/><route id="right" edges="51o 1i 2o 52i" /><route id="left" edges="52o 2i 1o 51i" /><route id="down" edges="54o 4i 3o 53i" />""", file=routes)vehNr = 0for 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 += 1if random.uniform(0, 1) < pEW:print('    <vehicle id="left_%i" type="typeWE" route="left" depart="%i" />' % (vehNr, i), file=routes)vehNr += 1if 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 += 1print("</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():"""execute the TraCI control loop"""step = 0# we start with phase 2 where EW has greentraci.trafficlight.setPhase("0", 2)while traci.simulation.getMinExpectedNumber() > 0:traci.simulationStep()if traci.trafficlight.getPhase("0") == 2:# we are not already switchingif traci.inductionloop.getLastStepVehicleNumber("0") > 0:# there is a vehicle from the north, switchtraci.trafficlight.setPhase("0", 3)else:# otherwise try to keep green for EWtraci.trafficlight.setPhase("0", 2)step += 1traci.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 runif options.nogui:sumoBinary = checkBinary('sumo')else:sumoBinary = checkBinary('sumo-gui')# first, generate the route file for this simulationgenerate_routefile()# this is the normal way of using traci. sumo is started as a# subprocess and then the python script connects and runstraci.start([sumoBinary, "-c", "D:/Sumo/doc/tutorial/traci_tls/data/cross.sumocfg","--tripinfo-output", "tripinfo.xml"])run()

如果你的环境变量且traci是配置好了的,这个脚本是可以直接跑的,下面将详细讲解每段代码的含义:

# 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'")

这里是查看你的sumo环境变量是否配置成功 如果代码报错在这里 请检查你的环境配置

def generate_routefile():random.seed(42)  # make tests reproducibleN = 3600  # number of time steps# demand per second from different directionspWE = 1. / 10pEW = 1. / 11pNS = 1. / 30with open(r"D:\Sumo\doc\tutorial\traci_tls\data\cross.rou.xml", "w") as routes: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="7" minGap="3" maxSpeed="25" guiShape="bus"/><route id="right" edges="51o 1i 2o 52i" /><route id="left" edges="52o 2i 1o 51i" /><route id="down" edges="54o 4i 3o 53i" />""", file=routes)vehNr = 0for 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 += 1if random.uniform(0, 1) < pEW:print('    <vehicle id="left_%i" type="typeWE" route="left" depart="%i" />' % (vehNr, i), file=routes)vehNr += 1if 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 += 1print("</routes>", file=routes)

这一段代码主要是通过对xml文件的操作,写入交叉口数据,其中< vType >标签表示vehicle type 即交通工具种类 xml的这个分支表示了 车辆id、加速度accel、减速度deccel、服从度(服从度指的是交通驾驶员服从交通规则的概率)sigma、车长length、最小间隙minGap、最大车速maxSpeed、图像显示类型guiShape。如下:

< vType id="typeNS" accel="0.8" decel="4.5" sigma="0.5" length="7" minGap="3" maxSpeed="25" guiShape="bus"/ >

然后< route >标签规定了道路的路径 edge表示道路边缘的id 如 edges=“51o 1i 2o 52i”
表示这个路径 从id为 51o -1i-2o-52i

def run():"""execute the TraCI control loop"""step = 0# 初始相位为两相位且东西为主路 traci.trafficlight.setPhase("0", 2)while traci.simulation.getMinExpectedNumber() > 0:traci.simulationStep()if traci.trafficlight.getPhase("0") == 2:# 尚未准备切换相位if traci.inductionloop.getLastStepVehicleNumber("0") > 0:# 北进口有来车 切换相位为南北放行traci.trafficlight.setPhase("0", 3)else:# 否则继续保持东西通行traci.trafficlight.setPhase("0", 2)step += 1traci.close()sys.stdout.flush()

这里是设置信号灯相位 初始相位为两相位且东西方向为绿灯(放行),这个循环的意义在于每当仿真步长走一步sumlationste判断南北方有无来车,以此达到感应控制的效果(感应控制不知道可以百度或者查看交通管理与控制这本书的相关部分),进而判断是否切断相位。

# 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 runif options.nogui:sumoBinary = checkBinary('sumo')else:sumoBinary = checkBinary('sumo-gui')# first, generate the route file for this simulationgenerate_routefile()# this is the normal way of using traci. sumo is started as a# subprocess and then the python script connects and runstraci.start([sumoBinary, "-c", "D:/Sumo/doc/tutorial/traci_tls/data/cross.sumocfg","--tripinfo-output", "tripinfo.xml"])run()

这是程序运行的主入口 没有什么好说明的

三、仿真运行结果


看懂代码之后可以自己修改代码 多试试。

Sumo学习日记 - day1 从traci开始相关推荐

  1. Python学习日记-day1基础篇 字符 输出 注释

    Python学习日记-day1基础篇 字符 输出 注释 by北栀一刺 # -*- coding: utf-8 -*- """ Spyder EditorThis is a ...

  2. 尚学堂Java学习日记Day1

    尚学堂学习日记Day1 #今天开始写学习博客记录自己学习java的点滴成长历程,希望能成为学弟学妹们的前车之鉴. 先大概的自我介绍下,我原本从事的是网络工程师,学习的是Cisco(思科)并拥有CCNP ...

  3. 爬虫学习日记 Day1 什么是request,respond,url,headers

    注:这些知识只是必要的前件知识,没有必要打破沙锅问到底,只需了解即可 前件知识: 1.request和respond request是爬虫向互联网发送请求,respond是互联网对爬虫的回应. 在我们 ...

  4. 阿昆同学的Java学习日记Day1

    学完了Java基础语法后,工作了一年的老哥准备把我搞到公司里头去,于是就让我看Javaweb的相关知识,跟着网课一步一步学到了开始需要实操的部分-Mysql数据库管理系统安装,别人偷懒说Mysql说成 ...

  5. 阿文的《Java从入门到精通(第二版)》学习日记DAY1

    目录 1️⃣前言: 2️⃣书籍:<Java从入门到精通(第二版)>张玉宏主编 3️⃣学习导图: 第0章 Java的学习指南 4️⃣学习笔记:

  6. Python学习日记 Day1

    写在前面 大一学了C语言和计算机网络,很多时候都是面向CSDN编程和找资料...这学期选了Python,突发奇想自己也应该在这平台上写点啥,一是督促自己好好学习,二是给自己留个纪念.至于启发别人什么的 ...

  7. java学习日记 day1

    前言 今天起学校带队去实训,实际上就是换个地方去上课啦,主要是学Java,老师让每天记录学习成果,想着既然要记录不如直接写个博客什么的,所以开坑 Java的基本操作 今天讲的主要是一些基本知识,我就不 ...

  8. JAVA学习日记DAY1

    基础概念 硬件:hardware 软件:software (microsoft) 操作系统: OS,operating system   裸机,类unix系统(linux<红旗,Redhat,. ...

  9. 微信小程序学习日记day1

    全局文件的设置 1.新增一个页面 当你想新建一个页面时,直接在app.json中加入page字段值,如图,保存后,系统自动创建一个页面 2.主界面设置 将主界面文件在app.json中page值放在最 ...

最新文章

  1. ZooKeeper学习
  2. Python 小程序(2)
  3. ubuntu交叉编译x264报错:‘X264_VERSION’ undeclared(已解决)运行version.sh
  4. 使用Apache配置Tomcat应用整合PHP论坛-Discuz
  5. MongoDB 字段拼接 $concat(aggregation)
  6. TensorFlow中读取图像数据的三种方式(转)
  7. js return 闭包为null_那么如何让你的 JS 写得更漂亮?
  8. splice方法_Array中splice用法
  9. 阿里云服务器ECS和腾讯云服务器如何安装宝塔面板?
  10. 从Linux服务用命令直接拿文件保存到本机
  11. Android 设置电话号码拦截(黑名单)
  12. Spring tool suite修改主题
  13. oracle修改dbf文件,如何修改Oracle的dbf文件位置
  14. python爬取b站搜索结果播放地址_Golang 爬虫快速入门 | 获取B站全站的视频数据
  15. 多线程基础之设计模式Guarded Suspension模式
  16. UNIX v6 fork()源码分析
  17. ngro_k服务器搭建(本地电脑与微信交互)
  18. c语言scandf用法,scan的用法总结大全
  19. EasyExcel 实践与源码梳理
  20. 无线网络技术——星链——三两问

热门文章

  1. 【热门主题:加勒比海盗桌面主题】
  2. 龙贝格观测器在PMSM无位置传感器控制上的运用详解
  3. 【天光学术】科学教育论文:幼儿园科学教育环境创设的原则与策略(节选)
  4. 从多个例子来看Ansys多点约束(MPC)的强大
  5. android手机刷ios6,管你iOS6还是WP8 市场Android强机盘点
  6. 关于网站推广的一些建议
  7. ESP8266--驱动DS18B20
  8. [iOS]NSArray:数组(NSArray)使用注意
  9. 大数据时代-使用关系型数据库的价值意义?
  10. 【毕业设计】基于微信小程序的备忘录记事助手