openx.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Mar 14 15:44:01 2022
  5. @author: lxj
  6. """
  7. import xml.etree.ElementTree as ET
  8. from scenariogeneration import xodr
  9. from scenariogeneration import xosc
  10. from scenariogeneration import ScenarioGenerator
  11. from scenariogeneration.xodr import RoadSide, Object, ObjectType, Dynamic, Orientation
  12. import math, os
  13. from xodr_generator2 import road_detector_new
  14. from datetime import datetime
  15. import traceback
  16. import json
  17. import pandas as pd
  18. from enum import Enum
  19. import elevation_0323 as el
  20. from xml.sax.saxutils import escape
  21. import warnings
  22. warnings.filterwarnings("ignore")
  23. #
  24. # #xodr_list = ['/home/hancheng/taiheqiao_map/thq_1116.xodr', '/home/hancheng/gongyuanbeihuan_map/OD/OpenDRIVE.xodr','/home/hancheng/glyt_map/OpenDRIVE/OpenDRIVE2.xodr']
  25. # #osgb_list = ['/home/hancheng/taiheqiao_map/thq_1116.opt.osgb', '/home/hancheng/gongyuanbeihuan_map/osgb/GJBM_20km_0822.opt.osgb', '/home/hancheng/glyt_map/OSGB/jinlong_20231129_2_guazai.opt.osgb']
  26. # xodr_list = ['/root/rosmerge/resource/thq.xodr', '/root/rosmerge/resource/OpenDRIVE.xodr','/root/rosmerge/resource/gelan.xodr']
  27. # osgb_list = ['/root/rosmerge/resource/thq.opt.osgb', '/root/rosmerge/resource/GJBM_20km_0822.opt.osgb', '/root/rosmerge/resource/gelan.opt.osgb']
  28. class Scenario(ScenarioGenerator):
  29. def __init__(self, gps, obs, gps_time, ego_speed, work_mode, period, abspath, timeofday):
  30. ScenarioGenerator.__init__(self)
  31. self.gps = gps
  32. self.obs = obs
  33. self.gps_time = gps_time
  34. self.ego_speed = ego_speed
  35. self.work_mode = work_mode
  36. self.period = period # 场景持续的时间
  37. self.abspath = abspath
  38. self.weather = xosc.PrecipitationType.dry # 默认是晴天
  39. self.visual_fog_range = 20000 # 正常的能见度,没有雾
  40. self.time = 43200 # 强制为白天
  41. # self.map_id = map_id
  42. # self.ObjectID = ObjectID
  43. # self.Speed = Speed
  44. def road(self, **kwargs):
  45. positionEgo = self.gps
  46. planview = xodr.PlanView()
  47. nextx = positionEgo[0].x
  48. nexty = positionEgo[0].y
  49. h = float(positionEgo[0].h)
  50. # for i in range(len(positionEgo) - 1):
  51. # x = 0.000001 if abs(positionEgo[i].x) < 0.000001 else positionEgo[i].x
  52. # y = 0.000001 if abs(positionEgo[i].y) < 0.000001 else positionEgo[i].y
  53. # nextx = 0.000001 if abs(positionEgo[i + 1].x) < 0.000001 else positionEgo[i + 1].x
  54. # nexty = 0.000001 if abs(positionEgo[i + 1].y) < 0.000001 else positionEgo[i + 1].y
  55. # h = float(positionEgo[i].h)
  56. #
  57. # planview.add_fixed_geometry(xodr.Line(math.sqrt(math.pow(nextx - x, 2) + math.pow(nexty - y, 2))), x, y, h)
  58. planview.add_fixed_geometry(xodr.Line(100), nextx, nexty, h)
  59. # create two different roadmarkings
  60. rm_solid = xodr.RoadMark(xodr.RoadMarkType.solid, 0.2)
  61. rm_dashed = xodr.RoadMark(xodr.RoadMarkType.broken, 0.2)
  62. # create simple lanes
  63. lanes = xodr.Lanes()
  64. lanesection1 = xodr.LaneSection(0, xodr.standard_lane(offset=1.75, rm=rm_dashed))
  65. lanesection1.add_left_lane(xodr.standard_lane(offset=3.5, rm=rm_dashed))
  66. lanesection1.add_left_lane(xodr.standard_lane(offset=3.5, rm=rm_dashed))
  67. lanesection1.add_left_lane(xodr.standard_lane(offset=3.5, rm=rm_solid))
  68. lanesection1.add_right_lane(xodr.standard_lane(offset=3.5, rm=rm_dashed))
  69. lanesection1.add_right_lane(xodr.standard_lane(offset=3.5, rm=rm_dashed))
  70. lanesection1.add_right_lane(xodr.standard_lane(offset=3.5, rm=rm_solid))
  71. lanes.add_lanesection(lanesection1)
  72. lanes.add_laneoffset(xodr.LaneOffset(a=1.75))
  73. road = xodr.Road(0, planview, lanes)
  74. odr = xodr.OpenDrive('myroad')
  75. # 静态元素
  76. tree = ET.parse(os.getcwd() + '/models/static_object_models.xodr')
  77. root = tree.getroot()
  78. objects_dict = root.iter(tag='object')
  79. road = create_static_object(road, objects_dict)
  80. # road = create_static_object(road, object_id=0, object_type=ObjectType.railing, repeat_flag=1)
  81. odr.add_road(road)
  82. odr.adjust_roads_and_lanes()
  83. return odr
  84. def get_section(self, left_lanemark):
  85. return None
  86. def split_road_section(self, enu_file, lane_file):
  87. lane_content = pd.read_csv(lane_file)
  88. # 把车道分割开来,一个车道段,多种geometry
  89. # 首先判断车道线数值是否有断裂,断裂处根据自车轨迹生成道路参数
  90. left_lanemark = lane_content[lane_content['LaneID'] == 1][['Time','FrameID','LanePosition','LaneQuality']]
  91. right_lanemark = lane_content[lane_content['LaneID'] == 2][['Time','FrameID','LanePosition','LaneQuality']]
  92. left_break_section = self.get_section(left_lanemark, 1)
  93. right_break_section = self.get_section(right_lanemark, 1)
  94. break_section = []
  95. normal_section = []
  96. # 判断是否变道,然后判断是否弯道
  97. # 最终目标是得到多个geometry参数,确定每个连接线处的s/t偏移量?,以及左右道路的个数和宽度
  98. return None
  99. def check_outliers_and_modify(self, datalist):
  100. for index in datalist.index:
  101. if index < 3:
  102. datalist.loc[index] = datalist[index] if abs(datalist[index] - datalist[index + 1:index + 3].mean()) < 0.5 else 2 * datalist[index + 1] - datalist[index + 1:index + 3].mean()
  103. elif 3 <= index < len(datalist) - 3:
  104. datalist.loc[index] = datalist[index] if abs(datalist[index] - datalist[index + 1:index + 3].mean()) < 0.5 or abs(datalist[index] - datalist[index - 3:index].mean()) < 0.5 else (datalist[index - 1] + datalist[index + 1]) / 2
  105. else:
  106. datalist.loc[index] = datalist[index] if abs(datalist[index] - datalist[index - 3:index].mean()) < 0.5 else 2 * datalist[index - 1] - datalist[index - 3:index].mean()
  107. return datalist
  108. def get_new_LaneID(self, change_flag, laneID, frameid, item):
  109. '''
  110. 修改laneID,change_list包含了每个变道片段
  111. '''
  112. if item[0] <= frameid < item[1]:
  113. return laneID + change_flag
  114. else:
  115. return laneID
  116. def get_lane_width(self, data1, data2):
  117. lane_union = pd.merge(data1, data2, on=['FrameID'])
  118. lane_union['width'] = lane_union['LanePosition_y'] - lane_union['LanePosition_x']
  119. a = lane_union["width"].quantile(0.75)
  120. b = lane_union["width"].quantile(0.25)
  121. lane_width = abs((a + b) / 2)
  122. return lane_width
  123. def road_pre_study(self, label_file, lane_file):
  124. laneDF = pd.read_csv(lane_file)
  125. road_label = ''
  126. flag = 0 # flag = 0 can use road_ego to generate .xodr, flag = 1 better use road to generate .xodr
  127. with open(label_file) as f:
  128. label = json.load(f)
  129. ego_actions = label['自车行为']
  130. for item in ego_actions:
  131. if ('变道' in item['type_']) or ('转成功' in item['type_']) or ('掉头' in item['type_']):
  132. road_label = item['type_']
  133. flag = 1
  134. break
  135. else:
  136. road_label = item['type_']
  137. if road_label == '向左变道成功':
  138. # 查找变道标记点
  139. change_flag = 1
  140. lane_1 = laneDF[(laneDF['LaneID'] == 1) & (laneDF['LaneQuality'] > 1)]
  141. lane_1 = lane_1.reset_index(drop=True)
  142. leftlanepositon = lane_1['LanePosition']
  143. lane_1['LanePosition'] = self.check_outliers_and_modify(leftlanepositon)
  144. lane_1['last_Position'] = lane_1[['LanePosition']].shift(axis = 0, periods = 1) #axis指定移动的轴:0为行,1为列
  145. lane_1['last_FrameID'] = lane_1[['FrameID']].shift(axis = 0, periods = 1) #axis指定移动的轴:0为行,1为列
  146. lane_1['change_flag'] = lane_1.apply(lambda x: change_flag if (x['LanePosition'] - x['last_Position'] <= -3) and (x['FrameID'] - x['last_FrameID'] == 1) else 0, axis=1) # 默认情况下 axis=0 表示按列,axis=1 表示按行。
  147. lane_1['split_flag'] = lane_1.apply(lambda x: 99 if x['FrameID'] - x['last_FrameID'] > 1 else 0, axis=1)
  148. lane_2 = laneDF[(laneDF['LaneID'] == 2) & (laneDF['LaneQuality'] > 1)]
  149. lane_2 = lane_2.reset_index(drop=True)
  150. rightlanepositon = lane_2['LanePosition']
  151. lane_2['LanePosition'] = self.check_outliers_and_modify(rightlanepositon)
  152. lane_2['last_Position'] = lane_2[['LanePosition']].shift(axis = 0, periods = 1) #axis指定移动的轴:0为行,1为列
  153. lane_2['last_FrameID'] = lane_2[['FrameID']].shift(axis = 0, periods = 1) #axis指定移动的轴:0为行,1为列
  154. lane_2['change_flag'] = lane_2.apply(lambda x: change_flag if (x['LanePosition'] - x['last_Position'] <= -3) and (x['FrameID'] - x['last_FrameID'] == 1) else 0, axis=1) # 默认情况下 axis=0 表示按列,axis=1 表示按行。
  155. lane_2['split_flag'] = lane_2.apply(lambda x: 99 if x['FrameID'] - x['last_FrameID'] > 1 else 0, axis=1)
  156. lane_width = self.get_lane_width(lane_1[['FrameID','LanePosition']], lane_2[['FrameID','LanePosition']])
  157. # 左变道用左车道线数据靠谱,不会有他车遮挡,找到变道数据段
  158. change_lane_point = list(lane_1[lane_1['change_flag'] == change_flag]['change_flag'].index) + [list(lane_1.index)[-1]]
  159. change_lane_section = [(lane_1.loc[change_lane_point[i], 'FrameID'], lane_1.loc[change_lane_point[i+1], 'FrameID']) for i in range(len(change_lane_point)-1)]
  160. for item in change_lane_section:
  161. # 变道后修改原始laneID
  162. # laneDF['LaneID'] = laneDF.apply(lambda x: x['LaneID'] - change_flag if item[0] <= x['FrameID'] < item[1] else x['LaneID'], axis=1)
  163. # laneDF['LanePosition'] = laneDF.apply(lambda x: x['LanePosition'] - change_flag * lane_width if item[0] <= x['FrameID'] < item[1] else x['LanePosition'], axis=1)
  164. # laneDF['LaneID'] = laneDF.apply(lambda x: x['LaneID'] - change_flag if x['FrameID'] == max(laneDF['FrameID']) else x['LaneID'], axis=1)
  165. # laneDF['LanePosition'] = laneDF.apply(lambda x: x['LanePosition'] - change_flag * lane_width if x['FrameID'] == max(laneDF['FrameID']) else x['LanePosition'], axis=1)
  166. # 修正左左车道线和右右车道线数值
  167. if change_flag == 1:
  168. lane_0 = laneDF[(laneDF['LaneID'] == 0) & (laneDF['LaneQuality'] > 1) & (laneDF['FrameID'] < item[0])]
  169. if not lane_0.empty:
  170. left_lane_width = self.get_lane_width(lane_0[['FrameID','LanePosition']], lane_1[['FrameID','LanePosition']])
  171. else:
  172. left_lane_width = lane_width
  173. print(left_lane_width)
  174. # new_lane_1 = laneDF[laneDF['LaneID'] == 1][['FrameID','LanePosition']]
  175. # new_lane_1.rename(columns={'LanePosition':'LanePosition2'},inplace=True)
  176. # laneDF = pd.merge(laneDF, new_lane_1, on=['FrameID'])
  177. # laneDF['LanePosition'] = laneDF.apply(lambda x: x['LanePosition2'] - left_lane_width if (item[0] <= x['FrameID'] < item[1]) and (x['LaneID'] == 0) else x['LanePosition'], axis=1)
  178. # laneDF['LanePosition'] = laneDF.apply(lambda x: x['LanePosition2'] - left_lane_width if x['FrameID'] == max(laneDF['FrameID']) and (x['LaneID'] == 0) else x['LanePosition'], axis=1)
  179. # laneDF['LanePosition'] = laneDF.apply(lambda x: x['LanePosition2'] - left_lane_width if (item[0] <= x['FrameID'] < item[1]) and (x['LaneID'] == -1) else x['LanePosition'], axis=1)
  180. # laneDF['LanePosition'] = laneDF.apply(lambda x: x['LanePosition2'] - left_lane_width if x['FrameID'] == max(laneDF['FrameID']) and (x['LaneID'] == 0) else x['LanePosition'], axis=1)
  181. # laneDF['LaneID'] = laneDF.apply(lambda x: 3 if x['LaneID'] == -1 else x['LaneID'], axis=1)
  182. # 缺右车道线right_lane_width处理
  183. print(laneDF[laneDF['FrameID']>1860][['FrameID', 'LaneID', 'LanePosition']].head(50))
  184. print('road_label: ', road_label)
  185. return laneDF
  186. def road_new(self, **kwargs):
  187. polyfit_fig_path = os.path.join(self.abspath, 'simulation','polyfit.jpg')
  188. # run road detector
  189. enu_file = os.path.join(self.abspath, 'pos.csv')
  190. lane_file = os.path.join(self.abspath, 'lane.csv')
  191. label_file = os.path.join(self.abspath, 'label.json')
  192. # study road style: straight\curve\split-line; ego action: change-lane\no-change\cross-turn
  193. lane_content = self.road_pre_study(label_file, lane_file)
  194. # road split sections
  195. # self.split_road_section(enu_file, lane_file)
  196. try:
  197. laneid_tuple = [0, 1, 2, 3]
  198. uv_coord_info, road_info, left_lane_info, right_lane_info = road_detector_new(enu_file, lane_content, laneid_tuple, polyfit_fig_path)
  199. except:
  200. print('road detection failed!!!! Use ego trail road.')
  201. error = {'time':datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3],'traceback':traceback.format_exc()}
  202. with open('error.log','a+') as f:
  203. json.dump(error, f, indent=4)
  204. f.write('\n')
  205. return self.road_ego()
  206. origin_x = uv_coord_info[0]
  207. origin_y = uv_coord_info[1]
  208. uv_coord_hdg = uv_coord_info[2]
  209. reference_line_offset = road_info[0]
  210. model_u = road_info[1] # in fomrat [c3, c2, c1, c0]
  211. model_v = road_info[2] # in fomrat [c3, c2, c1, c0]
  212. road_length = road_info[3]
  213. print(uv_coord_info)
  214. print(road_info)
  215. # generate xodr file
  216. planview = xodr.PlanView(origin_x, origin_y, uv_coord_hdg)
  217. # Create geometry and add it to the planview
  218. # parampoly3 = xodr.ParamPoly3(au=model_u[3], bu=model_u[2], cu=model_u[1], du=model_u[0], av=model_v[3], bv=model_v[2], cv=model_v[1], dv=model_v[0], prange='arcLength',length=road_length)
  219. parampoly3 = xodr.ParamPoly3(au=0, bu=model_u[2], cu=model_u[1], du=model_u[0], av=0, bv=model_v[2], cv=model_v[1], dv=model_v[0], prange='arcLength',length=road_length)
  220. planview.add_geometry(parampoly3)
  221. # create two different roadmarkings
  222. rm_solid = xodr.RoadMark(xodr.RoadMarkType.solid,0.2)
  223. rm_dashed = xodr.RoadMark(xodr.RoadMarkType.broken,0.2,laneChange=xodr.LaneChange.both)
  224. ##4. Create centerlane
  225. centerlane = xodr.Lane(a=reference_line_offset)
  226. centerlane.add_roadmark(rm_dashed)
  227. ##5. Create lane section form the centerlane
  228. lanesec = xodr.LaneSection(0,centerlane)
  229. ##6. Create left and right lanes
  230. lane_id = 0
  231. for lane in left_lane_info:
  232. lane_id += 1
  233. lane_width = lane[0]
  234. spd_limit = lane[1]
  235. lane_left = xodr.Lane(a=lane_width)
  236. lane_left.add_roadmark(rm_dashed)
  237. # Add lanes to lane section
  238. lanesec.add_left_lane(lane_left)
  239. lane_id = 0
  240. for lane in right_lane_info:
  241. lane_id -= 1
  242. lane_width = lane[0]
  243. spd_limit = lane[1]
  244. lane_right = xodr.Lane(a=lane_width)
  245. lane_right.add_roadmark(rm_dashed)
  246. # Add lanes to lane section
  247. lanesec.add_right_lane(lane_right)
  248. ##8. Add lane section to Lanes
  249. lanes = xodr.Lanes()
  250. lanes.add_laneoffset(xodr.LaneOffset(s = 0, a=reference_line_offset))
  251. lanes.add_lanesection(lanesec)
  252. ##9. Create Road from Planview and Lanes
  253. road = xodr.Road(1,planview,lanes)
  254. ##10. Create the OpenDrive class (Master class)
  255. odr = xodr.OpenDrive('myroad')
  256. ##11. Finally add roads to Opendrive
  257. odr.add_road(road)
  258. ##12. Adjust initial positions of the roads looking at succ-pred logic
  259. odr.adjust_roads_and_lanes()
  260. # ##13. Print the .xodr file
  261. # xodr.prettyprint(odr.get_element())
  262. # ##14. Run the .xodr with esmini
  263. # xodr.run_road(odr,os.path.join('..','pyoscx','esmini'))
  264. return odr
  265. def getXoscPosition(egodata, t, e, n, h, z, obj_type, offset_x, offset_y, offset_h, start_time):
  266. '将dataframe的轨迹转换为场景文件的轨迹数据, Time, ego_e, ego_n, headinga'
  267. position = []
  268. time = []
  269. # cur_time = 0.0
  270. egodata = egodata[[t, e, n, h, z, obj_type]]
  271. egodata = egodata.reset_index(drop=True)
  272. # egodata[t] = egodata.index / 10
  273. egodata[t] = (egodata[t] - start_time) / 1000
  274. egodata[e] = egodata[e] + offset_x
  275. egodata[n] = egodata[n] + offset_y
  276. egodata[h] = egodata[h] + offset_h
  277. egodata[h] = egodata.apply(lambda x: x[h] if x[h] < 360 else x[h] - 360, axis=1)
  278. type_list = list(egodata[obj_type])
  279. ego_type = int(max(type_list, key=type_list.count))
  280. lasth = float(egodata.at[0, h])
  281. init_flag = True
  282. # two method to set z value
  283. zflag = 0 # 1
  284. if zflag:
  285. # 根据地图的xy值计算z值
  286. zfile = '/home/hancheng/weihao/gongyuanbei_elevation.csv'
  287. # zfile = '/home/hancheng/simulation_dynamic/elevation_df_taiheqiao.csv'
  288. zdata = pd.read_csv(zfile)
  289. for row in egodata.iterrows():
  290. hhh = math.radians(row[1][h])
  291. xodr_z = el.cal_elevation(zdata, float(row[1][e]), float(row[1][n]))
  292. if init_flag:
  293. position.append(xosc.WorldPosition(x=float(row[1][e]), y=float(row[1][n]), z=xodr_z, h=hhh, p=0, r=0))
  294. init_flag = False
  295. else:
  296. if float(row[1][h]) - lasth > 300:
  297. hhh = math.radians(float(row[1][h]) - 360)
  298. elif float(row[1][h]) - lasth < -300:
  299. hhh = math.radians(float(row[1][h]) + 360)
  300. position.append(xosc.WorldPosition(x=float(row[1][e]), y=float(row[1][n]), z=xodr_z, h=hhh, p=0, r=0))
  301. lasth = float(row[1][h])
  302. time.append(float(row[1][t]))
  303. # time.append(cur_time)
  304. # cur_time += 0.1
  305. return position, time, ego_type
  306. else:
  307. # z = 0
  308. for row in egodata.iterrows():
  309. hhh = math.radians(row[1][h])
  310. if init_flag:
  311. position.append(xosc.WorldPosition(x=float(row[1][e]), y=float(row[1][n]), z=float(row[1][z]), h=hhh, p=0, r=0))
  312. init_flag = False
  313. else:
  314. if float(row[1][h]) - lasth > 300:
  315. hhh = math.radians(float(row[1][h]) - 360)
  316. elif float(row[1][h]) - lasth < -300:
  317. hhh = math.radians(float(row[1][h]) + 360)
  318. position.append(xosc.WorldPosition(x=float(row[1][e]), y=float(row[1][n]), z=float(row[1][z]), h=hhh, p=0, r=0))
  319. lasth = float(row[1][h])
  320. time.append(float(row[1][t]))
  321. # time.append(cur_time)
  322. # cur_time += 0.1
  323. return position, time, ego_type
  324. def scenario(self, **kwargs):
  325. road = xosc.RoadNetwork(roadfile='/root/rosmerge/resource/OpenDRIVE2_add_stop_line_marking_20231229.xodr', scenegraph='/root/rosmerge/resource/jinlong_all_addtrafficlight_20240226_5_guazai_2.opt.osgb')
  326. catalog = xosc.Catalog()
  327. catalog.add_catalog('VehicleCatalog', 'Distros/Current/Config/Players/Vehicles')
  328. catalog.add_catalog('PedestrianCatalog', 'Distros/Current/Config/Players/Pedestrians')
  329. catalog.add_catalog('MiscObjectCatalog', 'Distros/Current/Config/Players/Objects')
  330. catalog.add_catalog('ControllerCatalog', 'Distros/Current/Config/Players/driverCfg.xml')
  331. pbb = xosc.BoundingBox(0.5, 0.5, 1.8, 2.0, 0, 0.9)
  332. mbb = xosc.BoundingBox(1, 2, 1.7, 1.5, 0, 0.9)
  333. bb = xosc.BoundingBox(2.1, 4.5, 1.8, 1.5, 0, 0.9)
  334. bus_bb = xosc.BoundingBox(2.55, 10.5, 3.1, 5.1, 0, 1.45)
  335. bus_fa = xosc.Axle(0.48, 0.91, 2.5, 4.5, 1.5)
  336. bus_ba = xosc.Axle(0, 0.91, 2.5, 4.5, 1.5)
  337. truck_bb = xosc.BoundingBox(2.8, 8.744, 3.78, 4.372, 0, 1.89)
  338. truck_fa = xosc.Axle(0.48, 1, 2.8, 4.372, 1.5)
  339. truck_ba = xosc.Axle(0, 1, 2.8, 4.372, 1.5)
  340. fa = xosc.Axle(0.5, 0.6, 1.8, 3.1, 0.3)
  341. ba = xosc.Axle(0, 0.6, 1.8, 0, 0.3)
  342. cone_bb = xosc.BoundingBox(0.5, 0.5, 1.0, 2.0, 0, 0.9)
  343. red_veh = xosc.Vehicle('Audi_A3_2009_black', xosc.VehicleCategory.car, bb, fa, ba, 69.444, 200, 10)
  344. red_veh.add_property(name='control', value='external')
  345. segway = xosc.Vehicle('Segway', xosc.VehicleCategory.car, pbb, fa, ba, 69.444, 200, 10)
  346. segway.add_property(name='control', value='external')
  347. white_veh = xosc.Vehicle('Audi_A3_2009_red', xosc.VehicleCategory.car, bb, fa, ba, 69.444, 200, 10)
  348. male_ped = xosc.Pedestrian('Christian', 'male_adult', 70, xosc.PedestrianCategory.pedestrian, pbb)
  349. motorcycle = xosc.Vehicle('Kawasaki_ZX-9R_black', xosc.VehicleCategory.motorbike, mbb, fa, ba, 69.444, 200, 10)
  350. motorcycle.add_property(name='control', value='external')
  351. truck = xosc.Vehicle('MANTGS_11_Black', xosc.VehicleCategory.truck, truck_bb, truck_fa,
  352. truck_ba, 26.4, 10, 10)
  353. bus = xosc.Vehicle('MercedesTravego_10_ArcticWhite', xosc.VehicleCategory.bus, bus_bb, bus_fa, bus_ba, 29, 10,
  354. 10)
  355. cone = xosc.MiscObject('RdMiscPylon03-32cm', 10, xosc.MiscObjectCategory.obstacle, cone_bb)
  356. prop = xosc.Properties()
  357. cnt = xosc.Controller('DefaultDriver', prop)
  358. cnt2 = xosc.Controller('No Driver', prop)
  359. # 添加自车实体
  360. egoname = 'Ego'
  361. entities = xosc.Entities()
  362. entities.add_scenario_object(egoname, segway, cnt)
  363. # 添加目标车实体
  364. objname = 'Player'
  365. ped_type, car_type, bicycle_motor_type, bus_type, truct_type, cone_type = get_obj_type(self.work_mode)
  366. positionEgo = self.gps
  367. positionObj = self.obs
  368. for i, row in enumerate(positionObj):
  369. if len(row[1]) < 1:
  370. continue
  371. obj_type = row[2] # 根据目标物类型添加对应的实体
  372. if obj_type in ped_type:
  373. entities.add_scenario_object(objname + str(i), male_ped)
  374. elif obj_type in car_type:
  375. entities.add_scenario_object(objname + str(i), white_veh, cnt2)
  376. elif obj_type in bicycle_motor_type:
  377. entities.add_scenario_object(objname + str(i), motorcycle, cnt2)
  378. elif obj_type in bus_type:
  379. entities.add_scenario_object(objname + str(i), bus, cnt2)
  380. elif obj_type in truct_type:
  381. entities.add_scenario_object(objname + str(i), truck, cnt2)
  382. elif obj_type in cone_type:
  383. entities.add_scenario_object(objname + str(i), cone)
  384. # 初始化
  385. init = xosc.Init()
  386. step_time = xosc.TransitionDynamics(xosc.DynamicsShapes.step, xosc.DynamicsDimension.time, 0)
  387. egospeed = xosc.AbsoluteSpeedAction(self.ego_speed, step_time)
  388. # 设置初始环境要素,例如天气时间等
  389. default_precipitation = xosc.PrecipitationType.dry
  390. default_cloudstate = xosc.CloudState.free
  391. # json_path = os.path.join(self.abspath, 'label.json')
  392. # with open(json_path, 'r', encoding='utf-8') as f:
  393. # sc_json = json.load(f)
  394. # weather = sc_json['天气情况'][0]['type_'] #['自然环境']
  395. # if weather == '晴':
  396. # f.close()
  397. # elif weather == '多云':
  398. # default_cloudstate = xosc.CloudState.cloudy
  399. # elif weather == '阴':
  400. # default_cloudstate = xosc.CloudState.overcast
  401. # elif weather == '雨':
  402. # default_cloudstate = xosc.CloudState.overcast
  403. # default_precipitation = xosc.PrecipitationType.rain
  404. # elif weather == '雪':
  405. # default_cloudstate = xosc.CloudState.overcast
  406. # default_precipitation = xosc.PrecipitationType.snow
  407. # elif weather == '雾霾' or weather == '沙尘':
  408. # self.visual_fog_range = 700
  409. # default_cloudstate = xosc.CloudState.cloudy
  410. init.add_global_action(
  411. xosc.EnvironmentAction(name="InitEnvironment", environment=xosc.Environment(
  412. xosc.TimeOfDay(True, 2019, 12, 19, 12, 0, 0),
  413. xosc.Weather(
  414. sun_intensity=2000, sun_azimuth=40, sun_elevation=20,
  415. cloudstate=default_cloudstate,
  416. precipitation=default_precipitation,
  417. precipitation_intensity=1,
  418. visual_fog_range=self.visual_fog_range),
  419. xosc.RoadCondition(friction_scale_factor=0.7))))
  420. # ego car init
  421. ego_init_h = positionEgo[0].h
  422. init.add_init_action(egoname, xosc.TeleportAction(
  423. xosc.WorldPosition(x=positionEgo[0].x, y=positionEgo[0].y, z=positionEgo[0].z, h=ego_init_h, p=0, r=0)))
  424. init.add_init_action(egoname, egospeed)
  425. # ego car trail
  426. trajectory = xosc.Trajectory('egoTrajectory', False)
  427. polyline = xosc.Polyline(self.gps_time, positionEgo)
  428. trajectory.add_shape(polyline)
  429. speedaction = xosc.FollowTrajectoryAction(trajectory, xosc.FollowMode.position, xosc.ReferenceContext.absolute,
  430. 1, 0)
  431. trigger = xosc.ValueTrigger('drive_start_trigger', 0, xosc.ConditionEdge.rising,
  432. xosc.SimulationTimeCondition(0, xosc.Rule.greaterThan))
  433. trigger_init = xosc.ValueTrigger(name='init_trigger', delay=0, conditionedge=xosc.ConditionEdge.rising,
  434. valuecondition=xosc.SimulationTimeCondition(value=0,
  435. rule=xosc.Rule.greaterThan))
  436. event_init = xosc.Event('Event_init', xosc.Priority.overwrite)
  437. action_light = xosc.CustomCommandAction(0, 0, 0, 0, 1, 0, 0)
  438. light_flag = 'auto'
  439. if self.time == 64800:
  440. light_flag = 'true'
  441. text = f'<Environment><TimeOfDay headlights="{light_flag}" timezone="8" value="{self.time}" /></Environment>'
  442. node = ET.Element("CustomCommandAction")
  443. node.attrib = {'type': 'scp'}
  444. node.text = f"<![CDATA[\n{text}]\n]>"
  445. action_light.add_element(node)
  446. event_init.add_action('headlight', action_light)
  447. event_init.add_trigger(trigger_init)
  448. event = xosc.Event('Event1', xosc.Priority.overwrite)
  449. event.add_trigger(trigger)
  450. event.add_action('newspeed', speedaction)
  451. man = xosc.Maneuver('my maneuver')
  452. man.add_event(event_init)
  453. man.add_event(event)
  454. mangr = xosc.ManeuverGroup('mangroup', selecttriggeringentities=True)
  455. mangr.add_actor('Ego')
  456. mangr.add_maneuver(man)
  457. trigger0 = xosc.Trigger('start')
  458. act = xosc.Act('Act1', trigger0)
  459. act.add_maneuver_group(mangr)
  460. ego_story = xosc.Story('mystory_ego')
  461. ego_story.add_act(act)
  462. stop_trigger = xosc.ValueTrigger('stop_trigger', 0, xosc.ConditionEdge.none,
  463. xosc.SimulationTimeCondition(self.period, xosc.Rule.greaterThan), 'stop')
  464. sb = xosc.StoryBoard(init, stoptrigger=stop_trigger)
  465. sb.add_story(ego_story)
  466. # object car trail
  467. if positionObj:
  468. for i, row in enumerate(positionObj):
  469. name = objname + str(i)
  470. if len(row[1]) < 2:
  471. continue
  472. obj_type = row[2]
  473. # 根据目标车需要动态创建实体
  474. x = row[0][0].x
  475. y = row[0][0].y
  476. z = row[0][0].z
  477. h = row[0][0].h
  478. start_time = row[1][0]
  479. init_position = xosc.WorldPosition(x=x, y=y, z=z, h=h, p=0, r=0)
  480. newentity = xosc.AddEntityAction(name, init_position)
  481. newentity_trigger = xosc.ValueTrigger(name='newentity_trigger', delay=0,
  482. conditionedge=xosc.ConditionEdge.rising,
  483. valuecondition=xosc.SimulationTimeCondition(value=start_time,
  484. rule=xosc.Rule.greaterThan))
  485. newentity_event = xosc.Event('Event_newentity', xosc.Priority.overwrite)
  486. newentity_event.add_trigger(newentity_trigger)
  487. newentity_event.add_action('newentity_action', newentity)
  488. man_obj = xosc.Maneuver('my maneuver')
  489. man_obj.add_event(newentity_event)
  490. if obj_type != 103:
  491. # 添加目标车轨迹
  492. trajectoryM = xosc.Trajectory('objectTrajectory', False)
  493. polylineM = xosc.Polyline(row[1], row[0])
  494. trajectoryM.add_shape(polylineM)
  495. obj_trail_action = xosc.FollowTrajectoryAction(trajectory=trajectoryM,
  496. following_mode=xosc.FollowMode.position,
  497. reference_domain=xosc.ReferenceContext.absolute,
  498. scale=1, offset=0, initialDistanceOffset=0)
  499. obj_trail_event = xosc.Event('Event1', xosc.Priority.overwrite)
  500. # obj_start_trigger = xosc.EntityTrigger("obj-start-trigger", 0, xosc.ConditionEdge.rising, xosc.SpeedCondition(0, xosc.Rule.greaterThan),'Ego')
  501. obj_start_trigger = xosc.ValueTrigger('obj_start_trigger', 0, xosc.ConditionEdge.rising,
  502. xosc.SimulationTimeCondition(start_time, xosc.Rule.greaterThan))
  503. obj_trail_event.add_trigger(obj_start_trigger)
  504. obj_trail_event.add_action('trail_action', obj_trail_action)
  505. # if obj_type in ped_type:
  506. # walp_trigger = xosc.EntityTrigger('ped_walp_trigger', 0, xosc.ConditionEdge.rising,\
  507. # xosc.TimeToCollisionCondition(self.intersectime, xosc.Rule.lessThan, entity=name), 'Ego')
  508. # obj_trail_event.add_trigger(walp_trigger)
  509. man_obj.add_event(obj_trail_event)
  510. # 行人特有的事件
  511. if obj_type in ped_type:
  512. ped_event = xosc.Event('Event_ped', xosc.Priority.overwrite)
  513. ped_event.add_trigger(obj_start_trigger)
  514. ped_action = xosc.CustomCommandAction(0, 0, 0, 0, 1, 0, 0)
  515. ped_action.add_element(self.createUDAction(name))
  516. ped_event.add_action('ped_trail_action', ped_action)
  517. man_obj.add_event(ped_event)
  518. # finish_trigger = xosc.EntityTrigger('finish_trigger', 0, xosc.ConditionEdge.rising, xosc.ReachPositionCondition(position=row[1][0],tolerance=1),name)
  519. # event4 = xosc.Event('Event_ped',xosc.Priority.overwrite)
  520. # event4.add_trigger(finish_trigger)
  521. # be_still_action = xosc.AbsoluteSpeedAction(0, xosc.TransitionDynamics(xosc.DynamicsShapes.step, xosc.DynamicsDimension.time, 1))
  522. # event4.add_action('ped_be_still_action',be_still_action)
  523. # man_obj.add_event(event4)
  524. # 轨迹最后删除实体
  525. last_time = row[1][-1]
  526. del_action = xosc.DeleteEntityAction(name)
  527. del_trigger = xosc.ValueTrigger(name='entity_del_trigger', delay=0,
  528. conditionedge=xosc.ConditionEdge.rising,
  529. valuecondition=xosc.SimulationTimeCondition(value=last_time,
  530. rule=xosc.Rule.greaterThan))
  531. del_event = xosc.Event('Event_del', xosc.Priority.overwrite)
  532. del_event.add_trigger(del_trigger)
  533. del_event.add_action('del_action', del_action)
  534. man_obj.add_event(del_event)
  535. obj_mangroup = xosc.ManeuverGroup('mangroup', selecttriggeringentities=True)
  536. obj_mangroup.add_actor(name)
  537. obj_mangroup.add_maneuver(man_obj)
  538. obj_act = xosc.Act('Act2', trigger0)
  539. obj_act.add_maneuver_group(obj_mangroup)
  540. obj_story = xosc.Story('mystory_' + name)
  541. obj_story.add_act(obj_act)
  542. sb.add_story(obj_story)
  543. # prettyprint(sb.get_element())
  544. paramet = xosc.ParameterDeclarations()
  545. sce = xosc.Scenario('my scenario', 'Maggie', paramet, entities, sb, road, catalog)
  546. return sce
  547. def createUDAction(self, name):
  548. # tree = ET.parse('./models/ped_CDATA.xosc')
  549. # root = tree.getroot()
  550. # ele = root[5][2][1][0][1][1][0][0][0]
  551. # newnode = ET.Element("CustomCommandAction")
  552. # newnode.attrib = {'type': 'scp'}
  553. # newnode.text = '<![CDATA[\n' + ele.text + ']\n]>'
  554. speed = 3
  555. motion = 'walk'
  556. # text = f'<Traffic>\n <ActionMotion actor="{name}" move="{motion}" speed="{speed}" force="false" ' \
  557. # f'rate="0" delayTime="0.0" activateOnExit="false"/>\n</Traffic>'
  558. text = '<Traffic>\n <ActionMotion actor="{}" move="{}" speed="{}" force="false" \
  559. rate="0" delayTime="0.0" activateOnExit="false"/>\n</Traffic>'.format(name, motion, speed)
  560. # text = '&lt;Traffic&gt; &lt;ActionMotion actor=&quot;Player0&quot; move=&quot;walk&quot; speed=&quot;3&quot; force=&quot;false&quot;rate=&quot;0&quot; delayTime=&quot;0.0&quot; activateOnExit=&quot;false&quot;/&gt;&lt;/Traffic&gt;'.format(name, motion, speed)
  561. newnode = ET.Element("CustomCommandAction")
  562. newnode.attrib = {'type': 'scp'}
  563. newnode.text = "<![CDATA[\n{}]\n]>".format(text)
  564. return newnode
  565. class WorkMode(Enum):
  566. cicv = 0 # CICV车端
  567. roadside = 1 # 车网路端
  568. car = 2 # 车网车端
  569. merge = 3 # 车网车端路端融合
  570. def get_obj_type(mode):
  571. if mode == WorkMode.cicv.value:
  572. # CICV车端
  573. ped_type = [7]
  574. car_type = [2]
  575. bicycle_motor_type = [8]
  576. bus_type = [3]
  577. truct_type = [4]
  578. cone_type = [103]
  579. elif mode == WorkMode.roadside.value:
  580. # 车网路端
  581. ped_type = [0]
  582. car_type = [2]
  583. bicycle_motor_type = [1, 3]
  584. bus_type = [5]
  585. truct_type = [7]
  586. cone_type = [103]
  587. elif mode == WorkMode.car.value:
  588. # 车网车端
  589. ped_type = [1]
  590. car_type = [6]
  591. bicycle_motor_type = [2, 3, 4, 5]
  592. bus_type = [7, 8]
  593. truct_type = [9]
  594. cone_type = [103]
  595. else:
  596. # 车网车端路端融合
  597. ped_type = [1]
  598. car_type = [6]
  599. bicycle_motor_type = [2, 3, 4, 5]
  600. bus_type = [7, 8]
  601. truct_type = [9]
  602. cone_type = [103]
  603. return ped_type, car_type, bicycle_motor_type, bus_type, truct_type, cone_type
  604. # 创建道路旁静止的场景
  605. def create_static_object(road, object_dict):
  606. for single_object in object_dict:
  607. for k, v in ObjectType.__members__.items():
  608. if k == single_object.attrib['type']:
  609. single_object.attrib['type'] = v
  610. break
  611. road_object = Object(
  612. s=single_object.attrib['s'],
  613. t=single_object.attrib['t'],
  614. Type=single_object.attrib['type'],
  615. dynamic=Dynamic.no,
  616. id=single_object.attrib['id'],
  617. name=single_object.attrib['name'],
  618. zOffset=single_object.attrib['zOffset'],
  619. validLength=single_object.attrib['validLength'],
  620. orientation=Orientation.none,
  621. length=single_object.attrib['length'],
  622. width=single_object.attrib['width'],
  623. height=single_object.attrib['height'],
  624. pitch=single_object.attrib['pitch'],
  625. roll=single_object.attrib['roll']
  626. )
  627. # 判断此object是否是重复的元素
  628. repeat = single_object.find('repeat')
  629. if repeat is not None:
  630. road.add_object_roadside(road_object_prototype=road_object, repeatDistance=0, side=RoadSide.left,
  631. tOffset=1.75)
  632. road.add_object_roadside(road_object_prototype=road_object, repeatDistance=0, side=RoadSide.right,
  633. tOffset=-1.755)
  634. else:
  635. road.add_object(road_object)
  636. return road
  637. def change_CDATA(filepath):
  638. '行人场景特例,对xosc文件内的特殊字符做转换'
  639. f = open(filepath, "r", encoding="UTF-8")
  640. txt = f.readline()
  641. all_line = []
  642. # txt是否为空可以作为判断文件是否到了末尾
  643. while txt:
  644. txt = txt.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&").replace("&quot;", '"').replace(
  645. "&apos;", "'")
  646. all_line.append(txt)
  647. # 读取文件的下一行
  648. txt = f.readline()
  649. f.close()
  650. f1 = open(filepath, 'w', encoding="UTF-8")
  651. for line in all_line:
  652. f1.write(line)
  653. f1.close()
  654. def path_changer(xosc_path, xodr_path, osgb_path):
  655. """
  656. provided by Dongpeng Ding
  657. :param xosc_path:
  658. :param xodr_path:
  659. :param osgb_path:
  660. :return:
  661. """
  662. tree = ET.parse(xosc_path)
  663. treeRoot = tree.getroot()
  664. # for OpenScenario v0.9, v1.0
  665. for RoadNetwork in treeRoot.findall('RoadNetwork'):
  666. for Logics in RoadNetwork.findall('LogicFile'):
  667. Logics.attrib['filepath'] = xodr_path
  668. for SceneGraph in RoadNetwork.findall('SceneGraphFile'):
  669. SceneGraph.attrib['filepath'] = osgb_path
  670. for Logics in RoadNetwork.findall('Logics'):
  671. Logics.attrib['filepath'] = xodr_path
  672. for SceneGraph in RoadNetwork.findall('SceneGraph'):
  673. SceneGraph.attrib['filepath'] = osgb_path
  674. # for VTD xml
  675. for Layout in treeRoot.findall('Layout'):
  676. Layout.attrib['File'] = xodr_path
  677. Layout.attrib['Database'] = osgb_path
  678. tree.write(xosc_path, xml_declaration=True)
  679. def readXML(xoscPath):
  680. xodrFileName = ""
  681. osgbFileName = ""
  682. tree = ET.parse(xoscPath)
  683. treeRoot = tree.getroot()
  684. for RoadNetwork in treeRoot.findall('RoadNetwork'):
  685. for Logics in RoadNetwork.findall('LogicFile'):
  686. xodrFileName = Logics.attrib['filepath']
  687. for SceneGraph in RoadNetwork.findall('SceneGraphFile'):
  688. osgbFileName = SceneGraph.attrib['filepath']
  689. for Logics in RoadNetwork.findall('Logics'):
  690. xodrFileName = Logics.attrib['filepath']
  691. for SceneGraph in RoadNetwork.findall('SceneGraph'):
  692. osgbFileName = SceneGraph.attrib['filepath']
  693. return xodrFileName[xodrFileName.rindex("/") + 1:], osgbFileName[osgbFileName.rindex("/") + 1:]
  694. def formatThree(rootDirectory):
  695. """
  696. xodr and osgb file path are fixed
  697. :return:
  698. """
  699. for root, dirs, files in os.walk(rootDirectory):
  700. for file in files:
  701. if ".xosc" == file[-5:]:
  702. # xodrFilePath = "/volume4T/goodscenarios/generalization/toyiqi/model/Rd_001.xodr" # 泛化效果好的场景用的
  703. # osgbFilePath = "/volume4T/goodscenarios/generalization/toyiqi/model/Rd_001.osgb" # 泛化效果好的场景用的
  704. # xodrFilePath = "/volume4T/goodscenarios/generalization/toyiqi/model/Cross.xodr" # 泛化效果好的场景用的
  705. # osgbFilePath = "/volume4T/goodscenarios/generalization/toyiqi/model/Cross.osgb" # 泛化效果好的场景用的
  706. xodrFilePath = "/home/hancheng/hc_project/2023-08-08-10-50-16_jsons1/2023-08-08-10-50-16_jsons_0/2023-08-08-10-50-16_jsons_0.xodr" # 直路,泛化好用
  707. osgbFilePath = "/home/hancheng/VIRES/VTD.2022.1/Runtime/Tools/RodDistro_7001_Rod4.6.3/DefaultProject/Database/json0.opt.osgb" # 直路,泛化好用
  708. # xodrFilePath = "/home/lxj/wendang_lxj/L4/L4_scenarios/piliang_model/China_Crossing_002.xodr" # 十字路口,泛化好用
  709. # osgbFilePath = "/home/lxj/wendang_lxj/L4/L4_scenarios/piliang_model/China_Crossing_002.opt.osgb" # 十字路口,泛化好用
  710. # xodrFilePath = "/home/lxj/wendang_lxj/Sharing_VAN/homework/test/DF_yuexiang_1224.xodr" # Sharing-van还原用的
  711. # osgbFilePath = "/home/lxj/wendang_lxj/Sharing_VAN/homework/test/DF_yuexiang_1224.opt.osgb" # Sharing-van还原用的
  712. path_changer(root + "/" + file, xodrFilePath, osgbFilePath)
  713. print("Change success: " + root + "/" + file)
  714. def formatTwo(rootDirectory):
  715. """
  716. data format:
  717. simulation
  718. file.xosc
  719. file.xodr
  720. file.osgb
  721. :return:
  722. """
  723. for root, dirs, files in os.walk(rootDirectory):
  724. for file in files:
  725. if ".xosc" == file[-5:]:
  726. xodrFilePath = ""
  727. osgbFilePath = ""
  728. for odrFile in os.listdir(root):
  729. if ".xodr" == odrFile[-5:]:
  730. xodrFilePath = root + "/" + odrFile
  731. break
  732. for osgbFile in os.listdir(root):
  733. if ".osgb" == osgbFile[-5:]:
  734. osgbFilePath = root + "/" + osgbFile
  735. break
  736. path_changer(root + "/" + file, xodrFilePath, osgbFilePath)
  737. print("Change success: " + root + "/" + file)
  738. def formatOne(rootDirectory):
  739. """
  740. data format:
  741. openx
  742. xosc
  743. file.xosc
  744. xodr
  745. file.xodr
  746. osgb
  747. file.osgb
  748. :return:
  749. """
  750. for root, dirs, files in os.walk(rootDirectory):
  751. for file in files:
  752. if "xosc" == file[-4:]:
  753. xodrFilePath = ""
  754. osgbFilePath = ""
  755. for odrFile in os.listdir(root[:-4] + "xodr"):
  756. if "xodr" == odrFile[-4:]:
  757. xodrFilePath = root[:-4] + "xodr/" + odrFile
  758. break
  759. for osgbFile in os.listdir(root[:-4] + "osgb"):
  760. if "osgb" == osgbFile[-4:]:
  761. osgbFilePath = root[:-4] + "osgb/" + osgbFile
  762. break
  763. path_changer(root + "/" + file, xodrFilePath, osgbFilePath)
  764. print("Change success: " + root + "/" + file)
  765. def chongQingFormat(rootDirectory):
  766. """
  767. supporting file format: chong qing folder format
  768. :return:
  769. """
  770. counter = 1
  771. for root, dirs, files in os.walk(rootDirectory):
  772. for file in files:
  773. if "xosc" == file[-4:]:
  774. if "ver1.0.xosc" == file[-11:]:
  775. xodrFileName, osgbFileName = readXML(root + "/" + file)
  776. xodrFilePath = "/Xodrs/" + xodrFileName
  777. osgbFilePath = "/Databases/" + osgbFileName
  778. path_changer(root + "/" + file, xodrFilePath, osgbFilePath)
  779. print(counter, "Change success: " + root + "/" + file)
  780. else:
  781. xodrFileName, osgbFileName = readXML(root + "/" + file)
  782. xodrFilePath = "/Xodrs/" + xodrFileName
  783. osgbFilePath = "/Databases/" + osgbFileName
  784. path_changer(root + "/" + file, xodrFilePath, osgbFilePath)
  785. print(counter, "Change success: " + root + "/" + file)
  786. counter += 1