comfort.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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, get_frame_with_time
  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 _cal_max_min_avg(self, num_list):
  161. maxx = round(max(num_list), 4) if num_list else "-"
  162. minn = round(min(num_list), 4) if num_list else "-"
  163. avg = round(sum(num_list) / len(num_list), 4) if num_list else "-"
  164. result = {
  165. "max": maxx,
  166. "min": minn,
  167. "avg": avg
  168. }
  169. return result
  170. def _comf_param_cal(self):
  171. """
  172. """
  173. # for i in range(len(self.optimal_list)):
  174. # if i % 3 == 2:
  175. # continue
  176. # else:
  177. # self.optimal_list[i] = round(self.optimal_list[i] * self.mileage / 100000, 8)
  178. # self.optimal_list = [round(self.optimal_list[i] * self.mileage / 100000, 8) for i in range(len(self.optimal_list))]
  179. self.optimal_dict = {key: value * self.mileage / 100000 for key, value in self.optimal_dict.copy().items()}
  180. # self.optimal1_dict = {key: value * self.mileage / 100000 for key, value in self.optimal1_dict.copy().items()}
  181. # self.optimal2_dict = {key: value * self.mileage / 100000 for key, value in self.optimal2_dict.copy().items()}
  182. # [log]
  183. self.ego_df['ip_acc'] = self.ego_df['v'].apply(get_interpolation, point1=[18, 4], point2=[72, 2])
  184. self.ego_df['ip_dec'] = self.ego_df['v'].apply(get_interpolation, point1=[18, -5], point2=[72, -3.5])
  185. self.ego_df['slam_brake'] = self.ego_df.apply(
  186. lambda row: self._slam_brake_process(row['lon_acc'], row['ip_dec']), axis=1)
  187. self.ego_df['slam_accel'] = self.ego_df.apply(
  188. lambda row: self._slam_accelerate_process(row['lon_acc'], row['ip_acc']), axis=1)
  189. self.ego_df['cadence'] = self.ego_df.apply(
  190. lambda row: self._cadence_process_new(row['lon_acc'], row['ip_acc'], row['ip_dec']), axis=1)
  191. self.speed_list = self.ego_df['v'].values.tolist()
  192. self.commandSpeed_list = self.ego_df['cmd_lon_v'].values.tolist()
  193. self.accel_list = self.ego_df['accel'].values.tolist()
  194. self.accelH_list = self.ego_df['accelH'].values.tolist()
  195. v_jump_threshold = 0.5
  196. self.ego_df['cmd_lon_v_diff'] = self.ego_df['cmd_lon_v'].diff()
  197. self.ego_df['cmd_v_jump'] = (abs(self.ego_df['cmd_lon_v_diff']) > v_jump_threshold).astype(int)
  198. self.linear_accel_dict = self._cal_max_min_avg(self.ego_df['accel'].dropna().values.tolist())
  199. self.angular_accel_dict = self._cal_max_min_avg(self.ego_df['accelH'].dropna().values.tolist())
  200. self.speed_instruction_dict = self._cal_max_min_avg(self.ego_df['cmd_lon_v_diff'].dropna().values.tolist())
  201. def _peak_valley_determination(self, df):
  202. """
  203. Determine the peak and valley of the vehicle based on its current angular velocity.
  204. Parameters:
  205. df: Dataframe containing the vehicle angular velocity.
  206. Returns:
  207. peak_valley: List of indices representing peaks and valleys.
  208. """
  209. peaks, _ = scipy.signal.find_peaks(df['speedH'], height=0.01, distance=1, prominence=0.01)
  210. valleys, _ = scipy.signal.find_peaks(-df['speedH'], height=0.01, distance=1, prominence=0.01)
  211. peak_valley = sorted(list(peaks) + list(valleys))
  212. return peak_valley
  213. def _peak_valley_judgment(self, p_last, p_curr, tw=6000, avg=0.4):
  214. """
  215. Determine if the given peaks and valleys satisfy certain conditions.
  216. Parameters:
  217. p_last: Previous peak or valley data point.
  218. p_curr: Current peak or valley data point.
  219. tw: Threshold time difference between peaks and valleys.
  220. avg: Angular velocity gap threshold.
  221. Returns:
  222. Boolean indicating whether the conditions are satisfied.
  223. """
  224. t_diff = p_curr[0] - p_last[0]
  225. v_diff = abs(p_curr[1] - p_last[1])
  226. s = p_curr[1] * p_last[1]
  227. zigzag_flag = t_diff < tw and v_diff > avg and s < 0
  228. if zigzag_flag and ([p_last[0], p_curr[0]] not in self.zigzag_time_list):
  229. self.zigzag_time_list.append([p_last[0], p_curr[0]])
  230. return zigzag_flag
  231. @peak_valley_decorator
  232. def zigzag_count_func(self, p_curr, p_last, flag=True):
  233. """
  234. Count the number of zigzag movements.
  235. Parameters:
  236. df: Input dataframe data.
  237. Returns:
  238. zigzag_count: Number of zigzag movements.
  239. """
  240. if flag:
  241. self.zigzag_count += 1
  242. else:
  243. self.zigzag_count += 0
  244. @peak_valley_decorator
  245. def cal_zigzag_strength_strength(self, p_curr, p_last, flag=True):
  246. """
  247. Calculate various strength statistics.
  248. Returns:
  249. Tuple containing maximum strength, minimum strength,
  250. average strength, and 99th percentile strength.
  251. """
  252. if flag:
  253. v_diff = abs(p_curr[1] - p_last[1])
  254. t_diff = p_curr[0] - p_last[0]
  255. self.zigzag_stre_list.append(v_diff / t_diff) # 平均角加速度
  256. else:
  257. self.zigzag_stre_list = []
  258. def _cadence_process(self, lon_acc_roc, ip_dec_roc):
  259. if abs(lon_acc_roc) >= abs(ip_dec_roc) or abs(lon_acc_roc) < 1:
  260. return np.nan
  261. # elif abs(lon_acc_roc) == 0:
  262. elif abs(lon_acc_roc) == 0:
  263. return 0
  264. elif lon_acc_roc > 0 and lon_acc_roc < -ip_dec_roc:
  265. return 1
  266. elif lon_acc_roc < 0 and lon_acc_roc > ip_dec_roc:
  267. return -1
  268. def _slam_brake_process(self, lon_acc, ip_dec):
  269. if lon_acc - ip_dec < 0:
  270. return 1
  271. else:
  272. return 0
  273. def _slam_accelerate_process(self, lon_acc, ip_acc):
  274. if lon_acc - ip_acc > 0:
  275. return 1
  276. else:
  277. return 0
  278. def _cadence_process_new(self, lon_acc, ip_acc, ip_dec):
  279. if abs(lon_acc) < 1 or lon_acc > ip_acc or lon_acc < ip_dec:
  280. return np.nan
  281. # elif abs(lon_acc_roc) == 0:
  282. elif abs(lon_acc) == 0:
  283. return 0
  284. elif lon_acc > 0 and lon_acc < ip_acc:
  285. return 1
  286. elif lon_acc < 0 and lon_acc > ip_dec:
  287. return -1
  288. def _cadence_detector(self):
  289. """
  290. # 加速度突变:先加后减,先减后加,先加然后停,先减然后停
  291. # 顿挫:2s内多次加速度变化率突变
  292. # 求出每一个特征点,然后提取,然后将每一个特征点后面的2s做一个窗口,统计频率,避免无效运算
  293. # 将特征点筛选出来
  294. # 将特征点时间作为聚类标准,大于1s的pass,小于等于1s的聚类到一个分组
  295. # 去掉小于3个特征点的分组
  296. """
  297. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'cadence']].copy()
  298. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'lon_acc_roc', 'cadence']].copy()
  299. time_list = data['simTime'].values.tolist()
  300. data = data[data['cadence'] != np.nan]
  301. data['cadence_diff'] = data['cadence'].diff()
  302. data.dropna(subset='cadence_diff', inplace=True)
  303. data = data[data['cadence_diff'] != 0]
  304. t_list = data['simTime'].values.tolist()
  305. f_list = data['simFrame'].values.tolist()
  306. group_time = []
  307. group_frame = []
  308. sub_group_time = []
  309. sub_group_frame = []
  310. for i in range(len(f_list)):
  311. if not sub_group_time or t_list[i] - t_list[i - 1] <= 1: # 特征点相邻一秒内的,算作同一组顿挫
  312. sub_group_time.append(t_list[i])
  313. sub_group_frame.append(f_list[i])
  314. else:
  315. group_time.append(sub_group_time)
  316. group_frame.append(sub_group_frame)
  317. sub_group_time = [t_list[i]]
  318. sub_group_frame = [f_list[i]]
  319. group_time.append(sub_group_time)
  320. group_frame.append(sub_group_frame)
  321. group_time = [g for g in group_time if len(g) >= 1] # 有一次特征点则算作一次顿挫
  322. # group_frame = [g for g in group_frame if len(g) >= 1]
  323. # 输出图表值
  324. cadence_time = [[g[0], g[-1]] for g in group_time]
  325. # cadence_frame = [[g[0], g[-1]] for g in group_frame]
  326. # 将顿挫组的起始时间为组重新统计时间
  327. cadence_time_list = [time for pair in cadence_time for time in time_list if pair[0] <= time <= pair[1]]
  328. # stre_list = []
  329. freq_list = []
  330. for g in group_time:
  331. # calculate strength
  332. g_df = data[data['simTime'].isin(g)]
  333. # strength = g_df['lon_acc'].abs().mean()
  334. # stre_list.append(strength)
  335. # calculate frequency
  336. cnt = len(g)
  337. t_start = g_df['simTime'].iloc[0]
  338. t_end = g_df['simTime'].iloc[-1]
  339. t_delta = t_end - t_start
  340. frequency = cnt / t_delta
  341. freq_list.append(frequency)
  342. self.cadence_count = len(freq_list)
  343. # cadence_stre = sum(stre_list) / len(stre_list) if stre_list else 0
  344. return cadence_time_list
  345. def _slam_brake_detector(self):
  346. # 统计急刹全为1的分段的个数,记录分段开头的frame_ID
  347. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'ip_dec_roc', 'slam_brake']].copy()
  348. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'lon_acc_roc', 'ip_dec', 'slam_brake']].copy()
  349. # data['slam_diff'] = data['slam_brake'].diff()
  350. # res_df = data[data['slam_diff'] == 1]
  351. res_df = data[data['slam_brake'] == 1]
  352. t_list = res_df['simTime'].values
  353. f_list = res_df['simFrame'].values.tolist()
  354. group_time = []
  355. group_frame = []
  356. sub_group_time = []
  357. sub_group_frame = []
  358. for i in range(len(f_list)):
  359. if not sub_group_time or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急刹
  360. sub_group_time.append(t_list[i])
  361. sub_group_frame.append(f_list[i])
  362. else:
  363. group_time.append(sub_group_time)
  364. group_frame.append(sub_group_frame)
  365. sub_group_time = [t_list[i]]
  366. sub_group_frame = [f_list[i]]
  367. group_time.append(sub_group_time)
  368. group_frame.append(sub_group_frame)
  369. group_time = [g for g in group_time if len(g) >= 2] # 达到两帧算作一次急刹
  370. # group_frame = [g for g in group_frame if len(g) >= 2]
  371. time_list = [element for sublist in group_time for element in sublist]
  372. self.slam_brake_count = len(group_time) # / self.mileage # * 1000000
  373. return time_list
  374. def _slam_accel_detector(self):
  375. # 统计急刹全为1的分段的个数,记录分段开头的frame_ID
  376. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'ip_acc_roc', 'slam_accel']].copy()
  377. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'ip_acc', 'slam_accel']].copy()
  378. # data['slam_diff'] = data['slam_accel'].diff()
  379. # res_df = data.loc[data['slam_diff'] == 1]
  380. res_df = data.loc[data['slam_accel'] == 1]
  381. t_list = res_df['simTime'].values
  382. f_list = res_df['simFrame'].values.tolist()
  383. group_time = []
  384. group_frame = []
  385. sub_group_time = []
  386. sub_group_frame = []
  387. for i in range(len(f_list)):
  388. if not group_time or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急加速
  389. sub_group_time.append(t_list[i])
  390. sub_group_frame.append(f_list[i])
  391. else:
  392. group_time.append(sub_group_time)
  393. group_frame.append(sub_group_frame)
  394. sub_group_time = [t_list[i]]
  395. sub_group_frame = [f_list[i]]
  396. group_time.append(sub_group_time)
  397. group_frame.append(sub_group_frame)
  398. group_time = [g for g in group_time if len(g) >= 2]
  399. # group_frame = [g for g in group_frame if len(g) >= 2]
  400. time_list = [element for sublist in group_time for element in sublist]
  401. self.slam_accel_count = len(group_time) # / self.mileage # * 1000000
  402. return time_list
  403. def _speed_instruction_jump_detector(self):
  404. data = self.ego_df[['simTime', 'simFrame', 'cmd_lon_v', 'cmd_lon_v_diff', 'cmd_v_jump']].copy()
  405. # data['slam_diff'] = data['slam_accel'].diff()
  406. # res_df = data.loc[data['slam_diff'] == 1]
  407. res_df = data.loc[data['cmd_v_jump'] == 1]
  408. t_list = res_df['simTime'].values
  409. f_list = res_df['simFrame'].values.tolist()
  410. group_time = []
  411. group_frame = []
  412. sub_group_time = []
  413. sub_group_frame = []
  414. for i in range(len(f_list)):
  415. if not group_time or f_list[i] - f_list[i - 1] <= 10: # 连续帧的算作同一组跳变
  416. sub_group_time.append(t_list[i])
  417. sub_group_frame.append(f_list[i])
  418. else:
  419. group_time.append(sub_group_time)
  420. group_frame.append(sub_group_frame)
  421. sub_group_time = [t_list[i]]
  422. sub_group_frame = [f_list[i]]
  423. group_time.append(sub_group_time)
  424. group_frame.append(sub_group_frame)
  425. group_time = [g for g in group_time if len(g) >= 2]
  426. # group_frame = [g for g in group_frame if len(g) >= 2]
  427. time_list = [element for sublist in group_time for element in sublist]
  428. self.speed_instruction_jump_count = len(group_time) # / self.mileage # * 1000000
  429. return time_list
  430. def comf_statistic(self):
  431. """
  432. """
  433. # df = self.ego_df[['simTime', 'cur_diff', 'lon_acc', 'lon_acc_roc', 'accelH']].copy()
  434. df = self.ego_df[['simTime', 'lon_acc', 'lon_acc_roc', 'accelH']].copy()
  435. self.zigzag_count_func()
  436. self.cal_zigzag_strength_strength()
  437. # if self.zigzag_time_list:
  438. # zigzag_df = pd.DataFrame(self.zigzag_time_list, columns=['start_time', 'end_time'])
  439. # zigzag_df = get_frame_with_time(zigzag_df, self.ego_df)
  440. # zigzag_df['type'] = 'zigzag'
  441. # self.discomfort_df = pd.concat([self.discomfort_df, zigzag_df], ignore_index=True)
  442. # discomfort_df = pd.concat([time_df, frame_df], axis=1)
  443. # self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  444. zigzag_t_list = []
  445. # 只有[t_start, t_end]数对,要提取为完整time list
  446. t_list = df['simTime'].values.tolist()
  447. for t_start, t_end in self.zigzag_time_list:
  448. index_1 = t_list.index(t_start)
  449. index_2 = t_list.index(t_end)
  450. zigzag_t_list.extend(t_list[index_1:index_2 + 1])
  451. zigzag_t_list = list(set(zigzag_t_list))
  452. # shake_t_list = self._shake_detector()
  453. cadence_t_list = self._cadence_detector()
  454. slam_brake_t_list = self._slam_brake_detector()
  455. slam_accel_t_list = self._slam_accel_detector()
  456. speed_instruction_jump_t_list = self._speed_instruction_jump_detector()
  457. discomfort_time_list = zigzag_t_list + cadence_t_list + slam_brake_t_list + slam_accel_t_list + speed_instruction_jump_t_list
  458. discomfort_time_list = sorted(discomfort_time_list) # 排序
  459. discomfort_time_list = list(set(discomfort_time_list)) # 去重
  460. time_diff = self.time_list[3] - self.time_list[2]
  461. # time_diff = 0.4
  462. self.discomfort_duration = len(discomfort_time_list) * time_diff
  463. self.count_dict = {
  464. "zigzag": self.zigzag_count,
  465. # "shake": self.shake_count,
  466. "cadence": self.cadence_count,
  467. "slamBrake": self.slam_brake_count,
  468. "slamAccelerate": self.slam_accel_count,
  469. "speedInstructionJump": self.speed_instruction_jump_count
  470. }
  471. tmp_comf_arr = [self.zigzag_count, self.cadence_count, self.slam_brake_count, self.slam_accel_count,
  472. self.speed_instruction_jump_count]
  473. self.discomfort_count = sum(tmp_comf_arr)
  474. comf_arr = [tmp_comf_arr]
  475. return comf_arr
  476. # def _nan_detect(self, num):
  477. # if math.isnan(num):
  478. # return 0
  479. # return num
  480. def comf_score_new(self):
  481. arr_comf = self.comf_statistic()
  482. print("\n[平顺性表现及得分情况]")
  483. print("平顺性各指标值:", [[round(num, 2) for num in row] for row in arr_comf])
  484. arr_comf = np.array(arr_comf)
  485. score_model = self.scoreModel(self.kind_list, self.optimal_list, self.multiple_list, arr_comf)
  486. score_sub = score_model.cal_score()
  487. score_metric = list(map(lambda x: 80 if np.isnan(x) else x, score_sub))
  488. metric_list = [x for x in self.metric_list if x in self.config.builtinMetricList]
  489. score_metric_dict = {key: value for key, value in zip(metric_list, score_metric)}
  490. # custom_metric_list = list(self.customMetricParam.keys())
  491. # for metric in custom_metric_list:
  492. # value = self.custom_data[metric]['value']
  493. # param_list = self.customMetricParam[metric]
  494. # score = self.custom_metric_score(metric, value, param_list)
  495. # score_metric_dict[metric] = round(score, 2)
  496. # score_metric_dict = {key: score_metric_dict[key] for key in self.metric_list}
  497. # score_metric = list(score_metric_dict.values())
  498. score_type_dict = {}
  499. if self.weight_custom: # 自定义权重
  500. score_metric_with_weight_dict = {key: score_metric_dict[key] * self.weight_dict[key] for key in
  501. self.weight_dict}
  502. for type in self.type_list:
  503. type_score = sum(
  504. value for key, value in score_metric_with_weight_dict.items() if key in self.metric_dict[type])
  505. score_type_dict[type] = round(type_score, 2)
  506. score_type_with_weight_dict = {key: score_type_dict[key] * self.weight_type_dict[key] for key in
  507. score_type_dict}
  508. score_comfort = sum(score_type_with_weight_dict.values())
  509. else: # 客观赋权
  510. self.weight_list = cal_weight_from_80(score_metric)
  511. self.weight_dict = {key: value for key, value in zip(self.metric_list, self.weight_list)}
  512. score_comfort = cal_score_with_priority(score_metric, self.weight_list, self.priority_list)
  513. for type in self.type_list:
  514. type_weight = sum(value for key, value in self.weight_dict.items() if key in self.metric_dict[type])
  515. self.weight_dict = {key: round(value / type_weight, 4) for key, value in self.weight_dict.items() if
  516. key in self.metric_dict[type]}
  517. type_score_metric = [value for key, value in score_metric_dict.items() if key in self.metric_dict[type]]
  518. type_weight_list = [value for key, value in self.weight_dict.items() if key in self.metric_dict[type]]
  519. type_priority_list = [value for key, value in self.priority_dict.items() if
  520. key in self.metric_dict[type]]
  521. type_score = cal_score_with_priority(type_score_metric, type_weight_list, type_priority_list)
  522. score_type_dict[type] = round(type_score, 2)
  523. score_comfort = round(score_comfort, 2)
  524. print("平顺性各指标基准值:", self.optimal_list)
  525. print(f"平顺性得分为:{score_comfort:.2f}分。")
  526. print(f"平顺性各类型得分为:{score_type_dict}。")
  527. print(f"平顺性各指标得分为:{score_metric_dict}。")
  528. return score_comfort, score_type_dict, score_metric_dict
  529. def zip_time_pairs(self, zip_list, upper_limit=9999):
  530. zip_time_pairs = zip(self.time_list, zip_list)
  531. zip_vs_time = [[x, upper_limit if y > upper_limit else y] for x, y in zip_time_pairs if not math.isnan(y)]
  532. return zip_vs_time
  533. def report_statistic(self):
  534. """
  535. Returns:
  536. """
  537. # report_dict = {
  538. # "name": "平顺性",
  539. # "weight": f"{self.weight * 100:.2f}%",
  540. # "weightDistribution": weight_distribution,
  541. # "score": score_comfort,
  542. # "level": grade_comfort,
  543. # 'discomfortCount': self.discomfort_count,
  544. # "description1": comf_description1,
  545. # "description2": comf_description2,
  546. # "description3": comf_description3,
  547. # "description4": comf_description4,
  548. #
  549. # "comfortLat": lat_dict,
  550. # "comfortLon": lon_dict,
  551. #
  552. # "speData": ego_speed_vs_time,
  553. # "speMarkLine": discomfort_slices,
  554. #
  555. # "accData": lon_acc_vs_time,
  556. # "accMarkLine": discomfort_acce_slices,
  557. #
  558. # "anvData": yawrate_vs_time,
  559. # "anvMarkLine": discomfort_zigzag_slices,
  560. #
  561. # "anaData": yawrate_roc_vs_time,
  562. # "anaMarkLine": discomfort_zigzag_slices,
  563. #
  564. # "curData": [cur_ego_path_vs_time, curvature_vs_time],
  565. # "curMarkLine": discomfort_shake_slices,
  566. # }
  567. # brakePedal_list = self.data_processed.driver_ctrl_data['brakePedal_list']
  568. # throttlePedal_list = self.data_processed.driver_ctrl_data['throttlePedal_list']
  569. # steeringWheel_list = self.data_processed.driver_ctrl_data['steeringWheel_list']
  570. #
  571. # # common parameter calculate
  572. # brake_vs_time = self.zip_time_pairs(brakePedal_list, 100)
  573. # throttle_vs_time = self.zip_time_pairs(throttlePedal_list, 100)
  574. # steering_vs_time = self.zip_time_pairs(steeringWheel_list)
  575. report_dict = {
  576. "name": "平顺性",
  577. "weight": f"{self.weight * 100:.2f}%",
  578. # 'discomfortCount': self.discomfort_count,
  579. }
  580. score_comfort, score_type_dict, score_metric_dict = self.comf_score_new()
  581. score_comfort = int(score_comfort) if int(score_comfort) == score_comfort else round(score_comfort, 2)
  582. grade_comfort = score_grade(score_comfort)
  583. report_dict["score"] = score_comfort
  584. report_dict["level"] = grade_comfort
  585. description = f"· 在平顺性方面,得分{score_comfort}分,表现{grade_comfort},"
  586. is_good = True
  587. if any(score_metric_dict[metric] < 80 for metric in self.lon_metric_list):
  588. is_good = False
  589. description += "线加速度变化剧烈,"
  590. tmp = [metric for metric in self.lon_metric_list if score_metric_dict[metric] < 80]
  591. str_tmp = "、".join(tmp)
  592. description += f"有{str_tmp}情况,需重点优化。"
  593. if any(score_metric_dict[metric] < 80 for metric in self.lat_metric_list):
  594. is_good = False
  595. description += "角加速度变化剧烈,"
  596. tmp = [metric for metric in self.lat_metric_list if score_metric_dict[metric] < 80]
  597. str_tmp = "、".join(tmp)
  598. description += f"有{str_tmp}情况,需重点优化。"
  599. if is_good:
  600. description += f"线加速度和角加速度变化平顺,表现{grade_comfort}。"
  601. report_dict["description"] = replace_key_with_value(description, self.name_dict)
  602. # indexes
  603. description1 = f"最大值:{self.linear_accel_dict['max']}m/s²;" \
  604. f"最小值:{self.linear_accel_dict['min']}m/s²;" \
  605. f"平均值:{self.linear_accel_dict['avg']}m/s²"
  606. description2 = f"最大值:{self.angular_accel_dict['max']}rad/s²;" \
  607. f"最小值:{self.angular_accel_dict['min']}rad/s²;" \
  608. f"平均值:{self.angular_accel_dict['avg']}rad/s²"
  609. description3 = f"最大值:{self.speed_instruction_dict['max']}m/s;" \
  610. f"最小值:{self.speed_instruction_dict['min']}m/s;" \
  611. f"平均值:{self.speed_instruction_dict['avg']}m/s"
  612. linearAccelerate_index = {
  613. "weight": self.weight_type_dict['comfortLon'],
  614. "score": score_type_dict['comfortLon'],
  615. "description": description1
  616. }
  617. angularAccelerate_index = {
  618. "weight": self.weight_type_dict['comfortLat'],
  619. "score": score_type_dict['comfortLat'],
  620. "description": description2
  621. }
  622. speedInstruction_index = {
  623. "weight": self.weight_type_dict['comfortSpeed'],
  624. "score": score_type_dict['comfortSpeed'],
  625. "description": description3
  626. }
  627. indexes_dict = {
  628. "comfortLat": linearAccelerate_index,
  629. "comfortLon": angularAccelerate_index,
  630. "comfortSpeed": speedInstruction_index
  631. }
  632. report_dict["indexes"] = indexes_dict
  633. # LinearAccelerate.png
  634. plt.figure(figsize=(12, 3))
  635. plt.plot(self.time_list, self.accel_list, label='Linear Accelerate')
  636. plt.xlabel('Time(s)')
  637. plt.ylabel('Linear Accelerate(m/s^2)')
  638. plt.legend()
  639. # 调整布局,消除空白边界
  640. plt.tight_layout()
  641. plt.savefig(os.path.join(self.resultPath, "LinearAccelerate.png"))
  642. plt.close()
  643. # AngularAccelerate.png
  644. plt.figure(figsize=(12, 3))
  645. plt.plot(self.time_list, self.accelH_list, label='Angular Accelerate')
  646. plt.xlabel('Time(s)')
  647. plt.ylabel('Angular Accelerate(rad/s^2)')
  648. plt.legend()
  649. # 调整布局,消除空白边界
  650. plt.tight_layout()
  651. plt.savefig(os.path.join(self.resultPath, "AngularAccelerate.png"))
  652. plt.close()
  653. # Speed.png
  654. plt.figure(figsize=(12, 3))
  655. plt.plot(self.time_list, self.speed_list, label='Speed')
  656. plt.xlabel('Time(s)')
  657. plt.ylabel('Speed(m/s)')
  658. plt.legend()
  659. # 调整布局,消除空白边界
  660. plt.tight_layout()
  661. plt.savefig(os.path.join(self.resultPath, "Speed.png"))
  662. plt.close()
  663. # commandSpeed.png draw
  664. plt.figure(figsize=(12, 3))
  665. plt.plot(self.time_list, self.commandSpeed_list, label='commandSpeed')
  666. plt.xlabel('Time(s)')
  667. plt.ylabel('commandSpeed(m/s)')
  668. plt.legend()
  669. # 调整布局,消除空白边界
  670. plt.tight_layout()
  671. plt.savefig(os.path.join(self.resultPath, "CommandSpeed.png"))
  672. plt.close()
  673. print(report_dict)
  674. return report_dict
  675. # def get_eval_data(self):
  676. # df = self.eval_data[
  677. # ['simTime', 'simFrame', 'playerId', 'ip_acc', 'ip_dec', 'slam_brake', 'slam_accel', 'cadence']].copy()
  678. # return df