function.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. ego_speed_simtime = ego_df[ego_df['accel'] <= -4]['simTime'].tolist() # 单位m/s^2
  232. warning_simTime = ego_df[ego_df['ifwarning'] == correctwarning]['simTime'].tolist()
  233. if (len(warning_simTime) == 0) and (len(ego_speed_simtime) == 0):
  234. return {"warningDelayTimeofReachDecel_LST": 0}
  235. elif (len(warning_simTime) == 0) and (len(ego_speed_simtime) > 0):
  236. return {"warningDelayTimeofReachDecel_LST": ego_speed_simtime[0]}
  237. elif (len(warning_simTime) > 0) and (len(ego_speed_simtime) == 0):
  238. return {"warningDelayTimeofReachDecel_LST": None}
  239. else:
  240. return {"warningDelayTimeofReachDecel_LST": warning_simTime[0] - ego_speed_simtime[0]}
  241. def rightWarningSignal_LST(data):
  242. scenario_name = find_nested_name(data.function_config["function"])
  243. correctwarning = scenario_sign_dict[scenario_name]
  244. # 将correctwarning保存到data对象中,供图表生成使用
  245. data.correctwarning = correctwarning
  246. ego_df = data.ego_data
  247. if ego_df['ifwarning'].empty:
  248. print("无法获取正确预警信号标志位!")
  249. return
  250. warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]
  251. if warning_rows.empty:
  252. return {"rightWarningSignal_LST": -1}
  253. else:
  254. return {"rightWarningSignal_LST": 1}
  255. def ifCrossingRedLight_LST(data):
  256. scenario_name = find_nested_name(data.function_config["function"])
  257. correctwarning = scenario_sign_dict[scenario_name]
  258. # 将correctwarning保存到data对象中,供图表生成使用
  259. data.correctwarning = correctwarning
  260. ego_df = data.ego_data
  261. redlight_simtime = ego_df[
  262. (ego_df['ifwarning'] == correctwarning) & (ego_df['stateMask'] == 1) & (ego_df['relative_dist'] == 0) & (
  263. ego_df['v'] != 0)]['simTime']
  264. if redlight_simtime.empty:
  265. return {"ifCrossingRedLight_LST": -1}
  266. else:
  267. return {"ifCrossingRedLight_LST": 1}
  268. def ifStopgreenWaveSpeedGuidance_LST(data):
  269. scenario_name = find_nested_name(data.function_config["function"])
  270. correctwarning = scenario_sign_dict[scenario_name]
  271. # 将correctwarning保存到data对象中,供图表生成使用
  272. data.correctwarning = correctwarning
  273. ego_df = data.ego_data
  274. greenlight_simtime = \
  275. ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['stateMask'] == 0) & (ego_df['v'] == 0)]['simTime']
  276. if greenlight_simtime.empty:
  277. return {"ifStopgreenWaveSpeedGuidance_LST": -1}
  278. else:
  279. return {"ifStopgreenWaveSpeedGuidance_LST": 1}
  280. # ------ 单车智能指标 ------
  281. def limitSpeed_LST(data):
  282. ego_df = data.ego_data
  283. speed_limit = ego_df[ego_df['x_relative_dist'] == 0]['v'].tolist()
  284. if len(speed_limit) == 0:
  285. return {"speedLimit_LST": -1}
  286. max_speed = max(speed_limit)
  287. generate_function_chart_data(data, 'limitspeed_LST')
  288. return {"speedLimit_LST": max_speed}
  289. def limitSpeedPastLimitSign_LST(data):
  290. ego_df = data.ego_data
  291. car_length = data.function_config["vehicle"]['CAR_LENGTH']
  292. ego_speed = ego_df[ego_df['x_relative_dist'] == -100 - car_length]['v'].tolist()
  293. if len(ego_speed) == 0:
  294. return {"speedPastLimitSign_LST": -1}
  295. generate_function_chart_data(data, 'limitSpeedPastLimitSign_LST')
  296. return {"speedPastLimitSign_LST": ego_speed[0]}
  297. def leastDistance_LST(data):
  298. ego_df = data.ego_data
  299. dist_row = ego_df[ego_df['v'] == 0]['relative_dist'].tolist()
  300. if len(dist_row) == 0:
  301. return {"minimumDistance_LST": -1}
  302. else:
  303. min_dist = min(dist_row)
  304. return {"minimumDistance_LST": min_dist}
  305. def launchTimeinStopLine_LST(data):
  306. ego_df = data.ego_data
  307. simtime_row = ego_df[ego_df['v'] == 0]['simTime'].tolist()
  308. if len(simtime_row) == 0:
  309. return {"launchTimeinStopLine_LST": -1}
  310. else:
  311. delta_t = simtime_row[-1] - simtime_row[0]
  312. return {"launchTimeinStopLine_LST": delta_t}
  313. def launchTimewhenFollowingCar_LST(data):
  314. ego_df = data.ego_data
  315. t_interval = ego_df['simTime'].tolist()[1] - ego_df['simTime'].tolist()[0]
  316. simtime_row = ego_df[ego_df['v'] == 0]['simTime'].tolist()
  317. if len(simtime_row) == 0:
  318. return {"launchTimewhenFollowingCar_LST": 0}
  319. else:
  320. time_interval = _is_segment_by_interval(simtime_row, t_interval)
  321. delta_t = []
  322. for t in time_interval:
  323. delta_t.append(t[-1] - t[0])
  324. return {"launchTimewhenFollowingCar_LST": max(delta_t)}
  325. def noStop_LST(data):
  326. ego_df = data.ego_data
  327. speed = ego_df['v'].tolist()
  328. if (speed.any() == 0):
  329. return {"noStop_LST": -1}
  330. else:
  331. return {"noStop_LST": 1}
  332. def launchTimeinTrafficLight_LST(data):
  333. '''
  334. 待修改:
  335. 红灯的状态值:1
  336. 绿灯的状态值:0
  337. '''
  338. ego_df = data.ego_data
  339. simtime_of_redlight = ego_df[ego_df['stateMask'] == 0]['simTime']
  340. simtime_of_stop = ego_df[ego_df['v'] == 0]['simTime']
  341. if simtime_of_stop.empty() or simtime_of_redlight.empty():
  342. return {"timeInterval_LST": -1}
  343. simtime_of_launch = simtime_of_redlight[simtime_of_redlight.isin(simtime_of_stop)].tolist()
  344. if len(simtime_of_launch) == 0:
  345. return {"timeInterval_LST": -1}
  346. return {"timeInterval_LST": simtime_of_launch[-1] - simtime_of_launch[0]}
  347. def crossJunctionToTargetLane_LST(data):
  348. ego_df = data.ego_data
  349. lane_in_leftturn = set(ego_df['lane_id'].tolist())
  350. target_lane_id = data.function_config["function"]["scenario"]["crossJunctionToTargetLane_LST"]['max']
  351. if target_lane_id not in lane_in_leftturn:
  352. return {"crossJunctionToTargetLane_LST": -1}
  353. else:
  354. return {"crossJunctionToTargetLane_LST": target_lane_id}
  355. def keepInLane_LST(data):
  356. ego_df = data.ego_data
  357. target_road_type = data.function_config["function"]["scenario"]["keepInLane_LST"]['max']
  358. data_in_tunnel = ego_df[ego_df['road_type'] == target_road_type]
  359. if data_in_tunnel.empty:
  360. return {"keepInLane_LST": -1}
  361. else:
  362. tunnel_lane = data_in_tunnel['lane_id'].tolist()
  363. if len(set(tunnel_lane)) >= 2:
  364. return {"keepInLane_LST": -1}
  365. else:
  366. return {"keepInLane_LST": target_road_type}
  367. def leastLateralDistance_LST(data):
  368. ego_df = data.ego_data
  369. lane_width = ego_df[ego_df['x_relative_dist'] == 0]['lane_width']
  370. if lane_width.empty():
  371. return {"leastLateralDistance_LST": -1}
  372. else:
  373. y_relative_dist = ego_df[ego_df['x_relative_dist'] == 0]['y_relative_dist']
  374. if (y_relative_dist <= lane_width / 2).all():
  375. return {"leastLateralDistance_LST": 1}
  376. else:
  377. return {"leastLateralDistance_LST": -1}
  378. def waitTimeAtCrosswalkwithPedestrian_LST(data):
  379. ego_df = data.ego_data
  380. object_df = data.object_data
  381. data['in_crosswalk'] = []
  382. position_data = data.drop_duplicates(subset=['cross_id', 'cross_coords'], inplace=True)
  383. for cross_id in position_data['cross_id'].tolist():
  384. for posX, posY in object_df['posX', 'posY']:
  385. pedestrian_pos = (posX, posY)
  386. plogan_pos = position_data[position_data['cross_id'] == cross_id]['cross_coords'].tolist()[0]
  387. if _is_pedestrian_in_crosswalk(plogan_pos, pedestrian_pos):
  388. data[data['playerId'] == 2]['in_crosswalk'] = 1
  389. else:
  390. data[data['playerId'] == 2]['in_crosswalk'] = 0
  391. car_stop_time = ego_df[ego_df['v'] == 0]['simTime']
  392. pedestrian_in_crosswalk_time = data[(data['in_crosswalk'] == 1)]['simTime']
  393. car_wait_pedestrian = car_stop_time.isin(pedestrian_in_crosswalk_time).tolist()
  394. return {'waitTimeAtCrosswalkwithPedestrian_LST': car_wait_pedestrian[-1] - car_wait_pedestrian[0] if len(
  395. car_wait_pedestrian) > 0 else 0}
  396. def launchTimewhenPedestrianLeave_LST(data):
  397. ego_df = data.ego_data
  398. car_stop_time = ego_df[ego_df['v'] == 0]["simTime"]
  399. if car_stop_time.empty():
  400. return {"launchTimewhenPedestrianLeave_LST": -1}
  401. else:
  402. lane_width = ego_df[ego_df['v'] == 0]['lane_width'].tolist()[0]
  403. car_to_pedestrain = ego_df[ego_df['y_relative_dist'] <= lane_width / 2]["simTime"]
  404. legal_stop_time = car_stop_time.isin(car_to_pedestrain).tolist()
  405. return {"launchTimewhenPedestrianLeave_LST": legal_stop_time[-1] - legal_stop_time[0]}
  406. def noCollision_LST(data):
  407. ego_df = data.ego_data
  408. if ego_df['relative_dist'].any() == 0:
  409. return {"noCollision_LST": -1}
  410. else:
  411. return {"noCollision_LST": 1}
  412. def noReverse_LST(data):
  413. ego_df = data.ego_data
  414. if ego_df["lon_v_vehicle"] * ego_df["posH"].any() < 0:
  415. return {"noReverse_LST": -1}
  416. else:
  417. return {"noReverse_LST": 1}
  418. def turnAround_LST(data):
  419. ego_df = data.ego_data
  420. if (ego_df["lon_v_vehicle"].tolist()[0] * ego_df["lon_v_vehicle"].tolist()[-1] < 0) and (
  421. ego_df["lon_v_vehicle"] * ego_df["posH"].all() > 0):
  422. return {"turnAround_LST": 1}
  423. else:
  424. return {"turnAround_LST": -1}
  425. def laneOffset_LST(data):
  426. car_width = data.function_config['vehicle']['CAR_WIDTH']
  427. ego_df = data.ego_data
  428. laneoffset = ego_df['y_relative_dist'] - car_width / 2
  429. return {"laneOffset_LST": max(laneoffset)}
  430. def maxLongitudeDist_LST(data):
  431. ego_df = data.ego_data
  432. if len(ego_df['x_relative_dist']) == 0:
  433. return {"maxLongitudeDist_LST": -1}
  434. generate_function_chart_data(data, 'maxLongitudeDist_LST')
  435. return {"maxLongDist_LST": max(ego_df['x_relative_dist'])}
  436. def noEmergencyBraking_LST(data):
  437. ego_df = data.ego_data
  438. ego_df['ip_dec'] = ego_df['v'].apply(
  439. get_interpolation, point1=[18, -5], point2=[72, -3.5])
  440. ego_df['slam_brake'] = (ego_df['accleX'] - ego_df['ip_dec']).apply(
  441. lambda x: 1 if x < 0 else 0)
  442. if sum(ego_df['slam_brake']) == 0:
  443. return {"noEmergencyBraking_LST": 1}
  444. else:
  445. return {"noEmergencyBraking_LST": -1}
  446. def rightWarningSignal_PGVIL(data_processed) -> dict:
  447. """判断是否发出正确预警信号"""
  448. ego_df = data_processed.ego_data
  449. scenario_name = find_nested_name(data_processed.function_config["function"])
  450. correctwarning = scenario_sign_dict[scenario_name]
  451. if correctwarning is None:
  452. print("无法获取正确的预警信号标志位!")
  453. return None
  454. # 找出本行 correctwarning 和 ifwarning 相等,且 correctwarning 不是 NaN 的行
  455. warning_rows = ego_df[
  456. (ego_df["ifwarning"] == correctwarning) & (ego_df["ifwarning"].notna())
  457. ]
  458. if warning_rows.empty:
  459. return {"rightWarningSignal_PGVIL": -1}
  460. else:
  461. return {"rightWarningSignal_PGVIL": 1}
  462. def latestWarningDistance_PGVIL(data_processed) -> dict:
  463. """预警距离计算流水线"""
  464. ego_df = data_processed.ego_data
  465. obj_df = data_processed.object_df
  466. warning_data = get_first_warning(data_processed)
  467. if warning_data is None:
  468. return {"latestWarningDistance_PGVIL": 0.0}
  469. ego, obj = extract_ego_obj(warning_data)
  470. distances = calculate_distance_PGVIL(
  471. np.array([[ego["posX"], ego["posY"]]]), obj[["posX", "posY"]].values
  472. )
  473. if distances.size == 0:
  474. print("没有找到数据!")
  475. return {"latestWarningDistance_PGVIL": 15} # 或返回其他默认值,如0.0
  476. return {"latestWarningDistance_PGVIL": float(np.min(distances))}
  477. def latestWarningDistance_TTC_PGVIL(data_processed) -> dict:
  478. """TTC计算流水线"""
  479. ego_df = data_processed.ego_data
  480. obj_df = data_processed.object_df
  481. warning_data = get_first_warning(data_processed)
  482. if warning_data is None:
  483. return {"latestWarningDistance_TTC_PGVIL": 0.0}
  484. ego, obj = extract_ego_obj(warning_data)
  485. # 向量化计算
  486. ego_pos = np.array([[ego["posX"], ego["posY"]]])
  487. ego_speed = np.array([[ego["speedX"], ego["speedY"]]])
  488. obj_pos = obj[["posX", "posY"]].values
  489. obj_speed = obj[["speedX", "speedY"]].values
  490. distances = calculate_distance_PGVIL(ego_pos, obj_pos)
  491. rel_speeds = calculate_relative_speed_PGVIL(ego_speed, obj_speed)
  492. with np.errstate(divide="ignore", invalid="ignore"):
  493. ttc = np.where(rel_speeds != 0, distances / rel_speeds, np.inf)
  494. if ttc.size == 0:
  495. print("没有找到数据!")
  496. return {"latestWarningDistance_TTC_PGVIL": 2} # 或返回其他默认值,如0.0
  497. return {"latestWarningDistance_TTC_PGVIL": float(np.nanmin(ttc))}
  498. def earliestWarningDistance_PGVIL(data_processed) -> dict:
  499. """预警距离计算流水线"""
  500. ego_df = data_processed.ego_data
  501. obj_df = data_processed.object_df
  502. warning_data = get_first_warning(data_processed)
  503. if warning_data is None:
  504. return {"earliestWarningDistance_PGVIL": 0}
  505. ego, obj = extract_ego_obj(warning_data)
  506. distances = calculate_distance_PGVIL(
  507. np.array([[ego["posX"], ego["posY"]]]), obj[["posX", "posY"]].values
  508. )
  509. if distances.size == 0:
  510. print("没有找到数据!")
  511. return {"earliestWarningDistance_PGVIL": 15} # 或返回其他默认值,如0.0
  512. return {"earliestWarningDistance": float(np.min(distances))}
  513. def earliestWarningDistance_TTC_PGVIL(data_processed) -> dict:
  514. """TTC计算流水线"""
  515. ego_df = data_processed.ego_data
  516. obj_df = data_processed.object_df
  517. warning_data = get_first_warning(data_processed)
  518. if warning_data is None:
  519. return {"earliestWarningDistance_TTC_PGVIL": 0.0}
  520. ego, obj = extract_ego_obj(warning_data)
  521. # 向量化计算
  522. ego_pos = np.array([[ego["posX"], ego["posY"]]])
  523. ego_speed = np.array([[ego["speedX"], ego["speedY"]]])
  524. obj_pos = obj[["posX", "posY"]].values
  525. obj_speed = obj[["speedX", "speedY"]].values
  526. distances = calculate_distance_PGVIL(ego_pos, obj_pos)
  527. rel_speeds = calculate_relative_speed_PGVIL(ego_speed, obj_speed)
  528. with np.errstate(divide="ignore", invalid="ignore"):
  529. ttc = np.where(rel_speeds != 0, distances / rel_speeds, np.inf)
  530. if ttc.size == 0:
  531. print("没有找到数据!")
  532. return {"earliestWarningDistance_TTC_PGVIL": 2} # 或返回其他默认值,如0.0
  533. return {"earliestWarningDistance_TTC_PGVIL": float(np.nanmin(ttc))}
  534. # def delayOfEmergencyBrakeWarning(data_processed) -> dict:
  535. # #预警时机相对背景车辆减速度达到-4m/s2后的时延
  536. # ego_df = data_processed.ego_data
  537. # obj_df = data_processed.object_df
  538. # warning_data = get_first_warning(data_processed)
  539. # if warning_data is None:
  540. # return {"delayOfEmergencyBrakeWarning": -1}
  541. # try:
  542. # ego, obj = extract_ego_obj(warning_data)
  543. # # 向量化计算
  544. # obj_speed = np.array([[obj_df["speedX"], obj_df["speedY"]]])
  545. # # 计算背景车辆减速度
  546. # simtime_gap = obj["simTime"].iloc[1] - obj["simTime"].iloc[0]
  547. # simtime_freq = 1 / simtime_gap#每秒采样频率
  548. # # simtime_freq为一个时间窗,找出时间窗内的最大减速度
  549. # obj_speed_magnitude = np.linalg.norm(obj_speed, axis=1)#速度向量的模长
  550. # obj_speed_change = np.diff(speed_magnitude)#速度模长的变化量
  551. # obj_deceleration = np.diff(obj_speed_magnitude) / simtime_gap
  552. # #找到最大减速度,若最大减速度小于-4m/s2,则计算最大减速度对应的时间,和warning_data的差值进行对比
  553. # max_deceleration = np.max(obj_deceleration)
  554. # if max_deceleration < -4:
  555. # max_deceleration_times = obj["simTime"].iloc[np.argmax(obj_deceleration)]
  556. # max_deceleration_time = max_deceleration_times.iloc[0]
  557. # delay_time = ego["simTime"] - max_deceleration_time
  558. # return {"delayOfEmergencyBrakeWarning": float(delay_time)}
  559. # else:
  560. # print("没有达到预警减速度阈值:-4m/s^2")
  561. # return {"delayOfEmergencyBrakeWarning": -1}
  562. def warningDelayTime_PGVIL(data_processed) -> dict:
  563. """车端接收到预警到HMI发出预警的时延"""
  564. ego_df = data_processed.ego_data
  565. # #打印ego_df的列名
  566. # print(ego_df.columns.tolist())
  567. warning_data = get_first_warning(data_processed)
  568. if warning_data is None:
  569. return {"warningDelayTime_PGVIL": -1}
  570. try:
  571. ego, obj = extract_ego_obj(warning_data)
  572. # 找到event_Type不为空,且playerID为1的行
  573. rosbag_warning_rows = ego_df[(ego_df["event_Type"].notna())]
  574. first_time = rosbag_warning_rows["simTime"].iloc[0]
  575. warning_time = warning_data[warning_data["playerId"] == 1]["simTime"].iloc[0]
  576. delay_time = warning_time - first_time
  577. return {"warningDelayTime_PGVIL": float(delay_time)}
  578. except Exception as e:
  579. print(f"计算预警时延时发生错误: {e}")
  580. return {"warningDelayTime_PGVIL": -1}
  581. def get_car_to_stop_line_distance(ego, car_point, stop_line_points):
  582. """
  583. 计算主车后轴中心点到停止线的距离
  584. :return 距离
  585. """
  586. distance_carpoint_carhead = ego["dimX"] / 2 + ego["offX"]
  587. # 计算停止线的方向向量
  588. line_vector = np.array(
  589. [
  590. stop_line_points[1][0] - stop_line_points[0][0],
  591. stop_line_points[1][1] - stop_line_points[0][1],
  592. ]
  593. )
  594. direction_vector_norm = np.linalg.norm(line_vector)
  595. direction_vector_unit = (
  596. line_vector / direction_vector_norm
  597. if direction_vector_norm != 0
  598. else np.array([0, 0])
  599. )
  600. # 计算主车后轴中心点到停止线投影的坐标(垂足)
  601. projection_length = np.dot(car_point - stop_line_points[0], direction_vector_unit)
  602. perpendicular_foot = stop_line_points[0] + projection_length * direction_vector_unit
  603. # 计算主车后轴中心点到垂足的距离
  604. distance_to_foot = np.linalg.norm(car_point - perpendicular_foot)
  605. carhead_distance_to_foot = distance_to_foot - distance_carpoint_carhead
  606. return carhead_distance_to_foot
  607. def ifCrossingRedLight_PGVIL(data_processed) -> dict:
  608. # 判断车辆是否闯红灯
  609. stop_line_points = np.array([(276.555, -35.575), (279.751, -33.683)])
  610. X_OFFSET = 258109.4239876
  611. Y_OFFSET = 4149969.964821
  612. stop_line_points += np.array([[X_OFFSET, Y_OFFSET]])
  613. ego_df = data_processed.ego_data
  614. prev_distance = float("inf") # 初始化为正无穷大
  615. """
  616. traffic_light_status
  617. 0x100000为绿灯,1048576
  618. 0x1000000为黄灯,16777216
  619. 0x10000000为红灯,268435456
  620. """
  621. red_light_violation = False
  622. for index, ego in ego_df.iterrows():
  623. car_point = (ego["posX"], ego["posY"])
  624. stateMask = ego["stateMask"]
  625. simTime = ego["simTime"]
  626. distance_to_stopline = get_car_to_stop_line_distance(
  627. ego, car_point, stop_line_points
  628. )
  629. # 主车车头跨越停止线时非绿灯,返回-1,闯红灯
  630. if prev_distance > 0 and distance_to_stopline < 0:
  631. if stateMask is not None and stateMask != 1048576:
  632. red_light_violation = True
  633. break
  634. prev_distance = distance_to_stopline
  635. if red_light_violation:
  636. return {"ifCrossingRedLight_PGVIL": -1} # 闯红灯
  637. else:
  638. return {"ifCrossingRedLight_PGVIL": 1} # 没有闯红灯
  639. # def ifStopgreenWaveSpeedGuidance(data_processed) -> dict:
  640. # #在绿波车速引导期间是否发生停车
  641. # def mindisStopline(data_processed) -> dict:
  642. # """
  643. # 当有停车让行标志/标线时车辆最前端与停车让行线的最小距离应在0-4m之间
  644. # """
  645. # ego_df = data_processed.ego_data
  646. # obj_df = data_processed.object_df
  647. # stop_giveway_simtime = ego_df[
  648. # ego_df["sign_type1"] == 32 |
  649. # ego_df["stopline_type"] == 3
  650. # ]["simTime"]
  651. # stop_giveway_data = ego_df[
  652. # ego_df["sign_type1"] == 32 |
  653. # ego_df["stopline_type"] == 3
  654. # ]["simTime"]
  655. # if stop_giveway_simtime.empty:
  656. # print("没有停车让行标志/标线")
  657. # ego_data = stop_giveway_data[stop_giveway_data['playerId'] == 1]
  658. # distance_carpoint_carhead = ego_data['dimX'].iloc[0]/2 + ego_data['offX'].iloc[0]
  659. # distance_to_stoplines = []
  660. # for _,row in ego_data.iterrows():
  661. # ego_pos = np.array([row["posX"], row["posY"], row["posH"]])
  662. # stop_line_points = [
  663. # [row["stopline_x1"], row["stopline_y1"]],
  664. # [row["stopline_x2"], row["stopline_y2"]],
  665. # ]
  666. # distance_to_stopline = get_car_to_stop_line_distance(ego_pos, stop_line_points)
  667. # distance_to_stoplines.append(distance_to_stopline)
  668. # mindisStopline = np.min(distance_to_stoplines) - distance_carpoint_carhead
  669. # return {"mindisStopline": mindisStopline}
  670. class FunctionRegistry:
  671. """动态函数注册器(支持参数验证)"""
  672. def __init__(self, data_processed):
  673. self.logger = LogManager().get_logger() # 获取全局日志实例
  674. self.data = data_processed
  675. self.fun_config = data_processed.function_config["function"]
  676. self.level_3_merics = self._extract_level_3_metrics(self.fun_config)
  677. self._registry: Dict[str, Callable] = {}
  678. self._registry = self._build_registry()
  679. def _extract_level_3_metrics(self, config_node: dict) -> list:
  680. """DFS遍历提取第三层指标(时间复杂度O(n))[4](@ref)"""
  681. metrics = []
  682. def _recurse(node):
  683. if isinstance(node, dict):
  684. if "name" in node and not any(
  685. isinstance(v, dict) for v in node.values()
  686. ):
  687. metrics.append(node["name"])
  688. for v in node.values():
  689. _recurse(v)
  690. _recurse(config_node)
  691. self.logger.info(f"评比的功能指标列表:{metrics}")
  692. return metrics
  693. def _build_registry(self) -> dict:
  694. """自动注册指标函数(防御性编程)"""
  695. registry = {}
  696. for func_name in self.level_3_merics:
  697. try:
  698. registry[func_name] = globals()[func_name]
  699. except KeyError:
  700. print(f"未实现指标函数: {func_name}")
  701. self.logger.error(f"未实现指标函数: {func_name}")
  702. return registry
  703. def batch_execute(self) -> dict:
  704. """批量执行指标计算(带熔断机制)"""
  705. results = {}
  706. for name, func in self._registry.items():
  707. try:
  708. result = func(self.data) # 统一传递数据上下文
  709. results.update(result)
  710. except Exception as e:
  711. print(f"{name} 执行失败: {str(e)}")
  712. self.logger.error(f"{name} 执行失败: {str(e)}", exc_info=True)
  713. results[name] = None
  714. self.logger.info(f"功能指标计算结果:{results}")
  715. return results
  716. class FunctionManager:
  717. """管理功能指标计算的类"""
  718. def __init__(self, data_processed):
  719. self.data = data_processed
  720. self.function = FunctionRegistry(self.data)
  721. def report_statistic(self):
  722. """
  723. 计算并报告功能指标结果。
  724. :return: 评估结果
  725. """
  726. function_result = self.function.batch_execute()
  727. print("\n[功能性表现及评价结果]")
  728. return function_result
  729. # self.logger.info(f'Function Result: {function_result}')
  730. # 使用示例
  731. if __name__ == "__main__":
  732. pass
  733. # print("\n[功能类表现及得分情况]")