function.py 22 KB

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