comfort.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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 sys
  15. import math
  16. import pandas as pd
  17. import numpy as np
  18. import scipy.signal
  19. sys.path.append('../common')
  20. sys.path.append('../modules')
  21. sys.path.append('../results')
  22. from data_info import DataInfoList
  23. from score_weight import cal_score_with_priority, cal_weight_from_80
  24. from common import get_interpolation, score_grade, string_concatenate, replace_key_with_value, get_frame_with_time, \
  25. score_over_100
  26. def peak_valley_decorator(method):
  27. def wrapper(self, *args, **kwargs):
  28. peak_valley = self._peak_valley_determination(self.df)
  29. pv_list = self.df.loc[peak_valley, ['simTime', 'speedH']].values.tolist()
  30. if len(pv_list) != 0:
  31. flag = True
  32. p_last = pv_list[0]
  33. for i in range(1, len(pv_list)):
  34. p_curr = pv_list[i]
  35. if self._peak_valley_judgment(p_last, p_curr):
  36. # method(self, p_curr, p_last)
  37. method(self, p_curr, p_last, flag, *args, **kwargs)
  38. else:
  39. p_last = p_curr
  40. return method
  41. else:
  42. flag = False
  43. p_curr = [0, 0]
  44. p_last = [0, 0]
  45. method(self, p_curr, p_last, flag, *args, **kwargs)
  46. return method
  47. return wrapper
  48. class Comfort(object):
  49. """
  50. Class for achieving comfort metrics for autonomous driving.
  51. Attributes:
  52. dataframe: Vehicle driving data, stored in dataframe format.
  53. """
  54. def __init__(self, data_processed, custom_data, scoreModel):
  55. self.eval_data = pd.DataFrame()
  56. self.data_processed = data_processed
  57. self.scoreModel = scoreModel
  58. self.data = data_processed.obj_data[1]
  59. self.mileage = data_processed.report_info['mileage']
  60. self.ego_df = pd.DataFrame()
  61. self.discomfort_df = pd.DataFrame(columns=['start_time', 'end_time', 'start_frame', 'end_frame', 'type'])
  62. self.df_drivectrl = data_processed.driver_ctrl_df
  63. self.config = data_processed.config
  64. comfort_config = self.config.config['comfort']
  65. self.comfort_config = comfort_config
  66. # common data
  67. self.bulitin_metric_list = self.config.builtinMetricList
  68. # dimension data
  69. self.weight_custom = comfort_config['weightCustom']
  70. self.metric_list = comfort_config['metric']
  71. self.type_list = comfort_config['type']
  72. self.type_name_dict = comfort_config['typeName']
  73. self.name_dict = comfort_config['name']
  74. self.unit_dict = comfort_config['unit']
  75. # custom metric data
  76. self.customMetricParam = comfort_config['customMetricParam']
  77. self.custom_metric_list = list(self.customMetricParam.keys())
  78. self.custom_data = custom_data
  79. self.custom_param_dict = {}
  80. # score data
  81. self.weight = comfort_config['weightDimension']
  82. self.weight_type_dict = comfort_config['typeWeight']
  83. self.weight_type_list = comfort_config['typeWeightList']
  84. self.weight_dict = comfort_config['weight']
  85. self.weight_list = comfort_config['weightList']
  86. self.priority_dict = comfort_config['priority']
  87. self.priority_list = comfort_config['priorityList']
  88. self.kind_dict = comfort_config['kind']
  89. self.optimal_dict = comfort_config['optimal']
  90. self.optimal1_dict = self.optimal_dict[0]
  91. self.optimal2_dict = self.optimal_dict[1]
  92. self.optimal3_dict = self.optimal_dict[2]
  93. self.multiple_dict = comfort_config['multiple']
  94. self.kind_list = comfort_config['kindList']
  95. self.optimal_list = comfort_config['optimalList']
  96. self.multiple_list = comfort_config['multipleList']
  97. # metric data
  98. self.metric_dict = comfort_config['typeMetricDict']
  99. self.lat_metric_list = self.metric_dict['comfortLat']
  100. self.lon_metric_list = self.metric_dict['comfortLon']
  101. # self.lat_metric_list = ["zigzag", "shake"]
  102. # self.lon_metric_list = ["cadence", "slamBrake", "slamAccelerate"]
  103. self.time_list = data_processed.driver_ctrl_data['time_list']
  104. self.frame_list = data_processed.driver_ctrl_data['frame_list']
  105. self.count_dict = {}
  106. self.duration_dict = {}
  107. self.strength_dict = {}
  108. self.discomfort_count = 0
  109. self.zigzag_count = 0
  110. self.shake_count = 0
  111. self.cadence_count = 0
  112. self.slam_brake_count = 0
  113. self.slam_accel_count = 0
  114. self.zigzag_strength = 0
  115. self.shake_strength = 0
  116. self.cadence_strength = 0
  117. self.slam_brake_strength = 0
  118. self.slam_accel_strength = 0
  119. self.discomfort_duration = 0
  120. self.zigzag_duration = 0
  121. self.shake_duration = 0
  122. self.cadence_duration = 0
  123. self.slam_brake_duration = 0
  124. self.slam_accel_duration = 0
  125. self.zigzag_time_list = []
  126. self.zigzag_frame_list = []
  127. self.zigzag_stre_list = []
  128. self.cur_ego_path_list = []
  129. self.curvature_list = []
  130. self._get_data()
  131. self._comf_param_cal()
  132. def _get_data(self):
  133. """
  134. """
  135. comfort_info_list = DataInfoList.COMFORT_INFO
  136. self.ego_df = self.data[comfort_info_list].copy()
  137. # self.df = self.ego_df.set_index('simFrame') # 索引是csv原索引
  138. self.df = self.ego_df.reset_index(drop=True) # 索引是csv原索引
  139. def _cal_cur_ego_path(self, row):
  140. try:
  141. divide = (row['speedX'] ** 2 + row['speedY'] ** 2) ** (3 / 2)
  142. if not divide:
  143. res = None
  144. else:
  145. res = (row['speedX'] * row['accelY'] - row['speedY'] * row['accelX']) / divide
  146. except:
  147. res = None
  148. return res
  149. def _comf_param_cal(self):
  150. """
  151. """
  152. UNIT_DISTANCE = 100000
  153. for i in range(len(self.optimal_list)):
  154. if i % 3 == 2:
  155. continue
  156. else:
  157. self.optimal_list[i] = round(self.optimal_list[i] * self.mileage / UNIT_DISTANCE, 8)
  158. self.optimal1_dict = {key: value * self.mileage / UNIT_DISTANCE for key, value in
  159. self.optimal1_dict.copy().items()}
  160. self.optimal2_dict = {key: value * self.mileage / UNIT_DISTANCE for key, value in
  161. self.optimal2_dict.copy().items()}
  162. # [log]
  163. self.ego_df['ip_acc'] = self.ego_df['v'].apply(get_interpolation, point1=[18, 4], point2=[72, 2])
  164. self.ego_df['ip_dec'] = self.ego_df['v'].apply(get_interpolation, point1=[18, -5], point2=[72, -3.5])
  165. self.ego_df['slam_brake'] = (self.ego_df['lon_acc'] - self.ego_df['ip_dec']).apply(
  166. lambda x: 1 if x < 0 else 0)
  167. self.ego_df['slam_accel'] = (self.ego_df['lon_acc'] - self.ego_df['ip_acc']).apply(
  168. lambda x: 1 if x > 0 else 0)
  169. self.ego_df['cadence'] = self.ego_df.apply(
  170. lambda row: self._cadence_process_new(row['lon_acc'], row['ip_acc'], row['ip_dec']), axis=1)
  171. # for shake detector
  172. self.ego_df['cur_ego_path'] = self.ego_df.apply(self._cal_cur_ego_path, axis=1)
  173. self.ego_df['curvHor'] = self.ego_df['curvHor'].astype('float')
  174. self.ego_df['cur_diff'] = (self.ego_df['cur_ego_path'] - self.ego_df['curvHor']).abs()
  175. self.ego_df['R'] = self.ego_df['curvHor'].apply(lambda x: 10000 if x == 0 else 1 / x)
  176. self.ego_df['R_ego'] = self.ego_df['cur_ego_path'].apply(lambda x: 10000 if x == 0 else 1 / x)
  177. self.ego_df['R_diff'] = (self.ego_df['R_ego'] - self.ego_df['R']).abs()
  178. self.cur_ego_path_list = self.ego_df['cur_ego_path'].values.tolist()
  179. self.curvature_list = self.ego_df['curvHor'].values.tolist()
  180. def _peak_valley_determination(self, df):
  181. """
  182. Determine the peak and valley of the vehicle based on its current angular velocity.
  183. Parameters:
  184. df: Dataframe containing the vehicle angular velocity.
  185. Returns:
  186. peak_valley: List of indices representing peaks and valleys.
  187. """
  188. peaks, _ = scipy.signal.find_peaks(df['speedH'], height=0.01, distance=1, prominence=0.01)
  189. valleys, _ = scipy.signal.find_peaks(-df['speedH'], height=0.01, distance=1, prominence=0.01)
  190. peak_valley = sorted(list(peaks) + list(valleys))
  191. return peak_valley
  192. def _peak_valley_judgment(self, p_last, p_curr, tw=10000, avg=0.02):
  193. """
  194. Determine if the given peaks and valleys satisfy certain conditions.
  195. Parameters:
  196. p_last: Previous peak or valley data point.
  197. p_curr: Current peak or valley data point.
  198. tw: Threshold time difference between peaks and valleys.
  199. avg: Angular velocity gap threshold.
  200. Returns:
  201. Boolean indicating whether the conditions are satisfied.
  202. """
  203. t_diff = p_curr[0] - p_last[0]
  204. v_diff = abs(p_curr[1] - p_last[1])
  205. s = p_curr[1] * p_last[1]
  206. zigzag_flag = t_diff < tw and v_diff > avg and s < 0
  207. if zigzag_flag and ([p_last[0], p_curr[0]] not in self.zigzag_time_list):
  208. self.zigzag_time_list.append([p_last[0], p_curr[0]])
  209. return zigzag_flag
  210. @peak_valley_decorator
  211. def zigzag_count_func(self, p_curr, p_last, flag=True):
  212. """
  213. Count the number of zigzag movements.
  214. Parameters:
  215. df: Input dataframe data.
  216. Returns:
  217. zigzag_count: Number of zigzag movements.
  218. """
  219. if flag:
  220. self.zigzag_count += 1
  221. else:
  222. self.zigzag_count += 0
  223. @peak_valley_decorator
  224. def cal_zigzag_strength_strength(self, p_curr, p_last, flag=True):
  225. """
  226. Calculate various strength statistics.
  227. Returns:
  228. Tuple containing maximum strength, minimum strength,
  229. average strength, and 99th percentile strength.
  230. """
  231. if flag:
  232. v_diff = abs(p_curr[1] - p_last[1])
  233. t_diff = p_curr[0] - p_last[0]
  234. self.zigzag_stre_list.append(v_diff / t_diff) # 平均角加速度
  235. else:
  236. self.zigzag_stre_list = []
  237. def _shake_detector(self, Cr_diff=0.05, T_diff=0.39):
  238. """
  239. ego车横向加速度ax;
  240. ego车轨迹横向曲率;
  241. ego车轨迹曲率变化率;
  242. ego车所在车lane曲率;
  243. ego车所在车lane曲率变化率;
  244. 转向灯(暂时存疑,可不用)Cr_diff = 0.1, T_diff = 0.04
  245. 求解曲率公式k(t) = (x'(t) * y''(t) - y'(t) * x''(t)) / ((x'(t))^2 + (y'(t))^2)^(3/2)
  246. """
  247. time_list = []
  248. frame_list = []
  249. shake_time_list = []
  250. df = self.ego_df.copy()
  251. df = df[df['cur_diff'] > Cr_diff]
  252. df['frame_ID_diff'] = df['simFrame'].diff() # 找出行车轨迹曲率与道路曲率之差大于阈值的数据段
  253. filtered_df = df[df.frame_ID_diff > T_diff] # 此处是用大间隔区分多次晃动情景 。
  254. row_numbers = filtered_df.index.tolist()
  255. cut_column = pd.cut(df.index, bins=row_numbers)
  256. grouped = df.groupby(cut_column)
  257. dfs = {}
  258. for name, group in grouped:
  259. dfs[name] = group.reset_index(drop=True)
  260. for name, df_group in dfs.items():
  261. # 直道,未主动换道
  262. df_group['curvHor'] = df_group['curvHor'].abs()
  263. df_group_straight = df_group[(df_group.lightMask == 0) & (df_group.curvHor < 0.001)]
  264. if not df_group_straight.empty:
  265. tmp_list = df_group_straight['simTime'].values
  266. # shake_time_list.append([tmp_list[0], tmp_list[-1]])
  267. time_list.extend(df_group_straight['simTime'].values)
  268. frame_list.extend(df_group_straight['simFrame'].values)
  269. self.shake_count = self.shake_count + 1
  270. # 打转向灯,道路为直道,此时晃动判断标准车辆曲率变化率为一个更大的阈值
  271. df_group_change_lane = df_group[(df_group['lightMask'] != 0) & (df_group['curvHor'] < 0.001)]
  272. df_group_change_lane_data = df_group_change_lane[df_group_change_lane.cur_diff > Cr_diff + 0.2]
  273. if not df_group_change_lane_data.empty:
  274. tmp_list = df_group_change_lane_data['simTime'].values
  275. # shake_time_list.append([tmp_list[0], tmp_list[-1]])
  276. time_list.extend(df_group_change_lane_data['simTime'].values)
  277. frame_list.extend(df_group_change_lane_data['simFrame'].values)
  278. self.shake_count = self.shake_count + 1
  279. # 转弯,打转向灯
  280. df_group_turn = df_group[(df_group['lightMask'] != 0) & (df_group['curvHor'].abs() > 0.001)]
  281. df_group_turn_data = df_group_turn[df_group_turn.cur_diff.abs() > Cr_diff + 0.1]
  282. if not df_group_turn_data.empty:
  283. tmp_list = df_group_turn_data['simTime'].values
  284. # shake_time_list.append([tmp_list[0], tmp_list[-1]])
  285. time_list.extend(df_group_turn_data['simTime'].values)
  286. frame_list.extend(df_group_turn_data['simFrame'].values)
  287. self.shake_count = self.shake_count + 1
  288. TIME_RANGE = 1
  289. t_list = time_list
  290. f_list = frame_list
  291. group_time = []
  292. group_frame = []
  293. sub_group_time = []
  294. sub_group_frame = []
  295. for i in range(len(f_list)):
  296. if not sub_group_time or t_list[i] - t_list[i - 1] <= TIME_RANGE:
  297. sub_group_time.append(t_list[i])
  298. sub_group_frame.append(f_list[i])
  299. else:
  300. group_time.append(sub_group_time)
  301. group_frame.append(sub_group_frame)
  302. sub_group_time = [t_list[i]]
  303. sub_group_frame = [f_list[i]]
  304. # group_time.append(sub_group_time)
  305. # group_frame.append(sub_group_frame)
  306. # group_time = [g for g in group_time if len(g) >= 3]
  307. # group_frame = [g for g in group_frame if len(g) >= 3]
  308. #
  309. # group_time = []
  310. # sub_group = []
  311. # for i in range(len(t_list)):
  312. # if not sub_group or t_list[i] - t_list[i - 1] <= 0.2:
  313. # sub_group.append(t_list[i])
  314. # else:
  315. # group_time.append(sub_group)
  316. # sub_group = [t_list[i]]
  317. #
  318. # group_time.append(sub_group)
  319. # group_time = [g for g in group_time if len(g) >= 3]
  320. # 输出图表值
  321. shake_time = [[g[0], g[-1]] for g in group_time]
  322. shake_frame = [[g[0], g[-1]] for g in group_frame]
  323. self.shake_count = len(shake_time)
  324. if shake_time:
  325. time_df = pd.DataFrame(shake_time, columns=['start_time', 'end_time'])
  326. frame_df = pd.DataFrame(shake_frame, columns=['start_frame', 'end_frame'])
  327. discomfort_df = pd.concat([time_df, frame_df], axis=1)
  328. discomfort_df['type'] = 'shake'
  329. self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  330. return time_list
  331. def _cadence_process(self, lon_acc_roc, ip_dec_roc):
  332. if abs(lon_acc_roc) >= abs(ip_dec_roc) or abs(lon_acc_roc) < 1:
  333. return np.nan
  334. # elif abs(lon_acc_roc) == 0:
  335. elif abs(lon_acc_roc) == 0:
  336. return 0
  337. elif lon_acc_roc > 0 and lon_acc_roc < -ip_dec_roc:
  338. return 1
  339. elif lon_acc_roc < 0 and lon_acc_roc > ip_dec_roc:
  340. return -1
  341. def _cadence_process_new(self, lon_acc, ip_acc, ip_dec):
  342. if abs(lon_acc) < 1 or lon_acc > ip_acc or lon_acc < ip_dec:
  343. return np.nan
  344. # elif abs(lon_acc_roc) == 0:
  345. elif abs(lon_acc) == 0:
  346. return 0
  347. elif lon_acc > 0 and lon_acc < ip_acc:
  348. return 1
  349. elif lon_acc < 0 and lon_acc > ip_dec:
  350. return -1
  351. else:
  352. return 0
  353. def _cadence_detector(self):
  354. """
  355. # 加速度突变:先加后减,先减后加,先加然后停,先减然后停
  356. # 顿挫:2s内多次加速度变化率突变
  357. # 求出每一个特征点,然后提取,然后将每一个特征点后面的2s做一个窗口,统计频率,避免无效运算
  358. # 将特征点筛选出来
  359. # 将特征点时间作为聚类标准,大于1s的pass,小于等于1s的聚类到一个分组
  360. # 去掉小于3个特征点的分组
  361. """
  362. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'cadence']].copy()
  363. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'lon_acc_roc', 'cadence']].copy()
  364. time_list = data['simTime'].values.tolist()
  365. data = data[data['cadence'] != np.nan]
  366. data['cadence_diff'] = data['cadence'].diff()
  367. data.dropna(subset='cadence_diff', inplace=True)
  368. data = data[data['cadence_diff'] != 0]
  369. t_list = data['simTime'].values.tolist()
  370. f_list = data['simFrame'].values.tolist()
  371. TIME_RANGE = 1
  372. group_time = []
  373. group_frame = []
  374. sub_group_time = []
  375. sub_group_frame = []
  376. for i in range(len(f_list)):
  377. if not sub_group_time or t_list[i] - t_list[i - 1] <= TIME_RANGE: # 特征点相邻一秒内的,算作同一组顿挫
  378. sub_group_time.append(t_list[i])
  379. sub_group_frame.append(f_list[i])
  380. else:
  381. group_time.append(sub_group_time)
  382. group_frame.append(sub_group_frame)
  383. sub_group_time = [t_list[i]]
  384. sub_group_frame = [f_list[i]]
  385. group_time.append(sub_group_time)
  386. group_frame.append(sub_group_frame)
  387. group_time = [g for g in group_time if len(g) >= 1] # 有一次特征点则算作一次顿挫
  388. group_frame = [g for g in group_frame if len(g) >= 1]
  389. # group_time = []
  390. # sub_group = []
  391. #
  392. # for i in range(len(f_list)):
  393. # if not sub_group or t_list[i] - t_list[i - 1] <= 1: # 特征点相邻一秒内的,算作同一组顿挫
  394. # sub_group.append(t_list[i])
  395. # else:
  396. # group_time.append(sub_group)
  397. # sub_group = [t_list[i]]
  398. #
  399. # group_time.append(sub_group)
  400. # group_time = [g for g in group_time if len(g) >= 1] # 有一次特征点则算作一次顿挫
  401. # 输出图表值
  402. cadence_time = [[g[0], g[-1]] for g in group_time]
  403. cadence_frame = [[g[0], g[-1]] for g in group_frame]
  404. if cadence_time:
  405. time_df = pd.DataFrame(cadence_time, columns=['start_time', 'end_time'])
  406. frame_df = pd.DataFrame(cadence_frame, columns=['start_frame', 'end_frame'])
  407. discomfort_df = pd.concat([time_df, frame_df], axis=1)
  408. discomfort_df['type'] = 'cadence'
  409. self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  410. # 将顿挫组的起始时间为组重新统计时间
  411. cadence_time_list = [time for pair in cadence_time for time in time_list if pair[0] <= time <= pair[1]]
  412. # time_list = [element for sublist in group_time for element in sublist]
  413. # merged_list = [element for sublist in res_group for element in sublist]
  414. # res_df = data[data['simTime'].isin(merged_list)]
  415. stre_list = []
  416. freq_list = []
  417. for g in group_time:
  418. # calculate strength
  419. g_df = data[data['simTime'].isin(g)]
  420. strength = g_df['lon_acc'].abs().mean()
  421. stre_list.append(strength)
  422. # calculate frequency
  423. cnt = len(g)
  424. t_start = g_df['simTime'].iloc[0]
  425. t_end = g_df['simTime'].iloc[-1]
  426. t_delta = t_end - t_start
  427. frequency = cnt / t_delta
  428. freq_list.append(frequency)
  429. self.cadence_count = len(freq_list)
  430. cadence_stre = sum(stre_list) / len(stre_list) if stre_list else 0
  431. return cadence_time_list
  432. def _slam_brake_detector(self):
  433. # 统计急刹全为1的分段的个数,记录分段开头的frame_ID
  434. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'ip_dec_roc', 'slam_brake']].copy()
  435. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'lon_acc_roc', 'ip_dec', 'slam_brake']].copy()
  436. # data['slam_diff'] = data['slam_brake'].diff()
  437. # res_df = data[data['slam_diff'] == 1]
  438. res_df = data[data['slam_brake'] == 1]
  439. t_list = res_df['simTime'].values
  440. f_list = res_df['simFrame'].values.tolist()
  441. TIME_RANGE = 1
  442. group_time = []
  443. group_frame = []
  444. sub_group_time = []
  445. sub_group_frame = []
  446. for i in range(len(f_list)):
  447. if not sub_group_time or f_list[i] - f_list[i - 1] <= TIME_RANGE: # 连续帧的算作同一组急刹
  448. sub_group_time.append(t_list[i])
  449. sub_group_frame.append(f_list[i])
  450. else:
  451. group_time.append(sub_group_time)
  452. group_frame.append(sub_group_frame)
  453. sub_group_time = [t_list[i]]
  454. sub_group_frame = [f_list[i]]
  455. group_time.append(sub_group_time)
  456. group_frame.append(sub_group_frame)
  457. group_time = [g for g in group_time if len(g) >= 2] # 达到两帧算作一次急刹
  458. group_frame = [g for g in group_frame if len(g) >= 2]
  459. # group_time = []
  460. # sub_group = []
  461. #
  462. # for i in range(len(f_list)):
  463. # if not sub_group or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急刹
  464. # sub_group.append(t_list[i])
  465. # else:
  466. # group_time.append(sub_group)
  467. # sub_group = [t_list[i]]
  468. #
  469. # group_time.append(sub_group)
  470. # group_time = [g for g in group_time if len(g) >= 2] # 达到两帧算作一次急刹
  471. # 输出图表值
  472. slam_brake_time = [[g[0], g[-1]] for g in group_time]
  473. slam_brake_frame = [[g[0], g[-1]] for g in group_frame]
  474. if slam_brake_time:
  475. time_df = pd.DataFrame(slam_brake_time, columns=['start_time', 'end_time'])
  476. frame_df = pd.DataFrame(slam_brake_frame, columns=['start_frame', 'end_frame'])
  477. discomfort_df = pd.concat([time_df, frame_df], axis=1)
  478. discomfort_df['type'] = 'slam_brake'
  479. self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  480. time_list = [element for sublist in group_time for element in sublist]
  481. self.slam_brake_count = len(group_time) # / self.mileage # * 1000000
  482. return time_list
  483. def _slam_accel_detector(self):
  484. # 统计急刹全为1的分段的个数,记录分段开头的frame_ID
  485. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'ip_acc_roc', 'slam_accel']].copy()
  486. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'ip_acc', 'slam_accel']].copy()
  487. # data['slam_diff'] = data['slam_accel'].diff()
  488. # res_df = data.loc[data['slam_diff'] == 1]
  489. res_df = data.loc[data['slam_accel'] == 1]
  490. t_list = res_df['simTime'].values
  491. f_list = res_df['simFrame'].values.tolist()
  492. group_time = []
  493. group_frame = []
  494. sub_group_time = []
  495. sub_group_frame = []
  496. for i in range(len(f_list)):
  497. if not group_time or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急加速
  498. sub_group_time.append(t_list[i])
  499. sub_group_frame.append(f_list[i])
  500. else:
  501. group_time.append(sub_group_time)
  502. group_frame.append(sub_group_frame)
  503. sub_group_time = [t_list[i]]
  504. sub_group_frame = [f_list[i]]
  505. group_time.append(sub_group_time)
  506. group_frame.append(sub_group_frame)
  507. group_time = [g for g in group_time if len(g) >= 2]
  508. group_frame = [g for g in group_frame if len(g) >= 2]
  509. # group_time = []
  510. # sub_group = []
  511. #
  512. # for i in range(len(f_list)):
  513. # if not sub_group or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急加速
  514. # sub_group.append(t_list[i])
  515. # else:
  516. # group_time.append(sub_group)
  517. # sub_group = [t_list[i]]
  518. #
  519. # group_time.append(sub_group)
  520. # group_time = [g for g in group_time if len(g) >= 2] # 达到两帧算作一次急加速
  521. # 输出图表值
  522. slam_accel_time = [[g[0], g[-1]] for g in group_time]
  523. slam_accel_frame = [[g[0], g[-1]] for g in group_frame]
  524. if slam_accel_time:
  525. time_df = pd.DataFrame(slam_accel_time, columns=['start_time', 'end_time'])
  526. frame_df = pd.DataFrame(slam_accel_frame, columns=['start_frame', 'end_frame'])
  527. discomfort_df = pd.concat([time_df, frame_df], axis=1)
  528. discomfort_df['type'] = 'slam_accel'
  529. self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  530. time_list = [element for sublist in group_time for element in sublist]
  531. self.slam_accel_count = len(group_time) # / self.mileage # * 1000000
  532. return time_list
  533. def comf_statistic(self):
  534. """
  535. """
  536. df = self.ego_df[['simTime', 'cur_diff', 'lon_acc', 'lon_acc_roc', 'accelH']].copy()
  537. self.zigzag_count_func()
  538. self.cal_zigzag_strength_strength()
  539. if self.zigzag_time_list:
  540. zigzag_df = pd.DataFrame(self.zigzag_time_list, columns=['start_time', 'end_time'])
  541. zigzag_df = get_frame_with_time(zigzag_df, self.ego_df)
  542. zigzag_df['type'] = 'zigzag'
  543. self.discomfort_df = pd.concat([self.discomfort_df, zigzag_df], ignore_index=True)
  544. # discomfort_df = pd.concat([time_df, frame_df], axis=1)
  545. # self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  546. zigzag_t_list = []
  547. # 只有[t_start, t_end]数对,要提取为完整time list
  548. t_list = df['simTime'].values.tolist()
  549. for t_start, t_end in self.zigzag_time_list:
  550. index_1 = t_list.index(t_start)
  551. index_2 = t_list.index(t_end)
  552. zigzag_t_list.extend(t_list[index_1:index_2 + 1])
  553. zigzag_t_list = list(set(zigzag_t_list))
  554. shake_t_list = self._shake_detector()
  555. cadence_t_list = self._cadence_detector()
  556. slam_brake_t_list = self._slam_brake_detector()
  557. slam_accel_t_list = self._slam_accel_detector()
  558. # comfort_time_dict = {
  559. # 'zigzag_time_list': zigzag_t_list,
  560. # 'shake_time_list': shake_t_list,
  561. # 'cadence_time_list': cadence_t_list,
  562. # 'slam_brake_time_list': slam_brake_t_list,
  563. # 'slam_accelerate_time_list': slam_accel_t_list
  564. # }
  565. discomfort_time_list = zigzag_t_list + shake_t_list + cadence_t_list + slam_brake_t_list + slam_accel_t_list
  566. discomfort_time_list = sorted(discomfort_time_list) # 排序
  567. discomfort_time_list = list(set(discomfort_time_list)) # 去重
  568. # TIME_DIFF = self.time_list[3] - self.time_list[2]
  569. # TIME_DIFF = 0.4
  570. FREQUENCY = 100
  571. TIME_DIFF = 1 / FREQUENCY
  572. self.discomfort_duration = len(discomfort_time_list) * TIME_DIFF
  573. df['flag_zigzag'] = df['simTime'].apply(lambda x: 1 if x in zigzag_t_list else 0)
  574. df['flag_shake'] = df['simTime'].apply(lambda x: 1 if x in shake_t_list else 0)
  575. df['flag_cadence'] = df['simTime'].apply(lambda x: 1 if x in cadence_t_list else 0)
  576. df['flag_slam_brake'] = df['simTime'].apply(lambda x: 1 if x in slam_brake_t_list else 0)
  577. df['flag_slam_accel'] = df['simTime'].apply(lambda x: 1 if x in slam_accel_t_list else 0)
  578. HECTO_KILOMETER = 100000 # 百公里
  579. if self.mileage == 0:
  580. self.mileage = 9999
  581. self.zigzag_duration = df['flag_zigzag'].sum() * TIME_DIFF / self.mileage * HECTO_KILOMETER
  582. self.shake_duration = df['flag_shake'].sum() * TIME_DIFF / self.mileage * HECTO_KILOMETER
  583. self.cadence_duration = df['flag_cadence'].sum() * TIME_DIFF / self.mileage * HECTO_KILOMETER
  584. self.slam_brake_duration = df['flag_slam_brake'].sum() * TIME_DIFF / self.mileage * HECTO_KILOMETER
  585. self.slam_accel_duration = df['flag_slam_accel'].sum() * TIME_DIFF / self.mileage * HECTO_KILOMETER
  586. # 强度取值可考虑最大值,暂定平均值,具体视数据情况而定
  587. # self.zigzag_strength = np.mean(self.zigzag_stre_list) if self.zigzag_stre_list else 0
  588. self.zigzag_strength = (df['flag_shake'] * abs(df['accelH'])).mean()
  589. self.shake_strength = (df['flag_shake'] * abs(df['cur_diff'])).mean()
  590. self.cadence_strength = (df['flag_cadence'] * abs(df['lon_acc'])).mean()
  591. self.slam_brake_strength = (df['flag_slam_brake'] * abs(df['lon_acc'])).mean()
  592. self.slam_accel_strength = (df['flag_slam_accel'] * abs(df['lon_acc'])).mean()
  593. self.zigzag_strength = self._nan_detect(self.zigzag_strength)
  594. self.shake_strength = self._nan_detect(self.shake_strength)
  595. self.cadence_strength = self._nan_detect(self.cadence_strength)
  596. self.slam_brake_strength = self._nan_detect(self.slam_brake_strength)
  597. self.slam_accel_strength = self._nan_detect(self.slam_accel_strength)
  598. self.count_dict = {
  599. "zigzag": self.zigzag_count,
  600. "shake": self.shake_count,
  601. "cadence": self.cadence_count,
  602. "slamBrake": self.slam_brake_count,
  603. "slamAccelerate": self.slam_accel_count
  604. }
  605. self.duration_dict = {
  606. "zigzag": self.zigzag_duration,
  607. "shake": self.shake_duration,
  608. "cadence": self.cadence_duration,
  609. "slamBrake": self.slam_brake_duration,
  610. "slamAccelerate": self.slam_accel_duration
  611. }
  612. self.strength_dict = {
  613. "zigzag": self.zigzag_strength,
  614. "shake": self.shake_strength,
  615. "cadence": self.cadence_strength,
  616. "slamBrake": self.slam_brake_strength,
  617. "slamAccelerate": self.slam_accel_strength
  618. }
  619. zigzag_list = [self.zigzag_count, self.zigzag_duration, self.zigzag_strength]
  620. shake_list = [self.shake_count, self.shake_duration, self.shake_strength]
  621. cadence_list = [self.cadence_count, self.cadence_duration, self.cadence_strength]
  622. slam_brake_list = [self.slam_brake_count, self.slam_brake_duration, self.slam_brake_strength]
  623. slam_accel_list = [self.slam_accel_count, self.slam_accel_duration, self.slam_accel_strength]
  624. tmp_comf_arr = []
  625. if "zigzag" in self.metric_list:
  626. tmp_comf_arr += zigzag_list
  627. self.discomfort_count += self.zigzag_count
  628. if "shake" in self.metric_list:
  629. tmp_comf_arr += shake_list
  630. self.discomfort_count += self.shake_count
  631. if "cadence" in self.metric_list:
  632. tmp_comf_arr += cadence_list
  633. self.discomfort_count += self.cadence_count
  634. if "slamBrake" in self.metric_list:
  635. tmp_comf_arr += slam_brake_list
  636. self.discomfort_count += self.slam_brake_count
  637. if "slamAccelerate" in self.metric_list:
  638. tmp_comf_arr += slam_accel_list
  639. self.discomfort_count += self.slam_accel_count
  640. comf_arr = [tmp_comf_arr]
  641. return comf_arr
  642. def _nan_detect(self, num):
  643. if math.isnan(num):
  644. return 0
  645. return num
  646. def custom_metric_param_parser(self, param_list):
  647. """
  648. param_dict = {
  649. "paramA" [
  650. {
  651. "kind": "-1",
  652. "optimal": "1",
  653. "multiple": ["0.5","5"],
  654. "spare1": null,
  655. "spare2": null
  656. }
  657. ]
  658. }
  659. """
  660. kind_list = []
  661. optimal_list = []
  662. multiple_list = []
  663. spare_list = []
  664. # spare1_list = []
  665. # spare2_list = []
  666. for i in range(len(param_list)):
  667. kind_list.append(int(param_list[i]['kind']))
  668. optimal_list.append(float(param_list[i]['optimal']))
  669. multiple_list.append([float(x) for x in param_list[i]['multiple']])
  670. spare_list.append([item["param"] for item in param_list[i]["spare"]])
  671. # spare1_list.append(param_list[i]['spare1'])
  672. # spare2_list.append(param_list[i]['spare2'])
  673. result = {
  674. "kind": kind_list,
  675. "optimal": optimal_list,
  676. "multiple": multiple_list,
  677. "spare": spare_list,
  678. # "spare1": spare1_list,
  679. # "spare2": spare2_list
  680. }
  681. return result
  682. def custom_metric_score(self, metric, value, param_list):
  683. """
  684. """
  685. param = self.custom_metric_param_parser(param_list)
  686. self.custom_param_dict[metric] = param
  687. score_model = self.scoreModel(param['kind'], param['optimal'], param['multiple'], np.array([value]))
  688. score_sub = score_model.cal_score()
  689. score = sum(score_sub) / len(score_sub)
  690. return score
  691. def comf_score_new(self):
  692. score_metric_dict = {}
  693. score_type_dict = {}
  694. arr_comf = self.comf_statistic()
  695. print("\n[舒适性表现及得分情况]")
  696. print("舒适性各指标值:", [[round(num, 2) for num in row] for row in arr_comf])
  697. if arr_comf:
  698. arr_comf = np.array(arr_comf)
  699. score_model = self.scoreModel(self.kind_list, self.optimal_list, self.multiple_list, arr_comf)
  700. score_sub = score_model.cal_score()
  701. score_sub = list(map(lambda x: 80 if np.isnan(x) else x, score_sub))
  702. metric_list = [x for x in self.metric_list if x in self.config.builtinMetricList]
  703. score_metric = []
  704. for i in range(len(metric_list)):
  705. score_tmp = (score_sub[i * 3 + 0] + score_sub[i * 3 + 1] + score_sub[i * 3 + 2]) / 3
  706. score_metric.append(round(score_tmp, 2))
  707. score_metric_dict = {key: value for key, value in zip(metric_list, score_metric)}
  708. for metric in self.custom_metric_list:
  709. value = self.custom_data[metric]['value']
  710. param_list = self.customMetricParam[metric]
  711. score = self.custom_metric_score(metric, value, param_list)
  712. score_metric_dict[metric] = round(score, 2)
  713. score_metric_dict = {key: score_metric_dict[key] for key in self.metric_list}
  714. score_metric = list(score_metric_dict.values())
  715. if self.weight_custom: # 自定义权重
  716. score_metric_with_weight_dict = {key: score_metric_dict[key] * self.weight_dict[key] for key in
  717. self.weight_dict}
  718. for type in self.type_list:
  719. type_score = sum(
  720. value for key, value in score_metric_with_weight_dict.items() if key in self.metric_dict[type])
  721. score_type_dict[type] = round(type_score, 2) if type_score < 100 else 100
  722. score_type_with_weight_dict = {key: score_type_dict[key] * self.weight_type_dict[key] for key in
  723. score_type_dict}
  724. score_comfort = sum(score_type_with_weight_dict.values())
  725. else: # 客观赋权
  726. self.weight_list = cal_weight_from_80(score_metric)
  727. self.weight_dict = {key: value for key, value in zip(self.metric_list, self.weight_list)}
  728. score_comfort = cal_score_with_priority(score_metric, self.weight_list, self.priority_list)
  729. for type in self.type_list:
  730. type_weight = sum(value for key, value in self.weight_dict.items() if key in self.metric_dict[type])
  731. for key, value in self.weight_dict.items():
  732. if key in self.metric_dict[type]:
  733. # self.weight_dict[key] = round(value / type_weight, 4)
  734. self.weight_dict[key] = value / type_weight
  735. type_score_metric = [value for key, value in score_metric_dict.items() if key in self.metric_dict[type]]
  736. type_weight_list = [value for key, value in self.weight_dict.items() if key in self.metric_dict[type]]
  737. type_priority_list = [value for key, value in self.priority_dict.items() if
  738. key in self.metric_dict[type]]
  739. type_score = cal_score_with_priority(type_score_metric, type_weight_list, type_priority_list)
  740. score_type_dict[type] = round(type_score, 2) if type_score < 100 else 100
  741. for key in self.weight_dict:
  742. self.weight_dict[key] = round(self.weight_dict[key], 4)
  743. score_type = list(score_type_dict.values())
  744. self.weight_type_list = cal_weight_from_80(score_type)
  745. self.weight_type_dict = {key: value for key, value in zip(self.type_list, self.weight_type_list)}
  746. score_comfort = round(score_comfort, 2)
  747. print("舒适性各指标基准值:", self.optimal_list)
  748. print(f"舒适性得分为:{score_comfort:.2f}分。")
  749. print(f"舒适性各类型得分为:{score_type_dict}。")
  750. print(f"舒适性各指标得分为:{score_metric_dict}。")
  751. return score_comfort, score_type_dict, score_metric_dict
  752. # def zip_time_pairs(self, zip_list, upper_limit=9999):
  753. # zip_time_pairs = zip(self.time_list, zip_list)
  754. # zip_vs_time = [[x, upper_limit if y > upper_limit else y] for x, y in zip_time_pairs if not math.isnan(y)]
  755. # return zip_vs_time
  756. def zip_time_pairs(self, zip_list):
  757. zip_time_pairs = zip(self.time_list, zip_list)
  758. zip_vs_time = [[x, "" if math.isnan(y) else y] for x, y in zip_time_pairs]
  759. return zip_vs_time
  760. def comf_weight_distribution(self):
  761. # get weight distribution
  762. weight_distribution = {}
  763. weight_distribution["name"] = "舒适性"
  764. if "comfortLat" in self.type_list:
  765. lat_weight_indexes_dict = {key: f"{key}({value * 100:.2f}%)" for key, value in self.weight_dict.items() if
  766. key in self.lat_metric_list}
  767. weight_distribution_lat = {
  768. "latWeight": f"横向舒适度({self.weight_type_dict['comfortLat'] * 100:.2f}%)",
  769. "indexes": lat_weight_indexes_dict
  770. }
  771. weight_distribution['comfortLat'] = weight_distribution_lat
  772. if "comfortLon" in self.type_list:
  773. lon_weight_indexes_dict = {key: f"{key}({value * 100:.2f}%)" for key, value in self.weight_dict.items() if
  774. key in self.lon_metric_list}
  775. weight_distribution_lon = {
  776. "lonWeight": f"纵向舒适度({self.weight_type_dict['comfortLon'] * 100:.2f}%)",
  777. "indexes": lon_weight_indexes_dict
  778. }
  779. weight_distribution['comfortLon'] = weight_distribution_lon
  780. return weight_distribution
  781. def _get_weight_distribution(self, dimension):
  782. # get weight distribution
  783. weight_distribution = {}
  784. weight_distribution["name"] = self.config.dimension_name[dimension]
  785. for type in self.type_list:
  786. type_weight_indexes_dict = {key: f"{self.name_dict[key]}({value * 100:.2f}%)" for key, value in
  787. self.weight_dict.items() if
  788. key in self.metric_dict[type]}
  789. weight_distribution_type = {
  790. "weight": f"{self.type_name_dict[type]}({self.weight_type_dict[type] * 100:.2f}%)",
  791. "indexes": type_weight_indexes_dict
  792. }
  793. weight_distribution[type] = weight_distribution_type
  794. return weight_distribution
  795. def report_statistic(self):
  796. """
  797. Returns:
  798. """
  799. # report_dict = {
  800. # "name": "舒适性",
  801. # "weight": f"{self.weight * 100:.2f}%",
  802. # "weightDistribution": weight_distribution,
  803. # "score": score_comfort,
  804. # "level": grade_comfort,
  805. # 'discomfortCount': self.discomfort_count,
  806. # "description1": comf_description1,
  807. # "description2": comf_description2,
  808. # "description3": comf_description3,
  809. # "description4": comf_description4,
  810. #
  811. # "comfortLat": lat_dict,
  812. # "comfortLon": lon_dict,
  813. #
  814. # "speData": ego_speed_vs_time,
  815. # "speMarkLine": discomfort_slices,
  816. #
  817. # "accData": lon_acc_vs_time,
  818. # "accMarkLine": discomfort_acce_slices,
  819. #
  820. # "anvData": yawrate_vs_time,
  821. # "anvMarkLine": discomfort_zigzag_slices,
  822. #
  823. # "anaData": yawrate_roc_vs_time,
  824. # "anaMarkLine": discomfort_zigzag_slices,
  825. #
  826. # "curData": [cur_ego_path_vs_time, curvature_vs_time],
  827. # "curMarkLine": discomfort_shake_slices,
  828. # }
  829. brakePedal_list = self.data_processed.driver_ctrl_data['brakePedal_list']
  830. throttlePedal_list = self.data_processed.driver_ctrl_data['throttlePedal_list']
  831. steeringWheel_list = self.data_processed.driver_ctrl_data['steeringWheel_list']
  832. # common parameter calculate
  833. brake_vs_time = self.zip_time_pairs(brakePedal_list)
  834. throttle_vs_time = self.zip_time_pairs(throttlePedal_list)
  835. steering_vs_time = self.zip_time_pairs(steeringWheel_list)
  836. report_dict = {
  837. "name": "舒适性",
  838. "weight": f"{self.weight * 100:.2f}%",
  839. 'discomfortCount': self.discomfort_count,
  840. }
  841. # upper_limit = 40
  842. # times_upper = 2
  843. # len_time = len(self.time_list)
  844. duration = self.time_list[-1]
  845. # comfort score and grade
  846. score_comfort, score_type_dict, score_metric_dict = self.comf_score_new()
  847. # get weight distribution
  848. report_dict["weightDistribution"] = self._get_weight_distribution("comfort")
  849. score_comfort = int(score_comfort) if int(score_comfort) == score_comfort else round(score_comfort, 2)
  850. grade_comfort = score_grade(score_comfort)
  851. report_dict["score"] = score_comfort
  852. report_dict["level"] = grade_comfort
  853. # comfort data for graph
  854. ego_speed_list = self.ego_df['v'].values.tolist()
  855. ego_speed_vs_time = self.zip_time_pairs(ego_speed_list)
  856. lon_acc_list = self.ego_df['lon_acc'].values.tolist()
  857. lon_acc_vs_time = self.zip_time_pairs(lon_acc_list)
  858. yawrate_list = self.ego_df['speedH'].values.tolist()
  859. yawrate_vs_time = self.zip_time_pairs(yawrate_list)
  860. yawrate_roc_list = self.ego_df['accelH'].values.tolist()
  861. yawrate_roc_vs_time = self.zip_time_pairs(yawrate_roc_list)
  862. cur_ego_path_vs_time = self.zip_time_pairs(self.cur_ego_path_list)
  863. curvature_vs_time = self.zip_time_pairs(self.curvature_list)
  864. # markline
  865. discomfort_df = self.discomfort_df.copy().dropna()
  866. discomfort_df['type'] = "origin"
  867. discomfort_slices = discomfort_df.to_dict('records')
  868. # discomfort_zigzag_df = self.discomfort_df.copy()
  869. # discomfort_zigzag_df.loc[discomfort_zigzag_df['type'] != 'zigzag', 'type'] = "origin"
  870. # discomfort_zigzag_slices = discomfort_zigzag_df.to_dict('records')
  871. #
  872. # discomfort_shake_df = self.discomfort_df.copy()
  873. # discomfort_shake_df.loc[discomfort_shake_df['type'] != 'shake', 'type'] = "origin"
  874. # discomfort_shake_slices = discomfort_shake_df.to_dict('records')
  875. #
  876. # discomfort_acce_df = self.discomfort_df.copy()
  877. # discomfort_acce_df.loc[discomfort_acce_df['type'] == 'zigzag', 'type'] = "origin"
  878. # discomfort_acce_df.loc[discomfort_acce_df['type'] == 'shake', 'type'] = "origin"
  879. # discomfort_acce_slices = discomfort_acce_df.to_dict('records')
  880. # for description
  881. good_type_list = []
  882. bad_type_list = []
  883. good_metric_list = []
  884. bad_metric_list = []
  885. # str for comf description 1&2
  886. str_uncomf_count = ''
  887. str_uncomf_over_optimal = ''
  888. type_details_dict = {}
  889. for type in self.type_list:
  890. bad_type_list.append(type) if score_type_dict[type] < 80 else good_type_list.append(type)
  891. type_dict = {
  892. "name": f"{self.type_name_dict[type]}",
  893. }
  894. builtin_graph_dict = {}
  895. custom_graph_dict = {}
  896. score_type = score_type_dict[type]
  897. grade_type = score_grade(score_type)
  898. type_dict["score"] = score_type
  899. type_dict["level"] = grade_type
  900. type_dict_indexes = {}
  901. flag_acc = False
  902. for metric in self.metric_dict[type]:
  903. bad_metric_list.append(metric) if score_metric_dict[metric] < 80 else good_metric_list.append(metric)
  904. if metric in self.bulitin_metric_list:
  905. # for indexes
  906. type_dict_indexes[metric] = {
  907. # "name": f"{self.name_dict[metric]}({self.unit_dict[metric]})",
  908. "name": f"{self.name_dict[metric]}",
  909. "score": score_metric_dict[metric],
  910. "numberReal": f"{self.count_dict[metric]}",
  911. "numberRef": f"{self.optimal1_dict[metric]:.4f}",
  912. "durationReal": f"{self.duration_dict[metric]:.2f}",
  913. "durationRef": f"{self.optimal2_dict[metric]:.4f}",
  914. "strengthReal": f"{self.strength_dict[metric]:.2f}",
  915. "strengthRef": f"{self.optimal3_dict[metric]}"
  916. }
  917. str_uncomf_over_optimal = str_uncomf_over_optimal[:-1]
  918. # for description
  919. if self.count_dict[metric] > 0:
  920. str_uncomf_count += f'{self.count_dict[metric]}次{self.name_dict[metric]}行为、'
  921. if self.count_dict[metric] > self.optimal1_dict[metric]:
  922. over_optimal = ((self.count_dict[metric] - self.optimal1_dict[metric]) / self.optimal1_dict[
  923. metric]) * 100
  924. str_uncomf_over_optimal += f'{self.name_dict[metric]}次数比基准值高{over_optimal:.2f}%,'
  925. if self.duration_dict[metric] > self.optimal2_dict[metric]:
  926. over_optimal = ((self.duration_dict[metric] - self.optimal2_dict[metric]) / self.optimal2_dict[
  927. metric]) * 100
  928. str_uncomf_over_optimal += f'{self.name_dict[metric]}时长比基准值高{over_optimal:.2f}%,'
  929. if self.strength_dict[metric] > self.optimal3_dict[metric]:
  930. over_optimal = ((self.strength_dict[metric] - self.optimal3_dict[metric]) / self.optimal3_dict[
  931. metric]) * 100
  932. str_uncomf_over_optimal += f'{self.name_dict[metric]}强度比基准值高{over_optimal:.2f}%;'
  933. # report_dict["speData"] = ego_speed_vs_time
  934. # report_dict["accData"] = lon_acc_vs_time
  935. # report_dict["anvData"] = yawrate_vs_time
  936. # report_dict["anaData"] = yawrate_roc_vs_time
  937. # report_dict["curData"] = [cur_ego_path_vs_time, curvature_vs_time]
  938. # report_dict["speMarkLine"] = discomfort_slices
  939. # report_dict["accMarkLine"] = discomfort_acce_slices
  940. # report_dict["anvMarkLine"] = discomfort_zigzag_slices
  941. # report_dict["anaMarkLine"] = discomfort_zigzag_slices
  942. # report_dict["curMarkLine"] = discomfort_shake_slices
  943. if metric == "zigzag":
  944. metric_data = {
  945. "name": "横摆角加速度(rad/s²)",
  946. "data": yawrate_roc_vs_time,
  947. "range": f"[-{self.optimal3_dict[metric]}, {self.optimal3_dict[metric]}]",
  948. # "range": f"[0, {self.optimal3_dict[metric]}]",
  949. # "markLine": discomfort_zigzag_slices
  950. }
  951. builtin_graph_dict[metric] = metric_data
  952. elif metric == "shake":
  953. metric_data = {
  954. "name": "曲率(1/m)",
  955. "legend": ["自车轨迹曲率", "车道中心线曲率"],
  956. "data": [cur_ego_path_vs_time, curvature_vs_time],
  957. "range": f"[-{self.optimal3_dict[metric]}, {self.optimal3_dict[metric]}]",
  958. # "range": f"[0, {self.optimal3_dict[metric]}]",
  959. # "markLine": discomfort_shake_slices
  960. }
  961. builtin_graph_dict[metric] = metric_data
  962. elif metric in ["cadence", "slamBrake", "slamAccelerate"] and not flag_acc:
  963. metric_data = {
  964. "name": "自车纵向加速度(m/s²)",
  965. "data": lon_acc_vs_time,
  966. "range": f"[-{self.optimal3_dict[metric]}, {self.optimal3_dict[metric]}]",
  967. # "range": f"[0, {self.optimal3_dict[metric]}]",
  968. # "markLine": discomfort_acce_slices
  969. }
  970. flag_acc = True
  971. builtin_graph_dict[metric] = metric_data
  972. else:
  973. # for indexes
  974. type_dict_indexes[metric] = {
  975. # "name": f"{self.name_dict[metric]}({self.unit_dict[metric]})",
  976. "name": f"{self.name_dict[metric]}",
  977. "score": score_metric_dict[metric],
  978. "numberReal": f"{self.custom_data[metric]['tableData']['avg']}",
  979. "numberRef": f"-",
  980. "durationReal": f"{self.custom_data[metric]['tableData']['max']}",
  981. "durationRef": f"-",
  982. "strengthReal": f"{self.custom_data[metric]['tableData']['min']}",
  983. "strengthRef": f"-"
  984. }
  985. custom_graph_dict[metric] = self.custom_data[metric]['reportData']
  986. str_uncomf_over_optimal = str_uncomf_over_optimal[:-1] + ";"
  987. type_dict["indexes"] = type_dict_indexes
  988. type_dict["builtin"] = builtin_graph_dict
  989. type_dict["custom"] = custom_graph_dict
  990. type_details_dict[type] = type_dict
  991. str_uncomf_over_optimal = str_uncomf_over_optimal[:-1]
  992. report_dict["details"] = type_details_dict
  993. comf_description1 = ""
  994. # str for comf description2
  995. if grade_comfort == '优秀':
  996. comf_description1 = '乘客在本轮测试中体验舒适;'
  997. elif grade_comfort == '良好':
  998. comf_description1 = '算法在本轮测试中的表现满⾜设计指标要求;'
  999. elif grade_comfort == '一般':
  1000. str_bad_metric = string_concatenate(bad_metric_list)
  1001. comf_description1 = f'未满足设计指标要求。算法需要在{str_bad_metric}上进一步优化。在{(self.mileage / 1000):.2f}公里内,共发生{str_uncomf_count[:-1]};'
  1002. elif grade_comfort == '较差':
  1003. str_bad_metric = string_concatenate(bad_metric_list)
  1004. comf_description1 = f'乘客体验极不舒适,未满足设计指标要求。算法需要在{str_bad_metric}上进一步优化。在{(self.mileage / 1000):.2f}公里内,共发生{str_uncomf_count[:-1]};'
  1005. if not bad_metric_list:
  1006. str_comf_type = string_concatenate(good_metric_list)
  1007. comf_description2 = f"{str_comf_type}均表现良好。"
  1008. else:
  1009. str_bad_metric = string_concatenate(bad_metric_list)
  1010. if not good_metric_list:
  1011. comf_description2 = f"{str_bad_metric}表现不佳。其中{str_uncomf_over_optimal}。"
  1012. else:
  1013. str_comf_type = string_concatenate(good_metric_list)
  1014. comf_description2 = f"{str_comf_type}表现良好;{str_bad_metric}表现不佳。其中{str_uncomf_over_optimal}。"
  1015. # str for comf description3
  1016. control_type = []
  1017. if 'zigzag' in bad_metric_list or 'shake' in bad_metric_list:
  1018. control_type.append('横向')
  1019. if 'cadence' in bad_metric_list or 'slamBrake' in bad_metric_list or 'slamAccelerate' in bad_metric_list in bad_metric_list:
  1020. control_type.append('纵向')
  1021. str_control_type = '和'.join(control_type)
  1022. if not control_type:
  1023. comf_description3 = f"算法的横向和纵向控制表现俱佳,乘坐体验舒适。"
  1024. else:
  1025. comf_description3 = f"算法应该优化对车辆的{str_control_type}控制,优化乘坐体验。"
  1026. uncomf_time = self.discomfort_duration
  1027. if uncomf_time == 0:
  1028. comf_description4 = ""
  1029. else:
  1030. percent4 = uncomf_time / duration * 100
  1031. comf_description4 = f"在{duration}s时间内,乘客有{percent4:.2f}%的时间存在不舒适感受。"
  1032. report_dict["description1"] = replace_key_with_value(comf_description1, self.name_dict)
  1033. report_dict["description2"] = replace_key_with_value(comf_description2, self.name_dict)
  1034. report_dict["description3"] = comf_description3
  1035. report_dict["description4"] = comf_description4
  1036. report_dict['commonData'] = {
  1037. "per": {
  1038. "name": "刹车/油门踏板开度(百分比)",
  1039. "legend": ["刹车踏板开度", "油门踏板开度"],
  1040. "data": [brake_vs_time, throttle_vs_time]
  1041. },
  1042. "ang": {
  1043. "name": "方向盘转角(角度°)",
  1044. "data": steering_vs_time
  1045. },
  1046. "spe": {
  1047. "name": "速度(km/h)",
  1048. # "legend": ["自车速度", "目标车速度", "自车与目标车相对速度"],
  1049. "data": ego_speed_vs_time
  1050. },
  1051. # "acc": {
  1052. # "name": "自车纵向加速度(m/s²)",
  1053. # "data": lon_acc_vs_time
  1054. #
  1055. # },
  1056. # "dis": {
  1057. # "name": "前车距离(m)",
  1058. # "data": distance_vs_time
  1059. # }
  1060. }
  1061. report_dict["commonMarkLine"] = discomfort_slices
  1062. # report_dict = {
  1063. # "name": "舒适性",
  1064. # "weight": f"{self.weight * 100:.2f}%",
  1065. # "weightDistribution": weight_distribution,
  1066. # "score": score_comfort,
  1067. # "level": grade_comfort,
  1068. # 'discomfortCount': self.discomfort_count,
  1069. # "description1": comf_description1,
  1070. # "description2": comf_description2,
  1071. # "description3": comf_description3,
  1072. # "description4": comf_description4,
  1073. #
  1074. # "comfortLat": lat_dict,
  1075. # "comfortLon": lon_dict,
  1076. #
  1077. # "speData": ego_speed_vs_time,
  1078. # "speMarkLine": discomfort_slices,
  1079. #
  1080. # "accData": lon_acc_vs_time,
  1081. # "accMarkLine": discomfort_acce_slices,
  1082. #
  1083. # "anvData": yawrate_vs_time,
  1084. # "anvMarkLine": discomfort_zigzag_slices,
  1085. #
  1086. # "anaData": yawrate_roc_vs_time,
  1087. # "anaMarkLine": discomfort_zigzag_slices,
  1088. #
  1089. # "curData": [cur_ego_path_vs_time, curvature_vs_time],
  1090. # "curMarkLine": discomfort_shake_slices,
  1091. # }
  1092. self.eval_data = self.ego_df.copy()
  1093. self.eval_data['playerId'] = 1
  1094. return report_dict
  1095. def get_eval_data(self):
  1096. df = self.eval_data[
  1097. ['simTime', 'simFrame', 'playerId', 'ip_acc', 'ip_dec', 'slam_brake', 'slam_accel', 'cadence',
  1098. 'cur_ego_path', 'cur_diff', 'R', 'R_ego', 'R_diff']].copy()
  1099. return df