comfort.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ##################################################################
  4. #
  5. # Copyright (c) 2023 CICV, Inc. All Rights Reserved
  6. #
  7. ##################################################################
  8. """
  9. @Authors: zhanghaiwen(zhanghaiwen@china-icv.cn), yangzihao(yangzihao@china-icv.cn)
  10. @Data: 2023/06/25
  11. @Last Modified: 2023/06/25
  12. @Summary: Comfort metrics
  13. """
  14. import os
  15. import sys
  16. import math
  17. import pandas as pd
  18. import numpy as np
  19. import scipy.signal
  20. sys.path.append('../common')
  21. sys.path.append('../modules')
  22. sys.path.append('../results')
  23. from data_info import DataInfoList
  24. from score_weight import cal_score_with_priority, cal_weight_from_80
  25. from common import get_interpolation, score_grade, string_concatenate, replace_key_with_value, _cal_max_min_avg
  26. import matplotlib.pyplot as plt
  27. def peak_valley_decorator(method):
  28. def wrapper(self, *args, **kwargs):
  29. peak_valley = self._peak_valley_determination(self.df)
  30. pv_list = self.df.loc[peak_valley, ['simTime', 'speedH']].values.tolist()
  31. if len(pv_list) != 0:
  32. flag = True
  33. p_last = pv_list[0]
  34. for i in range(1, len(pv_list)):
  35. p_curr = pv_list[i]
  36. if self._peak_valley_judgment(p_last, p_curr):
  37. # method(self, p_curr, p_last)
  38. method(self, p_curr, p_last, flag, *args, **kwargs)
  39. else:
  40. p_last = p_curr
  41. return method
  42. else:
  43. flag = False
  44. p_curr = [0, 0]
  45. p_last = [0, 0]
  46. method(self, p_curr, p_last, flag, *args, **kwargs)
  47. return method
  48. return wrapper
  49. class Comfort(object):
  50. """
  51. Class for achieving comfort metrics for autonomous driving.
  52. Attributes:
  53. dataframe: Vehicle driving data, stored in dataframe format.
  54. """
  55. def __init__(self, data_processed, scoreModel, resultPath):
  56. self.eval_data = pd.DataFrame()
  57. self.data_processed = data_processed
  58. self.scoreModel = scoreModel
  59. self.resultPath = resultPath
  60. # self.data = data_processed.obj_data[1]
  61. self.data = data_processed.ego_df
  62. self.mileage = data_processed.report_info['mileage']
  63. self.ego_df = pd.DataFrame()
  64. # self.discomfort_df = pd.DataFrame(columns=['start_time', 'end_time', 'start_frame', 'end_frame', 'type'])
  65. self.config = data_processed.config
  66. comfort_config = data_processed.comfort_config
  67. self.comfort_config = comfort_config
  68. # common data
  69. self.bulitin_metric_list = self.config.builtinMetricList
  70. # dimension data
  71. self.weight_custom = comfort_config['weightCustom']
  72. self.metric_list = comfort_config['metric']
  73. self.type_list = comfort_config['type']
  74. self.type_name_dict = comfort_config['typeName']
  75. self.name_dict = comfort_config['name']
  76. self.unit_dict = comfort_config['unit']
  77. # custom metric data
  78. # self.customMetricParam = comfort_config['customMetricParam']
  79. # self.custom_metric_list = list(self.customMetricParam.keys())
  80. # self.custom_data = custom_data
  81. # self.custom_param_dict = {}
  82. # score data
  83. self.weight = comfort_config['weightDimension']
  84. self.weight_type_dict = comfort_config['typeWeight']
  85. self.weight_type_list = comfort_config['typeWeightList']
  86. self.weight_dict = comfort_config['weight']
  87. self.weight_list = comfort_config['weightList']
  88. self.priority_dict = comfort_config['priority']
  89. self.priority_list = comfort_config['priorityList']
  90. self.kind_dict = comfort_config['kind']
  91. self.optimal_dict = comfort_config['optimal']
  92. # self.optimal1_dict = self.optimal_dict[0]
  93. # self.optimal2_dict = self.optimal_dict[1]
  94. # self.optimal3_dict = self.optimal_dict[2]
  95. self.multiple_dict = comfort_config['multiple']
  96. self.kind_list = comfort_config['kindList']
  97. self.optimal_list = comfort_config['optimalList']
  98. self.multiple_list = comfort_config['multipleList']
  99. # metric data
  100. self.metric_dict = comfort_config['typeMetricDict']
  101. self.lat_metric_list = self.metric_dict['comfortLat']
  102. self.lon_metric_list = self.metric_dict['comfortLon']
  103. # self.lat_metric_list = ["zigzag", "shake"]
  104. # self.lon_metric_list = ["cadence", "slamBrake", "slamAccelerate"]
  105. self.time_list = data_processed.driver_ctrl_data['time_list']
  106. self.frame_list = data_processed.driver_ctrl_data['frame_list']
  107. self.speed_list = []
  108. self.commandSpeed_list = []
  109. self.accel_list = []
  110. self.accelH_list = []
  111. self.linear_accel_dict = dict()
  112. self.angular_accel_dict = dict()
  113. self.speed_instruction_dict = dict()
  114. self.count_dict = {}
  115. self.duration_dict = {}
  116. self.strength_dict = {}
  117. self.discomfort_count = 0
  118. self.zigzag_count = 0
  119. # self.shake_count = 0
  120. self.cadence_count = 0
  121. self.slam_brake_count = 0
  122. self.slam_accel_count = 0
  123. self.speed_instruction_jump_count = 0
  124. # self.zigzag_strength = 0
  125. # self.shake_strength = 0
  126. # self.cadence_strength = 0
  127. # self.slam_brake_strength = 0
  128. # self.slam_accel_strength = 0
  129. #
  130. self.discomfort_duration = 0
  131. # self.zigzag_duration = 0
  132. # self.shake_duration = 0
  133. # self.cadence_duration = 0
  134. # self.slam_brake_duration = 0
  135. # self.slam_accel_duration = 0
  136. self.zigzag_time_list = []
  137. # self.zigzag_frame_list = []
  138. self.zigzag_stre_list = []
  139. self.cur_ego_path_list = []
  140. self.curvature_list = []
  141. self._get_data()
  142. self._comf_param_cal()
  143. def _get_data(self):
  144. """
  145. """
  146. comfort_info_list = DataInfoList.COMFORT_INFO
  147. self.ego_df = self.data[comfort_info_list].copy()
  148. # self.df = self.ego_df.set_index('simFrame') # 索引是csv原索引
  149. self.df = self.ego_df.reset_index(drop=True) # 索引是csv原索引
  150. def _cal_cur_ego_path(self, row):
  151. try:
  152. divide = (row['speedX'] ** 2 + row['speedY'] ** 2) ** (3 / 2)
  153. if not divide:
  154. res = None
  155. else:
  156. res = (row['speedX'] * row['accelY'] - row['speedY'] * row['accelX']) / divide
  157. except:
  158. res = None
  159. return res
  160. def _comf_param_cal(self):
  161. """
  162. """
  163. # for i in range(len(self.optimal_list)):
  164. # if i % 3 == 2:
  165. # continue
  166. # else:
  167. # self.optimal_list[i] = round(self.optimal_list[i] * self.mileage / 100000, 8)
  168. # self.optimal_list = [round(self.optimal_list[i] * self.mileage / 100000, 8) for i in range(len(self.optimal_list))]
  169. self.optimal_dict = {key: value * self.mileage / 100000 for key, value in self.optimal_dict.copy().items()}
  170. # self.optimal1_dict = {key: value * self.mileage / 100000 for key, value in self.optimal1_dict.copy().items()}
  171. # self.optimal2_dict = {key: value * self.mileage / 100000 for key, value in self.optimal2_dict.copy().items()}
  172. # [log]
  173. self.ego_df['ip_acc'] = self.ego_df['v'].apply(get_interpolation, point1=[18, 4], point2=[72, 2])
  174. self.ego_df['ip_dec'] = self.ego_df['v'].apply(get_interpolation, point1=[18, -5], point2=[72, -3.5])
  175. self.ego_df['slam_brake'] = self.ego_df.apply(
  176. lambda row: self._slam_brake_process(row['lon_acc'], row['ip_dec']), axis=1)
  177. self.ego_df['slam_accel'] = self.ego_df.apply(
  178. lambda row: self._slam_accelerate_process(row['lon_acc'], row['ip_acc']), axis=1)
  179. self.ego_df['cadence'] = self.ego_df.apply(
  180. lambda row: self._cadence_process_new(row['lon_acc'], row['ip_acc'], row['ip_dec']), axis=1)
  181. self.speed_list = self.ego_df['v'].values.tolist()
  182. self.commandSpeed_list = self.ego_df['cmd_lon_v'].values.tolist()
  183. self.accel_list = self.ego_df['accel'].values.tolist()
  184. self.accelH_list = self.ego_df['accelH'].values.tolist()
  185. v_jump_threshold = 0.5
  186. self.ego_df['cmd_lon_v_diff'] = self.ego_df['cmd_lon_v'].diff()
  187. self.ego_df['cmd_v_jump'] = (abs(self.ego_df['cmd_lon_v_diff']) > v_jump_threshold).astype(int)
  188. self.linear_accel_dict = _cal_max_min_avg(self.ego_df['accel'].dropna().values.tolist())
  189. self.angular_accel_dict = _cal_max_min_avg(self.ego_df['accelH'].dropna().values.tolist())
  190. self.speed_instruction_dict = _cal_max_min_avg(self.ego_df['cmd_lon_v_diff'].dropna().values.tolist())
  191. def _peak_valley_determination(self, df):
  192. """
  193. Determine the peak and valley of the vehicle based on its current angular velocity.
  194. Parameters:
  195. df: Dataframe containing the vehicle angular velocity.
  196. Returns:
  197. peak_valley: List of indices representing peaks and valleys.
  198. """
  199. peaks, _ = scipy.signal.find_peaks(df['speedH'], height=0.01, distance=1, prominence=0.01)
  200. valleys, _ = scipy.signal.find_peaks(-df['speedH'], height=0.01, distance=1, prominence=0.01)
  201. peak_valley = sorted(list(peaks) + list(valleys))
  202. return peak_valley
  203. def _peak_valley_judgment(self, p_last, p_curr, tw=6000, avg=0.4):
  204. """
  205. Determine if the given peaks and valleys satisfy certain conditions.
  206. Parameters:
  207. p_last: Previous peak or valley data point.
  208. p_curr: Current peak or valley data point.
  209. tw: Threshold time difference between peaks and valleys.
  210. avg: Angular velocity gap threshold.
  211. Returns:
  212. Boolean indicating whether the conditions are satisfied.
  213. """
  214. t_diff = p_curr[0] - p_last[0]
  215. v_diff = abs(p_curr[1] - p_last[1])
  216. s = p_curr[1] * p_last[1]
  217. zigzag_flag = t_diff < tw and v_diff > avg and s < 0
  218. if zigzag_flag and ([p_last[0], p_curr[0]] not in self.zigzag_time_list):
  219. self.zigzag_time_list.append([p_last[0], p_curr[0]])
  220. return zigzag_flag
  221. @peak_valley_decorator
  222. def zigzag_count_func(self, p_curr, p_last, flag=True):
  223. """
  224. Count the number of zigzag movements.
  225. Parameters:
  226. df: Input dataframe data.
  227. Returns:
  228. zigzag_count: Number of zigzag movements.
  229. """
  230. if flag:
  231. self.zigzag_count += 1
  232. else:
  233. self.zigzag_count += 0
  234. @peak_valley_decorator
  235. def cal_zigzag_strength_strength(self, p_curr, p_last, flag=True):
  236. """
  237. Calculate various strength statistics.
  238. Returns:
  239. Tuple containing maximum strength, minimum strength,
  240. average strength, and 99th percentile strength.
  241. """
  242. if flag:
  243. v_diff = abs(p_curr[1] - p_last[1])
  244. t_diff = p_curr[0] - p_last[0]
  245. self.zigzag_stre_list.append(v_diff / t_diff) # 平均角加速度
  246. else:
  247. self.zigzag_stre_list = []
  248. def _cadence_process(self, lon_acc_roc, ip_dec_roc):
  249. if abs(lon_acc_roc) >= abs(ip_dec_roc) or abs(lon_acc_roc) < 1:
  250. return np.nan
  251. # elif abs(lon_acc_roc) == 0:
  252. elif abs(lon_acc_roc) == 0:
  253. return 0
  254. elif lon_acc_roc > 0 and lon_acc_roc < -ip_dec_roc:
  255. return 1
  256. elif lon_acc_roc < 0 and lon_acc_roc > ip_dec_roc:
  257. return -1
  258. def _slam_brake_process(self, lon_acc, ip_dec):
  259. if lon_acc - ip_dec < 0:
  260. return 1
  261. else:
  262. return 0
  263. def _slam_accelerate_process(self, lon_acc, ip_acc):
  264. if lon_acc - ip_acc > 0:
  265. return 1
  266. else:
  267. return 0
  268. def _cadence_process_new(self, lon_acc, ip_acc, ip_dec):
  269. if abs(lon_acc) < 1 or lon_acc > ip_acc or lon_acc < ip_dec:
  270. return np.nan
  271. # elif abs(lon_acc_roc) == 0:
  272. elif abs(lon_acc) == 0:
  273. return 0
  274. elif lon_acc > 0 and lon_acc < ip_acc:
  275. return 1
  276. elif lon_acc < 0 and lon_acc > ip_dec:
  277. return -1
  278. def _cadence_detector(self):
  279. """
  280. # 加速度突变:先加后减,先减后加,先加然后停,先减然后停
  281. # 顿挫:2s内多次加速度变化率突变
  282. # 求出每一个特征点,然后提取,然后将每一个特征点后面的2s做一个窗口,统计频率,避免无效运算
  283. # 将特征点筛选出来
  284. # 将特征点时间作为聚类标准,大于1s的pass,小于等于1s的聚类到一个分组
  285. # 去掉小于3个特征点的分组
  286. """
  287. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'cadence']].copy()
  288. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'lon_acc_roc', 'cadence']].copy()
  289. time_list = data['simTime'].values.tolist()
  290. data = data[data['cadence'] != np.nan]
  291. data['cadence_diff'] = data['cadence'].diff()
  292. data.dropna(subset='cadence_diff', inplace=True)
  293. data = data[data['cadence_diff'] != 0]
  294. t_list = data['simTime'].values.tolist()
  295. f_list = data['simFrame'].values.tolist()
  296. group_time = []
  297. group_frame = []
  298. sub_group_time = []
  299. sub_group_frame = []
  300. for i in range(len(f_list)):
  301. if not sub_group_time or t_list[i] - t_list[i - 1] <= 1: # 特征点相邻一秒内的,算作同一组顿挫
  302. sub_group_time.append(t_list[i])
  303. sub_group_frame.append(f_list[i])
  304. else:
  305. group_time.append(sub_group_time)
  306. group_frame.append(sub_group_frame)
  307. sub_group_time = [t_list[i]]
  308. sub_group_frame = [f_list[i]]
  309. group_time.append(sub_group_time)
  310. group_frame.append(sub_group_frame)
  311. group_time = [g for g in group_time if len(g) >= 1] # 有一次特征点则算作一次顿挫
  312. # group_frame = [g for g in group_frame if len(g) >= 1]
  313. # 输出图表值
  314. cadence_time = [[g[0], g[-1]] for g in group_time]
  315. # cadence_frame = [[g[0], g[-1]] for g in group_frame]
  316. # 将顿挫组的起始时间为组重新统计时间
  317. cadence_time_list = [time for pair in cadence_time for time in time_list if pair[0] <= time <= pair[1]]
  318. # stre_list = []
  319. freq_list = []
  320. for g in group_time:
  321. # calculate strength
  322. g_df = data[data['simTime'].isin(g)]
  323. # strength = g_df['lon_acc'].abs().mean()
  324. # stre_list.append(strength)
  325. # calculate frequency
  326. cnt = len(g)
  327. t_start = g_df['simTime'].iloc[0]
  328. t_end = g_df['simTime'].iloc[-1]
  329. t_delta = t_end - t_start
  330. frequency = cnt / t_delta
  331. freq_list.append(frequency)
  332. self.cadence_count = len(freq_list)
  333. # cadence_stre = sum(stre_list) / len(stre_list) if stre_list else 0
  334. return cadence_time_list
  335. def _slam_brake_detector(self):
  336. # 统计急刹全为1的分段的个数,记录分段开头的frame_ID
  337. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'ip_dec_roc', 'slam_brake']].copy()
  338. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'lon_acc_roc', 'ip_dec', 'slam_brake']].copy()
  339. # data['slam_diff'] = data['slam_brake'].diff()
  340. # res_df = data[data['slam_diff'] == 1]
  341. res_df = data[data['slam_brake'] == 1]
  342. t_list = res_df['simTime'].values
  343. f_list = res_df['simFrame'].values.tolist()
  344. group_time = []
  345. group_frame = []
  346. sub_group_time = []
  347. sub_group_frame = []
  348. for i in range(len(f_list)):
  349. if not sub_group_time or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急刹
  350. sub_group_time.append(t_list[i])
  351. sub_group_frame.append(f_list[i])
  352. else:
  353. group_time.append(sub_group_time)
  354. group_frame.append(sub_group_frame)
  355. sub_group_time = [t_list[i]]
  356. sub_group_frame = [f_list[i]]
  357. group_time.append(sub_group_time)
  358. group_frame.append(sub_group_frame)
  359. group_time = [g for g in group_time if len(g) >= 2] # 达到两帧算作一次急刹
  360. # group_frame = [g for g in group_frame if len(g) >= 2]
  361. time_list = [element for sublist in group_time for element in sublist]
  362. self.slam_brake_count = len(group_time) # / self.mileage # * 1000000
  363. return time_list
  364. def _slam_accel_detector(self):
  365. # 统计急刹全为1的分段的个数,记录分段开头的frame_ID
  366. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'ip_acc_roc', 'slam_accel']].copy()
  367. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'ip_acc', 'slam_accel']].copy()
  368. # data['slam_diff'] = data['slam_accel'].diff()
  369. # res_df = data.loc[data['slam_diff'] == 1]
  370. res_df = data.loc[data['slam_accel'] == 1]
  371. t_list = res_df['simTime'].values
  372. f_list = res_df['simFrame'].values.tolist()
  373. group_time = []
  374. group_frame = []
  375. sub_group_time = []
  376. sub_group_frame = []
  377. for i in range(len(f_list)):
  378. if not group_time or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急加速
  379. sub_group_time.append(t_list[i])
  380. sub_group_frame.append(f_list[i])
  381. else:
  382. group_time.append(sub_group_time)
  383. group_frame.append(sub_group_frame)
  384. sub_group_time = [t_list[i]]
  385. sub_group_frame = [f_list[i]]
  386. group_time.append(sub_group_time)
  387. group_frame.append(sub_group_frame)
  388. group_time = [g for g in group_time if len(g) >= 2]
  389. # group_frame = [g for g in group_frame if len(g) >= 2]
  390. time_list = [element for sublist in group_time for element in sublist]
  391. self.slam_accel_count = len(group_time) # / self.mileage # * 1000000
  392. return time_list
  393. def _speed_instruction_jump_detector(self):
  394. data = self.ego_df[['simTime', 'simFrame', 'cmd_lon_v', 'cmd_lon_v_diff', 'cmd_v_jump']].copy()
  395. # data['slam_diff'] = data['slam_accel'].diff()
  396. # res_df = data.loc[data['slam_diff'] == 1]
  397. res_df = data.loc[data['cmd_v_jump'] == 1]
  398. t_list = res_df['simTime'].values
  399. f_list = res_df['simFrame'].values.tolist()
  400. group_time = []
  401. group_frame = []
  402. sub_group_time = []
  403. sub_group_frame = []
  404. for i in range(len(f_list)):
  405. if not group_time or f_list[i] - f_list[i - 1] <= 10: # 连续帧的算作同一组跳变
  406. sub_group_time.append(t_list[i])
  407. sub_group_frame.append(f_list[i])
  408. else:
  409. group_time.append(sub_group_time)
  410. group_frame.append(sub_group_frame)
  411. sub_group_time = [t_list[i]]
  412. sub_group_frame = [f_list[i]]
  413. group_time.append(sub_group_time)
  414. group_frame.append(sub_group_frame)
  415. group_time = [g for g in group_time if len(g) >= 2]
  416. # group_frame = [g for g in group_frame if len(g) >= 2]
  417. time_list = [element for sublist in group_time for element in sublist]
  418. self.speed_instruction_jump_count = len(group_time) # / self.mileage # * 1000000
  419. return time_list
  420. def comf_statistic(self):
  421. """
  422. """
  423. # df = self.ego_df[['simTime', 'cur_diff', 'lon_acc', 'lon_acc_roc', 'accelH']].copy()
  424. df = self.ego_df[['simTime', 'lon_acc', 'lon_acc_roc', 'accelH']].copy()
  425. self.zigzag_count_func()
  426. self.cal_zigzag_strength_strength()
  427. # if self.zigzag_time_list:
  428. # zigzag_df = pd.DataFrame(self.zigzag_time_list, columns=['start_time', 'end_time'])
  429. # zigzag_df = get_frame_with_time(zigzag_df, self.ego_df)
  430. # zigzag_df['type'] = 'zigzag'
  431. # self.discomfort_df = pd.concat([self.discomfort_df, zigzag_df], ignore_index=True)
  432. # discomfort_df = pd.concat([time_df, frame_df], axis=1)
  433. # self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  434. zigzag_t_list = []
  435. # 只有[t_start, t_end]数对,要提取为完整time list
  436. t_list = df['simTime'].values.tolist()
  437. for t_start, t_end in self.zigzag_time_list:
  438. index_1 = t_list.index(t_start)
  439. index_2 = t_list.index(t_end)
  440. zigzag_t_list.extend(t_list[index_1:index_2 + 1])
  441. zigzag_t_list = list(set(zigzag_t_list))
  442. # shake_t_list = self._shake_detector()
  443. cadence_t_list = self._cadence_detector()
  444. slam_brake_t_list = self._slam_brake_detector()
  445. slam_accel_t_list = self._slam_accel_detector()
  446. speed_instruction_jump_t_list = self._speed_instruction_jump_detector()
  447. discomfort_time_list = zigzag_t_list + cadence_t_list + slam_brake_t_list + slam_accel_t_list + speed_instruction_jump_t_list
  448. discomfort_time_list = sorted(discomfort_time_list) # 排序
  449. discomfort_time_list = list(set(discomfort_time_list)) # 去重
  450. time_diff = self.time_list[3] - self.time_list[2]
  451. # time_diff = 0.4
  452. self.discomfort_duration = len(discomfort_time_list) * time_diff
  453. self.count_dict = {
  454. "zigzag": self.zigzag_count,
  455. # "shake": self.shake_count,
  456. "cadence": self.cadence_count,
  457. "slamBrake": self.slam_brake_count,
  458. "slamAccelerate": self.slam_accel_count,
  459. "speedInstructionJump": self.speed_instruction_jump_count
  460. }
  461. tmp_comf_arr = [self.zigzag_count, self.cadence_count, self.slam_brake_count, self.slam_accel_count,
  462. self.speed_instruction_jump_count]
  463. self.discomfort_count = sum(tmp_comf_arr)
  464. comf_arr = [tmp_comf_arr]
  465. return comf_arr
  466. # def _nan_detect(self, num):
  467. # if math.isnan(num):
  468. # return 0
  469. # return num
  470. def comf_score_new(self):
  471. arr_comf = self.comf_statistic()
  472. print("\n[平顺性表现及得分情况]")
  473. print("平顺性各指标值:", [[round(num, 2) for num in row] for row in arr_comf])
  474. arr_comf = np.array(arr_comf)
  475. score_model = self.scoreModel(self.kind_list, self.optimal_list, self.multiple_list, arr_comf)
  476. score_sub = score_model.cal_score()
  477. score_metric = list(map(lambda x: 80 if np.isnan(x) else x, score_sub))
  478. metric_list = [x for x in self.metric_list if x in self.config.builtinMetricList]
  479. score_metric_dict = {key: value for key, value in zip(metric_list, score_metric)}
  480. # custom_metric_list = list(self.customMetricParam.keys())
  481. # for metric in custom_metric_list:
  482. # value = self.custom_data[metric]['value']
  483. # param_list = self.customMetricParam[metric]
  484. # score = self.custom_metric_score(metric, value, param_list)
  485. # score_metric_dict[metric] = round(score, 2)
  486. # score_metric_dict = {key: score_metric_dict[key] for key in self.metric_list}
  487. # score_metric = list(score_metric_dict.values())
  488. score_type_dict = {}
  489. if self.weight_custom: # 自定义权重
  490. score_metric_with_weight_dict = {key: score_metric_dict[key] * self.weight_dict[key] for key in
  491. self.weight_dict}
  492. for type in self.type_list:
  493. type_score = sum(
  494. value for key, value in score_metric_with_weight_dict.items() if key in self.metric_dict[type])
  495. score_type_dict[type] = round(type_score, 2)
  496. score_type_with_weight_dict = {key: score_type_dict[key] * self.weight_type_dict[key] for key in
  497. score_type_dict}
  498. score_comfort = sum(score_type_with_weight_dict.values())
  499. else: # 客观赋权
  500. self.weight_list = cal_weight_from_80(score_metric)
  501. self.weight_dict = {key: value for key, value in zip(self.metric_list, self.weight_list)}
  502. score_comfort = cal_score_with_priority(score_metric, self.weight_list, self.priority_list)
  503. for type in self.type_list:
  504. type_weight = sum(value for key, value in self.weight_dict.items() if key in self.metric_dict[type])
  505. self.weight_dict = {key: round(value / type_weight, 4) for key, value in self.weight_dict.items() if
  506. key in self.metric_dict[type]}
  507. type_score_metric = [value for key, value in score_metric_dict.items() if key in self.metric_dict[type]]
  508. type_weight_list = [value for key, value in self.weight_dict.items() if key in self.metric_dict[type]]
  509. type_priority_list = [value for key, value in self.priority_dict.items() if
  510. key in self.metric_dict[type]]
  511. type_score = cal_score_with_priority(type_score_metric, type_weight_list, type_priority_list)
  512. score_type_dict[type] = round(type_score, 2)
  513. score_comfort = round(score_comfort, 2)
  514. print("平顺性各指标基准值:", self.optimal_list)
  515. print(f"平顺性得分为:{score_comfort:.2f}分。")
  516. print(f"平顺性各类型得分为:{score_type_dict}。")
  517. print(f"平顺性各指标得分为:{score_metric_dict}。")
  518. return score_comfort, score_type_dict, score_metric_dict
  519. def zip_time_pairs(self, zip_list, upper_limit=9999):
  520. zip_time_pairs = zip(self.time_list, zip_list)
  521. zip_vs_time = [[x, upper_limit if y > upper_limit else y] for x, y in zip_time_pairs if not math.isnan(y)]
  522. return zip_vs_time
  523. def report_statistic(self):
  524. """
  525. Returns:
  526. """
  527. # report_dict = {
  528. # "name": "平顺性",
  529. # "weight": f"{self.weight * 100:.2f}%",
  530. # "weightDistribution": weight_distribution,
  531. # "score": score_comfort,
  532. # "level": grade_comfort,
  533. # 'discomfortCount': self.discomfort_count,
  534. # "description1": comf_description1,
  535. # "description2": comf_description2,
  536. # "description3": comf_description3,
  537. # "description4": comf_description4,
  538. #
  539. # "comfortLat": lat_dict,
  540. # "comfortLon": lon_dict,
  541. #
  542. # "speData": ego_speed_vs_time,
  543. # "speMarkLine": discomfort_slices,
  544. #
  545. # "accData": lon_acc_vs_time,
  546. # "accMarkLine": discomfort_acce_slices,
  547. #
  548. # "anvData": yawrate_vs_time,
  549. # "anvMarkLine": discomfort_zigzag_slices,
  550. #
  551. # "anaData": yawrate_roc_vs_time,
  552. # "anaMarkLine": discomfort_zigzag_slices,
  553. #
  554. # "curData": [cur_ego_path_vs_time, curvature_vs_time],
  555. # "curMarkLine": discomfort_shake_slices,
  556. # }
  557. # brakePedal_list = self.data_processed.driver_ctrl_data['brakePedal_list']
  558. # throttlePedal_list = self.data_processed.driver_ctrl_data['throttlePedal_list']
  559. # steeringWheel_list = self.data_processed.driver_ctrl_data['steeringWheel_list']
  560. #
  561. # # common parameter calculate
  562. # brake_vs_time = self.zip_time_pairs(brakePedal_list, 100)
  563. # throttle_vs_time = self.zip_time_pairs(throttlePedal_list, 100)
  564. # steering_vs_time = self.zip_time_pairs(steeringWheel_list)
  565. report_dict = {
  566. "name": "平顺性",
  567. "weight": f"{self.weight * 100:.2f}%",
  568. # 'discomfortCount': self.discomfort_count,
  569. }
  570. score_comfort, score_type_dict, score_metric_dict = self.comf_score_new()
  571. score_comfort = int(score_comfort) if int(score_comfort) == score_comfort else round(score_comfort, 2)
  572. grade_comfort = score_grade(score_comfort)
  573. report_dict["score"] = score_comfort
  574. report_dict["level"] = grade_comfort
  575. description = f"· 在平顺性方面,得分{score_comfort}分,表现{grade_comfort},"
  576. is_good = True
  577. if any(score_metric_dict[metric] < 80 for metric in self.lon_metric_list):
  578. is_good = False
  579. description += "线加速度变化剧烈,"
  580. tmp = [metric for metric in self.lon_metric_list if score_metric_dict[metric] < 80]
  581. str_tmp = "、".join(tmp)
  582. description += f"有{str_tmp}情况,需重点优化。"
  583. if any(score_metric_dict[metric] < 80 for metric in self.lat_metric_list):
  584. is_good = False
  585. description += "角加速度变化剧烈,"
  586. tmp = [metric for metric in self.lat_metric_list if score_metric_dict[metric] < 80]
  587. str_tmp = "、".join(tmp)
  588. description += f"有{str_tmp}情况,需重点优化。"
  589. if is_good:
  590. description += f"线加速度和角加速度变化平顺,表现{grade_comfort}。"
  591. report_dict["description"] = replace_key_with_value(description, self.name_dict)
  592. # indexes
  593. description1 = f"最大值:{self.linear_accel_dict['max']}m/s²;" \
  594. f"最小值:{self.linear_accel_dict['min']}m/s²;" \
  595. f"平均值:{self.linear_accel_dict['avg']}m/s²"
  596. description2 = f"最大值:{self.angular_accel_dict['max']}rad/s²;" \
  597. f"最小值:{self.angular_accel_dict['min']}rad/s²;" \
  598. f"平均值:{self.angular_accel_dict['avg']}rad/s²"
  599. description3 = f"次数:{self.speed_instruction_jump_count}次; " \
  600. f"最大值:{self.speed_instruction_dict['max']}m/s;" \
  601. f"最小值:{self.speed_instruction_dict['min']}m/s;" \
  602. f"平均值:{self.speed_instruction_dict['avg']}m/s"
  603. linearAccelerate_index = {
  604. "weight": self.weight_type_dict['comfortLon'],
  605. "score": score_type_dict['comfortLon'],
  606. "description": description1
  607. }
  608. angularAccelerate_index = {
  609. "weight": self.weight_type_dict['comfortLat'],
  610. "score": score_type_dict['comfortLat'],
  611. "description": description2
  612. }
  613. speedInstruction_index = {
  614. "weight": self.weight_type_dict['comfortSpeed'],
  615. "score": score_type_dict['comfortSpeed'],
  616. "description": description3
  617. }
  618. indexes_dict = {
  619. "comfortLat": linearAccelerate_index,
  620. "comfortLon": angularAccelerate_index,
  621. "comfortSpeed": speedInstruction_index
  622. }
  623. report_dict["indexes"] = indexes_dict
  624. # LinearAccelerate.png
  625. plt.figure(figsize=(12, 3))
  626. plt.plot(self.time_list, self.accel_list, label='Linear Accelerate')
  627. plt.xlabel('Time(s)')
  628. plt.ylabel('Linear Accelerate(m/s^2)')
  629. plt.legend()
  630. # 调整布局,消除空白边界
  631. plt.tight_layout()
  632. plt.savefig(os.path.join(self.resultPath, "LinearAccelerate.png"))
  633. plt.close()
  634. # AngularAccelerate.png
  635. plt.figure(figsize=(12, 3))
  636. plt.plot(self.time_list, self.accelH_list, label='Angular Accelerate')
  637. plt.xlabel('Time(s)')
  638. plt.ylabel('Angular Accelerate(rad/s^2)')
  639. plt.legend()
  640. # 调整布局,消除空白边界
  641. plt.tight_layout()
  642. plt.savefig(os.path.join(self.resultPath, "AngularAccelerate.png"))
  643. plt.close()
  644. # Speed.png
  645. plt.figure(figsize=(12, 3))
  646. plt.plot(self.time_list, self.speed_list, label='Speed')
  647. plt.xlabel('Time(s)')
  648. plt.ylabel('Speed(m/s)')
  649. plt.legend()
  650. # 调整布局,消除空白边界
  651. plt.tight_layout()
  652. plt.savefig(os.path.join(self.resultPath, "Speed.png"))
  653. plt.close()
  654. # commandSpeed.png draw
  655. plt.figure(figsize=(12, 3))
  656. plt.plot(self.time_list, self.commandSpeed_list, label='commandSpeed')
  657. plt.xlabel('Time(s)')
  658. plt.ylabel('commandSpeed(m/s)')
  659. plt.legend()
  660. # 调整布局,消除空白边界
  661. plt.tight_layout()
  662. plt.savefig(os.path.join(self.resultPath, "CommandSpeed.png"))
  663. plt.close()
  664. print(report_dict)
  665. return report_dict
  666. # def get_eval_data(self):
  667. # df = self.eval_data[
  668. # ['simTime', 'simFrame', 'playerId', 'ip_acc', 'ip_dec', 'slam_brake', 'slam_accel', 'cadence']].copy()
  669. # return df