function.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. from modules.lib.score import Score
  20. from modules.lib.log_manager import LogManager
  21. import numpy as np
  22. from typing import Dict, Tuple, Optional, Callable, Any
  23. import pandas as pd
  24. import yaml
  25. # ----------------------
  26. # 基础工具函数 (Pure functions)
  27. # ----------------------
  28. scenario_sign_dict = {"LeftTurnAssist": 206, "HazardousLocationW": 207, "RedLightViolationW": 208,
  29. "CoorperativeIntersectionPassing": 225, "GreenLightOptimalSpeedAdvisory": 234,
  30. "ForwardCollision": 212}
  31. def calculate_distance_PGVIL(ego_pos: np.ndarray, obj_pos: np.ndarray) -> np.ndarray:
  32. """向量化距离计算"""
  33. return np.linalg.norm(ego_pos - obj_pos, axis=1)
  34. def calculate_relative_speed_PGVIL(
  35. ego_speed: np.ndarray, obj_speed: np.ndarray
  36. ) -> np.ndarray:
  37. """向量化相对速度计算"""
  38. return np.linalg.norm(ego_speed - obj_speed, axis=1)
  39. def calculate_distance(ego_df: pd.DataFrame, correctwarning: int) -> np.ndarray:
  40. """向量化距离计算"""
  41. dist = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['relative_dist']
  42. return dist
  43. def calculate_relative_speed(ego_df: pd.DataFrame, correctwarning: int) -> np.ndarray:
  44. """向量化相对速度计算"""
  45. return ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['composite_v']
  46. def extract_ego_obj(data: pd.DataFrame) -> Tuple[pd.Series, pd.DataFrame]:
  47. """数据提取函数"""
  48. ego = data[data["playerId"] == 1].iloc[0]
  49. obj = data[data["playerId"] != 1]
  50. return ego, obj
  51. def get_first_warning(data_processed) -> Optional[pd.DataFrame]:
  52. """带缓存的预警数据获取"""
  53. ego_df = data_processed.ego_data
  54. obj_df = data_processed.object_df
  55. scenario_name = data_processed.function_config["function"]["scenario"]["name"]
  56. correctwarning = scenario_sign_dict.get(scenario_name)
  57. if correctwarning is None:
  58. print("无法获取正确的预警信号标志位!")
  59. return None
  60. warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]
  61. warning_times = warning_rows['simTime']
  62. if warning_times.empty:
  63. print("没有找到预警数据!")
  64. return None
  65. first_time = warning_times.iloc[0]
  66. return obj_df[obj_df['simTime'] == first_time]
  67. # ----------------------
  68. # 核心计算功能函数
  69. # ----------------------
  70. def latestWarningDistance_LST(data) -> dict:
  71. """预警距离计算流水线"""
  72. scenario_name = data.function_config["function"]["scenario"]["name"]
  73. correctwarning = scenario_sign_dict[scenario_name]
  74. ego_df = data.ego_data
  75. warning_dist = calculate_distance(ego_df, correctwarning)
  76. if warning_dist.empty:
  77. return {"latestWarningDistance_LST": 0.0}
  78. return {"latestWarningDistance_LST": float(warning_dist.iloc[-1])}
  79. def earliestWarningDistance_LST(data) -> dict:
  80. """预警距离计算流水线"""
  81. scenario_name = data.function_config["function"]["scenario"]["name"]
  82. correctwarning = scenario_sign_dict[scenario_name]
  83. ego_df = data.ego_data
  84. warning_dist = calculate_distance(ego_df, correctwarning)
  85. if warning_dist.empty:
  86. return {"earliestWarningDistance_LST": 0.0}
  87. return {"earliestWarningDistance_LST": float(warning_dist.iloc[0]) if len(warning_dist) > 0 else np.inf}
  88. def latestWarningDistance_TTC_LST(data) -> dict:
  89. """TTC计算流水线"""
  90. scenario_name = data.function_config["function"]["scenario"]["name"]
  91. correctwarning = scenario_sign_dict[scenario_name]
  92. ego_df = data.ego_data
  93. warning_dist = calculate_distance(ego_df, correctwarning)
  94. if warning_dist.empty:
  95. return {"latestWarningDistance_TTC_LST": 0.0}
  96. warning_speed = calculate_relative_speed(ego_df, correctwarning)
  97. with np.errstate(divide='ignore', invalid='ignore'):
  98. ttc = np.where(warning_speed != 0, warning_dist / warning_speed, np.inf)
  99. return {"latestWarningDistance_TTC_LST": float(ttc[-1]) if len(ttc) > 0 else np.inf}
  100. def earliestWarningDistance_TTC_LST(data) -> dict:
  101. """TTC计算流水线"""
  102. scenario_name = data.function_config["function"]["scenario"]["name"]
  103. correctwarning = scenario_sign_dict[scenario_name]
  104. ego_df = data.ego_data
  105. warning_dist = calculate_distance(ego_df, correctwarning)
  106. if warning_dist.empty:
  107. return {"earliestWarningDistance_TTC_LST": 0.0}
  108. warning_speed = calculate_relative_speed(ego_df, correctwarning)
  109. with np.errstate(divide='ignore', invalid='ignore'):
  110. ttc = np.where(warning_speed != 0, warning_dist / warning_speed, np.inf)
  111. return {"earliestWarningDistance_TTC_LST": float(ttc[0]) if len(ttc) > 0 else np.inf}
  112. def warningDelayTime_LST(data):
  113. scenario_name = data.function_config["function"]["scenario"]["name"]
  114. correctwarning = scenario_sign_dict[scenario_name]
  115. ego_df = data.ego_data
  116. HMI_warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning)]['simTime'].tolist()
  117. simTime_HMI = HMI_warning_rows[0] if len(HMI_warning_rows) > 0 else None
  118. rosbag_warning_rows = ego_df[(ego_df['event_Type'].notna()) & ((ego_df['event_Type'] != np.nan))][
  119. 'simTime'].tolist()
  120. simTime_rosbag = rosbag_warning_rows[0] if len(rosbag_warning_rows) > 0 else None
  121. if (simTime_HMI is None) or (simTime_rosbag is None):
  122. print("预警出错!")
  123. delay_time = 100.0
  124. else:
  125. delay_time = abs(simTime_HMI - simTime_rosbag)
  126. return {"warningDelayTime_LST": delay_time}
  127. def warningDelayTimeOf4_LST(data):
  128. scenario_name = data.function_config["function"]["scenario"]["name"]
  129. correctwarning = scenario_sign_dict[scenario_name]
  130. ego_df = data.ego_data
  131. ego_speed_simtime = ego_df[ego_df['accel'] <= -4]['simTime'].tolist() # 单位m/s^2
  132. warning_simTime = ego_df[ego_df['ifwarning'] == correctwarning]['simTime'].tolist()
  133. if (len(warning_simTime) == 0) and (len(ego_speed_simtime) == 0):
  134. return {"warningDelayTimeOf4_LST": 0}
  135. elif (len(warning_simTime) == 0) and (len(ego_speed_simtime) > 0):
  136. return {"warningDelayTimeOf4_LST": ego_speed_simtime[0]}
  137. elif (len(warning_simTime) > 0) and (len(ego_speed_simtime) == 0):
  138. return {"warningDelayTimeOf4_LST": None}
  139. else:
  140. return {"warningDelayTimeOf4_LST": warning_simTime[0] - ego_speed_simtime[0]}
  141. def rightWarningSignal_LST(data):
  142. scenario_name = data.function_config["function"]["scenario"]["name"]
  143. correctwarning = scenario_sign_dict[scenario_name]
  144. ego_df = data.ego_data
  145. if ego_df['ifwarning'].empty:
  146. print("无法获取正确预警信号标志位!")
  147. return
  148. warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]
  149. if warning_rows.empty:
  150. return {"rightWarningSignal_LST": -1}
  151. else:
  152. return {"rightWarningSignal_LST": 1}
  153. def noWarning_LST(data):
  154. scenario_name = data.function_config["function"]["scenario"]["name"]
  155. correctwarning = scenario_sign_dict[scenario_name]
  156. ego_df = data.ego_data
  157. if ego_df['ifwarning'].empty:
  158. print("无法获取正确预警信号标志位!")
  159. return
  160. warning_rows = (ego_df['ifwarning'].dropna() == -1).all()
  161. if warning_rows:
  162. return {"noWarning_LST": 1}
  163. else:
  164. return {"noWarning_LST": -1}
  165. def ifCrossingRedLight_LST(data):
  166. scenario_name = data.function_config["function"]["scenario"]["name"]
  167. correctwarning = scenario_sign_dict[scenario_name]
  168. ego_df = data.ego_data
  169. redlight_simtime = ego_df[
  170. (ego_df['ifwarning'] == correctwarning) & (ego_df['stateMask'] == 1) & (ego_df['relative_dist'] == 0) & (
  171. ego_df['v'] != 0)]['simTime']
  172. if redlight_simtime.empty:
  173. return {"ifCrossingRedLight_LST": -1}
  174. else:
  175. return {"ifCrossingRedLight_LST": 1}
  176. def ifStopgreenWaveSpeedGuidance_LST(data):
  177. scenario_name = data.function_config["function"]["scenario"]["name"]
  178. correctwarning = scenario_sign_dict[scenario_name]
  179. ego_df = data.ego_data
  180. greenlight_simtime = \
  181. ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['stateMask'] == 0) & (ego_df['v'] == 0)]['simTime']
  182. if greenlight_simtime.empty:
  183. return {"ifStopgreenWaveSpeedGuidance_LST": -1}
  184. else:
  185. return {"ifStopgreenWaveSpeedGuidance_LST": 1}
  186. def rightWarningSignal_PGVIL(data_processed) -> dict:
  187. """判断是否发出正确预警信号"""
  188. ego_df = data_processed.ego_data
  189. scenario_name = data_processed.function_config["function"]["scenario"]["name"]
  190. correctwarning = scenario_sign_dict[scenario_name]
  191. if correctwarning is None:
  192. print("无法获取正确的预警信号标志位!")
  193. return None
  194. # 找出本行 correctwarning 和 ifwarning 相等,且 correctwarning 不是 NaN 的行
  195. warning_rows = ego_df[
  196. (ego_df["ifwarning"] == correctwarning) & (ego_df["ifwarning"].notna())
  197. ]
  198. if warning_rows.empty:
  199. return {"rightWarningSignal_PGVIL": -1}
  200. else:
  201. return {"rightWarningSignal_PGVIL": 1}
  202. def noWarning_PGVIL(data_processed):
  203. scenario_name = data_processed.function_config["function"]["scenario"]["name"]
  204. correctwarning = scenario_sign_dict[scenario_name]
  205. ego_df = data_processed.ego_data
  206. if ego_df['ifwarning'].empty:
  207. print("无法获取正确预警信号标志位!")
  208. return
  209. warning_rows = (ego_df['ifwarning'].dropna() == -1).all()
  210. if warning_rows:
  211. return {"noWarning_PGVIL": 1}
  212. else:
  213. return {"noWarning_PGVIL": -1}
  214. def latestWarningDistance_PGVIL(data_processed) -> dict:
  215. """预警距离计算流水线"""
  216. ego_df = data_processed.ego_data
  217. obj_df = data_processed.object_df
  218. warning_data = get_first_warning(data_processed)
  219. if warning_data is None:
  220. return {"latestWarningDistance_PGVIL": 0.0}
  221. ego, obj = extract_ego_obj(warning_data)
  222. distances = calculate_distance_PGVIL(
  223. np.array([[ego["posX"], ego["posY"]]]), obj[["posX", "posY"]].values
  224. )
  225. if distances.size == 0:
  226. print("没有找到数据!")
  227. return {"latestWarningDistance_PGVIL": 15} # 或返回其他默认值,如0.0
  228. return {"latestWarningDistance_PGVIL": float(np.min(distances))}
  229. def latestWarningDistance_TTC_PGVIL(data_processed) -> dict:
  230. """TTC计算流水线"""
  231. ego_df = data_processed.ego_data
  232. obj_df = data_processed.object_df
  233. warning_data = get_first_warning(data_processed)
  234. if warning_data is None:
  235. return {"latestWarningDistance_TTC_PGVIL": 0.0}
  236. ego, obj = extract_ego_obj(warning_data)
  237. # 向量化计算
  238. ego_pos = np.array([[ego["posX"], ego["posY"]]])
  239. ego_speed = np.array([[ego["speedX"], ego["speedY"]]])
  240. obj_pos = obj[["posX", "posY"]].values
  241. obj_speed = obj[["speedX", "speedY"]].values
  242. distances = calculate_distance_PGVIL(ego_pos, obj_pos)
  243. rel_speeds = calculate_relative_speed_PGVIL(ego_speed, obj_speed)
  244. with np.errstate(divide="ignore", invalid="ignore"):
  245. ttc = np.where(rel_speeds != 0, distances / rel_speeds, np.inf)
  246. if ttc.size == 0:
  247. print("没有找到数据!")
  248. return {"latestWarningDistance_TTC_PGVIL": 2} # 或返回其他默认值,如0.0
  249. return {"latestWarningDistance_TTC_PGVIL": float(np.nanmin(ttc))}
  250. def earliestWarningDistance_PGVIL(data_processed) -> dict:
  251. """预警距离计算流水线"""
  252. ego_df = data_processed.ego_data
  253. obj_df = data_processed.object_df
  254. warning_data = get_first_warning(data_processed)
  255. if warning_data is None:
  256. return {"earliestWarningDistance_PGVIL": 0}
  257. ego, obj = extract_ego_obj(warning_data)
  258. distances = calculate_distance_PGVIL(
  259. np.array([[ego["posX"], ego["posY"]]]), obj[["posX", "posY"]].values
  260. )
  261. if distances.size == 0:
  262. print("没有找到数据!")
  263. return {"earliestWarningDistance_PGVIL": 15} # 或返回其他默认值,如0.0
  264. return {"earliestWarningDistance": float(np.min(distances))}
  265. def earliestWarningDistance_TTC_PGVIL(data_processed) -> dict:
  266. """TTC计算流水线"""
  267. ego_df = data_processed.ego_data
  268. obj_df = data_processed.object_df
  269. warning_data = get_first_warning(data_processed)
  270. if warning_data is None:
  271. return {"earliestWarningDistance_TTC_PGVIL": 0.0}
  272. ego, obj = extract_ego_obj(warning_data)
  273. # 向量化计算
  274. ego_pos = np.array([[ego["posX"], ego["posY"]]])
  275. ego_speed = np.array([[ego["speedX"], ego["speedY"]]])
  276. obj_pos = obj[["posX", "posY"]].values
  277. obj_speed = obj[["speedX", "speedY"]].values
  278. distances = calculate_distance_PGVIL(ego_pos, obj_pos)
  279. rel_speeds = calculate_relative_speed_PGVIL(ego_speed, obj_speed)
  280. with np.errstate(divide="ignore", invalid="ignore"):
  281. ttc = np.where(rel_speeds != 0, distances / rel_speeds, np.inf)
  282. if ttc.size == 0:
  283. print("没有找到数据!")
  284. return {"earliestWarningDistance_TTC_PGVIL": 2} # 或返回其他默认值,如0.0
  285. return {"earliestWarningDistance_TTC_PGVIL": float(np.nanmin(ttc))}
  286. # def delayOfEmergencyBrakeWarning(data_processed) -> dict:
  287. # #预警时机相对背景车辆减速度达到-4m/s2后的时延
  288. # ego_df = data_processed.ego_data
  289. # obj_df = data_processed.object_df
  290. # warning_data = get_first_warning(data_processed)
  291. # if warning_data is None:
  292. # return {"delayOfEmergencyBrakeWarning": -1}
  293. # try:
  294. # ego, obj = extract_ego_obj(warning_data)
  295. # # 向量化计算
  296. # obj_speed = np.array([[obj_df["speedX"], obj_df["speedY"]]])
  297. # # 计算背景车辆减速度
  298. # simtime_gap = obj["simTime"].iloc[1] - obj["simTime"].iloc[0]
  299. # simtime_freq = 1 / simtime_gap#每秒采样频率
  300. # # simtime_freq为一个时间窗,找出时间窗内的最大减速度
  301. # obj_speed_magnitude = np.linalg.norm(obj_speed, axis=1)#速度向量的模长
  302. # obj_speed_change = np.diff(speed_magnitude)#速度模长的变化量
  303. # obj_deceleration = np.diff(obj_speed_magnitude) / simtime_gap
  304. # #找到最大减速度,若最大减速度小于-4m/s2,则计算最大减速度对应的时间,和warning_data的差值进行对比
  305. # max_deceleration = np.max(obj_deceleration)
  306. # if max_deceleration < -4:
  307. # max_deceleration_times = obj["simTime"].iloc[np.argmax(obj_deceleration)]
  308. # max_deceleration_time = max_deceleration_times.iloc[0]
  309. # delay_time = ego["simTime"] - max_deceleration_time
  310. # return {"delayOfEmergencyBrakeWarning": float(delay_time)}
  311. # else:
  312. # print("没有达到预警减速度阈值:-4m/s^2")
  313. # return {"delayOfEmergencyBrakeWarning": -1}
  314. def warningDelayTime_PGVIL(data_processed) -> dict:
  315. """车端接收到预警到HMI发出预警的时延"""
  316. ego_df = data_processed.ego_data
  317. # #打印ego_df的列名
  318. # print(ego_df.columns.tolist())
  319. warning_data = get_first_warning(data_processed)
  320. if warning_data is None:
  321. return {"warningDelayTime_PGVIL": -1}
  322. try:
  323. ego, obj = extract_ego_obj(warning_data)
  324. # 找到event_Type不为空,且playerID为1的行
  325. rosbag_warning_rows = ego_df[(ego_df["event_Type"].notna())]
  326. first_time = rosbag_warning_rows["simTime"].iloc[0]
  327. warning_time = warning_data[warning_data["playerId"] == 1]["simTime"].iloc[0]
  328. delay_time = warning_time - first_time
  329. return {"warningDelayTime_PGVIL": float(delay_time)}
  330. except Exception as e:
  331. print(f"计算预警时延时发生错误: {e}")
  332. return {"warningDelayTime_PGVIL": -1}
  333. def get_car_to_stop_line_distance(ego, car_point, stop_line_points):
  334. """
  335. 计算主车后轴中心点到停止线的距离
  336. :return 距离
  337. """
  338. distance_carpoint_carhead = ego["dimX"] / 2 + ego["offX"]
  339. # 计算停止线的方向向量
  340. line_vector = np.array(
  341. [
  342. stop_line_points[1][0] - stop_line_points[0][0],
  343. stop_line_points[1][1] - stop_line_points[0][1],
  344. ]
  345. )
  346. direction_vector_norm = np.linalg.norm(line_vector)
  347. direction_vector_unit = (
  348. line_vector / direction_vector_norm
  349. if direction_vector_norm != 0
  350. else np.array([0, 0])
  351. )
  352. # 计算主车后轴中心点到停止线投影的坐标(垂足)
  353. projection_length = np.dot(car_point - stop_line_points[0], direction_vector_unit)
  354. perpendicular_foot = stop_line_points[0] + projection_length * direction_vector_unit
  355. # 计算主车后轴中心点到垂足的距离
  356. distance_to_foot = np.linalg.norm(car_point - perpendicular_foot)
  357. carhead_distance_to_foot = distance_to_foot - distance_carpoint_carhead
  358. return carhead_distance_to_foot
  359. def ifCrossingRedLight_PGVIL(data_processed) -> dict:
  360. # 判断车辆是否闯红灯
  361. stop_line_points = np.array([(276.555, -35.575), (279.751, -33.683)])
  362. X_OFFSET = 258109.4239876
  363. Y_OFFSET = 4149969.964821
  364. stop_line_points += np.array([[X_OFFSET, Y_OFFSET]])
  365. ego_df = data_processed.ego_data
  366. prev_distance = float("inf") # 初始化为正无穷大
  367. """
  368. traffic_light_status
  369. 0x100000为绿灯,1048576
  370. 0x1000000为黄灯,16777216
  371. 0x10000000为红灯,268435456
  372. """
  373. red_light_violation = False
  374. for index, ego in ego_df.iterrows():
  375. car_point = (ego["posX"], ego["posY"])
  376. stateMask = ego["stateMask"]
  377. simTime = ego["simTime"]
  378. distance_to_stopline = get_car_to_stop_line_distance(
  379. ego, car_point, stop_line_points
  380. )
  381. # 主车车头跨越停止线时非绿灯,返回-1,闯红灯
  382. if prev_distance > 0 and distance_to_stopline < 0:
  383. if stateMask is not None and stateMask != 1048576:
  384. red_light_violation = True
  385. break
  386. prev_distance = distance_to_stopline
  387. if red_light_violation:
  388. return {"ifCrossingRedLight_PGVIL": -1} # 闯红灯
  389. else:
  390. return {"ifCrossingRedLight_PGVIL": 1} # 没有闯红灯
  391. # def ifStopgreenWaveSpeedGuidance(data_processed) -> dict:
  392. # #在绿波车速引导期间是否发生停车
  393. # def mindisStopline(data_processed) -> dict:
  394. # """
  395. # 当有停车让行标志/标线时车辆最前端与停车让行线的最小距离应在0-4m之间
  396. # """
  397. # ego_df = data_processed.ego_data
  398. # obj_df = data_processed.object_df
  399. # stop_giveway_simtime = ego_df[
  400. # ego_df["sign_type1"] == 32 |
  401. # ego_df["stopline_type"] == 3
  402. # ]["simTime"]
  403. # stop_giveway_data = ego_df[
  404. # ego_df["sign_type1"] == 32 |
  405. # ego_df["stopline_type"] == 3
  406. # ]["simTime"]
  407. # if stop_giveway_simtime.empty:
  408. # print("没有停车让行标志/标线")
  409. # ego_data = stop_giveway_data[stop_giveway_data['playerId'] == 1]
  410. # distance_carpoint_carhead = ego_data['dimX'].iloc[0]/2 + ego_data['offX'].iloc[0]
  411. # distance_to_stoplines = []
  412. # for _,row in ego_data.iterrows():
  413. # ego_pos = np.array([row["posX"], row["posY"], row["posH"]])
  414. # stop_line_points = [
  415. # [row["stopline_x1"], row["stopline_y1"]],
  416. # [row["stopline_x2"], row["stopline_y2"]],
  417. # ]
  418. # distance_to_stopline = get_car_to_stop_line_distance(ego_pos, stop_line_points)
  419. # distance_to_stoplines.append(distance_to_stopline)
  420. # mindisStopline = np.min(distance_to_stoplines) - distance_carpoint_carhead
  421. # return {"mindisStopline": mindisStopline}
  422. class FunctionRegistry:
  423. """动态函数注册器(支持参数验证)"""
  424. def __init__(self, data_processed):
  425. self.logger = LogManager().get_logger() # 获取全局日志实例
  426. self.data = data_processed
  427. self.fun_config = data_processed.function_config["function"]
  428. self.level_3_merics = self._extract_level_3_metrics(self.fun_config)
  429. self._registry: Dict[str, Callable] = {}
  430. self._registry = self._build_registry()
  431. def _extract_level_3_metrics(self, config_node: dict) -> list:
  432. """DFS遍历提取第三层指标(时间复杂度O(n))[4](@ref)"""
  433. metrics = []
  434. def _recurse(node):
  435. if isinstance(node, dict):
  436. if "name" in node and not any(
  437. isinstance(v, dict) for v in node.values()
  438. ):
  439. metrics.append(node["name"])
  440. for v in node.values():
  441. _recurse(v)
  442. _recurse(config_node)
  443. self.logger.info(f"评比的功能指标列表:{metrics}")
  444. return metrics
  445. def _build_registry(self) -> dict:
  446. """自动注册指标函数(防御性编程)"""
  447. registry = {}
  448. for func_name in self.level_3_merics:
  449. try:
  450. registry[func_name] = globals()[func_name]
  451. except KeyError:
  452. print(f"未实现指标函数: {func_name}")
  453. self.logger.error(f"未实现指标函数: {func_name}")
  454. return registry
  455. def batch_execute(self) -> dict:
  456. """批量执行指标计算(带熔断机制)"""
  457. results = {}
  458. for name, func in self._registry.items():
  459. try:
  460. result = func(self.data) # 统一传递数据上下文
  461. results.update(result)
  462. except Exception as e:
  463. print(f"{name} 执行失败: {str(e)}")
  464. self.logger.error(f"{name} 执行失败: {str(e)}", exc_info=True)
  465. results[name] = None
  466. self.logger.info(f"功能指标计算结果:{results}")
  467. return results
  468. class FunctionManager:
  469. """管理功能指标计算的类"""
  470. def __init__(self, data_processed):
  471. self.data = data_processed
  472. self.function = FunctionRegistry(self.data)
  473. def report_statistic(self):
  474. """
  475. 计算并报告功能指标结果。
  476. :return: 评估结果
  477. """
  478. function_result = self.function.batch_execute()
  479. evaluator = Score(self.data.function_config)
  480. result = evaluator.evaluate(function_result)
  481. print("\n[功能性表现及评价结果]")
  482. return result
  483. # self.logger.info(f'Function Result: {function_result}')
  484. # 使用示例
  485. if __name__ == "__main__":
  486. pass