comfort.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  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=6000, avg=0.4):
  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. def _cadence_detector(self):
  352. """
  353. # 加速度突变:先加后减,先减后加,先加然后停,先减然后停
  354. # 顿挫:2s内多次加速度变化率突变
  355. # 求出每一个特征点,然后提取,然后将每一个特征点后面的2s做一个窗口,统计频率,避免无效运算
  356. # 将特征点筛选出来
  357. # 将特征点时间作为聚类标准,大于1s的pass,小于等于1s的聚类到一个分组
  358. # 去掉小于3个特征点的分组
  359. """
  360. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'cadence']].copy()
  361. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'lon_acc_roc', 'cadence']].copy()
  362. time_list = data['simTime'].values.tolist()
  363. data = data[data['cadence'] != np.nan]
  364. data['cadence_diff'] = data['cadence'].diff()
  365. data.dropna(subset='cadence_diff', inplace=True)
  366. data = data[data['cadence_diff'] != 0]
  367. t_list = data['simTime'].values.tolist()
  368. f_list = data['simFrame'].values.tolist()
  369. TIME_RANGE = 1
  370. group_time = []
  371. group_frame = []
  372. sub_group_time = []
  373. sub_group_frame = []
  374. for i in range(len(f_list)):
  375. if not sub_group_time or t_list[i] - t_list[i - 1] <= TIME_RANGE: # 特征点相邻一秒内的,算作同一组顿挫
  376. sub_group_time.append(t_list[i])
  377. sub_group_frame.append(f_list[i])
  378. else:
  379. group_time.append(sub_group_time)
  380. group_frame.append(sub_group_frame)
  381. sub_group_time = [t_list[i]]
  382. sub_group_frame = [f_list[i]]
  383. group_time.append(sub_group_time)
  384. group_frame.append(sub_group_frame)
  385. group_time = [g for g in group_time if len(g) >= 1] # 有一次特征点则算作一次顿挫
  386. group_frame = [g for g in group_frame if len(g) >= 1]
  387. # group_time = []
  388. # sub_group = []
  389. #
  390. # for i in range(len(f_list)):
  391. # if not sub_group or t_list[i] - t_list[i - 1] <= 1: # 特征点相邻一秒内的,算作同一组顿挫
  392. # sub_group.append(t_list[i])
  393. # else:
  394. # group_time.append(sub_group)
  395. # sub_group = [t_list[i]]
  396. #
  397. # group_time.append(sub_group)
  398. # group_time = [g for g in group_time if len(g) >= 1] # 有一次特征点则算作一次顿挫
  399. # 输出图表值
  400. cadence_time = [[g[0], g[-1]] for g in group_time]
  401. cadence_frame = [[g[0], g[-1]] for g in group_frame]
  402. if cadence_time:
  403. time_df = pd.DataFrame(cadence_time, columns=['start_time', 'end_time'])
  404. frame_df = pd.DataFrame(cadence_frame, columns=['start_frame', 'end_frame'])
  405. discomfort_df = pd.concat([time_df, frame_df], axis=1)
  406. discomfort_df['type'] = 'cadence'
  407. self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  408. # 将顿挫组的起始时间为组重新统计时间
  409. cadence_time_list = [time for pair in cadence_time for time in time_list if pair[0] <= time <= pair[1]]
  410. # time_list = [element for sublist in group_time for element in sublist]
  411. # merged_list = [element for sublist in res_group for element in sublist]
  412. # res_df = data[data['simTime'].isin(merged_list)]
  413. stre_list = []
  414. freq_list = []
  415. for g in group_time:
  416. # calculate strength
  417. g_df = data[data['simTime'].isin(g)]
  418. strength = g_df['lon_acc'].abs().mean()
  419. stre_list.append(strength)
  420. # calculate frequency
  421. cnt = len(g)
  422. t_start = g_df['simTime'].iloc[0]
  423. t_end = g_df['simTime'].iloc[-1]
  424. t_delta = t_end - t_start
  425. frequency = cnt / t_delta
  426. freq_list.append(frequency)
  427. self.cadence_count = len(freq_list)
  428. cadence_stre = sum(stre_list) / len(stre_list) if stre_list else 0
  429. return cadence_time_list
  430. def _slam_brake_detector(self):
  431. # 统计急刹全为1的分段的个数,记录分段开头的frame_ID
  432. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'ip_dec_roc', 'slam_brake']].copy()
  433. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'lon_acc_roc', 'ip_dec', 'slam_brake']].copy()
  434. # data['slam_diff'] = data['slam_brake'].diff()
  435. # res_df = data[data['slam_diff'] == 1]
  436. res_df = data[data['slam_brake'] == 1]
  437. t_list = res_df['simTime'].values
  438. f_list = res_df['simFrame'].values.tolist()
  439. TIME_RANGE = 1
  440. group_time = []
  441. group_frame = []
  442. sub_group_time = []
  443. sub_group_frame = []
  444. for i in range(len(f_list)):
  445. if not sub_group_time or f_list[i] - f_list[i - 1] <= TIME_RANGE: # 连续帧的算作同一组急刹
  446. sub_group_time.append(t_list[i])
  447. sub_group_frame.append(f_list[i])
  448. else:
  449. group_time.append(sub_group_time)
  450. group_frame.append(sub_group_frame)
  451. sub_group_time = [t_list[i]]
  452. sub_group_frame = [f_list[i]]
  453. group_time.append(sub_group_time)
  454. group_frame.append(sub_group_frame)
  455. group_time = [g for g in group_time if len(g) >= 2] # 达到两帧算作一次急刹
  456. group_frame = [g for g in group_frame if len(g) >= 2]
  457. # group_time = []
  458. # sub_group = []
  459. #
  460. # for i in range(len(f_list)):
  461. # if not sub_group or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急刹
  462. # sub_group.append(t_list[i])
  463. # else:
  464. # group_time.append(sub_group)
  465. # sub_group = [t_list[i]]
  466. #
  467. # group_time.append(sub_group)
  468. # group_time = [g for g in group_time if len(g) >= 2] # 达到两帧算作一次急刹
  469. # 输出图表值
  470. slam_brake_time = [[g[0], g[-1]] for g in group_time]
  471. slam_brake_frame = [[g[0], g[-1]] for g in group_frame]
  472. if slam_brake_time:
  473. time_df = pd.DataFrame(slam_brake_time, columns=['start_time', 'end_time'])
  474. frame_df = pd.DataFrame(slam_brake_frame, columns=['start_frame', 'end_frame'])
  475. discomfort_df = pd.concat([time_df, frame_df], axis=1)
  476. discomfort_df['type'] = 'slam_brake'
  477. self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  478. time_list = [element for sublist in group_time for element in sublist]
  479. self.slam_brake_count = len(group_time) # / self.mileage # * 1000000
  480. return time_list
  481. def _slam_accel_detector(self):
  482. # 统计急刹全为1的分段的个数,记录分段开头的frame_ID
  483. # data = self.ego_df[['simTime', 'simFrame', 'lon_acc_roc', 'ip_acc_roc', 'slam_accel']].copy()
  484. data = self.ego_df[['simTime', 'simFrame', 'lon_acc', 'ip_acc', 'slam_accel']].copy()
  485. # data['slam_diff'] = data['slam_accel'].diff()
  486. # res_df = data.loc[data['slam_diff'] == 1]
  487. res_df = data.loc[data['slam_accel'] == 1]
  488. t_list = res_df['simTime'].values
  489. f_list = res_df['simFrame'].values.tolist()
  490. group_time = []
  491. group_frame = []
  492. sub_group_time = []
  493. sub_group_frame = []
  494. for i in range(len(f_list)):
  495. if not group_time or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急加速
  496. sub_group_time.append(t_list[i])
  497. sub_group_frame.append(f_list[i])
  498. else:
  499. group_time.append(sub_group_time)
  500. group_frame.append(sub_group_frame)
  501. sub_group_time = [t_list[i]]
  502. sub_group_frame = [f_list[i]]
  503. group_time.append(sub_group_time)
  504. group_frame.append(sub_group_frame)
  505. group_time = [g for g in group_time if len(g) >= 2]
  506. group_frame = [g for g in group_frame if len(g) >= 2]
  507. # group_time = []
  508. # sub_group = []
  509. #
  510. # for i in range(len(f_list)):
  511. # if not sub_group or f_list[i] - f_list[i - 1] <= 1: # 连续帧的算作同一组急加速
  512. # sub_group.append(t_list[i])
  513. # else:
  514. # group_time.append(sub_group)
  515. # sub_group = [t_list[i]]
  516. #
  517. # group_time.append(sub_group)
  518. # group_time = [g for g in group_time if len(g) >= 2] # 达到两帧算作一次急加速
  519. # 输出图表值
  520. slam_accel_time = [[g[0], g[-1]] for g in group_time]
  521. slam_accel_frame = [[g[0], g[-1]] for g in group_frame]
  522. if slam_accel_time:
  523. time_df = pd.DataFrame(slam_accel_time, columns=['start_time', 'end_time'])
  524. frame_df = pd.DataFrame(slam_accel_frame, columns=['start_frame', 'end_frame'])
  525. discomfort_df = pd.concat([time_df, frame_df], axis=1)
  526. discomfort_df['type'] = 'slam_accel'
  527. self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  528. time_list = [element for sublist in group_time for element in sublist]
  529. self.slam_accel_count = len(group_time) # / self.mileage # * 1000000
  530. return time_list
  531. def comf_statistic(self):
  532. """
  533. """
  534. df = self.ego_df[['simTime', 'cur_diff', 'lon_acc', 'lon_acc_roc', 'accelH']].copy()
  535. self.zigzag_count_func()
  536. self.cal_zigzag_strength_strength()
  537. if self.zigzag_time_list:
  538. zigzag_df = pd.DataFrame(self.zigzag_time_list, columns=['start_time', 'end_time'])
  539. zigzag_df = get_frame_with_time(zigzag_df, self.ego_df)
  540. zigzag_df['type'] = 'zigzag'
  541. self.discomfort_df = pd.concat([self.discomfort_df, zigzag_df], ignore_index=True)
  542. # discomfort_df = pd.concat([time_df, frame_df], axis=1)
  543. # self.discomfort_df = pd.concat([self.discomfort_df, discomfort_df], ignore_index=True)
  544. zigzag_t_list = []
  545. # 只有[t_start, t_end]数对,要提取为完整time list
  546. t_list = df['simTime'].values.tolist()
  547. for t_start, t_end in self.zigzag_time_list:
  548. index_1 = t_list.index(t_start)
  549. index_2 = t_list.index(t_end)
  550. zigzag_t_list.extend(t_list[index_1:index_2 + 1])
  551. zigzag_t_list = list(set(zigzag_t_list))
  552. shake_t_list = self._shake_detector()
  553. cadence_t_list = self._cadence_detector()
  554. slam_brake_t_list = self._slam_brake_detector()
  555. slam_accel_t_list = self._slam_accel_detector()
  556. # comfort_time_dict = {
  557. # 'zigzag_time_list': zigzag_t_list,
  558. # 'shake_time_list': shake_t_list,
  559. # 'cadence_time_list': cadence_t_list,
  560. # 'slam_brake_time_list': slam_brake_t_list,
  561. # 'slam_accelerate_time_list': slam_accel_t_list
  562. # }
  563. discomfort_time_list = zigzag_t_list + shake_t_list + cadence_t_list + slam_brake_t_list + slam_accel_t_list
  564. discomfort_time_list = sorted(discomfort_time_list) # 排序
  565. discomfort_time_list = list(set(discomfort_time_list)) # 去重
  566. # TIME_DIFF = self.time_list[3] - self.time_list[2]
  567. # TIME_DIFF = 0.4
  568. FREQUENCY = 100
  569. TIME_DIFF = 1 / FREQUENCY
  570. self.discomfort_duration = len(discomfort_time_list) * TIME_DIFF
  571. df['flag_zigzag'] = df['simTime'].apply(lambda x: 1 if x in zigzag_t_list else 0)
  572. df['flag_shake'] = df['simTime'].apply(lambda x: 1 if x in shake_t_list else 0)
  573. df['flag_cadence'] = df['simTime'].apply(lambda x: 1 if x in cadence_t_list else 0)
  574. df['flag_slam_brake'] = df['simTime'].apply(lambda x: 1 if x in slam_brake_t_list else 0)
  575. df['flag_slam_accel'] = df['simTime'].apply(lambda x: 1 if x in slam_accel_t_list else 0)
  576. # hectokilometer = 100000 # 百公里
  577. self.zigzag_duration = df['flag_zigzag'].sum() * TIME_DIFF # / self.mileage * hectokilometer
  578. self.shake_duration = df['flag_shake'].sum() * TIME_DIFF # / self.mileage * hectokilometer
  579. self.cadence_duration = df['flag_cadence'].sum() * TIME_DIFF # / self.mileage * hectokilometer
  580. self.slam_brake_duration = df['flag_slam_brake'].sum() * TIME_DIFF # / self.mileage * hectokilometer
  581. self.slam_accel_duration = df['flag_slam_accel'].sum() * TIME_DIFF # / self.mileage * hectokilometer
  582. # 强度取值可考虑最大值,暂定平均值,具体视数据情况而定
  583. # self.zigzag_strength = np.mean(self.zigzag_stre_list) if self.zigzag_stre_list else 0
  584. self.zigzag_strength = (df['flag_shake'] * abs(df['accelH'])).mean()
  585. self.shake_strength = (df['flag_shake'] * abs(df['cur_diff'])).mean()
  586. self.cadence_strength = (df['flag_cadence'] * abs(df['lon_acc'])).mean()
  587. self.slam_brake_strength = (df['flag_slam_brake'] * abs(df['lon_acc'])).mean()
  588. self.slam_accel_strength = (df['flag_slam_accel'] * abs(df['lon_acc'])).mean()
  589. self.zigzag_strength = self._nan_detect(self.zigzag_strength)
  590. self.shake_strength = self._nan_detect(self.shake_strength)
  591. self.cadence_strength = self._nan_detect(self.cadence_strength)
  592. self.slam_brake_strength = self._nan_detect(self.slam_brake_strength)
  593. self.slam_accel_strength = self._nan_detect(self.slam_accel_strength)
  594. self.count_dict = {
  595. "zigzag": self.zigzag_count,
  596. "shake": self.shake_count,
  597. "cadence": self.cadence_count,
  598. "slamBrake": self.slam_brake_count,
  599. "slamAccelerate": self.slam_accel_count
  600. }
  601. self.duration_dict = {
  602. "zigzag": self.zigzag_duration,
  603. "shake": self.shake_duration,
  604. "cadence": self.cadence_duration,
  605. "slamBrake": self.slam_brake_duration,
  606. "slamAccelerate": self.slam_accel_duration
  607. }
  608. self.strength_dict = {
  609. "zigzag": self.zigzag_strength,
  610. "shake": self.shake_strength,
  611. "cadence": self.cadence_strength,
  612. "slamBrake": self.slam_brake_strength,
  613. "slamAccelerate": self.slam_accel_strength
  614. }
  615. zigzag_list = [self.zigzag_count, self.zigzag_duration, self.zigzag_strength]
  616. shake_list = [self.shake_count, self.shake_duration, self.shake_strength]
  617. cadence_list = [self.cadence_count, self.cadence_duration, self.cadence_strength]
  618. slam_brake_list = [self.slam_brake_count, self.slam_brake_duration, self.slam_brake_strength]
  619. slam_accel_list = [self.slam_accel_count, self.slam_accel_duration, self.slam_accel_strength]
  620. tmp_comf_arr = []
  621. if "zigzag" in self.metric_list:
  622. tmp_comf_arr += zigzag_list
  623. self.discomfort_count += self.zigzag_count
  624. if "shake" in self.metric_list:
  625. tmp_comf_arr += shake_list
  626. self.discomfort_count += self.shake_count
  627. if "cadence" in self.metric_list:
  628. tmp_comf_arr += cadence_list
  629. self.discomfort_count += self.cadence_count
  630. if "slamBrake" in self.metric_list:
  631. tmp_comf_arr += slam_brake_list
  632. self.discomfort_count += self.slam_brake_count
  633. if "slamAccelerate" in self.metric_list:
  634. tmp_comf_arr += slam_accel_list
  635. self.discomfort_count += self.slam_accel_count
  636. comf_arr = [tmp_comf_arr]
  637. return comf_arr
  638. def _nan_detect(self, num):
  639. if math.isnan(num):
  640. return 0
  641. return num
  642. def custom_metric_param_parser(self, param_list):
  643. """
  644. param_dict = {
  645. "paramA" [
  646. {
  647. "kind": "-1",
  648. "optimal": "1",
  649. "multiple": ["0.5","5"],
  650. "spare1": null,
  651. "spare2": null
  652. }
  653. ]
  654. }
  655. """
  656. kind_list = []
  657. optimal_list = []
  658. multiple_list = []
  659. spare_list = []
  660. # spare1_list = []
  661. # spare2_list = []
  662. for i in range(len(param_list)):
  663. kind_list.append(int(param_list[i]['kind']))
  664. optimal_list.append(float(param_list[i]['optimal']))
  665. multiple_list.append([float(x) for x in param_list[i]['multiple']])
  666. spare_list.append([item["param"] for item in param_list[i]["spare"]])
  667. # spare1_list.append(param_list[i]['spare1'])
  668. # spare2_list.append(param_list[i]['spare2'])
  669. result = {
  670. "kind": kind_list,
  671. "optimal": optimal_list,
  672. "multiple": multiple_list,
  673. "spare": spare_list,
  674. # "spare1": spare1_list,
  675. # "spare2": spare2_list
  676. }
  677. return result
  678. def custom_metric_score(self, metric, value, param_list):
  679. """
  680. """
  681. param = self.custom_metric_param_parser(param_list)
  682. self.custom_param_dict[metric] = param
  683. score_model = self.scoreModel(param['kind'], param['optimal'], param['multiple'], np.array([value]))
  684. score_sub = score_model.cal_score()
  685. score = sum(score_sub) / len(score_sub)
  686. return score
  687. def comf_score_new(self):
  688. score_metric_dict = {}
  689. score_type_dict = {}
  690. arr_comf = self.comf_statistic()
  691. print("\n[舒适性表现及得分情况]")
  692. print("舒适性各指标值:", [[round(num, 2) for num in row] for row in arr_comf])
  693. if arr_comf:
  694. arr_comf = np.array(arr_comf)
  695. score_model = self.scoreModel(self.kind_list, self.optimal_list, self.multiple_list, arr_comf)
  696. score_sub = score_model.cal_score()
  697. score_sub = list(map(lambda x: 80 if np.isnan(x) else x, score_sub))
  698. metric_list = [x for x in self.metric_list if x in self.config.builtinMetricList]
  699. score_metric = []
  700. for i in range(len(metric_list)):
  701. score_tmp = (score_sub[i * 3 + 0] + score_sub[i * 3 + 1] + score_sub[i * 3 + 2]) / 3
  702. score_metric.append(round(score_tmp, 2))
  703. score_metric_dict = {key: value for key, value in zip(metric_list, score_metric)}
  704. for metric in self.custom_metric_list:
  705. value = self.custom_data[metric]['value']
  706. param_list = self.customMetricParam[metric]
  707. score = self.custom_metric_score(metric, value, param_list)
  708. score_metric_dict[metric] = round(score, 2)
  709. score_metric_dict = {key: score_metric_dict[key] for key in self.metric_list}
  710. score_metric = list(score_metric_dict.values())
  711. if self.weight_custom: # 自定义权重
  712. score_metric_with_weight_dict = {key: score_metric_dict[key] * self.weight_dict[key] for key in
  713. self.weight_dict}
  714. for type in self.type_list:
  715. type_score = sum(
  716. value for key, value in score_metric_with_weight_dict.items() if key in self.metric_dict[type])
  717. score_type_dict[type] = round(type_score, 2) if type_score < 100 else 100
  718. score_type_with_weight_dict = {key: score_type_dict[key] * self.weight_type_dict[key] for key in
  719. score_type_dict}
  720. score_comfort = sum(score_type_with_weight_dict.values())
  721. else: # 客观赋权
  722. self.weight_list = cal_weight_from_80(score_metric)
  723. self.weight_dict = {key: value for key, value in zip(self.metric_list, self.weight_list)}
  724. score_comfort = cal_score_with_priority(score_metric, self.weight_list, self.priority_list)
  725. for type in self.type_list:
  726. type_weight = sum(value for key, value in self.weight_dict.items() if key in self.metric_dict[type])
  727. for key, value in self.weight_dict.items():
  728. if key in self.metric_dict[type]:
  729. # self.weight_dict[key] = round(value / type_weight, 4)
  730. self.weight_dict[key] = value / type_weight
  731. type_score_metric = [value for key, value in score_metric_dict.items() if key in self.metric_dict[type]]
  732. type_weight_list = [value for key, value in self.weight_dict.items() if key in self.metric_dict[type]]
  733. type_priority_list = [value for key, value in self.priority_dict.items() if
  734. key in self.metric_dict[type]]
  735. type_score = cal_score_with_priority(type_score_metric, type_weight_list, type_priority_list)
  736. score_type_dict[type] = round(type_score, 2) if type_score < 100 else 100
  737. for key in self.weight_dict:
  738. self.weight_dict[key] = round(self.weight_dict[key], 4)
  739. score_type = list(score_type_dict.values())
  740. self.weight_type_list = cal_weight_from_80(score_type)
  741. self.weight_type_dict = {key: value for key, value in zip(self.type_list, self.weight_type_list)}
  742. score_comfort = round(score_comfort, 2)
  743. print("舒适性各指标基准值:", self.optimal_list)
  744. print(f"舒适性得分为:{score_comfort:.2f}分。")
  745. print(f"舒适性各类型得分为:{score_type_dict}。")
  746. print(f"舒适性各指标得分为:{score_metric_dict}。")
  747. return score_comfort, score_type_dict, score_metric_dict
  748. # def zip_time_pairs(self, zip_list, upper_limit=9999):
  749. # zip_time_pairs = zip(self.time_list, zip_list)
  750. # zip_vs_time = [[x, upper_limit if y > upper_limit else y] for x, y in zip_time_pairs if not math.isnan(y)]
  751. # return zip_vs_time
  752. def zip_time_pairs(self, zip_list):
  753. zip_time_pairs = zip(self.time_list, zip_list)
  754. zip_vs_time = [[x, "" if math.isnan(y) else y] for x, y in zip_time_pairs]
  755. return zip_vs_time
  756. def comf_weight_distribution(self):
  757. # get weight distribution
  758. weight_distribution = {}
  759. weight_distribution["name"] = "舒适性"
  760. if "comfortLat" in self.type_list:
  761. lat_weight_indexes_dict = {key: f"{key}({value * 100:.2f}%)" for key, value in self.weight_dict.items() if
  762. key in self.lat_metric_list}
  763. weight_distribution_lat = {
  764. "latWeight": f"横向舒适度({self.weight_type_dict['comfortLat'] * 100:.2f}%)",
  765. "indexes": lat_weight_indexes_dict
  766. }
  767. weight_distribution['comfortLat'] = weight_distribution_lat
  768. if "comfortLon" in self.type_list:
  769. lon_weight_indexes_dict = {key: f"{key}({value * 100:.2f}%)" for key, value in self.weight_dict.items() if
  770. key in self.lon_metric_list}
  771. weight_distribution_lon = {
  772. "lonWeight": f"纵向舒适度({self.weight_type_dict['comfortLon'] * 100:.2f}%)",
  773. "indexes": lon_weight_indexes_dict
  774. }
  775. weight_distribution['comfortLon'] = weight_distribution_lon
  776. return weight_distribution
  777. def _get_weight_distribution(self, dimension):
  778. # get weight distribution
  779. weight_distribution = {}
  780. weight_distribution["name"] = self.config.dimension_name[dimension]
  781. for type in self.type_list:
  782. type_weight_indexes_dict = {key: f"{self.name_dict[key]}({value * 100:.2f}%)" for key, value in
  783. self.weight_dict.items() if
  784. key in self.metric_dict[type]}
  785. weight_distribution_type = {
  786. "weight": f"{self.type_name_dict[type]}({self.weight_type_dict[type] * 100:.2f}%)",
  787. "indexes": type_weight_indexes_dict
  788. }
  789. weight_distribution[type] = weight_distribution_type
  790. return weight_distribution
  791. def report_statistic(self):
  792. """
  793. Returns:
  794. """
  795. # report_dict = {
  796. # "name": "舒适性",
  797. # "weight": f"{self.weight * 100:.2f}%",
  798. # "weightDistribution": weight_distribution,
  799. # "score": score_comfort,
  800. # "level": grade_comfort,
  801. # 'discomfortCount': self.discomfort_count,
  802. # "description1": comf_description1,
  803. # "description2": comf_description2,
  804. # "description3": comf_description3,
  805. # "description4": comf_description4,
  806. #
  807. # "comfortLat": lat_dict,
  808. # "comfortLon": lon_dict,
  809. #
  810. # "speData": ego_speed_vs_time,
  811. # "speMarkLine": discomfort_slices,
  812. #
  813. # "accData": lon_acc_vs_time,
  814. # "accMarkLine": discomfort_acce_slices,
  815. #
  816. # "anvData": yawrate_vs_time,
  817. # "anvMarkLine": discomfort_zigzag_slices,
  818. #
  819. # "anaData": yawrate_roc_vs_time,
  820. # "anaMarkLine": discomfort_zigzag_slices,
  821. #
  822. # "curData": [cur_ego_path_vs_time, curvature_vs_time],
  823. # "curMarkLine": discomfort_shake_slices,
  824. # }
  825. brakePedal_list = self.data_processed.driver_ctrl_data['brakePedal_list']
  826. throttlePedal_list = self.data_processed.driver_ctrl_data['throttlePedal_list']
  827. steeringWheel_list = self.data_processed.driver_ctrl_data['steeringWheel_list']
  828. # common parameter calculate
  829. brake_vs_time = self.zip_time_pairs(brakePedal_list)
  830. throttle_vs_time = self.zip_time_pairs(throttlePedal_list)
  831. steering_vs_time = self.zip_time_pairs(steeringWheel_list)
  832. report_dict = {
  833. "name": "舒适性",
  834. "weight": f"{self.weight * 100:.2f}%",
  835. 'discomfortCount': self.discomfort_count,
  836. }
  837. # upper_limit = 40
  838. # times_upper = 2
  839. # len_time = len(self.time_list)
  840. duration = self.time_list[-1]
  841. # comfort score and grade
  842. score_comfort, score_type_dict, score_metric_dict = self.comf_score_new()
  843. # get weight distribution
  844. report_dict["weightDistribution"] = self._get_weight_distribution("comfort")
  845. score_comfort = int(score_comfort) if int(score_comfort) == score_comfort else round(score_comfort, 2)
  846. grade_comfort = score_grade(score_comfort)
  847. report_dict["score"] = score_comfort
  848. report_dict["level"] = grade_comfort
  849. # comfort data for graph
  850. ego_speed_list = self.ego_df['v'].values.tolist()
  851. ego_speed_vs_time = self.zip_time_pairs(ego_speed_list)
  852. lon_acc_list = self.ego_df['lon_acc'].values.tolist()
  853. lon_acc_vs_time = self.zip_time_pairs(lon_acc_list)
  854. yawrate_list = self.ego_df['speedH'].values.tolist()
  855. yawrate_vs_time = self.zip_time_pairs(yawrate_list)
  856. yawrate_roc_list = self.ego_df['accelH'].values.tolist()
  857. yawrate_roc_vs_time = self.zip_time_pairs(yawrate_roc_list)
  858. cur_ego_path_vs_time = self.zip_time_pairs(self.cur_ego_path_list)
  859. curvature_vs_time = self.zip_time_pairs(self.curvature_list)
  860. # markline
  861. discomfort_df = self.discomfort_df.copy()
  862. discomfort_df['type'] = "origin"
  863. discomfort_slices = discomfort_df.to_dict('records')
  864. # discomfort_zigzag_df = self.discomfort_df.copy()
  865. # discomfort_zigzag_df.loc[discomfort_zigzag_df['type'] != 'zigzag', 'type'] = "origin"
  866. # discomfort_zigzag_slices = discomfort_zigzag_df.to_dict('records')
  867. #
  868. # discomfort_shake_df = self.discomfort_df.copy()
  869. # discomfort_shake_df.loc[discomfort_shake_df['type'] != 'shake', 'type'] = "origin"
  870. # discomfort_shake_slices = discomfort_shake_df.to_dict('records')
  871. #
  872. # discomfort_acce_df = self.discomfort_df.copy()
  873. # discomfort_acce_df.loc[discomfort_acce_df['type'] == 'zigzag', 'type'] = "origin"
  874. # discomfort_acce_df.loc[discomfort_acce_df['type'] == 'shake', 'type'] = "origin"
  875. # discomfort_acce_slices = discomfort_acce_df.to_dict('records')
  876. # for description
  877. good_type_list = []
  878. bad_type_list = []
  879. good_metric_list = []
  880. bad_metric_list = []
  881. # str for comf description 1&2
  882. str_uncomf_count = ''
  883. str_uncomf_over_optimal = ''
  884. type_details_dict = {}
  885. for type in self.type_list:
  886. bad_type_list.append(type) if score_type_dict[type] < 80 else good_type_list.append(type)
  887. type_dict = {
  888. "name": f"{self.type_name_dict[type]}",
  889. }
  890. builtin_graph_dict = {}
  891. custom_graph_dict = {}
  892. score_type = score_type_dict[type]
  893. grade_type = score_grade(score_type)
  894. type_dict["score"] = score_type
  895. type_dict["level"] = grade_type
  896. type_dict_indexes = {}
  897. flag_acc = False
  898. for metric in self.metric_dict[type]:
  899. bad_metric_list.append(metric) if score_metric_dict[metric] < 80 else good_metric_list.append(metric)
  900. if metric in self.bulitin_metric_list:
  901. # for indexes
  902. type_dict_indexes[metric] = {
  903. # "name": f"{self.name_dict[metric]}({self.unit_dict[metric]})",
  904. "name": f"{self.name_dict[metric]}",
  905. "score": score_metric_dict[metric],
  906. "numberReal": f"{self.count_dict[metric]}",
  907. "numberRef": f"{self.optimal1_dict[metric]:.4f}",
  908. "durationReal": f"{self.duration_dict[metric]:.2f}",
  909. "durationRef": f"{self.optimal2_dict[metric]:.4f}",
  910. "strengthReal": f"{self.strength_dict[metric]:.2f}",
  911. "strengthRef": f"{self.optimal3_dict[metric]}"
  912. }
  913. # for description
  914. if self.count_dict[metric] > 0:
  915. str_uncomf_count += f'{self.count_dict[metric]}次{self.name_dict[metric]}行为、'
  916. if self.count_dict[metric] > self.optimal1_dict[metric]:
  917. over_optimal = ((self.count_dict[metric] - self.optimal1_dict[metric]) / self.optimal1_dict[
  918. metric]) * 100
  919. str_uncomf_over_optimal += f'{self.name_dict[metric]}次数比基准值高{over_optimal:.2f}%,'
  920. if self.duration_dict[metric] > self.optimal2_dict[metric]:
  921. over_optimal = ((self.duration_dict[metric] - self.optimal2_dict[metric]) / self.optimal2_dict[
  922. metric]) * 100
  923. str_uncomf_over_optimal += f'{self.name_dict[metric]}时长比基准值高{over_optimal:.2f}%,'
  924. if self.strength_dict[metric] > self.optimal3_dict[metric]:
  925. over_optimal = ((self.strength_dict[metric] - self.optimal3_dict[metric]) / self.optimal3_dict[
  926. metric]) * 100
  927. str_uncomf_over_optimal += f'{self.name_dict[metric]}强度比基准值高{over_optimal:.2f}%;'
  928. # report_dict["speData"] = ego_speed_vs_time
  929. # report_dict["accData"] = lon_acc_vs_time
  930. # report_dict["anvData"] = yawrate_vs_time
  931. # report_dict["anaData"] = yawrate_roc_vs_time
  932. # report_dict["curData"] = [cur_ego_path_vs_time, curvature_vs_time]
  933. # report_dict["speMarkLine"] = discomfort_slices
  934. # report_dict["accMarkLine"] = discomfort_acce_slices
  935. # report_dict["anvMarkLine"] = discomfort_zigzag_slices
  936. # report_dict["anaMarkLine"] = discomfort_zigzag_slices
  937. # report_dict["curMarkLine"] = discomfort_shake_slices
  938. if metric == "zigzag":
  939. metric_data = {
  940. "name": "横摆角加速度(rad/s²)",
  941. "data": yawrate_roc_vs_time,
  942. "range": f"[-{self.optimal3_dict[metric]}, {self.optimal3_dict[metric]}]",
  943. # "range": f"[0, {self.optimal3_dict[metric]}]",
  944. # "markLine": discomfort_zigzag_slices
  945. }
  946. builtin_graph_dict[metric] = metric_data
  947. elif metric == "shake":
  948. metric_data = {
  949. "name": "曲率(1/m)",
  950. "legend": ["自车轨迹曲率", "车道中心线曲率"],
  951. "data": [cur_ego_path_vs_time, curvature_vs_time],
  952. "range": f"[-{self.optimal3_dict[metric]}, {self.optimal3_dict[metric]}]",
  953. # "range": f"[0, {self.optimal3_dict[metric]}]",
  954. # "markLine": discomfort_shake_slices
  955. }
  956. builtin_graph_dict[metric] = metric_data
  957. elif metric in ["cadence", "slamBrake", "slamAccelerate"] and not flag_acc:
  958. metric_data = {
  959. "name": "自车纵向加速度(m/s²)",
  960. "data": lon_acc_vs_time,
  961. "range": f"[-{self.optimal3_dict[metric]}, {self.optimal3_dict[metric]}]",
  962. # "range": f"[0, {self.optimal3_dict[metric]}]",
  963. # "markLine": discomfort_acce_slices
  964. }
  965. flag_acc = True
  966. builtin_graph_dict[metric] = metric_data
  967. else:
  968. # for indexes
  969. type_dict_indexes[metric] = {
  970. # "name": f"{self.name_dict[metric]}({self.unit_dict[metric]})",
  971. "name": f"{self.name_dict[metric]}",
  972. "score": score_metric_dict[metric],
  973. "numberReal": f"{self.custom_data[metric]['tableData']['avg']}",
  974. "numberRef": f"-",
  975. "durationReal": f"{self.custom_data[metric]['tableData']['max']}",
  976. "durationRef": f"-",
  977. "strengthReal": f"{self.custom_data[metric]['tableData']['min']}",
  978. "strengthRef": f"-"
  979. }
  980. custom_graph_dict[metric] = self.custom_data[metric]['reportData']
  981. str_uncomf_over_optimal = str_uncomf_over_optimal[:-1] + ";"
  982. type_dict["indexes"] = type_dict_indexes
  983. type_dict["builtin"] = builtin_graph_dict
  984. type_dict["custom"] = custom_graph_dict
  985. type_details_dict[type] = type_dict
  986. report_dict["details"] = type_details_dict
  987. # str for comf description2
  988. if grade_comfort == '优秀':
  989. comf_description1 = '乘客在本轮测试中体验舒适;'
  990. elif grade_comfort == '良好':
  991. comf_description1 = '算法在本轮测试中的表现满⾜设计指标要求;'
  992. elif grade_comfort == '一般':
  993. str_bad_metric = string_concatenate(bad_metric_list)
  994. comf_description1 = f'未满足设计指标要求。算法需要在{str_bad_metric}上进一步优化。在{(self.mileage / 1000):.2f}公里内,共发生{str_uncomf_count[:-1]};'
  995. elif grade_comfort == '较差':
  996. str_bad_metric = string_concatenate(bad_metric_list)
  997. comf_description1 = f'乘客体验极不舒适,未满足设计指标要求。算法需要在{str_bad_metric}上进一步优化。在{(self.mileage / 1000):.2f}公里内,共发生{str_uncomf_count[:-1]};'
  998. if not bad_metric_list:
  999. str_comf_type = string_concatenate(good_metric_list)
  1000. comf_description2 = f"{str_comf_type}均表现良好。"
  1001. else:
  1002. str_bad_metric = string_concatenate(bad_metric_list)
  1003. if not good_metric_list:
  1004. comf_description2 = f"{str_bad_metric}表现不佳。其中{str_uncomf_over_optimal}。"
  1005. else:
  1006. str_comf_type = string_concatenate(good_metric_list)
  1007. comf_description2 = f"{str_comf_type}表现良好;{str_bad_metric}表现不佳。其中{str_uncomf_over_optimal}。"
  1008. # str for comf description3
  1009. control_type = []
  1010. if 'zigzag' in bad_metric_list or 'shake' in bad_metric_list:
  1011. control_type.append('横向')
  1012. if 'cadence' in bad_metric_list or 'slamBrake' in bad_metric_list or 'slamAccelerate' in bad_metric_list in bad_metric_list:
  1013. control_type.append('纵向')
  1014. str_control_type = '和'.join(control_type)
  1015. if not control_type:
  1016. comf_description3 = f"算法的横向和纵向控制表现俱佳,乘坐体验舒适。"
  1017. else:
  1018. comf_description3 = f"算法应该优化对车辆的{str_control_type}控制,优化乘坐体验。"
  1019. uncomf_time = self.discomfort_duration
  1020. if uncomf_time == 0:
  1021. comf_description4 = ""
  1022. else:
  1023. percent4 = uncomf_time / duration * 100
  1024. comf_description4 = f"在{duration}s时间内,乘客有{percent4:.2f}%的时间存在不舒适感受。"
  1025. report_dict["description1"] = replace_key_with_value(comf_description1, self.name_dict)
  1026. report_dict["description2"] = replace_key_with_value(comf_description2, self.name_dict)
  1027. report_dict["description3"] = comf_description3
  1028. report_dict["description4"] = comf_description4
  1029. report_dict['commonData'] = {
  1030. "per": {
  1031. "name": "刹车/油门踏板开度(百分比)",
  1032. "legend": ["刹车踏板开度", "油门踏板开度"],
  1033. "data": [brake_vs_time, throttle_vs_time]
  1034. },
  1035. "ang": {
  1036. "name": "方向盘转角(角度°)",
  1037. "data": steering_vs_time
  1038. },
  1039. "spe": {
  1040. "name": "速度(km/h)",
  1041. # "legend": ["自车速度", "目标车速度", "自车与目标车相对速度"],
  1042. "data": ego_speed_vs_time
  1043. },
  1044. # "acc": {
  1045. # "name": "自车纵向加速度(m/s²)",
  1046. # "data": lon_acc_vs_time
  1047. #
  1048. # },
  1049. # "dis": {
  1050. # "name": "前车距离(m)",
  1051. # "data": distance_vs_time
  1052. # }
  1053. }
  1054. report_dict["commonMarkLine"] = discomfort_slices
  1055. # report_dict = {
  1056. # "name": "舒适性",
  1057. # "weight": f"{self.weight * 100:.2f}%",
  1058. # "weightDistribution": weight_distribution,
  1059. # "score": score_comfort,
  1060. # "level": grade_comfort,
  1061. # 'discomfortCount': self.discomfort_count,
  1062. # "description1": comf_description1,
  1063. # "description2": comf_description2,
  1064. # "description3": comf_description3,
  1065. # "description4": comf_description4,
  1066. #
  1067. # "comfortLat": lat_dict,
  1068. # "comfortLon": lon_dict,
  1069. #
  1070. # "speData": ego_speed_vs_time,
  1071. # "speMarkLine": discomfort_slices,
  1072. #
  1073. # "accData": lon_acc_vs_time,
  1074. # "accMarkLine": discomfort_acce_slices,
  1075. #
  1076. # "anvData": yawrate_vs_time,
  1077. # "anvMarkLine": discomfort_zigzag_slices,
  1078. #
  1079. # "anaData": yawrate_roc_vs_time,
  1080. # "anaMarkLine": discomfort_zigzag_slices,
  1081. #
  1082. # "curData": [cur_ego_path_vs_time, curvature_vs_time],
  1083. # "curMarkLine": discomfort_shake_slices,
  1084. # }
  1085. self.eval_data = self.ego_df.copy()
  1086. self.eval_data['playerId'] = 1
  1087. return report_dict
  1088. def get_eval_data(self):
  1089. df = self.eval_data[
  1090. ['simTime', 'simFrame', 'playerId', 'ip_acc', 'ip_dec', 'slam_brake', 'slam_accel', 'cadence',
  1091. 'cur_ego_path', 'cur_diff', 'R', 'R_ego', 'R_diff']].copy()
  1092. return df