#To.xml
import pickle
def node_to_xml(node_df_path):
# 读取输出的data_deal.py 输出的rou_df文件
with open(node_df_path, "rb") as file1:
node_df = pickle.load(file1)
with open("node.txt", "w") as f:
f.write("<nodes>\r\n")
for _, row in node_df.iterrows():
f.write(" <node id=\""+str(row['id'])+"\" x=\""+str(row['x'])+"\" y=\""+str(row['y'])+"\" type=\""+row['type']+"\"/>\r")
f.write("\r</nodes>")
def edge_to_xml(edge_df_path):
with open(edge_df_path, "rb") as file2:
edge_df = pickle.load(file2)
with open("edge.txt", "w") as f:
f.write("<edges>\r\n")
for _, row in edge_df.iterrows():
f.write(" <edge id=\""+str(row['id'])+"\" from=\""+str(row['from'])+"\" to=\""+str(row['to'])+"\" numLanes=\""+str(row['numLanes'])+"\" speed=\""+str(row['speed'])+"\"/>\r")
f.write("\r</edges>")
def rou_to_xml(rou_df_path):
with open(rou_df_path, "rb") as file3:
edge_df = pickle.load(file3)
with open("rou.txt", "w") as f:
f.write("<routes>\r\n")
for _, row in edge_df.iterrows():
f.write(" <vehicle id=\""+str(row['id'])+"\" depart=\""+str(row['depart'])+"\">\r")
f.write(" <route edges=\"" + ' '.join(str(e) for e in row['route']) + "\"/>\r")
f.write(" </vehicle>\r")
f.write("\r</routes>")
if __name__ == '__main__':
node_df_path=('C:/Users/sutpc/Desktop/成果/data_deal.py/node/node.df')
node_to_xml(node_df_path)
edge_df_path=('C:/Users/sutpc/Desktop/成果/data_deal.py/edge/edge.df')
edge_to_xml(edge_df_path)
rou_df_path=('C:/Users/sutpc/Desktop/成果/data_deal.py/rou/df_rou1h.df')
rou_to_xml(rou_df_path)
上面的输入为node.df,edge.df,rou1h.df,里面的内容可以根据我们自己所需的字段进行填充、调整,上面输出的均是txt文件,可以选择将文件重命名手动转换成xml文件,也可以使用以下简单代码实习自动生成转换。
import os
import shutil # 复制文件的库
txtpath = r"C:\Users\sutpc\Desktop\Luzhou_project\Output-To_xml"
os.chdir(txtpath)
filelist = os.listdir(txtpath) # 该文件夹下所有的文件(包括文件夹)
print(filelist) # 文件夹中所有文件名
for v in filelist:
old = v # 旧文件名
_list = v.split('.')
new = 'map.' + _list[0] + '.xml' # 新文件名
shutil.copy(old, new) # 复制后命名
最终可以输出以下六个文件:
当然,最后还得对node.xml和edge.xml进行netconvert操作。cmd接口调用代码如下:
import os
os.system("cd")
os.system("cd C:\\Users\\sutpc\\Desktop\\Luzhou_project\\Output-To_xml")
net_xml=os.system("netconvert --node-files=map.node.xml --edge-files=map.edge.xml --output-file=map.net.xml")
其次是实现自动生成sumocfg文件,实现代码如下:
def get_sumocfg():
with open("C:/Users/sutpc/Desktop/Luzhou_project/Input-sumo_connect/map.sumocfg.txt", "w") as f:
f.write("<configuration>\r")
f.write(" <input>\r")
f.write(" <net-file value=\"map.net.xml\"/>\r")
f.write(" <route-files value=\"map.rou.xml\"/>\r")
f.write(" </input>\r")
f.write(" <time>\r")
f.write(" <begin value=\"0\"/>\r")
f.write(" <end value=\"360000\"/>\r")
f.write(" </time>\r")
f.write("</configuration>\r")
txtpath = r"C:\Users\sutpc\Desktop\Luzhou_project\Input-sumo_connect"
os.chdir(txtpath)
old="map.sumocfg.txt"
new="map.sumocfg"
shutil.copy(old, new)
最后调用sumo的python接口进行sumo仿真即可。