generate_carla.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. from re import A
  2. from turtle import color
  3. from xml.dom.minidom import parse
  4. import xml.dom.minidom
  5. import random
  6. import json
  7. import os
  8. import sys
  9. import subprocess
  10. import signal
  11. from numpy import var
  12. from pyrsistent import v
  13. from regex import F
  14. from scipy import rand
  15. from ga_error_test import *
  16. model_name = "1"
  17. # day_of_month = [0,31,29,31,30,31,30,31,31,30,31,30,31]
  18. # Function vehicleRandomization
  19. #
  20. # Parameters:
  21. # name: 指定的ScenarioObject名称
  22. # car_type: boolean值,true时随机car类型,false时不发生随机
  23. # car_color: list[boolean],决定三种颜色RGB是否发生随机
  24. # var_map: dict 存储变量值
  25. def vehicleRandomization(name, red, green, blue, var_map, e, domain_flags):
  26. scenario_obj = e.getElementsByTagName("ScenarioObject")
  27. for obj in scenario_obj:
  28. if obj.getAttribute("name") == name:
  29. v = obj.getElementsByTagName('Vehicle')[0] # 获取带随机ScenarioObject代码块
  30. org_car_name = v.getAttribute("name")
  31. # variable["org_car_name"] = org_car_name
  32. p_1 = v.getElementsByTagName('Properties')[0] # Properties层
  33. p_2 = p_1.getElementsByTagName('Property')
  34. for p in p_2:
  35. if p.getAttribute("name") == "color":
  36. org_color = p.getAttribute("value")
  37. # print("[" + os.path.basename(__file__) + ", Line " + str(sys._getframe().f_lineno) + ", " + sys._getframe().f_code.co_name + "] ", "车辆原颜色为", org_color, '\n')
  38. color_list = org_color.split(",")
  39. var_map["org_R"] = color_list[0]
  40. var_map["org_G"] = color_list[1]
  41. var_map["org_B"] = color_list[2]
  42. if domain_flags[0]:
  43. final_color = ""
  44. c1 = str(red)
  45. var_map["rand_R"] = c1
  46. final_color += c1
  47. final_color += ","
  48. c2 = str(green)
  49. var_map["rand_G"] = c2
  50. final_color += c2
  51. final_color += ","
  52. c3 = str(blue)
  53. var_map["rand_B"] = c3
  54. final_color += c3
  55. p.setAttribute("value", final_color)
  56. print("[" + os.path.basename(__file__) + ", Line " + str(sys._getframe().f_lineno) + ", " + sys._getframe().f_code.co_name + "] ", "车辆颜色随机为", final_color)
  57. # Function envRandomization
  58. #
  59. # Parameters:
  60. # is_time: boolean值,true时随机日期类型,false时不发生随机
  61. # is_sun: boolean值,true时随机intensity,false时不发生随机
  62. # is_precipitation: boolean值,true时随机天气类型,在rain和dry中间取值
  63. # is_fog: boolean值,true时随机fog的visual_range以及intensity
  64. # var_map: dict 存储变量值
  65. def envRandomization(mut_date, mut_time, mut_fog, mut_precipitation, mut_sun_intensity, var_map, s, domain_flags): # 环境随机代码
  66. env = s.getElementsByTagName('Init')[0].getElementsByTagName('Actions')[0].getElementsByTagName('GlobalAction')[
  67. 0].getElementsByTagName('EnvironmentAction')[0].getElementsByTagName('Environment')[0]
  68. time_of_day = env.getElementsByTagName("TimeOfDay")[0]
  69. weather = env.getElementsByTagName("Weather")[0]
  70. sun = weather.getElementsByTagName("Sun")[0]
  71. fog = weather.getElementsByTagName("Fog")[0]
  72. p = weather.getElementsByTagName("Precipitation")[0]
  73. # 原始时间数据读取
  74. datetime = time_of_day.getAttribute("dateTime")
  75. var_map["org_time"] = datetime
  76. # 原始太阳照度读取
  77. org_s_intensity = sun.getAttribute("intensity")
  78. var_map["org_sun_intensity"] = org_s_intensity
  79. # 原始雾天数据读取
  80. fog_para = fog.getAttribute("visualRange").split("\\")
  81. if (len(fog_para) == 1):
  82. org_visual_range = fog_para[0]
  83. # org_f_intensity = 100
  84. # else:
  85. # org_visual_range = fog_para[0]
  86. # org_f_intensity = fog_para[1]
  87. var_map["org_visual_range"] = org_visual_range
  88. # var_map["org_fog_intensity"] = org_f_intensity
  89. # 原始降水数据读取
  90. org_precipitation = p.getAttribute("precipitationType")
  91. org_p_intensity = p.getAttribute("intensity")
  92. var_map["org_precipitation"] = org_precipitation
  93. var_map["org_precipitation_intensity"] = org_p_intensity
  94. if domain_flags[1]:
  95. # 日期
  96. time_of_day.setAttribute("animation", "true")
  97. date = str(datetime.split("T")[0])
  98. rand_month = mut_date
  99. ori_day = date[8:]
  100. if (rand_month < 10): # format
  101. rand_month = "0" + str(rand_month)
  102. # if(rand_day<10): #format
  103. # rand_day = "0" + str(rand_day)
  104. rand_date = "2020-" + str(rand_month) + "-" + str(ori_day)
  105. var_map["rand_date"] = rand_date
  106. # 时间
  107. time_of_day.setAttribute("animation", "true")
  108. date = rand_date
  109. rand_hour = mut_time
  110. if (rand_hour < 10): # format
  111. rand_hour = "0" + str(rand_hour)
  112. rand_time = date + "T" + str(rand_hour) + ":00:00"
  113. time_of_day.setAttribute("dateTime", rand_time)
  114. var_map["rand_time"] = rand_time
  115. if domain_flags[2]:
  116. # 照度
  117. rand_s_intensity = round((mut_sun_intensity / 100.0), 2)
  118. sun.setAttribute("intensity", str(rand_s_intensity))
  119. var_map["rand_sun_intensity"] = rand_s_intensity
  120. if domain_flags[3]:
  121. # 降水
  122. rand_p_intensity = round((mut_precipitation / 100.0), 2)
  123. p.setAttribute("intensity", str(rand_p_intensity))
  124. var_map["rand_precipitation_intensity"] = rand_p_intensity
  125. if domain_flags[4]:
  126. # 雾天及雾浓度
  127. rand_fog = str(mut_fog) # 雾天
  128. var_map["rand_fog"] = rand_fog
  129. fog_para = rand_fog
  130. fog.setAttribute("visualRange", fog_para)
  131. var_map["visualRange"] = fog_para
  132. print("[" + os.path.basename(__file__) + ", Line " + str(sys._getframe().f_lineno) + ", " + sys._getframe().f_code.co_name + "] ", "环境变量随机为", var_map, '\n')
  133. def Simulation(rand_para, var_map, e, s, domain_flags):
  134. vehicleRandomization("adversary", rand_para[0], rand_para[1], rand_para[2], var_map, e, domain_flags)
  135. envRandomization(rand_para[3], rand_para[4], rand_para[5], rand_para[6], rand_para[7], var_map, s, domain_flags)
  136. def writeBack(xml_path, DOMTree):
  137. # 写回源文件使属性修改生效
  138. fp = open(xml_path, 'w+', encoding='utf-8')
  139. DOMTree.writexml(fp, indent='', addindent='', newl='', encoding='utf-8')
  140. fp.close()
  141. def ga_sim(color1, color2, color3, time1, time2, fog, rain, sun, seed_name, domain_flags, data_collection_para):
  142. mutation_name = seed_name.split("_")
  143. complete_mutation_name = "seed_0_0_" + mutation_name[3]
  144. parse_path = "../seed_pool/" + complete_mutation_name
  145. # 使用minidom解析器打开 XML 文档
  146. DOMTree = xml.dom.minidom.parse(parse_path)
  147. # Linux下改一下路径
  148. ele = DOMTree.documentElement
  149. e = ele.getElementsByTagName("Entities")[0]
  150. s = ele.getElementsByTagName("Storyboard")[0]
  151. xml_path = '../seed_pool/' + seed_name
  152. variable = {"name": "origin & random parameters"}
  153. rand_para = [color1, color2, color3, time1, time2, fog, rain, sun]
  154. Simulation(rand_para, variable, e, s, domain_flags)
  155. # print("[" + os.path.basename(__file__) + ", Line " + str(sys._getframe().f_lineno) + ", " + sys._getframe().f_code.co_name + "] ", variable)
  156. writeBack(xml_path, DOMTree)
  157. print("[" + os.path.basename(__file__) + ", Line " + str(sys._getframe().f_lineno) + ", " + sys._getframe().f_code.co_name + "] ", "\n############# BEFORE RUNNING! ##############\n")
  158. os.system("pkill -9 Carla")
  159. os.system("bash ./ga_sim.sh " + seed_name)
  160. print("[" + os.path.basename(__file__) + ", Line " + str(sys._getframe().f_lineno) + ", " + sys._getframe().f_code.co_name + "] ", "\n############# AFTER RUNNING! ##############\n")
  161. data_collection_para = str(data_collection_para[0])+','+str(data_collection_para[1])+','+str(data_collection_para[2])
  162. os.system("python ga_error_test.py " + model_name + " 1 " + seed_name + " " + data_collection_para)
  163. error = 0
  164. div = 0
  165. list_er = []
  166. with open('list.txt', 'r') as p:
  167. for line in p:
  168. list_er.append(eval(line))
  169. # print("[" + os.path.basename(__file__) + ", Line " + str(sys._getframe().f_lineno) + ", " + sys._getframe().f_code.co_name + "] ", type(eval(line)))
  170. with open('./error_count.csv', 'r') as f:
  171. rows = len(f.readlines()) - 1
  172. f.seek(0)
  173. for i, line in enumerate(f):
  174. if i == 0:
  175. continue
  176. if line.split(',')[0] == seed_name:
  177. error = int(line.split(',')[1])
  178. div = int(line.split(',')[2])
  179. return error, div, list_er