function.py 24 KB

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