chart_generator.py 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. ##################################################################
  4. #
  5. # Copyright (c) 2023 CICV, Inc. All Rights Reserved
  6. #
  7. ##################################################################
  8. """
  9. @Authors: zhanghaiwen(zhanghaiwen@china-icv.cn)
  10. @Data: 2023/06/25
  11. @Last Modified: 2025/05/20
  12. @Summary: Chart generation utilities for metrics visualization
  13. """
  14. """
  15. 主要功能模块:
  16. 函数指标绘图(generate_function_chart_data)
  17. 舒适性指标绘图(generate_comfort_chart_data)
  18. 安全性指标绘图(generate_safety_chart_data)
  19. 交通指标绘图(generate_traffic_chart_data,待实现)
  20. 新增的急加速指标绘图:
  21. 在generate_comfort_chart_data中增加了slamaccelerate指标的支持
  22. 实现了完整的generate_slam_accelerate_chart函数,用于绘制急加速事件
  23. 该函数包含:
  24. 数据获取与预处理
  25. CSV数据保存与读取
  26. 纵向加速度与速度的双子图绘制
  27. 急加速事件的橙色背景标记
  28. 阈值线绘制
  29. 高质量图表输出(300dpi PNG)
  30. 其他关键特性:
  31. 统一的日志记录系统
  32. 阈值获取函数get_metric_thresholds
  33. 错误处理和异常捕获
  34. 时间戳管理
  35. 数据验证机制
  36. 详细的日志输出
  37. 辅助函数:
  38. calculate_distance 和 calculate_relative_speed(简化实现)
  39. scenario_sign_dict 场景签名字典(简化实现)
  40. 此代码实现了完整的指标可视化工具,特别针对急加速指标slamAccelerate提供了详细的绘图功能,能够清晰展示急加速事件的发生时间和相关数据变化。
  41. """
  42. import matplotlib
  43. matplotlib.use('Agg') # 使用非图形界面的后端
  44. import matplotlib.pyplot as plt
  45. import os
  46. import numpy as np
  47. import pandas as pd
  48. from typing import Optional, Dict, List, Any, Union
  49. from pathlib import Path
  50. from modules.lib.log_manager import LogManager
  51. def generate_function_chart_data(function_calculator, metric_name: str, output_dir: Optional[str] = None) -> Optional[
  52. str]:
  53. """
  54. Generate chart data for function metrics
  55. Args:
  56. function_calculator: FunctionCalculator instance
  57. metric_name: Metric name
  58. output_dir: Output directory
  59. Returns:
  60. str: Chart file path, or None if generation fails
  61. """
  62. logger = LogManager().get_logger()
  63. try:
  64. # 确保输出目录存在
  65. if output_dir:
  66. os.makedirs(output_dir, exist_ok=True)
  67. else:
  68. output_dir = os.path.join(os.getcwd(), 'data')
  69. # 根据指标名称选择不同的图表生成方法
  70. if metric_name.lower() == 'latestwarningdistance_ttc_lst':
  71. return generate_latest_warning_ttc_chart(function_calculator, output_dir)
  72. elif metric_name.lower() == 'earliestwarningdistance_ttc_lst':
  73. return generate_earliest_warning_distance_ttc_chart(function_calculator, output_dir)
  74. elif metric_name.lower() == 'earliestwarningdistance_lst':
  75. return generate_earliest_warning_distance_chart(function_calculator, output_dir)
  76. elif metric_name.lower() == 'latestwarningdistance_lst':
  77. return generate_latest_warning_distance_chart(function_calculator, output_dir)
  78. elif metric_name.lower() == 'limitspeed_lst':
  79. return generate_limit_speed_chart(function_calculator, output_dir)
  80. elif metric_name.lower() == 'limitspeedpastlimitsign_lst':
  81. return generate_limit_speed_past_sign_chart(function_calculator, output_dir)
  82. elif metric_name.lower() == 'maxlongitudedist_lst':
  83. return generate_max_longitude_dist_chart(function_calculator, output_dir)
  84. else:
  85. logger.warning(f"Chart generation not implemented for metric [{metric_name}]")
  86. return None
  87. except Exception as e:
  88. logger.error(f"Failed to generate chart data: {str(e)}", exc_info=True)
  89. return None
  90. def generate_earliest_warning_distance_chart(function_calculator, output_dir: str) -> Optional[str]:
  91. """
  92. Generate warning distance chart with data visualization.
  93. This function creates charts for earliestWarningDistance_LST and latestWarningDistance_LST metrics.
  94. Args:
  95. function_calculator: FunctionCalculator instance
  96. output_dir: Output directory
  97. Returns:
  98. str: Chart file path, or None if generation fails
  99. """
  100. logger = LogManager().get_logger()
  101. try:
  102. # Get data
  103. ego_df = function_calculator.ego_data.copy()
  104. # Check if correctwarning is already calculated
  105. correctwarning = getattr(function_calculator, 'correctwarning', None)
  106. # Get configured thresholds
  107. thresholds = get_metric_thresholds(function_calculator, 'earliestWarningDistance_LST')
  108. max_threshold = thresholds["max"]
  109. min_threshold = thresholds["min"]
  110. # Get calculated warning distance and speed
  111. warning_dist = getattr(function_calculator, 'warning_dist', None)
  112. if warning_dist.empty:
  113. logger.warning(f"Cannot generate {"earliestWarningDistance_LST"} chart: empty data")
  114. return None
  115. # Calculate metric value
  116. metric_value = float(warning_dist.iloc[0]) if len(warning_dist) >= 0.0 else max_threshold
  117. # Save CSV data
  118. csv_filename = os.path.join(output_dir, f"earliestWarningDistance_LST_data.csv")
  119. df_csv = pd.DataFrame({
  120. 'simTime': ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['simTime'],
  121. 'warning_distance': warning_dist,
  122. 'min_threshold': min_threshold,
  123. 'max_threshold': max_threshold,
  124. })
  125. df_csv.to_csv(csv_filename, index=False)
  126. logger.info(f"earliestWarningDistance_LST data saved to: {csv_filename}")
  127. # Read data from CSV
  128. df = pd.read_csv(csv_filename)
  129. # Create single chart for warning distance
  130. plt.figure(figsize=(12, 6), constrained_layout=True) # Adjusted height for single chart
  131. # Plot warning distance
  132. plt.plot(df['simTime'], df['warning_distance'], 'b-', label='Warning Distance')
  133. # Add threshold lines
  134. plt.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  135. plt.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  136. # Mark metric value
  137. if len(df) > 0:
  138. label_text = 'Earliest Warning Distance'
  139. plt.scatter(df['simTime'].iloc[0], df['warning_distance'].iloc[0],
  140. color='red', s=100, zorder=5,
  141. label=f'{label_text}: {metric_value:.2f}m')
  142. # Set y-axis range
  143. plt.ylim(bottom=-1, top=max(max_threshold * 1.1, df['warning_distance'].max() * 1.1))
  144. plt.xlabel('Time (s)')
  145. plt.ylabel('Distance (m)')
  146. plt.title(f'earliestWarningDistance_LST - Warning Distance Over Time')
  147. plt.grid(True)
  148. plt.legend()
  149. # Save image
  150. chart_filename = os.path.join(output_dir, f"earliestWarningDistance_LST_chart.png")
  151. plt.savefig(chart_filename, dpi=300)
  152. plt.close()
  153. logger.info(f"earliestWarningDistance_LST chart saved to: {chart_filename}")
  154. return chart_filename
  155. except Exception as e:
  156. logger.error(f"Failed to generate earliestWarningDistance_LST chart: {str(e)}", exc_info=True)
  157. return None
  158. def generate_earliest_warning_distance_pgvil_chart(function_calculator, output_dir: str) -> Optional[str]:
  159. """
  160. Generate warning distance chart with data visualization.
  161. This function creates charts for earliestWarningDistance_LST and latestWarningDistance_LST metrics.
  162. Args:
  163. function_calculator: FunctionCalculator instance
  164. output_dir: Output directory
  165. Returns:
  166. str: Chart file path, or None if generation fails
  167. """
  168. logger = LogManager().get_logger()
  169. try:
  170. # Get data
  171. ego_df = function_calculator.ego_data.copy()
  172. # Check if correctwarning is already calculated
  173. correctwarning = getattr(function_calculator, 'correctwarning', None)
  174. # Get configured thresholds
  175. thresholds = get_metric_thresholds(function_calculator, 'earliestWarningDistance_PGVIL')
  176. max_threshold = thresholds["max"]
  177. min_threshold = thresholds["min"]
  178. # Get calculated warning distance and speed
  179. warning_dist = getattr(function_calculator, 'warning_dist', None)
  180. if warning_dist.empty:
  181. logger.warning(f"Cannot generate {"earliestWarningDistance_LST"} chart: empty data")
  182. return None
  183. # Calculate metric value
  184. metric_value = float(warning_dist.iloc[0]) if len(warning_dist) >= 0.0 else max_threshold
  185. # Save CSV data
  186. csv_filename = os.path.join(output_dir, f"earliestWarningDistance_PGVIL_data.csv")
  187. df_csv = pd.DataFrame({
  188. 'simTime': ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['simTime'],
  189. 'warning_distance': warning_dist,
  190. 'min_threshold': min_threshold,
  191. 'max_threshold': max_threshold,
  192. })
  193. df_csv.to_csv(csv_filename, index=False)
  194. logger.info(f"earliestWarningDistance_PGVIL data saved to: {csv_filename}")
  195. # Read data from CSV
  196. df = pd.read_csv(csv_filename)
  197. # Create single chart for warning distance
  198. plt.figure(figsize=(12, 6), constrained_layout=True) # Adjusted height for single chart
  199. # Plot warning distance
  200. plt.plot(df['simTime'], df['warning_distance'], 'b-', label='Warning Distance')
  201. # Add threshold lines
  202. plt.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  203. plt.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  204. # Mark metric value
  205. if len(df) > 0:
  206. label_text = 'Earliest Warning Distance'
  207. plt.scatter(df['simTime'].iloc[0], df['warning_distance'].iloc[0],
  208. color='red', s=100, zorder=5,
  209. label=f'{label_text}: {metric_value:.2f}m')
  210. # Set y-axis range
  211. plt.ylim(bottom=-1, top=max(max_threshold * 1.1, df['warning_distance'].max() * 1.1))
  212. plt.xlabel('Time (s)')
  213. plt.ylabel('Distance (m)')
  214. plt.title(f'earliestWarningDistance_PGVIL - Warning Distance Over Time')
  215. plt.grid(True)
  216. plt.legend()
  217. # Save image
  218. chart_filename = os.path.join(output_dir, f"earliestWarningDistance_PGVIL_chart.png")
  219. plt.savefig(chart_filename, dpi=300)
  220. plt.close()
  221. logger.info(f"earliestWarningDistance_PGVIL chart saved to: {chart_filename}")
  222. return chart_filename
  223. except Exception as e:
  224. logger.error(f"Failed to generate earliestWarningDistance_PGVIL chart: {str(e)}", exc_info=True)
  225. return None
  226. # # 使用function.py中已实现的find_nested_name函数
  227. # from modules.metric.function import find_nested_name
  228. def generate_latest_warning_ttc_chart(function_calculator, output_dir: str) -> Optional[str]:
  229. """
  230. Generate TTC warning chart with data visualization.
  231. This version first saves data to CSV, then uses the CSV to generate the chart.
  232. Args:
  233. function_calculator: FunctionCalculator instance
  234. output_dir: Output directory
  235. Returns:
  236. str: Chart file path, or None if generation fails
  237. """
  238. logger = LogManager().get_logger()
  239. try:
  240. # 获取数据
  241. ego_df = function_calculator.ego_data.copy()
  242. correctwarning = getattr(function_calculator, 'correctwarning', None)
  243. # 获取配置的阈值
  244. thresholds = get_metric_thresholds(function_calculator, 'latestWarningDistance_TTC_LST')
  245. max_threshold = thresholds["max"]
  246. min_threshold = thresholds["min"]
  247. warning_dist = getattr(function_calculator, 'warning_dist', None)
  248. warning_speed = getattr(function_calculator, 'warning_speed', None)
  249. ttc = getattr(function_calculator, 'ttc', None)
  250. if warning_dist.empty:
  251. logger.warning("Cannot generate TTC warning chart: empty data")
  252. return None
  253. # 生成时间戳
  254. # 保存 CSV 数据
  255. csv_filename = os.path.join(output_dir, f"latestwarningdistance_ttc_lst_data.csv")
  256. df_csv = pd.DataFrame({
  257. 'simTime': ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['simTime'],
  258. 'warning_distance': warning_dist,
  259. 'warning_speed': warning_speed,
  260. 'ttc': ttc,
  261. 'min_threshold': min_threshold,
  262. 'max_threshold': max_threshold,
  263. })
  264. df_csv.to_csv(csv_filename, index=False)
  265. logger.info(f"latestwarningdistance_ttc_lst data saved to: {csv_filename}")
  266. # 从 CSV 读取数据
  267. df = pd.read_csv(csv_filename)
  268. # 创建图表
  269. plt.figure(figsize=(12, 8), constrained_layout=True)
  270. # 图 1:预警距离
  271. ax1 = plt.subplot(3, 1, 1)
  272. ax1.plot(df['simTime'], df['warning_distance'], 'b-', label='Warning Distance')
  273. ax1.set_xlabel('Time (s)')
  274. ax1.set_ylabel('Distance (m)')
  275. ax1.set_title('Warning Distance Over Time')
  276. ax1.grid(True)
  277. ax1.legend()
  278. # 图 2:相对速度
  279. ax2 = plt.subplot(3, 1, 2)
  280. ax2.plot(df['simTime'], df['warning_speed'], 'g-', label='Relative Speed')
  281. ax2.set_xlabel('Time (s)')
  282. ax2.set_ylabel('Speed (m/s)')
  283. ax2.set_title('Relative Speed Over Time')
  284. ax2.grid(True)
  285. ax2.legend()
  286. # 图 3:TTC
  287. ax3 = plt.subplot(3, 1, 3)
  288. ax3.plot(df['simTime'], df['ttc'], 'r-', label='TTC')
  289. # Add threshold lines
  290. ax3.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}s)')
  291. ax3.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  292. # Calculate metric value (latest TTC)
  293. metric_value = float(ttc[-1]) if len(ttc) > 0 else max_threshold
  294. # Mark latest TTC value
  295. if len(df) > 0:
  296. ax3.scatter(df['simTime'].iloc[-1], df['ttc'].iloc[-1],
  297. color='red', s=100, zorder=5,
  298. label=f'Latest TTC: {metric_value:.2f}s')
  299. ax3.set_xlabel('Time (s)')
  300. ax3.set_ylabel('TTC (s)')
  301. ax3.set_title('Time To Collision (TTC) Over Time')
  302. ax3.grid(True)
  303. ax3.legend()
  304. # 保存图像
  305. chart_filename = os.path.join(output_dir, f"latestwarningdistance_ttc_lst_chart.png")
  306. plt.savefig(chart_filename, dpi=300)
  307. plt.close()
  308. logger.info(f"latestwarningdistance_ttc_lst chart saved to: {chart_filename}")
  309. return chart_filename
  310. except Exception as e:
  311. logger.error(f"Failed to generate latestwarningdistance_ttc_lst chart: {str(e)}", exc_info=True)
  312. return None
  313. def generate_latest_warning_distance_chart(function_calculator, output_dir: str) -> Optional[str]:
  314. """
  315. Generate warning distance chart with data visualization.
  316. This function creates charts for latestWarningDistance_LST metric.
  317. Args:
  318. function_calculator: FunctionCalculator instance
  319. metric_name: Metric name (latestWarningDistance_LST)
  320. output_dir: Output directory
  321. Returns:
  322. str: Chart file path, or None if generation fails
  323. """
  324. logger = LogManager().get_logger()
  325. try:
  326. # Get data
  327. ego_df = function_calculator.ego_data.copy()
  328. # Check if correctwarning is already calculated
  329. correctwarning = getattr(function_calculator, 'correctwarning', None)
  330. # Get configured thresholds
  331. thresholds = get_metric_thresholds(function_calculator, 'latestWarningDistance_LST')
  332. max_threshold = thresholds["max"]
  333. min_threshold = thresholds["min"]
  334. # Get calculated warning distance and speed
  335. warning_dist = getattr(function_calculator, 'warning_dist', None)
  336. if warning_dist.empty:
  337. logger.warning(f"Cannot generate latestWarningDistance_LST chart: empty data")
  338. return None
  339. # Calculate metric value
  340. metric_value = float(warning_dist.iloc[-1]) if len(warning_dist) > 0 else max_threshold
  341. # Save CSV data
  342. csv_filename = os.path.join(output_dir, f"latestWarningDistance_LST_data.csv")
  343. df_csv = pd.DataFrame({
  344. 'simTime': ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['simTime'],
  345. 'warning_distance': warning_dist,
  346. 'min_threshold': min_threshold,
  347. 'max_threshold': max_threshold
  348. })
  349. df_csv.to_csv(csv_filename, index=False)
  350. logger.info(f"latestWarningDistance_LST data saved to: {csv_filename}")
  351. # Read data from CSV
  352. df = pd.read_csv(csv_filename)
  353. # Create single chart for warning distance
  354. plt.figure(figsize=(12, 6), constrained_layout=True) # Adjusted height for single chart
  355. # Plot warning distance
  356. plt.plot(df['simTime'], df['warning_distance'], 'b-', label='Warning Distance')
  357. # Add threshold lines
  358. plt.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  359. plt.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  360. # Mark metric value
  361. if len(df) > 0:
  362. label_text = 'Latest Warning Distance'
  363. plt.scatter(df['simTime'].iloc[-1], df['warning_distance'].iloc[-1],
  364. color='red', s=100, zorder=5,
  365. label=f'{label_text}: {metric_value:.2f}m')
  366. # Set y-axis range
  367. plt.ylim(bottom=-1, top=max(max_threshold * 1.1, df['warning_distance'].max() * 1.1))
  368. plt.xlabel('Time (s)')
  369. plt.ylabel('Distance (m)')
  370. plt.title(f'latestWarningDistance_LST - Warning Distance Over Time')
  371. plt.grid(True)
  372. plt.legend()
  373. # Save image
  374. chart_filename = os.path.join(output_dir, f"latestWarningDistance_LST_chart.png")
  375. plt.savefig(chart_filename, dpi=300)
  376. plt.close()
  377. logger.info(f"latestWarningDistance_LST chart saved to: {chart_filename}")
  378. return chart_filename
  379. except Exception as e:
  380. logger.error(f"Failed to generate latestWarningDistance_LST chart: {str(e)}", exc_info=True)
  381. return None
  382. def generate_earliest_warning_distance_ttc_chart(function_calculator, output_dir: str) -> Optional[str]:
  383. """
  384. Generate TTC warning chart with data visualization for earliestWarningDistance_TTC_LST metric.
  385. Args:
  386. function_calculator: FunctionCalculator instance
  387. output_dir: Output directory
  388. Returns:
  389. str: Chart file path, or None if generation fails
  390. """
  391. logger = LogManager().get_logger()
  392. metric_name = 'earliestWarningDistance_TTC_LST'
  393. try:
  394. # Get data
  395. ego_df = function_calculator.ego_data.copy()
  396. # Check if correctwarning is already calculated
  397. correctwarning = getattr(function_calculator, 'correctwarning', None)
  398. # Get configured thresholds
  399. thresholds = get_metric_thresholds(function_calculator, metric_name)
  400. max_threshold = thresholds["max"]
  401. min_threshold = thresholds["min"]
  402. # Get calculated warning distance and speed
  403. warning_dist = getattr(function_calculator, 'correctwarning', None)
  404. warning_speed = getattr(function_calculator, 'warning_speed', None)
  405. ttc = getattr(function_calculator, 'ttc', None)
  406. # Calculate metric value
  407. metric_value = float(ttc[0]) if len(ttc) > 0 else max_threshold
  408. # Save CSV data
  409. csv_filename = os.path.join(output_dir, f"{metric_name.lower()}_data.csv")
  410. df_csv = pd.DataFrame({
  411. 'simTime': ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['simTime'],
  412. 'warning_distance': warning_dist,
  413. 'warning_speed': warning_speed,
  414. 'ttc': ttc,
  415. 'min_threshold': min_threshold,
  416. 'max_threshold': max_threshold
  417. })
  418. df_csv.to_csv(csv_filename, index=False)
  419. logger.info(f"{metric_name} data saved to: {csv_filename}")
  420. # Read data from CSV
  421. df = pd.read_csv(csv_filename)
  422. # Create chart
  423. plt.figure(figsize=(12, 8), constrained_layout=True)
  424. # 图 1:预警距离
  425. ax1 = plt.subplot(3, 1, 1)
  426. ax1.plot(df['simTime'], df['warning_distance'], 'b-', label='Warning Distance')
  427. ax1.set_xlabel('Time (s)')
  428. ax1.set_ylabel('Distance (m)')
  429. ax1.set_title('Warning Distance Over Time')
  430. ax1.grid(True)
  431. ax1.legend()
  432. # 图 2:相对速度
  433. ax2 = plt.subplot(3, 1, 2)
  434. ax2.plot(df['simTime'], df['warning_speed'], 'g-', label='Relative Speed')
  435. ax2.set_xlabel('Time (s)')
  436. ax2.set_ylabel('Speed (m/s)')
  437. ax2.set_title('Relative Speed Over Time')
  438. ax2.grid(True)
  439. ax2.legend()
  440. # 图 3:TTC
  441. ax3 = plt.subplot(3, 1, 3)
  442. ax3.plot(df['simTime'], df['ttc'], 'r-', label='TTC')
  443. # Add threshold lines
  444. ax3.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}s)')
  445. ax3.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  446. # Mark earliest TTC value
  447. if len(df) > 0:
  448. ax3.scatter(df['simTime'].iloc[0], df['ttc'].iloc[0],
  449. color='red', s=100, zorder=5,
  450. label=f'Earliest TTC: {metric_value:.2f}s')
  451. ax3.set_xlabel('Time (s)')
  452. ax3.set_ylabel('TTC (s)')
  453. ax3.set_title('Time To Collision (TTC) Over Time')
  454. ax3.grid(True)
  455. ax3.legend()
  456. # Save image
  457. chart_filename = os.path.join(output_dir, f"earliestwarningdistance_ttc_lst_chart.png")
  458. plt.savefig(chart_filename, dpi=300)
  459. plt.close()
  460. logger.info(f"{metric_name} chart saved to: {chart_filename}")
  461. return chart_filename
  462. except Exception as e:
  463. logger.error(f"Failed to generate earliestwarningdistance_ttc_lst chart: {str(e)}", exc_info=True)
  464. return None
  465. def generate_limit_speed_chart(function_calculator, output_dir: str) -> Optional[str]:
  466. """
  467. Generate limit speed chart with data visualization for limitSpeed_LST metric.
  468. Args:
  469. function_calculator: FunctionCalculator instance
  470. output_dir: Output directory
  471. Returns:
  472. str: Chart file path, or None if generation fails
  473. """
  474. logger = LogManager().get_logger()
  475. metric_name = 'limitSpeed_LST'
  476. try:
  477. # Get data
  478. ego_df = function_calculator.ego_data.copy()
  479. # Get configured thresholds
  480. thresholds = get_metric_thresholds(function_calculator, metric_name)
  481. max_threshold = thresholds["max"]
  482. min_threshold = thresholds["min"]
  483. if ego_df.empty:
  484. logger.warning(f"Cannot generate {metric_name} chart: empty data")
  485. return None
  486. # Save CSV data
  487. csv_filename = os.path.join(output_dir, f"{metric_name.lower()}_data.csv")
  488. df_csv = pd.DataFrame({
  489. 'simTime': ego_df['simTime'],
  490. 'speed': ego_df['v'],
  491. 'speed_limit': ego_df.get('speed_limit', pd.Series([max_threshold] * len(ego_df)))
  492. })
  493. df_csv.to_csv(csv_filename, index=False)
  494. logger.info(f"{metric_name} data saved to: {csv_filename}")
  495. # Read data from CSV
  496. df = pd.read_csv(csv_filename)
  497. # Create chart
  498. plt.figure(figsize=(12, 6), constrained_layout=True)
  499. # Plot speed
  500. plt.plot(df['simTime'], df['speed'], 'b-', label='Vehicle Speed')
  501. plt.plot(df['simTime'], df['speed_limit'], 'r--', label='Speed Limit')
  502. # Set y-axis range
  503. plt.ylim(bottom=0, top=max(max_threshold * 1.1, df['speed'].max() * 1.1))
  504. plt.xlabel('Time (s)')
  505. plt.ylabel('Speed (m/s)')
  506. plt.title(f'{metric_name} - Vehicle Speed vs Speed Limit')
  507. plt.grid(True)
  508. plt.legend()
  509. # Save image
  510. chart_filename = os.path.join(output_dir, f"{metric_name.lower()}_chart.png")
  511. plt.savefig(chart_filename, dpi=300)
  512. plt.close()
  513. logger.info(f"{metric_name} chart saved to: {chart_filename}")
  514. return chart_filename
  515. except Exception as e:
  516. logger.error(f"Failed to generate {metric_name} chart: {str(e)}", exc_info=True)
  517. return None
  518. def generate_limit_speed_past_sign_chart(function_calculator, output_dir: str) -> Optional[str]:
  519. """
  520. Generate limit speed past sign chart with data visualization for limitSpeedPastLimitSign_LST metric.
  521. Args:
  522. function_calculator: FunctionCalculator instance
  523. output_dir: Output directory
  524. Returns:
  525. str: Chart file path, or None if generation fails
  526. """
  527. logger = LogManager().get_logger()
  528. metric_name = 'limitSpeedPastLimitSign_LST'
  529. try:
  530. # Get data
  531. ego_df = function_calculator.ego_data.copy()
  532. # Get configured thresholds
  533. thresholds = get_metric_thresholds(function_calculator, metric_name)
  534. max_threshold = thresholds["max"]
  535. min_threshold = thresholds["min"]
  536. if ego_df.empty:
  537. logger.warning(f"Cannot generate {metric_name} chart: empty data")
  538. return None
  539. # Get sign passing time if available
  540. sign_time = getattr(function_calculator, 'sign_pass_time', None)
  541. if sign_time is None:
  542. # Try to estimate sign passing time (middle of the simulation)
  543. sign_time = ego_df['simTime'].iloc[len(ego_df) // 2]
  544. # Save CSV data
  545. csv_filename = os.path.join(output_dir, f"{metric_name.lower()}_data.csv")
  546. df_csv = pd.DataFrame({
  547. 'simTime': ego_df['simTime'],
  548. 'speed': ego_df['v'],
  549. 'speed_limit': ego_df.get('speed_limit', pd.Series([max_threshold] * len(ego_df))),
  550. 'sign_pass_time': sign_time
  551. })
  552. df_csv.to_csv(csv_filename, index=False)
  553. logger.info(f"{metric_name} data saved to: {csv_filename}")
  554. # Read data from CSV
  555. df = pd.read_csv(csv_filename)
  556. # Create chart
  557. plt.figure(figsize=(12, 6), constrained_layout=True)
  558. # Plot speed
  559. plt.plot(df['simTime'], df['speed'], 'b-', label='Vehicle Speed')
  560. plt.plot(df['simTime'], df['speed_limit'], 'r--', label='Speed Limit')
  561. # Mark sign passing time
  562. plt.axvline(x=sign_time, color='g', linestyle='--', label='Speed Limit Sign')
  563. # Set y-axis range
  564. plt.ylim(bottom=0, top=max(max_threshold * 1.1, df['speed'].max() * 1.1))
  565. plt.xlabel('Time (s)')
  566. plt.ylabel('Speed (m/s)')
  567. plt.title(f'{metric_name} - Vehicle Speed vs Speed Limit')
  568. plt.grid(True)
  569. plt.legend()
  570. # Save image
  571. chart_filename = os.path.join(output_dir, f"{metric_name.lower()}_chart.png")
  572. plt.savefig(chart_filename, dpi=300)
  573. plt.close()
  574. logger.info(f"{metric_name} chart saved to: {chart_filename}")
  575. return chart_filename
  576. except Exception as e:
  577. logger.error(f"Failed to generate {metric_name} chart: {str(e)}", exc_info=True)
  578. return None
  579. def generate_max_longitude_dist_chart(function_calculator, output_dir: str) -> Optional[str]:
  580. """
  581. Generate maximum longitudinal distance chart with data visualization for maxLongitudeDist_LST metric.
  582. Args:
  583. function_calculator: FunctionCalculator instance
  584. output_dir: Output directory
  585. Returns:
  586. str: Chart file path, or None if generation fails
  587. """
  588. logger = LogManager().get_logger()
  589. metric_name = 'maxLongitudeDist_LST'
  590. try:
  591. # Get data
  592. ego_df = function_calculator.ego_data.copy()
  593. # Get configured thresholds
  594. thresholds = get_metric_thresholds(function_calculator, metric_name)
  595. max_threshold = thresholds["max"]
  596. min_threshold = thresholds["min"]
  597. # Get longitudinal distance data
  598. longitude_dist = ego_df['longitude_dist'] if 'longitude_dist' in ego_df.columns else None
  599. if longitude_dist is None or longitude_dist.empty:
  600. logger.warning(f"Cannot generate {metric_name} chart: missing longitudinal distance data")
  601. return None
  602. # Calculate metric value
  603. metric_value = longitude_dist.max()
  604. max_distance_time = ego_df.loc[longitude_dist.idxmax(), 'simTime']
  605. # Save CSV data
  606. csv_filename = os.path.join(output_dir, f"{metric_name.lower()}_data.csv")
  607. df_csv = pd.DataFrame({
  608. 'simTime': ego_df['simTime'],
  609. 'longitude_dist': longitude_dist,
  610. 'min_threshold': min_threshold,
  611. 'max_threshold': max_threshold
  612. })
  613. df_csv.to_csv(csv_filename, index=False)
  614. logger.info(f"{metric_name} data saved to: {csv_filename}")
  615. # Read data from CSV
  616. df = pd.read_csv(csv_filename)
  617. # Create chart
  618. plt.figure(figsize=(12, 6), constrained_layout=True)
  619. # Plot longitudinal distance
  620. plt.plot(df['simTime'], df['longitude_dist'], 'b-', label='Longitudinal Distance')
  621. # Add threshold lines
  622. plt.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  623. plt.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  624. # Mark maximum longitudinal distance
  625. plt.scatter(max_distance_time, metric_value,
  626. color='red', s=100, zorder=5,
  627. label=f'Maximum Longitudinal Distance: {metric_value:.2f}m')
  628. # Set y-axis range
  629. plt.ylim(bottom=min(0, min_threshold * 0.9), top=max(max_threshold * 1.1, df['longitude_dist'].max() * 1.1))
  630. plt.xlabel('Time (s)')
  631. plt.ylabel('Longitudinal Distance (m)')
  632. plt.title(f'{metric_name} - Longitudinal Distance Over Time')
  633. plt.grid(True)
  634. plt.legend()
  635. # Save image
  636. chart_filename = os.path.join(output_dir, f"{metric_name.lower()}_chart.png")
  637. plt.savefig(chart_filename, dpi=300)
  638. plt.close()
  639. logger.info(f"{metric_name} chart saved to: {chart_filename}")
  640. return chart_filename
  641. except Exception as e:
  642. logger.error(f"Failed to generate {metric_name} chart: {str(e)}", exc_info=True)
  643. return None
  644. def generate_warning_delay_time_chart(function_calculator, output_dir: str) -> Optional[str]:
  645. """
  646. Generate warning delay time chart with data visualization for warningDelayTime_LST metric.
  647. Args:
  648. function_calculator: FunctionCalculator instance
  649. output_dir: Output directory
  650. Returns:
  651. str: Chart file path, or None if generation fails
  652. """
  653. logger = LogManager().get_logger()
  654. metric_name = 'warningDelayTime_LST'
  655. try:
  656. # Get data
  657. ego_df = function_calculator.ego_data.copy()
  658. # Get configured thresholds
  659. thresholds = get_metric_thresholds(function_calculator, metric_name)
  660. max_threshold = thresholds["max"]
  661. min_threshold = thresholds["min"]
  662. # Check if correctwarning is already calculated
  663. correctwarning = getattr(function_calculator, 'correctwarning', None)
  664. if correctwarning is None:
  665. logger.warning(f"Cannot generate {metric_name} chart: missing correctwarning value")
  666. return None
  667. # Get HMI warning time and rosbag warning time
  668. HMI_warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning)]['simTime'].tolist()
  669. simTime_HMI = HMI_warning_rows[0] if len(HMI_warning_rows) > 0 else None
  670. rosbag_warning_rows = ego_df[(ego_df['event_Type'].notna()) & ((ego_df['event_Type'] != np.nan))][
  671. 'simTime'].tolist()
  672. simTime_rosbag = rosbag_warning_rows[0] if len(rosbag_warning_rows) > 0 else None
  673. if (simTime_HMI is None) or (simTime_rosbag is None):
  674. logger.warning(f"Cannot generate {metric_name} chart: missing warning time data")
  675. return None
  676. # Calculate delay time
  677. delay_time = abs(simTime_HMI - simTime_rosbag)
  678. # Save CSV data
  679. csv_filename = os.path.join(output_dir, f"{metric_name.lower()}_data.csv")
  680. df_csv = pd.DataFrame({
  681. 'HMI_warning_time': [simTime_HMI],
  682. 'rosbag_warning_time': [simTime_rosbag],
  683. 'delay_time': [delay_time],
  684. 'min_threshold': [min_threshold],
  685. 'max_threshold': [max_threshold]
  686. })
  687. df_csv.to_csv(csv_filename, index=False)
  688. logger.info(f"{metric_name} data saved to: {csv_filename}")
  689. # Create chart - bar chart for delay time
  690. plt.figure(figsize=(10, 6), constrained_layout=True)
  691. # Plot delay time as bar
  692. plt.bar(['Warning Delay Time'], [delay_time], color='blue', width=0.4)
  693. # Add threshold lines
  694. plt.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}s)')
  695. plt.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  696. # Add value label
  697. plt.text(0, delay_time + 0.05, f'{delay_time:.3f}s', ha='center', va='bottom', fontweight='bold')
  698. # Set y-axis range
  699. plt.ylim(bottom=0, top=max(max_threshold * 1.2, delay_time * 1.2))
  700. plt.ylabel('Delay Time (s)')
  701. plt.title(f'{metric_name} - Warning Delay Time')
  702. plt.grid(True, axis='y')
  703. plt.legend()
  704. # Save image
  705. chart_filename = os.path.join(output_dir, f"{metric_name.lower()}_chart.png")
  706. plt.savefig(chart_filename, dpi=300)
  707. plt.close()
  708. logger.info(f"{metric_name} chart saved to: {chart_filename}")
  709. return chart_filename
  710. except Exception as e:
  711. logger.error(f"Failed to generate {metric_name} chart: {str(e)}", exc_info=True)
  712. return None
  713. def generate_comfort_chart_data(comfort_calculator, metric_name: str, output_dir: Optional[str] = None) -> Optional[
  714. str]:
  715. """
  716. Generate chart data for comfort metrics
  717. Args:
  718. comfort_calculator: ComfortCalculator instance
  719. metric_name: Metric name
  720. output_dir: Output directory
  721. Returns:
  722. str: Chart file path, or None if generation fails
  723. """
  724. logger = LogManager().get_logger()
  725. try:
  726. # 确保输出目录存在
  727. if output_dir:
  728. os.makedirs(output_dir, exist_ok=True)
  729. else:
  730. output_dir = os.getcwd()
  731. # 根据指标名称选择不同的图表生成方法
  732. if metric_name.lower() == 'shake':
  733. return generate_shake_chart(comfort_calculator, output_dir)
  734. elif metric_name.lower() == 'zigzag':
  735. return generate_zigzag_chart(comfort_calculator, output_dir)
  736. elif metric_name.lower() == 'cadence':
  737. return generate_cadence_chart(comfort_calculator, output_dir)
  738. elif metric_name.lower() == 'slambrake':
  739. return generate_slam_brake_chart(comfort_calculator, output_dir)
  740. elif metric_name.lower() == 'slamaccelerate':
  741. return generate_slam_accelerate_chart(comfort_calculator, output_dir)
  742. else:
  743. logger.warning(f"Chart generation not implemented for metric [{metric_name}]")
  744. return None
  745. except Exception as e:
  746. logger.error(f"Failed to generate chart data: {str(e)}", exc_info=True)
  747. return None
  748. def generate_shake_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  749. """
  750. Generate shake metric chart with orange background for shake events.
  751. This version first saves data to CSV, then uses the CSV to generate the chart.
  752. Args:
  753. comfort_calculator: ComfortCalculator instance
  754. output_dir: Output directory
  755. Returns:
  756. str: Chart file path, or None if generation fails
  757. """
  758. logger = LogManager().get_logger()
  759. try:
  760. # 获取数据
  761. df = comfort_calculator.ego_df.copy()
  762. shake_events = comfort_calculator.shake_events
  763. if df.empty:
  764. logger.warning("Cannot generate shake chart: empty data")
  765. return None
  766. # 生成时间戳
  767. # 保存 CSV 数据(第一步)
  768. csv_filename = os.path.join(output_dir, f"shake_data.csv")
  769. df_csv = pd.DataFrame({
  770. 'simTime': df['simTime'],
  771. 'lat_acc': df['lat_acc'],
  772. 'lat_acc_rate': df['lat_acc_rate'],
  773. 'speedH_std': df['speedH_std'],
  774. 'lat_acc_threshold': df.get('lat_acc_threshold', pd.Series([None] * len(df))),
  775. 'lat_acc_rate_threshold': 0.5,
  776. 'speedH_std_threshold': df.get('speedH_threshold', pd.Series([None] * len(df))),
  777. })
  778. df_csv.to_csv(csv_filename, index=False)
  779. logger.info(f"Shake data saved to: {csv_filename}")
  780. # 第二步:从 CSV 读取(可验证保存数据无误)
  781. df = pd.read_csv(csv_filename)
  782. # 创建图表(第三步)
  783. import matplotlib.pyplot as plt
  784. plt.figure(figsize=(12, 8), constrained_layout=True)
  785. # 图 1:横向加速度
  786. ax1 = plt.subplot(3, 1, 1)
  787. ax1.plot(df['simTime'], df['lat_acc'], 'b-', label='Lateral Acceleration')
  788. if 'lat_acc_threshold' in df.columns:
  789. ax1.plot(df['simTime'], df['lat_acc_threshold'], 'r--', label='lat_acc_threshold')
  790. for idx, event in enumerate(shake_events):
  791. label = 'Shake Event' if idx == 0 else None
  792. ax1.axvspan(event['start_time'], event['end_time'], alpha=0.3, color='orange', label=label)
  793. ax1.set_xlabel('Time (s)')
  794. ax1.set_ylabel('Lateral Acceleration (m/s²)')
  795. ax1.set_title('Shake Event Detection - Lateral Acceleration')
  796. ax1.grid(True)
  797. ax1.legend()
  798. # 图 2:lat_acc_rate
  799. ax2 = plt.subplot(3, 1, 2)
  800. ax2.plot(df['simTime'], df['lat_acc_rate'], 'g-', label='lat_acc_rate')
  801. ax2.axhline(
  802. y=0.5, color='orange', linestyle='--', linewidth=1.2, label='lat_acc_rate_threshold'
  803. )
  804. for idx, event in enumerate(shake_events):
  805. label = 'Shake Event' if idx == 0 else None
  806. ax2.axvspan(event['start_time'], event['end_time'], alpha=0.3, color='orange', label=label)
  807. ax2.set_xlabel('Time (s)')
  808. ax2.set_ylabel('Angular Velocity (m/s³)')
  809. ax2.set_title('Shake Event Detection - lat_acc_rate')
  810. ax2.grid(True)
  811. ax2.legend()
  812. # 图 3:speedH_std
  813. ax3 = plt.subplot(3, 1, 3)
  814. ax3.plot(df['simTime'], df['speedH_std'], 'b-', label='speedH_std')
  815. if 'speedH_std_threshold' in df.columns:
  816. ax3.plot(df['simTime'], df['speedH_std_threshold'], 'r--', label='speedH_threshold')
  817. for idx, event in enumerate(shake_events):
  818. label = 'Shake Event' if idx == 0 else None
  819. ax3.axvspan(event['start_time'], event['end_time'], alpha=0.3, color='orange', label=label)
  820. ax3.set_xlabel('Time (s)')
  821. ax3.set_ylabel('Angular Velocity (deg/s)')
  822. ax3.set_title('Shake Event Detection - speedH_std')
  823. ax3.grid(True)
  824. ax3.legend()
  825. # 保存图像
  826. chart_filename = os.path.join(output_dir, f"shake_chart.png")
  827. plt.savefig(chart_filename, dpi=300)
  828. plt.close()
  829. logger.info(f"Shake chart saved to: {chart_filename}")
  830. return chart_filename
  831. except Exception as e:
  832. logger.error(f"Failed to generate shake chart: {str(e)}", exc_info=True)
  833. return None
  834. def generate_zigzag_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  835. """
  836. Generate zigzag metric chart with orange background for zigzag events.
  837. This version first saves data to CSV, then uses the CSV to generate the chart.
  838. Args:
  839. comfort_calculator: ComfortCalculator instance
  840. output_dir: Output directory
  841. Returns:
  842. str: Chart file path, or None if generation fails
  843. """
  844. logger = LogManager().get_logger()
  845. try:
  846. # 获取数据
  847. df = comfort_calculator.ego_df.copy()
  848. zigzag_events = comfort_calculator.discomfort_df[
  849. comfort_calculator.discomfort_df['type'] == 'zigzag'
  850. ].copy()
  851. if df.empty:
  852. logger.warning("Cannot generate zigzag chart: empty data")
  853. return None
  854. # 生成时间戳
  855. # 保存 CSV 数据(第一步)
  856. csv_filename = os.path.join(output_dir, f"zigzag_data.csv")
  857. df_csv = pd.DataFrame({
  858. 'simTime': df['simTime'],
  859. 'speedH': df['speedH'],
  860. 'posH': df['posH'],
  861. 'min_speedH_threshold': -2.3, # 可替换为动态阈值
  862. 'max_speedH_threshold': 2.3
  863. })
  864. df_csv.to_csv(csv_filename, index=False)
  865. logger.info(f"Zigzag data saved to: {csv_filename}")
  866. # 第二步:从 CSV 读取(可验证保存数据无误)
  867. df = pd.read_csv(csv_filename)
  868. # 创建图表(第三步)
  869. import matplotlib.pyplot as plt
  870. plt.figure(figsize=(12, 8), constrained_layout=True)
  871. # ===== 子图1:Yaw Rate =====
  872. ax1 = plt.subplot(2, 1, 1)
  873. ax1.plot(df['simTime'], df['speedH'], 'g-', label='Yaw Rate')
  874. # 添加 speedH 上下限阈值线
  875. ax1.axhline(y=2.3, color='m', linestyle='--', linewidth=1.2, label='Max Threshold (+2.3)')
  876. ax1.axhline(y=-2.3, color='r', linestyle='--', linewidth=1.2, label='Min Threshold (-2.3)')
  877. # 添加橙色背景:Zigzag Events
  878. for idx, event in zigzag_events.iterrows():
  879. label = 'Zigzag Event' if idx == 0 else None
  880. ax1.axvspan(event['start_time'], event['end_time'],
  881. alpha=0.3, color='orange', label=label)
  882. ax1.set_xlabel('Time (s)')
  883. ax1.set_ylabel('Angular Velocity (deg/s)')
  884. ax1.set_title('Zigzag Event Detection - Yaw Rate')
  885. ax1.grid(True)
  886. ax1.legend(loc='upper left')
  887. # ===== 子图2:Yaw Angle =====
  888. ax2 = plt.subplot(2, 1, 2)
  889. ax2.plot(df['simTime'], df['posH'], 'b-', label='Yaw')
  890. # 添加橙色背景:Zigzag Events
  891. for idx, event in zigzag_events.iterrows():
  892. label = 'Zigzag Event' if idx == 0 else None
  893. ax2.axvspan(event['start_time'], event['end_time'],
  894. alpha=0.3, color='orange', label=label)
  895. ax2.set_xlabel('Time (s)')
  896. ax2.set_ylabel('Yaw (deg)')
  897. ax2.set_title('Zigzag Event Detection - Yaw Angle')
  898. ax2.grid(True)
  899. ax2.legend(loc='upper left')
  900. # 保存图像
  901. chart_filename = os.path.join(output_dir, f"zigzag_chart.png")
  902. plt.savefig(chart_filename, dpi=300)
  903. plt.close()
  904. logger.info(f"Zigzag chart saved to: {chart_filename}")
  905. return csv_filename
  906. except Exception as e:
  907. logger.error(f"Failed to generate zigzag chart: {str(e)}", exc_info=True)
  908. return None
  909. def generate_cadence_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  910. """
  911. Generate cadence metric chart with orange background for cadence events.
  912. This version first saves data to CSV, then uses the CSV to generate the chart.
  913. Args:
  914. comfort_calculator: ComfortCalculator instance
  915. output_dir: Output directory
  916. Returns:
  917. str: Chart file path, or None if generation fails
  918. """
  919. logger = LogManager().get_logger()
  920. try:
  921. # 获取数据
  922. df = comfort_calculator.ego_df.copy()
  923. cadence_events = comfort_calculator.discomfort_df[comfort_calculator.discomfort_df['type'] == 'cadence'].copy()
  924. if df.empty:
  925. logger.warning("Cannot generate cadence chart: empty data")
  926. return None
  927. # 生成时间戳
  928. # 保存 CSV 数据(第一步)
  929. csv_filename = os.path.join(output_dir, f"cadence_data.csv")
  930. df_csv = pd.DataFrame({
  931. 'simTime': df['simTime'],
  932. 'lon_acc': df['lon_acc'],
  933. 'v': df['v'],
  934. 'ip_acc': df.get('ip_acc', pd.Series([None] * len(df))),
  935. 'ip_dec': df.get('ip_dec', pd.Series([None] * len(df)))
  936. })
  937. df_csv.to_csv(csv_filename, index=False)
  938. logger.info(f"Cadence data saved to: {csv_filename}")
  939. # 第二步:从 CSV 读取(可验证保存数据无误)
  940. df = pd.read_csv(csv_filename)
  941. # 创建图表(第三步)
  942. import matplotlib.pyplot as plt
  943. plt.figure(figsize=(12, 8), constrained_layout=True)
  944. # 图 1:纵向加速度
  945. ax1 = plt.subplot(2, 1, 1)
  946. ax1.plot(df['simTime'], df['lon_acc'], 'b-', label='Longitudinal Acceleration')
  947. if 'ip_acc' in df.columns and 'ip_dec' in df.columns:
  948. ax1.plot(df['simTime'], df['ip_acc'], 'r--', label='Acceleration Threshold')
  949. ax1.plot(df['simTime'], df['ip_dec'], 'g--', label='Deceleration Threshold')
  950. # 添加橙色背景标识顿挫事件
  951. for idx, event in cadence_events.iterrows():
  952. label = 'Cadence Event' if idx == 0 else None
  953. ax1.axvspan(event['start_time'], event['end_time'],
  954. alpha=0.3, color='orange', label=label)
  955. ax1.set_xlabel('Time (s)')
  956. ax1.set_ylabel('Longitudinal Acceleration (m/s²)')
  957. ax1.set_title('Cadence Event Detection - Longitudinal Acceleration')
  958. ax1.grid(True)
  959. ax1.legend()
  960. # 图 2:速度
  961. ax2 = plt.subplot(2, 1, 2)
  962. ax2.plot(df['simTime'], df['v'], 'g-', label='Velocity')
  963. # 添加橙色背景标识顿挫事件
  964. for idx, event in cadence_events.iterrows():
  965. label = 'Cadence Event' if idx == 0 else None
  966. ax2.axvspan(event['start_time'], event['end_time'],
  967. alpha=0.3, color='orange', label=label)
  968. ax2.set_xlabel('Time (s)')
  969. ax2.set_ylabel('Velocity (m/s)')
  970. ax2.set_title('Cadence Event Detection - Vehicle Speed')
  971. ax2.grid(True)
  972. ax2.legend()
  973. # 保存图像
  974. chart_filename = os.path.join(output_dir, f"cadence_chart.png")
  975. plt.savefig(chart_filename, dpi=300)
  976. plt.close()
  977. logger.info(f"Cadence chart saved to: {chart_filename}")
  978. return chart_filename
  979. except Exception as e:
  980. logger.error(f"Failed to generate cadence chart: {str(e)}", exc_info=True)
  981. return None
  982. def generate_slam_brake_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  983. """
  984. Generate slam brake metric chart with orange background for slam brake events.
  985. This version first saves data to CSV, then uses the CSV to generate the chart.
  986. Args:
  987. comfort_calculator: ComfortCalculator instance
  988. output_dir: Output directory
  989. Returns:
  990. str: Chart file path, or None if generation fails
  991. """
  992. logger = LogManager().get_logger()
  993. try:
  994. # 获取数据
  995. df = comfort_calculator.ego_df.copy()
  996. slam_brake_events = comfort_calculator.discomfort_df[
  997. comfort_calculator.discomfort_df['type'] == 'slam_brake'].copy()
  998. if df.empty:
  999. logger.warning("Cannot generate slam brake chart: empty data")
  1000. return None
  1001. # 生成时间戳
  1002. # 保存 CSV 数据(第一步)
  1003. csv_filename = os.path.join(output_dir, f"slam_brake_data.csv")
  1004. df_csv = pd.DataFrame({
  1005. 'simTime': df['simTime'],
  1006. 'lon_acc': df['lon_acc'],
  1007. 'v': df['v'],
  1008. 'min_threshold': df.get('ip_dec', pd.Series([None] * len(df))),
  1009. 'max_threshold': 0.0
  1010. })
  1011. df_csv.to_csv(csv_filename, index=False)
  1012. logger.info(f"Slam brake data saved to: {csv_filename}")
  1013. # 第二步:从 CSV 读取(可验证保存数据无误)
  1014. df = pd.read_csv(csv_filename)
  1015. # 创建图表(第三步)
  1016. plt.figure(figsize=(12, 8), constrained_layout=True)
  1017. # 图 1:纵向加速度
  1018. ax1 = plt.subplot(2, 1, 1)
  1019. ax1.plot(df['simTime'], df['lon_acc'], 'b-', label='Longitudinal Acceleration')
  1020. if 'min_threshold' in df.columns:
  1021. ax1.plot(df['simTime'], df['min_threshold'], 'r--', label='Deceleration Threshold')
  1022. # 添加橙色背景标识急刹车事件
  1023. for idx, event in slam_brake_events.iterrows():
  1024. label = 'Slam Brake Event' if idx == 0 else None
  1025. ax1.axvspan(event['start_time'], event['end_time'],
  1026. alpha=0.3, color='orange', label=label)
  1027. ax1.set_xlabel('Time (s)')
  1028. ax1.set_ylabel('Longitudinal Acceleration (m/s²)')
  1029. ax1.set_title('Slam Brake Event Detection - Longitudinal Acceleration')
  1030. ax1.grid(True)
  1031. ax1.legend()
  1032. # 图 2:速度
  1033. ax2 = plt.subplot(2, 1, 2)
  1034. ax2.plot(df['simTime'], df['v'], 'g-', label='Velocity')
  1035. # 添加橙色背景标识急刹车事件
  1036. for idx, event in slam_brake_events.iterrows():
  1037. label = 'Slam Brake Event' if idx == 0 else None
  1038. ax2.axvspan(event['start_time'], event['end_time'],
  1039. alpha=0.3, color='orange', label=label)
  1040. ax2.set_xlabel('Time (s)')
  1041. ax2.set_ylabel('Velocity (m/s)')
  1042. ax2.set_title('Slam Brake Event Detection - Vehicle Speed')
  1043. ax2.grid(True)
  1044. ax2.legend()
  1045. # 保存图像
  1046. chart_filename = os.path.join(output_dir, f"slam_brake_chart.png")
  1047. plt.savefig(chart_filename, dpi=300)
  1048. plt.close()
  1049. logger.info(f"Slam brake chart saved to: {chart_filename}")
  1050. return chart_filename
  1051. except Exception as e:
  1052. logger.error(f"Failed to generate slam brake chart: {str(e)}", exc_info=True)
  1053. return None
  1054. def generate_slam_accelerate_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  1055. """
  1056. Generate slam accelerate metric chart with orange background for slam accelerate events.
  1057. This version first saves data to CSV, then uses the CSV to generate the chart.
  1058. Args:
  1059. comfort_calculator: ComfortCalculator instance
  1060. output_dir: Output directory
  1061. Returns:
  1062. str: Chart file path, or None if generation fails
  1063. """
  1064. logger = LogManager().get_logger()
  1065. try:
  1066. # 获取数据
  1067. df = comfort_calculator.ego_df.copy()
  1068. slam_accel_events = comfort_calculator.discomfort_df[
  1069. (comfort_calculator.discomfort_df['type'] == 'slam_accel')
  1070. ].copy()
  1071. if df.empty:
  1072. logger.warning("Cannot generate slam accelerate chart: empty data")
  1073. return None
  1074. # 生成时间戳
  1075. # 保存 CSV 数据(第一步)
  1076. csv_filename = os.path.join(output_dir, f"slam_accel_data.csv")
  1077. # 获取加速度阈值(如果存在)
  1078. accel_threshold = df.get('ip_acc', pd.Series([None] * len(df)))
  1079. df_csv = pd.DataFrame({
  1080. 'simTime': df['simTime'],
  1081. 'lon_acc': df['lon_acc'],
  1082. 'v': df['v'],
  1083. 'min_threshold': 0.0, # 加速度最小阈值设为0
  1084. 'max_threshold': accel_threshold # 急加速阈值
  1085. })
  1086. df_csv.to_csv(csv_filename, index=False)
  1087. logger.info(f"Slam accelerate data saved to: {csv_filename}")
  1088. # 第二步:从 CSV 读取(可验证保存数据无误)
  1089. df = pd.read_csv(csv_filename)
  1090. # 创建图表(第三步)
  1091. plt.figure(figsize=(12, 8), constrained_layout=True)
  1092. # 图 1:纵向加速度
  1093. ax1 = plt.subplot(2, 1, 1)
  1094. ax1.plot(df['simTime'], df['lon_acc'], 'b-', label='Longitudinal Acceleration')
  1095. # 添加加速度阈值线
  1096. if 'max_threshold' in df.columns and not df['max_threshold'].isnull().all():
  1097. ax1.plot(df['simTime'], df['max_threshold'], 'r--', label='Acceleration Threshold')
  1098. # 添加橙色背景标识急加速事件
  1099. for idx, event in slam_accel_events.iterrows():
  1100. label = 'Slam Accelerate Event' if idx == 0 else None
  1101. ax1.axvspan(event['start_time'], event['end_time'],
  1102. alpha=0.3, color='orange', label=label)
  1103. ax1.set_xlabel('Time (s)')
  1104. ax1.set_ylabel('Acceleration (m/s²)')
  1105. ax1.set_title('Slam Accelerate Event Detection - Longitudinal Acceleration')
  1106. ax1.grid(True)
  1107. ax1.legend()
  1108. # 图 2:速度
  1109. ax2 = plt.subplot(2, 1, 2)
  1110. ax2.plot(df['simTime'], df['v'], 'g-', label='Velocity')
  1111. # 添加橙色背景标识急加速事件
  1112. for idx, event in slam_accel_events.iterrows():
  1113. label = 'Slam Accelerate Event' if idx == 0 else None
  1114. ax2.axvspan(event['start_time'], event['end_time'],
  1115. alpha=0.3, color='orange', label=label)
  1116. ax2.set_xlabel('Time (s)')
  1117. ax2.set_ylabel('Velocity (m/s)')
  1118. ax2.set_title('Slam Accelerate Event Detection - Vehicle Speed')
  1119. ax2.grid(True)
  1120. ax2.legend()
  1121. # 保存图像
  1122. chart_filename = os.path.join(output_dir, f"slam_accel_chart.png")
  1123. plt.savefig(chart_filename, dpi=300)
  1124. plt.close()
  1125. logger.info(f"Slam accelerate chart saved to: {chart_filename}")
  1126. return chart_filename
  1127. except Exception as e:
  1128. logger.error(f"Failed to generate slam accelerate chart: {str(e)}", exc_info=True)
  1129. return None
  1130. def get_metric_thresholds(calculator, metric_name: str) -> dict:
  1131. """
  1132. 从配置文件中获取指标的阈值
  1133. Args:
  1134. calculator: Calculator instance (FunctionCalculator, SafetyCalculator, ComfortCalculator, EfficientCalculator, TrafficCalculator)
  1135. metric_name: 指标名称
  1136. Returns:
  1137. dict: 包含min和max阈值的字典
  1138. """
  1139. logger = LogManager().get_logger()
  1140. thresholds = {"min": None, "max": None}
  1141. try:
  1142. # 根据计算器类型获取配置
  1143. if hasattr(calculator, 'data_processed'):
  1144. # 检查安全性指标配置
  1145. if hasattr(calculator.data_processed,
  1146. 'safety_config') and 'safety' in calculator.data_processed.safety_config:
  1147. config = calculator.data_processed.safety_config['safety']
  1148. metric_type = 'safety'
  1149. # 检查舒适性指标配置
  1150. elif hasattr(calculator.data_processed,
  1151. 'comfort_config') and 'comfort' in calculator.data_processed.comfort_config:
  1152. config = calculator.data_processed.comfort_config['comfort']
  1153. metric_type = 'comfort'
  1154. # 检查功能性指标配置
  1155. elif hasattr(calculator.data_processed,
  1156. 'function_config') and 'function' in calculator.data_processed.function_config:
  1157. config = calculator.data_processed.function_config['function']
  1158. metric_type = 'function'
  1159. # 检查高效性指标配置
  1160. elif hasattr(calculator.data_processed,
  1161. 'efficient_config') and 'efficient' in calculator.data_processed.efficient_config:
  1162. config = calculator.data_processed.efficient_config['efficient']
  1163. metric_type = 'efficient'
  1164. # 检查交通性指标配置
  1165. elif hasattr(calculator.data_processed,
  1166. 'traffic_config') and 'traffic' in calculator.data_processed.traffic_config:
  1167. config = calculator.data_processed.traffic_config['traffic']
  1168. metric_type = 'traffic'
  1169. else:
  1170. # 直接检查calculator是否有function_config属性(针对FunctionCalculator)
  1171. if hasattr(calculator, 'function_config') and 'function' in calculator.function_config:
  1172. config = calculator.function_config['function']
  1173. metric_type = 'function'
  1174. else:
  1175. logger.warning(f"无法找到{metric_name}的配置信息")
  1176. return thresholds
  1177. else:
  1178. # 直接检查calculator是否有function_config属性(针对FunctionCalculator)
  1179. if hasattr(calculator, 'function_config') and 'function' in calculator.function_config:
  1180. config = calculator.function_config['function']
  1181. metric_type = 'function'
  1182. else:
  1183. logger.warning(f"计算器没有data_processed属性或function_config属性")
  1184. return thresholds
  1185. # 递归查找指标配置
  1186. def find_metric_config(node, target_name):
  1187. if isinstance(node, dict):
  1188. if 'name' in node and node['name'].lower() == target_name.lower() and 'min' in node and 'max' in node:
  1189. return node
  1190. for key, value in node.items():
  1191. result = find_metric_config(value, target_name)
  1192. if result:
  1193. return result
  1194. return None
  1195. # 查找指标配置
  1196. metric_config = find_metric_config(config, metric_name)
  1197. if metric_config:
  1198. thresholds["min"] = metric_config.get("min")
  1199. thresholds["max"] = metric_config.get("max")
  1200. logger.info(f"找到{metric_name}的阈值: min={thresholds['min']}, max={thresholds['max']}")
  1201. else:
  1202. logger.warning(f"在{metric_type}配置中未找到{metric_name}的阈值信息")
  1203. except Exception as e:
  1204. logger.error(f"获取{metric_name}阈值时出错: {str(e)}", exc_info=True)
  1205. return thresholds
  1206. def generate_safety_chart_data(safety_calculator, metric_name: str, output_dir: Optional[str] = None) -> Optional[str]:
  1207. """
  1208. Generate chart data for safety metrics
  1209. Args:
  1210. safety_calculator: SafetyCalculator instance
  1211. metric_name: Metric name
  1212. output_dir: Output directory
  1213. Returns:
  1214. str: Chart file path, or None if generation fails
  1215. """
  1216. logger = LogManager().get_logger()
  1217. try:
  1218. # 确保输出目录存在
  1219. if output_dir:
  1220. os.makedirs(output_dir, exist_ok=True)
  1221. else:
  1222. output_dir = os.getcwd()
  1223. # 根据指标名称选择不同的图表生成方法
  1224. if metric_name.lower() == 'ttc':
  1225. return generate_ttc_chart(safety_calculator, output_dir)
  1226. elif metric_name.lower() == 'mttc':
  1227. return generate_mttc_chart(safety_calculator, output_dir)
  1228. elif metric_name.lower() == 'thw':
  1229. return generate_thw_chart(safety_calculator, output_dir)
  1230. elif metric_name.lower() == 'lonsd':
  1231. return generate_lonsd_chart(safety_calculator, output_dir)
  1232. elif metric_name.lower() == 'latsd':
  1233. return generate_latsd_chart(safety_calculator, output_dir)
  1234. elif metric_name.lower() == 'btn':
  1235. return generate_btn_chart(safety_calculator, output_dir)
  1236. elif metric_name.lower() == 'collisionrisk':
  1237. return generate_collision_risk_chart(safety_calculator, output_dir)
  1238. elif metric_name.lower() == 'collisionseverity':
  1239. return generate_collision_severity_chart(safety_calculator, output_dir)
  1240. else:
  1241. logger.warning(f"Chart generation not implemented for metric [{metric_name}]")
  1242. return None
  1243. except Exception as e:
  1244. logger.error(f"Failed to generate chart data: {str(e)}", exc_info=True)
  1245. return None
  1246. def generate_ttc_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1247. """
  1248. Generate TTC metric chart with orange background for unsafe events.
  1249. This version first saves data to CSV, then uses the CSV to generate the chart.
  1250. Args:
  1251. safety_calculator: SafetyCalculator instance
  1252. output_dir: Output directory
  1253. Returns:
  1254. str: Chart file path, or None if generation fails
  1255. """
  1256. logger = LogManager().get_logger()
  1257. try:
  1258. # 获取数据
  1259. ttc_data = safety_calculator.ttc_data
  1260. if not ttc_data:
  1261. logger.warning("Cannot generate TTC chart: empty data")
  1262. return None
  1263. # 创建DataFrame
  1264. df = pd.DataFrame(ttc_data)
  1265. # 获取阈值
  1266. thresholds = get_metric_thresholds(safety_calculator, 'TTC')
  1267. min_threshold = thresholds.get('min')
  1268. max_threshold = thresholds.get('max')
  1269. # 生成时间戳
  1270. # 保存 CSV 数据(第一步)
  1271. csv_filename = os.path.join(output_dir, f"ttc_data.csv")
  1272. df_csv = pd.DataFrame({
  1273. 'simTime': df['simTime'],
  1274. 'simFrame': df['simFrame'],
  1275. 'TTC': df['TTC'],
  1276. 'min_threshold': min_threshold,
  1277. 'max_threshold': max_threshold
  1278. })
  1279. df_csv.to_csv(csv_filename, index=False)
  1280. logger.info(f"TTC data saved to: {csv_filename}")
  1281. # 第二步:从 CSV 读取(可验证保存数据无误)
  1282. df = pd.read_csv(csv_filename)
  1283. # 检测超阈值事件
  1284. unsafe_events = []
  1285. if min_threshold is not None:
  1286. # 对于TTC,小于最小阈值视为不安全
  1287. unsafe_condition = df['TTC'] < min_threshold
  1288. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1289. for _, group in df[unsafe_condition].groupby(event_groups):
  1290. if len(group) >= 2: # 至少2帧才算一次事件
  1291. start_time = group['simTime'].iloc[0]
  1292. end_time = group['simTime'].iloc[-1]
  1293. duration = end_time - start_time
  1294. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1295. unsafe_events.append({
  1296. 'start_time': start_time,
  1297. 'end_time': end_time,
  1298. 'start_frame': group['simFrame'].iloc[0],
  1299. 'end_frame': group['simFrame'].iloc[-1],
  1300. 'duration': duration,
  1301. 'min_ttc': group['TTC'].min()
  1302. })
  1303. # 创建图表(第三步)
  1304. plt.figure(figsize=(12, 8))
  1305. plt.plot(df['simTime'], df['TTC'], 'b-', label='TTC')
  1306. # 添加阈值线
  1307. if min_threshold is not None:
  1308. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  1309. if max_threshold is not None:
  1310. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold})')
  1311. # 添加橙色背景标识不安全事件
  1312. for idx, event in enumerate(unsafe_events):
  1313. label = 'Unsafe TTC Event' if idx == 0 else None
  1314. plt.axvspan(event['start_time'], event['end_time'],
  1315. alpha=0.3, color='orange', label=label)
  1316. plt.xlabel('Time (s)')
  1317. plt.ylabel('TTC (s)')
  1318. plt.title('Time To Collision (TTC) Trend')
  1319. plt.grid(True)
  1320. plt.legend()
  1321. # 保存图像
  1322. chart_filename = os.path.join(output_dir, f"ttc_chart.png")
  1323. plt.savefig(chart_filename, dpi=300)
  1324. plt.close()
  1325. # 记录不安全事件信息
  1326. if unsafe_events:
  1327. logger.info(f"检测到 {len(unsafe_events)} 个TTC不安全事件")
  1328. for i, event in enumerate(unsafe_events):
  1329. logger.info(
  1330. f"TTC不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最小TTC={event['min_ttc']:.2f}s")
  1331. logger.info(f"TTC chart saved to: {chart_filename}")
  1332. return chart_filename
  1333. except Exception as e:
  1334. logger.error(f"Failed to generate TTC chart: {str(e)}", exc_info=True)
  1335. return None
  1336. def generate_mttc_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1337. """
  1338. Generate MTTC metric chart with orange background for unsafe events
  1339. Args:
  1340. safety_calculator: SafetyCalculator instance
  1341. output_dir: Output directory
  1342. Returns:
  1343. str: Chart file path, or None if generation fails
  1344. """
  1345. logger = LogManager().get_logger()
  1346. try:
  1347. # 获取数据
  1348. mttc_data = safety_calculator.mttc_data
  1349. if not mttc_data:
  1350. logger.warning("Cannot generate MTTC chart: empty data")
  1351. return None
  1352. # 创建DataFrame
  1353. df = pd.DataFrame(mttc_data)
  1354. # 获取阈值
  1355. thresholds = get_metric_thresholds(safety_calculator, 'MTTC')
  1356. min_threshold = thresholds.get('min')
  1357. max_threshold = thresholds.get('max')
  1358. # 检测超阈值事件
  1359. unsafe_events = []
  1360. if min_threshold is not None:
  1361. # 对于MTTC,小于最小阈值视为不安全
  1362. unsafe_condition = df['MTTC'] < min_threshold
  1363. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1364. for _, group in df[unsafe_condition].groupby(event_groups):
  1365. if len(group) >= 2: # 至少2帧才算一次事件
  1366. start_time = group['simTime'].iloc[0]
  1367. end_time = group['simTime'].iloc[-1]
  1368. duration = end_time - start_time
  1369. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1370. unsafe_events.append({
  1371. 'start_time': start_time,
  1372. 'end_time': end_time,
  1373. 'start_frame': group['simFrame'].iloc[0],
  1374. 'end_frame': group['simFrame'].iloc[-1],
  1375. 'duration': duration,
  1376. 'min_mttc': group['MTTC'].min()
  1377. })
  1378. # 创建图表
  1379. plt.figure(figsize=(12, 6))
  1380. plt.plot(df['simTime'], df['MTTC'], 'g-', label='MTTC')
  1381. # 添加阈值线
  1382. if min_threshold is not None:
  1383. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  1384. if max_threshold is not None:
  1385. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold})')
  1386. # 添加橙色背景标识不安全事件
  1387. for idx, event in enumerate(unsafe_events):
  1388. label = 'Unsafe MTTC Event' if idx == 0 else None
  1389. plt.axvspan(event['start_time'], event['end_time'],
  1390. alpha=0.3, color='orange', label=label)
  1391. plt.xlabel('Time (s)')
  1392. plt.ylabel('MTTC (s)')
  1393. plt.title('Modified Time To Collision (MTTC) Trend')
  1394. plt.grid(True)
  1395. plt.legend()
  1396. # 保存图表
  1397. chart_filename = os.path.join(output_dir, f"mttc_chart.png")
  1398. plt.savefig(chart_filename, dpi=300)
  1399. plt.close()
  1400. # 保存CSV数据,包含阈值信息
  1401. csv_filename = os.path.join(output_dir, f"mttc_data.csv")
  1402. df_csv = df.copy()
  1403. df_csv['min_threshold'] = min_threshold
  1404. df_csv['max_threshold'] = max_threshold
  1405. df_csv.to_csv(csv_filename, index=False)
  1406. # 记录不安全事件信息
  1407. if unsafe_events:
  1408. logger.info(f"检测到 {len(unsafe_events)} 个MTTC不安全事件")
  1409. for i, event in enumerate(unsafe_events):
  1410. logger.info(
  1411. f"MTTC不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最小MTTC={event['min_mttc']:.2f}s")
  1412. logger.info(f"MTTC chart saved to: {chart_filename}")
  1413. logger.info(f"MTTC data saved to: {csv_filename}")
  1414. return chart_filename
  1415. except Exception as e:
  1416. logger.error(f"Failed to generate MTTC chart: {str(e)}", exc_info=True)
  1417. return None
  1418. def generate_thw_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1419. """
  1420. Generate THW metric chart with orange background for unsafe events
  1421. Args:
  1422. safety_calculator: SafetyCalculator instance
  1423. output_dir: Output directory
  1424. Returns:
  1425. str: Chart file path, or None if generation fails
  1426. """
  1427. logger = LogManager().get_logger()
  1428. try:
  1429. # 获取数据
  1430. thw_data = safety_calculator.thw_data
  1431. if not thw_data:
  1432. logger.warning("Cannot generate THW chart: empty data")
  1433. return None
  1434. # 创建DataFrame
  1435. df = pd.DataFrame(thw_data)
  1436. # 获取阈值
  1437. thresholds = get_metric_thresholds(safety_calculator, 'THW')
  1438. min_threshold = thresholds.get('min')
  1439. max_threshold = thresholds.get('max')
  1440. # 检测超阈值事件
  1441. unsafe_events = []
  1442. if min_threshold is not None:
  1443. # 对于THW,小于最小阈值视为不安全
  1444. unsafe_condition = df['THW'] < min_threshold
  1445. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1446. for _, group in df[unsafe_condition].groupby(event_groups):
  1447. if len(group) >= 2: # 至少2帧才算一次事件
  1448. start_time = group['simTime'].iloc[0]
  1449. end_time = group['simTime'].iloc[-1]
  1450. duration = end_time - start_time
  1451. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1452. unsafe_events.append({
  1453. 'start_time': start_time,
  1454. 'end_time': end_time,
  1455. 'start_frame': group['simFrame'].iloc[0],
  1456. 'end_frame': group['simFrame'].iloc[-1],
  1457. 'duration': duration,
  1458. 'min_thw': group['THW'].min()
  1459. })
  1460. # 创建图表
  1461. plt.figure(figsize=(12, 10))
  1462. plt.plot(df['simTime'], df['THW'], 'c-', label='THW')
  1463. # 添加阈值线
  1464. if min_threshold is not None:
  1465. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  1466. if max_threshold is not None:
  1467. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold})')
  1468. # 添加橙色背景标识不安全事件
  1469. for idx, event in enumerate(unsafe_events):
  1470. label = 'Unsafe THW Event' if idx == 0 else None
  1471. plt.axvspan(event['start_time'], event['end_time'],
  1472. alpha=0.3, color='orange', label=label)
  1473. plt.xlabel('Time (s)')
  1474. plt.ylabel('THW (s)')
  1475. plt.title('Time Headway (THW) Trend')
  1476. plt.grid(True)
  1477. plt.legend()
  1478. # 保存图表
  1479. chart_filename = os.path.join(output_dir, f"thw_chart.png")
  1480. plt.savefig(chart_filename, dpi=300)
  1481. plt.close()
  1482. # 保存CSV数据,包含阈值信息
  1483. csv_filename = os.path.join(output_dir, f"thw_data.csv")
  1484. df_csv = df.copy()
  1485. df_csv['min_threshold'] = min_threshold
  1486. df_csv['max_threshold'] = max_threshold
  1487. df_csv.to_csv(csv_filename, index=False)
  1488. # 记录不安全事件信息
  1489. if unsafe_events:
  1490. logger.info(f"检测到 {len(unsafe_events)} 个THW不安全事件")
  1491. for i, event in enumerate(unsafe_events):
  1492. logger.info(
  1493. f"THW不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最小THW={event['min_thw']:.2f}s")
  1494. logger.info(f"THW chart saved to: {chart_filename}")
  1495. logger.info(f"THW data saved to: {csv_filename}")
  1496. return chart_filename
  1497. except Exception as e:
  1498. logger.error(f"Failed to generate THW chart: {str(e)}", exc_info=True)
  1499. return None
  1500. def generate_lonsd_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1501. """
  1502. Generate Longitudinal Safe Distance metric chart
  1503. Args:
  1504. safety_calculator: SafetyCalculator instance
  1505. output_dir: Output directory
  1506. Returns:
  1507. str: Chart file path, or None if generation fails
  1508. """
  1509. logger = LogManager().get_logger()
  1510. try:
  1511. # 获取数据
  1512. lonsd_data = safety_calculator.lonsd_data
  1513. if not lonsd_data:
  1514. logger.warning("Cannot generate Longitudinal Safe Distance chart: empty data")
  1515. return None
  1516. # 创建DataFrame
  1517. df = pd.DataFrame(lonsd_data)
  1518. # 获取阈值
  1519. thresholds = get_metric_thresholds(safety_calculator, 'LonSD')
  1520. min_threshold = thresholds.get('min')
  1521. max_threshold = thresholds.get('max')
  1522. # 创建图表
  1523. plt.figure(figsize=(12, 6))
  1524. plt.plot(df['simTime'], df['LonSD'], 'm-', label='Longitudinal Safe Distance')
  1525. # 添加阈值线
  1526. if min_threshold is not None:
  1527. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  1528. if max_threshold is not None:
  1529. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  1530. plt.xlabel('Time (s)')
  1531. plt.ylabel('Distance (m)')
  1532. plt.title('Longitudinal Safe Distance (LonSD) Trend')
  1533. plt.grid(True)
  1534. plt.legend()
  1535. # 保存图表
  1536. chart_filename = os.path.join(output_dir, f"lonsd_chart.png")
  1537. plt.savefig(chart_filename, dpi=300)
  1538. plt.close()
  1539. # 保存CSV数据,包含阈值信息
  1540. csv_filename = os.path.join(output_dir, f"lonsd_data.csv")
  1541. df_csv = df.copy()
  1542. df_csv['min_threshold'] = min_threshold
  1543. df_csv['max_threshold'] = max_threshold
  1544. df_csv.to_csv(csv_filename, index=False)
  1545. logger.info(f"Longitudinal Safe Distance chart saved to: {chart_filename}")
  1546. logger.info(f"Longitudinal Safe Distance data saved to: {csv_filename}")
  1547. return chart_filename
  1548. except Exception as e:
  1549. logger.error(f"Failed to generate Longitudinal Safe Distance chart: {str(e)}", exc_info=True)
  1550. return None
  1551. def generate_latsd_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1552. """
  1553. Generate Lateral Safe Distance metric chart with orange background for unsafe events
  1554. Args:
  1555. safety_calculator: SafetyCalculator instance
  1556. output_dir: Output directory
  1557. Returns:
  1558. str: Chart file path, or None if generation fails
  1559. """
  1560. logger = LogManager().get_logger()
  1561. try:
  1562. # 获取数据
  1563. latsd_data = safety_calculator.latsd_data
  1564. if not latsd_data:
  1565. logger.warning("Cannot generate Lateral Safe Distance chart: empty data")
  1566. return None
  1567. # 创建DataFrame
  1568. df = pd.DataFrame(latsd_data)
  1569. # 获取阈值
  1570. thresholds = get_metric_thresholds(safety_calculator, 'LatSD')
  1571. min_threshold = thresholds.get('min')
  1572. max_threshold = thresholds.get('max')
  1573. # 检测超阈值事件
  1574. unsafe_events = []
  1575. if min_threshold is not None:
  1576. # 对于LatSD,小于最小阈值视为不安全
  1577. unsafe_condition = df['LatSD'] < min_threshold
  1578. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1579. for _, group in df[unsafe_condition].groupby(event_groups):
  1580. if len(group) >= 2: # 至少2帧才算一次事件
  1581. start_time = group['simTime'].iloc[0]
  1582. end_time = group['simTime'].iloc[-1]
  1583. duration = end_time - start_time
  1584. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1585. unsafe_events.append({
  1586. 'start_time': start_time,
  1587. 'end_time': end_time,
  1588. 'start_frame': group['simFrame'].iloc[0],
  1589. 'end_frame': group['simFrame'].iloc[-1],
  1590. 'duration': duration,
  1591. 'min_latsd': group['LatSD'].min()
  1592. })
  1593. # 创建图表
  1594. plt.figure(figsize=(12, 6))
  1595. plt.plot(df['simTime'], df['LatSD'], 'y-', label='Lateral Safe Distance')
  1596. # 添加阈值线
  1597. if min_threshold is not None:
  1598. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  1599. if max_threshold is not None:
  1600. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  1601. # 添加橙色背景标识不安全事件
  1602. for idx, event in enumerate(unsafe_events):
  1603. label = 'Unsafe LatSD Event' if idx == 0 else None
  1604. plt.axvspan(event['start_time'], event['end_time'],
  1605. alpha=0.3, color='orange', label=label)
  1606. plt.xlabel('Time (s)')
  1607. plt.ylabel('Distance (m)')
  1608. plt.title('Lateral Safe Distance (LatSD) Trend')
  1609. plt.grid(True)
  1610. plt.legend()
  1611. # 保存图表
  1612. chart_filename = os.path.join(output_dir, f"latsd_chart.png")
  1613. plt.savefig(chart_filename, dpi=300)
  1614. plt.close()
  1615. # 保存CSV数据,包含阈值信息
  1616. csv_filename = os.path.join(output_dir, f"latsd_data.csv")
  1617. df_csv = df.copy()
  1618. df_csv['min_threshold'] = min_threshold
  1619. df_csv['max_threshold'] = max_threshold
  1620. df_csv.to_csv(csv_filename, index=False)
  1621. # 记录不安全事件信息
  1622. if unsafe_events:
  1623. logger.info(f"检测到 {len(unsafe_events)} 个LatSD不安全事件")
  1624. for i, event in enumerate(unsafe_events):
  1625. logger.info(
  1626. f"LatSD不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最小LatSD={event['min_latsd']:.2f}m")
  1627. logger.info(f"Lateral Safe Distance chart saved to: {chart_filename}")
  1628. logger.info(f"Lateral Safe Distance data saved to: {csv_filename}")
  1629. return chart_filename
  1630. except Exception as e:
  1631. logger.error(f"Failed to generate Lateral Safe Distance chart: {str(e)}", exc_info=True)
  1632. return None
  1633. def generate_btn_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1634. """
  1635. Generate Brake Threat Number metric chart with orange background for unsafe events
  1636. Args:
  1637. safety_calculator: SafetyCalculator instance
  1638. output_dir: Output directory
  1639. Returns:
  1640. str: Chart file path, or None if generation fails
  1641. """
  1642. logger = LogManager().get_logger()
  1643. try:
  1644. # 获取数据
  1645. btn_data = safety_calculator.btn_data
  1646. if not btn_data:
  1647. logger.warning("Cannot generate Brake Threat Number chart: empty data")
  1648. return None
  1649. # 创建DataFrame
  1650. df = pd.DataFrame(btn_data)
  1651. # 获取阈值
  1652. thresholds = get_metric_thresholds(safety_calculator, 'BTN')
  1653. min_threshold = thresholds.get('min')
  1654. max_threshold = thresholds.get('max')
  1655. # 检测超阈值事件
  1656. unsafe_events = []
  1657. if max_threshold is not None:
  1658. # 对于BTN,大于最大阈值视为不安全
  1659. unsafe_condition = df['BTN'] > max_threshold
  1660. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1661. for _, group in df[unsafe_condition].groupby(event_groups):
  1662. if len(group) >= 2: # 至少2帧才算一次事件
  1663. start_time = group['simTime'].iloc[0]
  1664. end_time = group['simTime'].iloc[-1]
  1665. duration = end_time - start_time
  1666. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1667. unsafe_events.append({
  1668. 'start_time': start_time,
  1669. 'end_time': end_time,
  1670. 'start_frame': group['simFrame'].iloc[0],
  1671. 'end_frame': group['simFrame'].iloc[-1],
  1672. 'duration': duration,
  1673. 'max_btn': group['BTN'].max()
  1674. })
  1675. # 创建图表
  1676. plt.figure(figsize=(12, 6))
  1677. plt.plot(df['simTime'], df['BTN'], 'r-', label='Brake Threat Number')
  1678. # 添加阈值线
  1679. if min_threshold is not None:
  1680. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold})')
  1681. if max_threshold is not None:
  1682. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold})')
  1683. # 添加橙色背景标识不安全事件
  1684. for idx, event in enumerate(unsafe_events):
  1685. label = 'Unsafe BTN Event' if idx == 0 else None
  1686. plt.axvspan(event['start_time'], event['end_time'],
  1687. alpha=0.3, color='orange', label=label)
  1688. plt.xlabel('Time (s)')
  1689. plt.ylabel('BTN')
  1690. plt.title('Brake Threat Number (BTN) Trend')
  1691. plt.grid(True)
  1692. plt.legend()
  1693. # 保存图表
  1694. chart_filename = os.path.join(output_dir, f"btn_chart.png")
  1695. plt.savefig(chart_filename, dpi=300)
  1696. plt.close()
  1697. # 保存CSV数据,包含阈值信息
  1698. csv_filename = os.path.join(output_dir, f"btn_data.csv")
  1699. df_csv = df.copy()
  1700. df_csv['min_threshold'] = min_threshold
  1701. df_csv['max_threshold'] = max_threshold
  1702. df_csv.to_csv(csv_filename, index=False)
  1703. # 记录不安全事件信息
  1704. if unsafe_events:
  1705. logger.info(f"检测到 {len(unsafe_events)} 个BTN不安全事件")
  1706. for i, event in enumerate(unsafe_events):
  1707. logger.info(
  1708. f"BTN不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最大BTN={event['max_btn']:.2f}")
  1709. logger.info(f"Brake Threat Number chart saved to: {chart_filename}")
  1710. logger.info(f"Brake Threat Number data saved to: {csv_filename}")
  1711. return chart_filename
  1712. except Exception as e:
  1713. logger.error(f"Failed to generate Brake Threat Number chart: {str(e)}", exc_info=True)
  1714. return None
  1715. def generate_collision_risk_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1716. """
  1717. Generate Collision Risk metric chart
  1718. Args:
  1719. safety_calculator: SafetyCalculator instance
  1720. output_dir: Output directory
  1721. Returns:
  1722. str: Chart file path, or None if generation fails
  1723. """
  1724. logger = LogManager().get_logger()
  1725. try:
  1726. # 获取数据
  1727. risk_data = safety_calculator.collision_risk_data
  1728. if not risk_data:
  1729. logger.warning("Cannot generate Collision Risk chart: empty data")
  1730. return None
  1731. # 创建DataFrame
  1732. df = pd.DataFrame(risk_data)
  1733. # 获取阈值
  1734. thresholds = get_metric_thresholds(safety_calculator, 'collisionRisk')
  1735. min_threshold = thresholds.get('min')
  1736. max_threshold = thresholds.get('max')
  1737. # 创建图表
  1738. plt.figure(figsize=(12, 6))
  1739. plt.plot(df['simTime'], df['collisionRisk'], 'r-', label='Collision Risk')
  1740. # 添加阈值线
  1741. if min_threshold is not None:
  1742. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}%)')
  1743. if max_threshold is not None:
  1744. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold}%)')
  1745. plt.xlabel('Time (s)')
  1746. plt.ylabel('Risk Value (%)')
  1747. plt.title('Collision Risk (collisionRisk) Trend')
  1748. plt.grid(True)
  1749. plt.legend()
  1750. # 保存图表
  1751. chart_filename = os.path.join(output_dir, f"collision_risk_chart.png")
  1752. plt.savefig(chart_filename, dpi=300)
  1753. plt.close()
  1754. # 保存CSV数据,包含阈值信息
  1755. csv_filename = os.path.join(output_dir, f"collisionrisk_data.csv")
  1756. df_csv = df.copy()
  1757. df_csv['min_threshold'] = min_threshold
  1758. df_csv['max_threshold'] = max_threshold
  1759. df_csv.to_csv(csv_filename, index=False)
  1760. logger.info(f"Collision Risk chart saved to: {chart_filename}")
  1761. logger.info(f"Collision Risk data saved to: {csv_filename}")
  1762. return chart_filename
  1763. except Exception as e:
  1764. logger.error(f"Failed to generate Collision Risk chart: {str(e)}", exc_info=True)
  1765. return None
  1766. def generate_collision_severity_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1767. """
  1768. Generate Collision Severity metric chart
  1769. Args:
  1770. safety_calculator: SafetyCalculator instance
  1771. output_dir: Output directory
  1772. Returns:
  1773. str: Chart file path, or None if generation fails
  1774. """
  1775. logger = LogManager().get_logger()
  1776. try:
  1777. # 获取数据
  1778. severity_data = safety_calculator.collision_severity_data
  1779. if not severity_data:
  1780. logger.warning("Cannot generate Collision Severity chart: empty data")
  1781. return None
  1782. # 创建DataFrame
  1783. df = pd.DataFrame(severity_data)
  1784. # 获取阈值
  1785. thresholds = get_metric_thresholds(safety_calculator, 'collisionSeverity')
  1786. min_threshold = thresholds.get('min')
  1787. max_threshold = thresholds.get('max')
  1788. # 创建图表
  1789. plt.figure(figsize=(12, 6))
  1790. plt.plot(df['simTime'], df['collisionSeverity'], 'r-', label='Collision Severity')
  1791. # 添加阈值线
  1792. if min_threshold is not None:
  1793. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}%)')
  1794. if max_threshold is not None:
  1795. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold}%)')
  1796. plt.xlabel('Time (s)')
  1797. plt.ylabel('Severity (%)')
  1798. plt.title('Collision Severity (collisionSeverity) Trend')
  1799. plt.grid(True)
  1800. plt.legend()
  1801. # 保存图表
  1802. chart_filename = os.path.join(output_dir, f"collision_severity_chart.png")
  1803. plt.savefig(chart_filename, dpi=300)
  1804. plt.close()
  1805. # 保存CSV数据,包含阈值信息
  1806. csv_filename = os.path.join(output_dir, f"collisionseverity_data.csv")
  1807. df_csv = df.copy()
  1808. df_csv['min_threshold'] = min_threshold
  1809. df_csv['max_threshold'] = max_threshold
  1810. df_csv.to_csv(csv_filename, index=False)
  1811. logger.info(f"Collision Severity chart saved to: {chart_filename}")
  1812. logger.info(f"Collision Severity data saved to: {csv_filename}")
  1813. return chart_filename
  1814. except Exception as e:
  1815. logger.error(f"Failed to generate Collision Severity chart: {str(e)}", exc_info=True)
  1816. return None
  1817. def generate_traffic_chart_data(traffic_calculator, metric_name: str, output_dir: Optional[str] = None) -> Optional[
  1818. str]:
  1819. """Generate chart data for traffic metrics"""
  1820. # 待实现
  1821. return None
  1822. def calculate_distance(ego_df, correctwarning):
  1823. """计算预警距离"""
  1824. dist = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['relative_dist']
  1825. return dist
  1826. def calculate_relative_speed(ego_df, correctwarning):
  1827. """计算相对速度"""
  1828. return ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['composite_v']
  1829. # 使用function.py中已实现的scenario_sign_dict
  1830. from modules.metric.function import scenario_sign_dict
  1831. if __name__ == "__main__":
  1832. # 测试代码
  1833. print("Metrics visualization utilities loaded.")