function.py 23 KB

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