function.py 23 KB

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