function.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ##################################################################
  4. #
  5. # Copyright (c) 2025 CICV, Inc. All Rights Reserved
  6. #
  7. ##################################################################
  8. """
  9. @Authors: zhanghaiwen(zhanghaiwen@china-icv.cn)
  10. @Data: 2025/01/5
  11. @Last Modified: 2025/01/5
  12. @Summary: Function Metrics Calculation
  13. """
  14. import sys
  15. from pathlib import Path
  16. # 添加项目根目录到系统路径
  17. root_path = Path(__file__).resolve().parent.parent
  18. sys.path.append(str(root_path))
  19. print(root_path)
  20. from modules.lib.score import Score
  21. from modules.lib.log_manager import LogManager
  22. import numpy as np
  23. from typing import Dict, Tuple, Optional, Callable, Any
  24. import pandas as pd
  25. import yaml
  26. from modules.lib.chart_generator import generate_function_chart_data
  27. from shapely.geometry import Point, Polygon
  28. from modules.lib.common import get_interpolation
  29. # ----------------------
  30. # 基础工具函数 (Pure functions)
  31. # ----------------------
  32. scenario_sign_dict = {"LeftTurnAssist": 206, "HazardousLocationW": 207, "RedLightViolationW": 208,
  33. "CoorperativeIntersectionPassing": 225, "GreenLightOptimalSpeedAdvisory": 234,
  34. "ForwardCollision": 212}
  35. def _is_pedestrian_in_crosswalk(polygon, test_point) -> bool:
  36. polygon = Polygon(polygon)
  37. point = Point(test_point)
  38. return polygon.contains(point)
  39. def _is_segment_by_interval(time_list, expected_step) -> list:
  40. """
  41. 根据时间戳之间的间隔进行分段。
  42. 参数:
  43. time_list (list): 时间戳列表。
  44. expected_step (float): 预期的固定步长。
  45. 返回:
  46. list: 分段后的时间戳列表,每个元素是一个子列表。
  47. """
  48. if not time_list:
  49. return []
  50. segments = []
  51. current_segment = [time_list[0]]
  52. for i in range(1, len(time_list)):
  53. actual_step = time_list[i] - time_list[i - 1]
  54. if actual_step != expected_step:
  55. # 如果间隔不符合预期,则开始一个新的段
  56. segments.append(current_segment)
  57. current_segment = [time_list[i]]
  58. else:
  59. # 否则,将当前时间戳添加到当前段中
  60. current_segment.append(time_list[i])
  61. # 添加最后一个段
  62. if current_segment:
  63. segments.append(current_segment)
  64. return segments
  65. # 寻找二级指标的名称
  66. def find_nested_name(data):
  67. """
  68. 查找字典中嵌套的name结构。
  69. :param data: 要搜索的字典
  70. :return: 找到的第一个嵌套name结构的值,如果没有找到则返回None
  71. """
  72. if isinstance(data, dict):
  73. for key, value in data.items():
  74. if isinstance(value, dict) and 'name' in value:
  75. return value['name']
  76. # 递归查找嵌套字典
  77. result = find_nested_name(value)
  78. if result is not None:
  79. return result
  80. elif isinstance(data, list):
  81. for item in data:
  82. result = find_nested_name(item)
  83. if result is not None:
  84. return result
  85. return None
  86. def calculate_distance_PGVIL(ego_pos: np.ndarray, obj_pos: np.ndarray) -> np.ndarray:
  87. """向量化距离计算"""
  88. return np.linalg.norm(ego_pos - obj_pos, axis=1)
  89. def calculate_relative_speed_PGVIL(
  90. ego_speed: np.ndarray, obj_speed: np.ndarray
  91. ) -> np.ndarray:
  92. """向量化相对速度计算"""
  93. return np.linalg.norm(ego_speed - obj_speed, axis=1)
  94. def calculate_distance(ego_df: pd.DataFrame, correctwarning: int) -> np.ndarray:
  95. """向量化距离计算"""
  96. dist = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['relative_dist']
  97. return dist
  98. def calculate_relative_speed(ego_df: pd.DataFrame, correctwarning: int) -> np.ndarray:
  99. """向量化相对速度计算"""
  100. return ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['composite_v']
  101. def extract_ego_obj(data: pd.DataFrame) -> Tuple[pd.Series, pd.DataFrame]:
  102. """数据提取函数"""
  103. ego = data[data["playerId"] == 1].iloc[0]
  104. obj = data[data["playerId"] != 1]
  105. return ego, obj
  106. def get_first_warning(data_processed) -> Optional[pd.DataFrame]:
  107. """带缓存的预警数据获取"""
  108. ego_df = data_processed.ego_data
  109. obj_df = data_processed.object_df
  110. scenario_name = find_nested_name(data_processed.function_config["function"])
  111. correctwarning = scenario_sign_dict.get(scenario_name)
  112. if correctwarning is None:
  113. print("无法获取正确的预警信号标志位!")
  114. return None
  115. warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]
  116. warning_times = warning_rows['simTime']
  117. if warning_times.empty:
  118. print("没有找到预警数据!")
  119. return None
  120. first_time = warning_times.iloc[0]
  121. return obj_df[obj_df['simTime'] == first_time]
  122. # ----------------------
  123. # 核心计算功能函数
  124. # ----------------------
  125. def latestWarningDistance_LST(data) -> dict:
  126. """预警距离计算流水线"""
  127. scenario_name = find_nested_name(data.function_config["function"])
  128. value = data.function_config["function"][scenario_name]["latestWarningDistance_LST"]["max"]
  129. correctwarning = scenario_sign_dict[scenario_name]
  130. ego_df = data.ego_data
  131. warning_dist = calculate_distance(ego_df, correctwarning)
  132. warning_speed = calculate_relative_speed(ego_df, correctwarning)
  133. # 将计算结果保存到data对象中,供图表生成使用
  134. data.warning_dist = warning_dist
  135. data.warning_speed = warning_speed
  136. data.correctwarning = correctwarning
  137. if warning_dist.empty:
  138. return {"latestWarningDistance_LST": 0.0}
  139. # 生成图表数据
  140. generate_function_chart_data(data, 'latestWarningDistance_LST')
  141. return {"latestWarningDistance_LST": float(warning_dist.iloc[-1]) if len(warning_dist) > 0 else value}
  142. def earliestWarningDistance_LST(data) -> dict:
  143. """预警距离计算流水线"""
  144. scenario_name = find_nested_name(data.function_config["function"])
  145. value = data.function_config["function"][scenario_name]["earliestWarningDistance_LST"]["max"]
  146. correctwarning = scenario_sign_dict[scenario_name]
  147. ego_df = data.ego_data
  148. warning_dist = calculate_distance(ego_df, correctwarning)
  149. warning_speed = calculate_relative_speed(ego_df, correctwarning)
  150. # 将计算结果保存到data对象中,供图表生成使用
  151. data.warning_dist = warning_dist
  152. data.warning_speed = warning_speed
  153. data.correctwarning = correctwarning
  154. if warning_dist.empty:
  155. return {"earliestWarningDistance_LST": 0.0}
  156. # 生成图表数据
  157. generate_function_chart_data(data, 'earliestWarningDistance_LST')
  158. return {"earliestWarningDistance_LST": float(warning_dist.iloc[0]) if len(warning_dist) > 0 else value}
  159. def latestWarningDistance_TTC_LST(data) -> dict:
  160. """TTC计算流水线"""
  161. scenario_name = find_nested_name(data.function_config["function"])
  162. value = data.function_config["function"][scenario_name]["latestWarningDistance_TTC_LST"]["max"]
  163. correctwarning = scenario_sign_dict[scenario_name]
  164. ego_df = data.ego_data
  165. warning_dist = calculate_distance(ego_df, correctwarning)
  166. if warning_dist.empty:
  167. return {"latestWarningDistance_TTC_LST": 0.0}
  168. # 将correctwarning保存到data对象中,供图表生成使用
  169. data.correctwarning = correctwarning
  170. warning_speed = calculate_relative_speed(ego_df, correctwarning)
  171. with np.errstate(divide='ignore', invalid='ignore'):
  172. ttc = np.where(warning_speed != 0, warning_dist / warning_speed, np.inf)
  173. # 处理无效的TTC值
  174. for i in range(len(ttc)):
  175. ttc[i] = float(value) if (not ttc[i] or ttc[i] < 0) else ttc[i]
  176. data.warning_dist = warning_dist
  177. data.warning_speed = warning_speed
  178. data.ttc = ttc
  179. # 生成图表数据
  180. # from modules.lib.chart_generator import generate_function_chart_data
  181. generate_function_chart_data(data, 'latestWarningDistance_TTC_LST')
  182. return {"latestWarningDistance_TTC_LST": float(ttc[-1]) if len(ttc) > 0 else value}
  183. def earliestWarningDistance_TTC_LST(data) -> dict:
  184. """TTC计算流水线"""
  185. scenario_name = find_nested_name(data.function_config["function"])
  186. value = data.function_config["function"][scenario_name]["earliestWarningDistance_TTC_LST"]["max"]
  187. correctwarning = scenario_sign_dict[scenario_name]
  188. ego_df = data.ego_data
  189. warning_dist = calculate_distance(ego_df, correctwarning)
  190. if warning_dist.empty:
  191. return {"earliestWarningDistance_TTC_LST": 0.0}
  192. # 将correctwarning保存到data对象中,供图表生成使用
  193. data.correctwarning = correctwarning
  194. warning_speed = calculate_relative_speed(ego_df, correctwarning)
  195. with np.errstate(divide='ignore', invalid='ignore'):
  196. ttc = np.where(warning_speed != 0, warning_dist / warning_speed, np.inf)
  197. # 处理无效的TTC值
  198. for i in range(len(ttc)):
  199. ttc[i] = float(value) if (not ttc[i] or ttc[i] < 0) else ttc[i]
  200. # 将计算结果保存到data对象中,供图表生成使用
  201. data.warning_dist = warning_dist
  202. data.warning_speed = warning_speed
  203. data.ttc = ttc
  204. data.correctwarning = correctwarning
  205. # 生成图表数据
  206. generate_function_chart_data(data, 'earliestWarningDistance_TTC_LST')
  207. return {"earliestWarningDistance_TTC_LST": float(ttc[0]) if len(ttc) > 0 else value}
  208. def warningDelayTime_LST(data):
  209. scenario_name = find_nested_name(data.function_config["function"])
  210. correctwarning = scenario_sign_dict[scenario_name]
  211. # 将correctwarning保存到data对象中,供图表生成使用
  212. data.correctwarning = correctwarning
  213. ego_df = data.ego_data
  214. HMI_warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning)]['simTime'].tolist()
  215. simTime_HMI = HMI_warning_rows[0] if len(HMI_warning_rows) > 0 else None
  216. rosbag_warning_rows = ego_df[(ego_df['event_Type'].notna()) & ((ego_df['event_Type'] != np.nan))][
  217. 'simTime'].tolist()
  218. simTime_rosbag = rosbag_warning_rows[0] if len(rosbag_warning_rows) > 0 else None
  219. if (simTime_HMI is None) or (simTime_rosbag is None):
  220. print("预警出错!")
  221. delay_time = 100.0
  222. else:
  223. delay_time = abs(simTime_HMI - simTime_rosbag)
  224. return {"warningDelayTime_LST": delay_time}
  225. def warningDelayTimeofReachDecel_LST(data):
  226. scenario_name = find_nested_name(data.function_config["function"])
  227. correctwarning = scenario_sign_dict[scenario_name]
  228. # 将correctwarning保存到data对象中,供图表生成使用
  229. data.correctwarning = correctwarning
  230. ego_df = data.ego_data
  231. obj_df = data.obj_data
  232. obj_speed_simtime = obj_df[obj_df['accel'] <= -4]['simTime'].tolist() # 单位m/s^2
  233. warning_simTime = ego_df[ego_df['ifwarning'] == correctwarning]['simTime'].tolist()
  234. if (len(warning_simTime) == 0) and (len(obj_speed_simtime) == 0):
  235. return {"warningDelayTimeofReachDecel_LST": 0}
  236. elif (len(warning_simTime) == 0) and (len(obj_speed_simtime) > 0):
  237. return {"warningDelayTimeofReachDecel_LST": obj_speed_simtime[0]}
  238. elif (len(warning_simTime) > 0) and (len(obj_speed_simtime) == 0):
  239. return {"warningDelayTimeofReachDecel_LST": None}
  240. else:
  241. return {"warningDelayTimeofReachDecel_LST": warning_simTime[0] - obj_speed_simtime[0]}
  242. def rightWarningSignal_LST(data):
  243. scenario_name = find_nested_name(data.function_config["function"])
  244. correctwarning = scenario_sign_dict[scenario_name]
  245. # 将correctwarning保存到data对象中,供图表生成使用
  246. data.correctwarning = correctwarning
  247. ego_df = data.ego_data
  248. if ego_df['ifwarning'].empty:
  249. print("无法获取正确预警信号标志位!")
  250. return
  251. warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]
  252. if warning_rows.empty:
  253. return {"rightWarningSignal_LST": -1}
  254. else:
  255. return {"rightWarningSignal_LST": 1}
  256. def ifCrossingRedLight_LST(data):
  257. scenario_name = find_nested_name(data.function_config["function"])
  258. correctwarning = scenario_sign_dict[scenario_name]
  259. # 将correctwarning保存到data对象中,供图表生成使用
  260. data.correctwarning = correctwarning
  261. ego_df = data.ego_data
  262. redlight_simtime = ego_df[
  263. (ego_df['ifwarning'] == correctwarning) & (ego_df['stateMask'] == 1) & (ego_df['relative_dist'] == 0) & (
  264. ego_df['v'] != 0)]['simTime']
  265. if redlight_simtime.empty:
  266. return {"ifCrossingRedLight_LST": -1}
  267. else:
  268. return {"ifCrossingRedLight_LST": 1}
  269. def ifStopgreenWaveSpeedGuidance_LST(data):
  270. scenario_name = find_nested_name(data.function_config["function"])
  271. correctwarning = scenario_sign_dict[scenario_name]
  272. # 将correctwarning保存到data对象中,供图表生成使用
  273. data.correctwarning = correctwarning
  274. ego_df = data.ego_data
  275. greenlight_simtime = \
  276. ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['stateMask'] == 0) & (ego_df['v'] == 0)]['simTime']
  277. if greenlight_simtime.empty:
  278. return {"ifStopgreenWaveSpeedGuidance_LST": -1}
  279. else:
  280. return {"ifStopgreenWaveSpeedGuidance_LST": 1}
  281. # ------ 单车智能指标 ------
  282. def limitSpeed_LST(data):
  283. ego_df = data.ego_data
  284. speed_limit = ego_df[ego_df['x_relative_dist'] == 0]['v'].tolist()
  285. if len(speed_limit) == 0:
  286. return {"speedLimit_LST": -1}
  287. max_speed = max(speed_limit)
  288. generate_function_chart_data(data, 'limitspeed_LST')
  289. return {"speedLimit_LST": max_speed}
  290. def limitSpeedPastLimitSign_LST(data):
  291. ego_df = data.ego_data
  292. car_length = data.function_config["vehicle"]['CAR_LENGTH']
  293. ego_speed = ego_df[ego_df['x_relative_dist'] == -100 - car_length]['v'].tolist()
  294. if len(ego_speed) == 0:
  295. return {"speedPastLimitSign_LST": -1}
  296. generate_function_chart_data(data, 'limitSpeedPastLimitSign_LST')
  297. return {"speedPastLimitSign_LST": ego_speed[0]}
  298. def leastDistance_LST(data):
  299. ego_df = data.ego_data
  300. dist_row = ego_df[ego_df['v'] == 0]['relative_dist'].tolist()
  301. if len(dist_row) == 0:
  302. return {"leastDistance_LST": -1}
  303. else:
  304. min_dist = min(dist_row)
  305. return {"leastDistance_LST": min_dist}
  306. def launchTimeinStopLine_LST(data):
  307. ego_df = data.ego_data
  308. simtime_row = ego_df[ego_df['v'] == 0]['simTime'].tolist()
  309. if len(simtime_row) == 0:
  310. return {"launchTimeinStopLine_LST": -1}
  311. else:
  312. delta_t = simtime_row[-1] - simtime_row[0]
  313. return {"launchTimeinStopLine_LST": delta_t}
  314. def launchTimewhenFollowingCar_LST(data):
  315. ego_df = data.ego_data
  316. t_interval = ego_df['simTime'].tolist()[1] - ego_df['simTime'].tolist()[0]
  317. simtime_row = ego_df[ego_df['v'] == 0]['simTime'].tolist()
  318. if len(simtime_row) == 0:
  319. return {"launchTimewhenFollowingCar_LST": 0}
  320. else:
  321. time_interval = _is_segment_by_interval(simtime_row, t_interval)
  322. delta_t = []
  323. for t in time_interval:
  324. delta_t.append(t[-1] - t[0])
  325. return {"launchTimewhenFollowingCar_LST": max(delta_t)}
  326. def noStop_LST(data):
  327. ego_df_ini = data.ego_data
  328. min_time = ego_df_ini['simTime'].min() + 5
  329. max_time = ego_df_ini['simTime'].max() - 5
  330. ego_df = ego_df_ini[(ego_df_ini['simTime'] >= min_time) & (ego_df_ini['simTime'] <= max_time)]
  331. speed = ego_df['v'].tolist()
  332. if (any(speed) == 0):
  333. return {"noStop_LST": -1}
  334. else:
  335. return {"noStop_LST": 1}
  336. def launchTimeinTrafficLight_LST(data):
  337. '''
  338. 待修改:
  339. 红灯的状态值:1
  340. 绿灯的状态值:0
  341. '''
  342. ego_df = data.ego_data
  343. simtime_of_redlight = ego_df[ego_df['stateMask'] == 0]['simTime']
  344. simtime_of_stop = ego_df[ego_df['v'] == 0]['simTime']
  345. if len(simtime_of_stop) or len(simtime_of_redlight):
  346. return {"timeInterval_LST": -1}
  347. simtime_of_launch = simtime_of_redlight[simtime_of_redlight.isin(simtime_of_stop)].tolist()
  348. if len(simtime_of_launch) == 0:
  349. return {"timeInterval_LST": -1}
  350. return {"timeInterval_LST": simtime_of_launch[-1] - simtime_of_launch[0]}
  351. def crossJunctionToTargetLane_LST(data):
  352. ego_df = data.ego_data
  353. lane_in_leftturn = set(ego_df['lane_id'].tolist())
  354. scenario_name = find_nested_name(data.function_config["function"])
  355. target_lane_id = data.function_config["function"][scenario_name]["crossJunctionToTargetLane_LST"]['max']
  356. if target_lane_id not in lane_in_leftturn:
  357. return {"crossJunctionToTargetLane_LST": -1}
  358. else:
  359. return {"crossJunctionToTargetLane_LST": target_lane_id}
  360. def keepInLane_LST(data):
  361. ego_df = data.ego_data
  362. notkeepinlane = ego_df[ego_df['laneOffset'] > ego_df['lane_width']/2].tolist()
  363. if len(notkeepinlane):
  364. return {"keepInLane_LST": -1}
  365. return {"keepInLane_LST": 1}
  366. def leastLateralDistance_LST(data):
  367. ego_df = data.ego_data
  368. lane_width = ego_df[ego_df['x_relative_dist'] == 0]['lane_width']
  369. if lane_width.empty():
  370. return {"leastLateralDistance_LST": -1}
  371. else:
  372. y_relative_dist = ego_df[ego_df['x_relative_dist'] == 0]['y_relative_dist']
  373. if (y_relative_dist <= lane_width / 2).all():
  374. return {"leastLateralDistance_LST": 1}
  375. else:
  376. return {"leastLateralDistance_LST": -1}
  377. def waitTimeAtCrosswalkwithPedestrian_LST(data):
  378. ego_df = data.ego_data
  379. object_df = data.object_data
  380. data['in_crosswalk'] = []
  381. position_data = data.drop_duplicates(subset=['cross_id', 'cross_coords'], inplace=True)
  382. for cross_id in position_data['cross_id'].tolist():
  383. for posX, posY in object_df['posX', 'posY']:
  384. pedestrian_pos = (posX, posY)
  385. plogan_pos = position_data[position_data['cross_id'] == cross_id]['cross_coords'].tolist()[0]
  386. if _is_pedestrian_in_crosswalk(plogan_pos, pedestrian_pos):
  387. data[data['playerId'] == 2]['in_crosswalk'] = 1
  388. else:
  389. data[data['playerId'] == 2]['in_crosswalk'] = 0
  390. car_stop_time = ego_df[ego_df['v'] == 0]['simTime']
  391. pedestrian_in_crosswalk_time = data[(data['in_crosswalk'] == 1)]['simTime']
  392. car_wait_pedestrian = car_stop_time.isin(pedestrian_in_crosswalk_time).tolist()
  393. return {'waitTimeAtCrosswalkwithPedestrian_LST': car_wait_pedestrian[-1] - car_wait_pedestrian[0] if len(
  394. car_wait_pedestrian) > 0 else 0}
  395. def launchTimewhenPedestrianLeave_LST(data):
  396. ego_df = data.ego_data
  397. car_stop_time = ego_df[ego_df['v'] == 0]["simTime"]
  398. if car_stop_time.empty():
  399. return {"launchTimewhenPedestrianLeave_LST": -1}
  400. else:
  401. lane_width = ego_df[ego_df['v'] == 0]['lane_width'].tolist()[0]
  402. car_to_pedestrain = ego_df[ego_df['y_relative_dist'] <= lane_width / 2]["simTime"]
  403. legal_stop_time = car_stop_time.isin(car_to_pedestrain).tolist()
  404. return {"launchTimewhenPedestrianLeave_LST": legal_stop_time[-1] - legal_stop_time[0]}
  405. def noCollision_LST(data):
  406. ego_df = data.ego_data
  407. if ego_df['relative_dist'].any() == 0:
  408. return {"noCollision_LST": -1}
  409. else:
  410. return {"noCollision_LST": 1}
  411. def noReverse_LST(data):
  412. ego_df = data.ego_data
  413. if (ego_df["lon_v_vehicle"] * ego_df["posH"]).any() < 0:
  414. return {"noReverse_LST": -1}
  415. else:
  416. return {"noReverse_LST": 1}
  417. def turnAround_LST(data):
  418. ego_df = data.ego_data
  419. if (ego_df["lon_v_vehicle"].tolist()[0] * ego_df["lon_v_vehicle"].tolist()[-1] < 0) and (
  420. ego_df["lon_v_vehicle"] * ego_df["posH"].all() > 0):
  421. return {"turnAround_LST": 1}
  422. else:
  423. return {"turnAround_LST": -1}
  424. def laneOffset_LST(data):
  425. car_width = data.function_config['vehicle']['CAR_WIDTH']
  426. ego_df_ini = data.ego_data
  427. min_time = ego_df_ini['simTime'].min() + 5
  428. max_time = ego_df_ini['simTime'].max() - 5
  429. ego_df = ego_df_ini[(ego_df_ini['simTime'] >= min_time) & (ego_df_ini['simTime'] <= max_time)]
  430. laneoffset = ego_df['y_relative_dist'] - car_width / 2
  431. return {"laneOffset_LST": max(laneoffset)}
  432. def maxLongitudeDist_LST(data):
  433. ego_df = data.ego_data
  434. if len(ego_df['x_relative_dist']) == 0:
  435. return {"maxLongitudeDist_LST": -1}
  436. generate_function_chart_data(data, 'maxLongitudeDist_LST')
  437. return {"maxLongDist_LST": max(ego_df['x_relative_dist'])}
  438. def noEmergencyBraking_LST(data):
  439. ego_df = data.ego_data
  440. ego_df['ip_dec'] = ego_df['v'].apply(
  441. get_interpolation, point1=[18, -5], point2=[72, -3.5])
  442. ego_df['slam_brake'] = (ego_df['accleX'] - ego_df['ip_dec']).apply(
  443. lambda x: 1 if x < 0 else 0)
  444. if sum(ego_df['slam_brake']) == 0:
  445. return {"noEmergencyBraking_LST": 1}
  446. else:
  447. return {"noEmergencyBraking_LST": -1}
  448. def rightWarningSignal_PGVIL(data_processed) -> dict:
  449. """判断是否发出正确预警信号"""
  450. ego_df = data_processed.ego_data
  451. scenario_name = find_nested_name(data_processed.function_config["function"])
  452. correctwarning = scenario_sign_dict[scenario_name]
  453. if correctwarning is None:
  454. print("无法获取正确的预警信号标志位!")
  455. return None
  456. # 找出本行 correctwarning 和 ifwarning 相等,且 correctwarning 不是 NaN 的行
  457. warning_rows = ego_df[
  458. (ego_df["ifwarning"] == correctwarning) & (ego_df["ifwarning"].notna())
  459. ]
  460. if warning_rows.empty:
  461. return {"rightWarningSignal_PGVIL": -1}
  462. else:
  463. return {"rightWarningSignal_PGVIL": 1}
  464. def latestWarningDistance_PGVIL(data_processed) -> dict:
  465. """预警距离计算流水线"""
  466. ego_df = data_processed.ego_data
  467. obj_df = data_processed.object_df
  468. warning_data = get_first_warning(data_processed)
  469. if warning_data is None:
  470. return {"latestWarningDistance_PGVIL": 0.0}
  471. ego, obj = extract_ego_obj(warning_data)
  472. distances = calculate_distance_PGVIL(
  473. np.array([[ego["posX"], ego["posY"]]]), obj[["posX", "posY"]].values
  474. )
  475. # 将计算结果保存到data对象中,供图表生成使用
  476. data_processed.warning_dist = distances
  477. if distances.size == 0:
  478. print("没有找到数据!")
  479. return {"latestWarningDistance_PGVIL": 15} # 或返回其他默认值,如0.0
  480. return {"latestWarningDistance_PGVIL": float(np.min(distances))}
  481. def latestWarningDistance_TTC_PGVIL(data_processed) -> dict:
  482. """TTC计算流水线"""
  483. ego_df = data_processed.ego_data
  484. obj_df = data_processed.object_df
  485. warning_data = get_first_warning(data_processed)
  486. if warning_data is None:
  487. return {"latestWarningDistance_TTC_PGVIL": 0.0}
  488. ego, obj = extract_ego_obj(warning_data)
  489. # 向量化计算
  490. ego_pos = np.array([[ego["posX"], ego["posY"]]])
  491. ego_speed = np.array([[ego["speedX"], ego["speedY"]]])
  492. obj_pos = obj[["posX", "posY"]].values
  493. obj_speed = obj[["speedX", "speedY"]].values
  494. distances = calculate_distance_PGVIL(ego_pos, obj_pos)
  495. rel_speeds = calculate_relative_speed_PGVIL(ego_speed, obj_speed)
  496. data_processed.warning_dist = distances
  497. data_processed.warning_speed = rel_speeds
  498. with np.errstate(divide="ignore", invalid="ignore"):
  499. ttc = np.where(rel_speeds != 0, distances / rel_speeds, np.inf)
  500. if ttc.size == 0:
  501. print("没有找到数据!")
  502. return {"latestWarningDistance_TTC_PGVIL": 2} # 或返回其他默认值,如0.0
  503. data_processed.ttc = ttc
  504. return {"latestWarningDistance_TTC_PGVIL": float(np.nanmin(ttc))}
  505. def earliestWarningDistance_PGVIL(data_processed) -> dict:
  506. """预警距离计算流水线"""
  507. ego_df = data_processed.ego_data
  508. obj_df = data_processed.object_df
  509. warning_data = get_first_warning(data_processed)
  510. if warning_data is None:
  511. return {"earliestWarningDistance_PGVIL": 0}
  512. ego, obj = extract_ego_obj(warning_data)
  513. distances = calculate_distance_PGVIL(
  514. np.array([[ego["posX"], ego["posY"]]]), obj[["posX", "posY"]].values
  515. )
  516. # 将计算结果保存到data对象中,供图表生成使用
  517. data_processed.warning_dist = distances
  518. if distances.size == 0:
  519. print("没有找到数据!")
  520. return {"earliestWarningDistance_PGVIL": 15} # 或返回其他默认值,如0.0
  521. return {"earliestWarningDistance": float(np.min(distances))}
  522. def earliestWarningDistance_TTC_PGVIL(data_processed) -> dict:
  523. """TTC计算流水线"""
  524. ego_df = data_processed.ego_data
  525. obj_df = data_processed.object_df
  526. warning_data = get_first_warning(data_processed)
  527. if warning_data is None:
  528. return {"earliestWarningDistance_TTC_PGVIL": 0.0}
  529. ego, obj = extract_ego_obj(warning_data)
  530. # 向量化计算
  531. ego_pos = np.array([[ego["posX"], ego["posY"]]])
  532. ego_speed = np.array([[ego["speedX"], ego["speedY"]]])
  533. obj_pos = obj[["posX", "posY"]].values
  534. obj_speed = obj[["speedX", "speedY"]].values
  535. distances = calculate_distance_PGVIL(ego_pos, obj_pos)
  536. rel_speeds = calculate_relative_speed_PGVIL(ego_speed, obj_speed)
  537. data_processed.warning_dist = distances
  538. data_processed.warning_speed = rel_speeds
  539. with np.errstate(divide="ignore", invalid="ignore"):
  540. ttc = np.where(rel_speeds != 0, distances / rel_speeds, np.inf)
  541. if ttc.size == 0:
  542. print("没有找到数据!")
  543. return {"earliestWarningDistance_TTC_PGVIL": 2} # 或返回其他默认值,如0.0
  544. data_processed.ttc = ttc
  545. return {"earliestWarningDistance_TTC_PGVIL": float(np.nanmin(ttc))}
  546. # def delayOfEmergencyBrakeWarning(data_processed) -> dict:
  547. # #预警时机相对背景车辆减速度达到-4m/s2后的时延
  548. # ego_df = data_processed.ego_data
  549. # obj_df = data_processed.object_df
  550. # warning_data = get_first_warning(data_processed)
  551. # if warning_data is None:
  552. # return {"delayOfEmergencyBrakeWarning": -1}
  553. # try:
  554. # ego, obj = extract_ego_obj(warning_data)
  555. # # 向量化计算
  556. # obj_speed = np.array([[obj_df["speedX"], obj_df["speedY"]]])
  557. # # 计算背景车辆减速度
  558. # simtime_gap = obj["simTime"].iloc[1] - obj["simTime"].iloc[0]
  559. # simtime_freq = 1 / simtime_gap#每秒采样频率
  560. # # simtime_freq为一个时间窗,找出时间窗内的最大减速度
  561. # obj_speed_magnitude = np.linalg.norm(obj_speed, axis=1)#速度向量的模长
  562. # obj_speed_change = np.diff(speed_magnitude)#速度模长的变化量
  563. # obj_deceleration = np.diff(obj_speed_magnitude) / simtime_gap
  564. # #找到最大减速度,若最大减速度小于-4m/s2,则计算最大减速度对应的时间,和warning_data的差值进行对比
  565. # max_deceleration = np.max(obj_deceleration)
  566. # if max_deceleration < -4:
  567. # max_deceleration_times = obj["simTime"].iloc[np.argmax(obj_deceleration)]
  568. # max_deceleration_time = max_deceleration_times.iloc[0]
  569. # delay_time = ego["simTime"] - max_deceleration_time
  570. # return {"delayOfEmergencyBrakeWarning": float(delay_time)}
  571. # else:
  572. # print("没有达到预警减速度阈值:-4m/s^2")
  573. # return {"delayOfEmergencyBrakeWarning": -1}
  574. def warningDelayTime_PGVIL(data_processed) -> dict:
  575. """车端接收到预警到HMI发出预警的时延"""
  576. ego_df = data_processed.ego_data
  577. # #打印ego_df的列名
  578. # print(ego_df.columns.tolist())
  579. warning_data = get_first_warning(data_processed)
  580. if warning_data is None:
  581. return {"warningDelayTime_PGVIL": -1}
  582. try:
  583. ego, obj = extract_ego_obj(warning_data)
  584. # 找到event_Type不为空,且playerID为1的行
  585. rosbag_warning_rows = ego_df[(ego_df["event_Type"].notna())]
  586. first_time = rosbag_warning_rows["simTime"].iloc[0]
  587. warning_time = warning_data[warning_data["playerId"] == 1]["simTime"].iloc[0]
  588. delay_time = warning_time - first_time
  589. return {"warningDelayTime_PGVIL": float(delay_time)}
  590. except Exception as e:
  591. print(f"计算预警时延时发生错误: {e}")
  592. return {"warningDelayTime_PGVIL": -1}
  593. def get_car_to_stop_line_distance(ego, car_point, stop_line_points):
  594. """
  595. 计算主车后轴中心点到停止线的距离
  596. :return 距离
  597. """
  598. distance_carpoint_carhead = ego["dimX"] / 2 + ego["offX"]
  599. # 计算停止线的方向向量
  600. line_vector = np.array(
  601. [
  602. stop_line_points[1][0] - stop_line_points[0][0],
  603. stop_line_points[1][1] - stop_line_points[0][1],
  604. ]
  605. )
  606. direction_vector_norm = np.linalg.norm(line_vector)
  607. direction_vector_unit = (
  608. line_vector / direction_vector_norm
  609. if direction_vector_norm != 0
  610. else np.array([0, 0])
  611. )
  612. # 计算主车后轴中心点到停止线投影的坐标(垂足)
  613. projection_length = np.dot(car_point - stop_line_points[0], direction_vector_unit)
  614. perpendicular_foot = stop_line_points[0] + projection_length * direction_vector_unit
  615. # 计算主车后轴中心点到垂足的距离
  616. distance_to_foot = np.linalg.norm(car_point - perpendicular_foot)
  617. carhead_distance_to_foot = distance_to_foot - distance_carpoint_carhead
  618. return carhead_distance_to_foot
  619. def ifCrossingRedLight_PGVIL(data_processed) -> dict:
  620. # 判断车辆是否闯红灯
  621. stop_line_points = np.array([(276.555, -35.575), (279.751, -33.683)])
  622. X_OFFSET = 258109.4239876
  623. Y_OFFSET = 4149969.964821
  624. stop_line_points += np.array([[X_OFFSET, Y_OFFSET]])
  625. ego_df = data_processed.ego_data
  626. prev_distance = float("inf") # 初始化为正无穷大
  627. """
  628. traffic_light_status
  629. 0x100000为绿灯,1048576
  630. 0x1000000为黄灯,16777216
  631. 0x10000000为红灯,268435456
  632. """
  633. red_light_violation = False
  634. for index, ego in ego_df.iterrows():
  635. car_point = (ego["posX"], ego["posY"])
  636. stateMask = ego["stateMask"]
  637. simTime = ego["simTime"]
  638. distance_to_stopline = get_car_to_stop_line_distance(
  639. ego, car_point, stop_line_points
  640. )
  641. # 主车车头跨越停止线时非绿灯,返回-1,闯红灯
  642. if prev_distance > 0 and distance_to_stopline < 0:
  643. if stateMask is not None and stateMask != 1048576:
  644. red_light_violation = True
  645. break
  646. prev_distance = distance_to_stopline
  647. if red_light_violation:
  648. return {"ifCrossingRedLight_PGVIL": -1} # 闯红灯
  649. else:
  650. return {"ifCrossingRedLight_PGVIL": 1} # 没有闯红灯
  651. # def ifStopgreenWaveSpeedGuidance(data_processed) -> dict:
  652. # #在绿波车速引导期间是否发生停车
  653. # def mindisStopline(data_processed) -> dict:
  654. # """
  655. # 当有停车让行标志/标线时车辆最前端与停车让行线的最小距离应在0-4m之间
  656. # """
  657. # ego_df = data_processed.ego_data
  658. # obj_df = data_processed.object_df
  659. # stop_giveway_simtime = ego_df[
  660. # ego_df["sign_type1"] == 32 |
  661. # ego_df["stopline_type"] == 3
  662. # ]["simTime"]
  663. # stop_giveway_data = ego_df[
  664. # ego_df["sign_type1"] == 32 |
  665. # ego_df["stopline_type"] == 3
  666. # ]["simTime"]
  667. # if stop_giveway_simtime.empty:
  668. # print("没有停车让行标志/标线")
  669. # ego_data = stop_giveway_data[stop_giveway_data['playerId'] == 1]
  670. # distance_carpoint_carhead = ego_data['dimX'].iloc[0]/2 + ego_data['offX'].iloc[0]
  671. # distance_to_stoplines = []
  672. # for _,row in ego_data.iterrows():
  673. # ego_pos = np.array([row["posX"], row["posY"], row["posH"]])
  674. # stop_line_points = [
  675. # [row["stopline_x1"], row["stopline_y1"]],
  676. # [row["stopline_x2"], row["stopline_y2"]],
  677. # ]
  678. # distance_to_stopline = get_car_to_stop_line_distance(ego_pos, stop_line_points)
  679. # distance_to_stoplines.append(distance_to_stopline)
  680. # mindisStopline = np.min(distance_to_stoplines) - distance_carpoint_carhead
  681. # return {"mindisStopline": mindisStopline}
  682. class FunctionRegistry:
  683. """动态函数注册器(支持参数验证)"""
  684. def __init__(self, data_processed):
  685. self.logger = LogManager().get_logger() # 获取全局日志实例
  686. self.data = data_processed
  687. self.fun_config = data_processed.function_config["function"]
  688. self.level_3_merics = self._extract_level_3_metrics(self.fun_config)
  689. self._registry: Dict[str, Callable] = {}
  690. self._registry = self._build_registry()
  691. def _extract_level_3_metrics(self, config_node: dict) -> list:
  692. """DFS遍历提取第三层指标(时间复杂度O(n))[4](@ref)"""
  693. metrics = []
  694. def _recurse(node):
  695. if isinstance(node, dict):
  696. if "name" in node and not any(
  697. isinstance(v, dict) for v in node.values()
  698. ):
  699. metrics.append(node["name"])
  700. for v in node.values():
  701. _recurse(v)
  702. _recurse(config_node)
  703. self.logger.info(f"评比的功能指标列表:{metrics}")
  704. return metrics
  705. def _build_registry(self) -> dict:
  706. """自动注册指标函数(防御性编程)"""
  707. registry = {}
  708. for func_name in self.level_3_merics:
  709. try:
  710. registry[func_name] = globals()[func_name]
  711. except KeyError:
  712. print(f"未实现指标函数: {func_name}")
  713. self.logger.error(f"未实现指标函数: {func_name}")
  714. return registry
  715. def batch_execute(self) -> dict:
  716. """批量执行指标计算(带熔断机制)"""
  717. results = {}
  718. for name, func in self._registry.items():
  719. try:
  720. result = func(self.data) # 统一传递数据上下文
  721. results.update(result)
  722. except Exception as e:
  723. print(f"{name} 执行失败: {str(e)}")
  724. self.logger.error(f"{name} 执行失败: {str(e)}", exc_info=True)
  725. results[name] = None
  726. self.logger.info(f"功能指标计算结果:{results}")
  727. return results
  728. class FunctionManager:
  729. """管理功能指标计算的类"""
  730. def __init__(self, data_processed):
  731. self.data = data_processed
  732. self.function = FunctionRegistry(self.data)
  733. def report_statistic(self):
  734. """
  735. 计算并报告功能指标结果。
  736. :return: 评估结果
  737. """
  738. function_result = self.function.batch_execute()
  739. print("\n[功能性表现及评价结果]")
  740. return function_result
  741. # self.logger.info(f'Function Result: {function_result}')
  742. # 使用示例
  743. if __name__ == "__main__":
  744. pass
  745. # print("\n[功能类表现及得分情况]")