function.py 24 KB

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