chart_generator.py 101 KB

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