function.py 35 KB

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