chart_generator.py 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  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. if longitude_dist is None or longitude_dist.empty:
  848. logger.warning(f"Cannot generate {metric_name} chart: missing longitudinal distance data")
  849. return None
  850. # Calculate metric value
  851. metric_value = longitude_dist.max()
  852. max_distance_time = ego_df.loc[longitude_dist.idxmax(), 'simTime']
  853. # Save CSV data
  854. csv_filename = os.path.join(output_dir, f"{metric_name.lower()}_data.csv")
  855. df_csv = pd.DataFrame({
  856. 'simTime': ego_df['simTime'],
  857. 'longitude_dist': longitude_dist,
  858. 'min_threshold': min_threshold,
  859. 'max_threshold': max_threshold
  860. })
  861. df_csv.to_csv(csv_filename, index=False)
  862. logger.info(f"{metric_name} data saved to: {csv_filename}")
  863. # Read data from CSV
  864. df = pd.read_csv(csv_filename)
  865. # Create chart
  866. plt.figure(figsize=(12, 6), constrained_layout=True)
  867. # Plot longitudinal distance
  868. plt.plot(df['simTime'], df['longitude_dist'], 'b-', label='Longitudinal Distance')
  869. # Add threshold lines
  870. plt.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  871. plt.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  872. # Mark maximum longitudinal distance
  873. plt.scatter(max_distance_time, metric_value,
  874. color='red', s=100, zorder=5,
  875. label=f'Maximum Longitudinal Distance: {metric_value:.2f}m')
  876. # Set y-axis range
  877. plt.ylim(bottom=min(0, min_threshold * 0.9), top=max(max_threshold * 1.1, df['longitude_dist'].max() * 1.1))
  878. plt.xlabel('Time (s)')
  879. plt.ylabel('Longitudinal Distance (m)')
  880. plt.title(f'{metric_name} - Longitudinal Distance Over Time')
  881. plt.grid(True)
  882. plt.legend()
  883. # Save image
  884. chart_filename = os.path.join(output_dir, f"{metric_name.lower()}_chart.png")
  885. plt.savefig(chart_filename, dpi=300)
  886. plt.close()
  887. logger.info(f"{metric_name} chart saved to: {chart_filename}")
  888. return chart_filename
  889. except Exception as e:
  890. logger.error(f"Failed to generate {metric_name} chart: {str(e)}", exc_info=True)
  891. return None
  892. def generate_warning_delay_time_chart(function_calculator, output_dir: str) -> Optional[str]:
  893. """
  894. Generate warning delay time chart with data visualization for warningDelayTime_LST metric.
  895. Args:
  896. function_calculator: FunctionCalculator instance
  897. output_dir: Output directory
  898. Returns:
  899. str: Chart file path, or None if generation fails
  900. """
  901. logger = LogManager().get_logger()
  902. metric_name = 'warningDelayTime_LST'
  903. try:
  904. # Get data
  905. ego_df = function_calculator.ego_data.copy()
  906. # Get configured thresholds
  907. thresholds = get_metric_thresholds(function_calculator, metric_name)
  908. max_threshold = thresholds["max"]
  909. min_threshold = thresholds["min"]
  910. # Check if correctwarning is already calculated
  911. correctwarning = getattr(function_calculator, 'correctwarning', None)
  912. if correctwarning is None:
  913. logger.warning(f"Cannot generate {metric_name} chart: missing correctwarning value")
  914. return None
  915. # Get HMI warning time and rosbag warning time
  916. HMI_warning_rows = ego_df[(ego_df['ifwarning'] == correctwarning)]['simTime'].tolist()
  917. simTime_HMI = HMI_warning_rows[0] if len(HMI_warning_rows) > 0 else None
  918. rosbag_warning_rows = ego_df[(ego_df['event_Type'].notna()) & ((ego_df['event_Type'] != np.nan))][
  919. 'simTime'].tolist()
  920. simTime_rosbag = rosbag_warning_rows[0] if len(rosbag_warning_rows) > 0 else None
  921. if (simTime_HMI is None) or (simTime_rosbag is None):
  922. logger.warning(f"Cannot generate {metric_name} chart: missing warning time data")
  923. return None
  924. # Calculate delay time
  925. delay_time = abs(simTime_HMI - simTime_rosbag)
  926. # Save CSV data
  927. csv_filename = os.path.join(output_dir, f"{metric_name.lower()}_data.csv")
  928. df_csv = pd.DataFrame({
  929. 'HMI_warning_time': [simTime_HMI],
  930. 'rosbag_warning_time': [simTime_rosbag],
  931. 'delay_time': [delay_time],
  932. 'min_threshold': [min_threshold],
  933. 'max_threshold': [max_threshold]
  934. })
  935. df_csv.to_csv(csv_filename, index=False)
  936. logger.info(f"{metric_name} data saved to: {csv_filename}")
  937. # Create chart - bar chart for delay time
  938. plt.figure(figsize=(10, 6), constrained_layout=True)
  939. # Plot delay time as bar
  940. plt.bar(['Warning Delay Time'], [delay_time], color='blue', width=0.4)
  941. # Add threshold lines
  942. plt.axhline(y=max_threshold, color='r', linestyle='--', label=f'Max Threshold ({max_threshold}s)')
  943. plt.axhline(y=min_threshold, color='g', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  944. # Add value label
  945. plt.text(0, delay_time + 0.05, f'{delay_time:.3f}s', ha='center', va='bottom', fontweight='bold')
  946. # Set y-axis range
  947. plt.ylim(bottom=0, top=max(max_threshold * 1.2, delay_time * 1.2))
  948. plt.ylabel('Delay Time (s)')
  949. plt.title(f'{metric_name} - Warning Delay Time')
  950. plt.grid(True, axis='y')
  951. plt.legend()
  952. # Save image
  953. chart_filename = os.path.join(output_dir, f"{metric_name.lower()}_chart.png")
  954. plt.savefig(chart_filename, dpi=300)
  955. plt.close()
  956. logger.info(f"{metric_name} chart saved to: {chart_filename}")
  957. return chart_filename
  958. except Exception as e:
  959. logger.error(f"Failed to generate {metric_name} chart: {str(e)}", exc_info=True)
  960. return None
  961. def generate_comfort_chart_data(comfort_calculator, metric_name: str, output_dir: Optional[str] = None) -> Optional[
  962. str]:
  963. """
  964. Generate chart data for comfort metrics
  965. Args:
  966. comfort_calculator: ComfortCalculator instance
  967. metric_name: Metric name
  968. output_dir: Output directory
  969. Returns:
  970. str: Chart file path, or None if generation fails
  971. """
  972. logger = LogManager().get_logger()
  973. try:
  974. # 确保输出目录存在
  975. if output_dir:
  976. os.makedirs(output_dir, exist_ok=True)
  977. else:
  978. output_dir = os.getcwd()
  979. # 根据指标名称选择不同的图表生成方法
  980. if metric_name.lower() == 'shake':
  981. return generate_shake_chart(comfort_calculator, output_dir)
  982. elif metric_name.lower() == 'zigzag':
  983. return generate_zigzag_chart(comfort_calculator, output_dir)
  984. elif metric_name.lower() == 'cadence':
  985. return generate_cadence_chart(comfort_calculator, output_dir)
  986. elif metric_name.lower() == 'slambrake':
  987. return generate_slam_brake_chart(comfort_calculator, output_dir)
  988. elif metric_name.lower() == 'slamaccelerate':
  989. return generate_slam_accelerate_chart(comfort_calculator, output_dir)
  990. else:
  991. logger.warning(f"Chart generation not implemented for metric [{metric_name}]")
  992. return None
  993. except Exception as e:
  994. logger.error(f"Failed to generate chart data: {str(e)}", exc_info=True)
  995. return None
  996. def generate_shake_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  997. """
  998. Generate shake metric chart with orange background for shake events.
  999. This version first saves data to CSV, then uses the CSV to generate the chart.
  1000. Args:
  1001. comfort_calculator: ComfortCalculator instance
  1002. output_dir: Output directory
  1003. Returns:
  1004. str: Chart file path, or None if generation fails
  1005. """
  1006. logger = LogManager().get_logger()
  1007. try:
  1008. # 获取数据
  1009. df = comfort_calculator.ego_df.copy()
  1010. shake_events = comfort_calculator.shake_events
  1011. if df.empty:
  1012. logger.warning("Cannot generate shake chart: empty data")
  1013. return None
  1014. # 生成时间戳
  1015. # 保存 CSV 数据(第一步)
  1016. csv_filename = os.path.join(output_dir, f"shake_data.csv")
  1017. df_csv = pd.DataFrame({
  1018. 'simTime': df['simTime'],
  1019. 'lat_acc': df['lat_acc'],
  1020. 'lat_acc_rate': df['lat_acc_rate'],
  1021. 'speedH_std': df['speedH_std'],
  1022. 'lat_acc_threshold': df.get('lat_acc_threshold', pd.Series([None] * len(df))),
  1023. 'lat_acc_rate_threshold': 0.5,
  1024. 'speedH_std_threshold': df.get('speedH_threshold', pd.Series([None] * len(df))),
  1025. })
  1026. df_csv.to_csv(csv_filename, index=False)
  1027. logger.info(f"Shake data saved to: {csv_filename}")
  1028. # 第二步:从 CSV 读取(可验证保存数据无误)
  1029. df = pd.read_csv(csv_filename)
  1030. # 创建图表(第三步)
  1031. import matplotlib.pyplot as plt
  1032. plt.figure(figsize=(12, 8), constrained_layout=True)
  1033. # 图 1:横向加速度
  1034. ax1 = plt.subplot(3, 1, 1)
  1035. ax1.plot(df['simTime'], df['lat_acc'], 'b-', label='Lateral Acceleration')
  1036. if 'lat_acc_threshold' in df.columns:
  1037. ax1.plot(df['simTime'], df['lat_acc_threshold'], 'r--', label='lat_acc_threshold')
  1038. for idx, event in enumerate(shake_events):
  1039. label = 'Shake Event' if idx == 0 else None
  1040. ax1.axvspan(event['start_time'], event['end_time'], alpha=0.3, color='orange', label=label)
  1041. ax1.set_xlabel('Time (s)')
  1042. ax1.set_ylabel('Lateral Acceleration (m/s²)')
  1043. ax1.set_title('Shake Event Detection - Lateral Acceleration')
  1044. ax1.grid(True)
  1045. ax1.legend()
  1046. # 图 2:lat_acc_rate
  1047. ax2 = plt.subplot(3, 1, 2)
  1048. ax2.plot(df['simTime'], df['lat_acc_rate'], 'g-', label='lat_acc_rate')
  1049. ax2.axhline(
  1050. y=0.5, color='orange', linestyle='--', linewidth=1.2, label='lat_acc_rate_threshold'
  1051. )
  1052. for idx, event in enumerate(shake_events):
  1053. label = 'Shake Event' if idx == 0 else None
  1054. ax2.axvspan(event['start_time'], event['end_time'], alpha=0.3, color='orange', label=label)
  1055. ax2.set_xlabel('Time (s)')
  1056. ax2.set_ylabel('Angular Velocity (m/s³)')
  1057. ax2.set_title('Shake Event Detection - lat_acc_rate')
  1058. ax2.grid(True)
  1059. ax2.legend()
  1060. # 图 3:speedH_std
  1061. ax3 = plt.subplot(3, 1, 3)
  1062. ax3.plot(df['simTime'], df['speedH_std'], 'b-', label='speedH_std')
  1063. if 'speedH_std_threshold' in df.columns:
  1064. ax3.plot(df['simTime'], df['speedH_std_threshold'], 'r--', label='speedH_threshold')
  1065. for idx, event in enumerate(shake_events):
  1066. label = 'Shake Event' if idx == 0 else None
  1067. ax3.axvspan(event['start_time'], event['end_time'], alpha=0.3, color='orange', label=label)
  1068. ax3.set_xlabel('Time (s)')
  1069. ax3.set_ylabel('Angular Velocity (deg/s)')
  1070. ax3.set_title('Shake Event Detection - speedH_std')
  1071. ax3.grid(True)
  1072. ax3.legend()
  1073. # 保存图像
  1074. chart_filename = os.path.join(output_dir, f"shake_chart.png")
  1075. plt.savefig(chart_filename, dpi=300)
  1076. plt.close()
  1077. logger.info(f"Shake chart saved to: {chart_filename}")
  1078. return chart_filename
  1079. except Exception as e:
  1080. logger.error(f"Failed to generate shake chart: {str(e)}", exc_info=True)
  1081. return None
  1082. def generate_zigzag_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  1083. """
  1084. Generate zigzag metric chart with orange background for zigzag events.
  1085. This version first saves data to CSV, then uses the CSV to generate the chart.
  1086. Args:
  1087. comfort_calculator: ComfortCalculator instance
  1088. output_dir: Output directory
  1089. Returns:
  1090. str: Chart file path, or None if generation fails
  1091. """
  1092. logger = LogManager().get_logger()
  1093. try:
  1094. # 获取数据
  1095. df = comfort_calculator.ego_df.copy()
  1096. zigzag_events = comfort_calculator.discomfort_df[
  1097. comfort_calculator.discomfort_df['type'] == 'zigzag'
  1098. ].copy()
  1099. if df.empty:
  1100. logger.warning("Cannot generate zigzag chart: empty data")
  1101. return None
  1102. # 生成时间戳
  1103. # 保存 CSV 数据(第一步)
  1104. csv_filename = os.path.join(output_dir, f"zigzag_data.csv")
  1105. df_csv = pd.DataFrame({
  1106. 'simTime': df['simTime'],
  1107. 'speedH': df['speedH'],
  1108. 'posH': df['posH'],
  1109. 'min_speedH_threshold': -2.3, # 可替换为动态阈值
  1110. 'max_speedH_threshold': 2.3
  1111. })
  1112. df_csv.to_csv(csv_filename, index=False)
  1113. logger.info(f"Zigzag data saved to: {csv_filename}")
  1114. # 第二步:从 CSV 读取(可验证保存数据无误)
  1115. df = pd.read_csv(csv_filename)
  1116. # 创建图表(第三步)
  1117. import matplotlib.pyplot as plt
  1118. plt.figure(figsize=(12, 8), constrained_layout=True)
  1119. # ===== 子图1:Yaw Rate =====
  1120. ax1 = plt.subplot(2, 1, 1)
  1121. ax1.plot(df['simTime'], df['speedH'], 'g-', label='Yaw Rate')
  1122. # 添加 speedH 上下限阈值线
  1123. ax1.axhline(y=2.3, color='m', linestyle='--', linewidth=1.2, label='Max Threshold (+2.3)')
  1124. ax1.axhline(y=-2.3, color='r', linestyle='--', linewidth=1.2, label='Min Threshold (-2.3)')
  1125. # 添加橙色背景:Zigzag Events
  1126. for idx, event in zigzag_events.iterrows():
  1127. label = 'Zigzag Event' if idx == 0 else None
  1128. ax1.axvspan(event['start_time'], event['end_time'],
  1129. alpha=0.3, color='orange', label=label)
  1130. ax1.set_xlabel('Time (s)')
  1131. ax1.set_ylabel('Angular Velocity (deg/s)')
  1132. ax1.set_title('Zigzag Event Detection - Yaw Rate')
  1133. ax1.grid(True)
  1134. ax1.legend(loc='upper left')
  1135. # ===== 子图2:Yaw Angle =====
  1136. ax2 = plt.subplot(2, 1, 2)
  1137. ax2.plot(df['simTime'], df['posH'], 'b-', label='Yaw')
  1138. # 添加橙色背景:Zigzag Events
  1139. for idx, event in zigzag_events.iterrows():
  1140. label = 'Zigzag Event' if idx == 0 else None
  1141. ax2.axvspan(event['start_time'], event['end_time'],
  1142. alpha=0.3, color='orange', label=label)
  1143. ax2.set_xlabel('Time (s)')
  1144. ax2.set_ylabel('Yaw (deg)')
  1145. ax2.set_title('Zigzag Event Detection - Yaw Angle')
  1146. ax2.grid(True)
  1147. ax2.legend(loc='upper left')
  1148. # 保存图像
  1149. chart_filename = os.path.join(output_dir, f"zigzag_chart.png")
  1150. plt.savefig(chart_filename, dpi=300)
  1151. plt.close()
  1152. logger.info(f"Zigzag chart saved to: {chart_filename}")
  1153. return csv_filename
  1154. except Exception as e:
  1155. logger.error(f"Failed to generate zigzag chart: {str(e)}", exc_info=True)
  1156. return None
  1157. def generate_cadence_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  1158. """
  1159. Generate cadence metric chart with orange background for cadence events.
  1160. This version first saves data to CSV, then uses the CSV to generate the chart.
  1161. Args:
  1162. comfort_calculator: ComfortCalculator instance
  1163. output_dir: Output directory
  1164. Returns:
  1165. str: Chart file path, or None if generation fails
  1166. """
  1167. logger = LogManager().get_logger()
  1168. try:
  1169. # 获取数据
  1170. df = comfort_calculator.ego_df.copy()
  1171. cadence_events = comfort_calculator.discomfort_df[comfort_calculator.discomfort_df['type'] == 'cadence'].copy()
  1172. if df.empty:
  1173. logger.warning("Cannot generate cadence chart: empty data")
  1174. return None
  1175. # 生成时间戳
  1176. # 保存 CSV 数据(第一步)
  1177. csv_filename = os.path.join(output_dir, f"cadence_data.csv")
  1178. df_csv = pd.DataFrame({
  1179. 'simTime': df['simTime'],
  1180. 'lon_acc': df['lon_acc'],
  1181. 'v': df['v'],
  1182. 'ip_acc': df.get('ip_acc', pd.Series([None] * len(df))),
  1183. 'ip_dec': df.get('ip_dec', pd.Series([None] * len(df)))
  1184. })
  1185. df_csv.to_csv(csv_filename, index=False)
  1186. logger.info(f"Cadence data saved to: {csv_filename}")
  1187. # 第二步:从 CSV 读取(可验证保存数据无误)
  1188. df = pd.read_csv(csv_filename)
  1189. # 创建图表(第三步)
  1190. import matplotlib.pyplot as plt
  1191. plt.figure(figsize=(12, 8), constrained_layout=True)
  1192. # 图 1:纵向加速度
  1193. ax1 = plt.subplot(2, 1, 1)
  1194. ax1.plot(df['simTime'], df['lon_acc'], 'b-', label='Longitudinal Acceleration')
  1195. if 'ip_acc' in df.columns and 'ip_dec' in df.columns:
  1196. ax1.plot(df['simTime'], df['ip_acc'], 'r--', label='Acceleration Threshold')
  1197. ax1.plot(df['simTime'], df['ip_dec'], 'g--', label='Deceleration Threshold')
  1198. # 添加橙色背景标识顿挫事件
  1199. for idx, event in cadence_events.iterrows():
  1200. label = 'Cadence Event' if idx == 0 else None
  1201. ax1.axvspan(event['start_time'], event['end_time'],
  1202. alpha=0.3, color='orange', label=label)
  1203. ax1.set_xlabel('Time (s)')
  1204. ax1.set_ylabel('Longitudinal Acceleration (m/s²)')
  1205. ax1.set_title('Cadence Event Detection - Longitudinal Acceleration')
  1206. ax1.grid(True)
  1207. ax1.legend()
  1208. # 图 2:速度
  1209. ax2 = plt.subplot(2, 1, 2)
  1210. ax2.plot(df['simTime'], df['v'], 'g-', label='Velocity')
  1211. # 添加橙色背景标识顿挫事件
  1212. for idx, event in cadence_events.iterrows():
  1213. label = 'Cadence Event' if idx == 0 else None
  1214. ax2.axvspan(event['start_time'], event['end_time'],
  1215. alpha=0.3, color='orange', label=label)
  1216. ax2.set_xlabel('Time (s)')
  1217. ax2.set_ylabel('Velocity (m/s)')
  1218. ax2.set_title('Cadence Event Detection - Vehicle Speed')
  1219. ax2.grid(True)
  1220. ax2.legend()
  1221. # 保存图像
  1222. chart_filename = os.path.join(output_dir, f"cadence_chart.png")
  1223. plt.savefig(chart_filename, dpi=300)
  1224. plt.close()
  1225. logger.info(f"Cadence chart saved to: {chart_filename}")
  1226. return chart_filename
  1227. except Exception as e:
  1228. logger.error(f"Failed to generate cadence chart: {str(e)}", exc_info=True)
  1229. return None
  1230. def generate_slam_brake_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  1231. """
  1232. Generate slam brake metric chart with orange background for slam brake events.
  1233. This version first saves data to CSV, then uses the CSV to generate the chart.
  1234. Args:
  1235. comfort_calculator: ComfortCalculator instance
  1236. output_dir: Output directory
  1237. Returns:
  1238. str: Chart file path, or None if generation fails
  1239. """
  1240. logger = LogManager().get_logger()
  1241. try:
  1242. # 获取数据
  1243. df = comfort_calculator.ego_df.copy()
  1244. slam_brake_events = comfort_calculator.discomfort_df[
  1245. comfort_calculator.discomfort_df['type'] == 'slam_brake'].copy()
  1246. if df.empty:
  1247. logger.warning("Cannot generate slam brake chart: empty data")
  1248. return None
  1249. # 生成时间戳
  1250. # 保存 CSV 数据(第一步)
  1251. csv_filename = os.path.join(output_dir, f"slam_brake_data.csv")
  1252. df_csv = pd.DataFrame({
  1253. 'simTime': df['simTime'],
  1254. 'lon_acc': df['lon_acc'],
  1255. 'v': df['v'],
  1256. 'min_threshold': df.get('ip_dec', pd.Series([None] * len(df))),
  1257. 'max_threshold': 0.0
  1258. })
  1259. df_csv.to_csv(csv_filename, index=False)
  1260. logger.info(f"Slam brake data saved to: {csv_filename}")
  1261. # 第二步:从 CSV 读取(可验证保存数据无误)
  1262. df = pd.read_csv(csv_filename)
  1263. # 创建图表(第三步)
  1264. plt.figure(figsize=(12, 8), constrained_layout=True)
  1265. # 图 1:纵向加速度
  1266. ax1 = plt.subplot(2, 1, 1)
  1267. ax1.plot(df['simTime'], df['lon_acc'], 'b-', label='Longitudinal Acceleration')
  1268. if 'min_threshold' in df.columns:
  1269. ax1.plot(df['simTime'], df['min_threshold'], 'r--', label='Deceleration Threshold')
  1270. # 添加橙色背景标识急刹车事件
  1271. for idx, event in slam_brake_events.iterrows():
  1272. label = 'Slam Brake Event' if idx == 0 else None
  1273. ax1.axvspan(event['start_time'], event['end_time'],
  1274. alpha=0.3, color='orange', label=label)
  1275. ax1.set_xlabel('Time (s)')
  1276. ax1.set_ylabel('Longitudinal Acceleration (m/s²)')
  1277. ax1.set_title('Slam Brake Event Detection - Longitudinal Acceleration')
  1278. ax1.grid(True)
  1279. ax1.legend()
  1280. # 图 2:速度
  1281. ax2 = plt.subplot(2, 1, 2)
  1282. ax2.plot(df['simTime'], df['v'], 'g-', label='Velocity')
  1283. # 添加橙色背景标识急刹车事件
  1284. for idx, event in slam_brake_events.iterrows():
  1285. label = 'Slam Brake Event' if idx == 0 else None
  1286. ax2.axvspan(event['start_time'], event['end_time'],
  1287. alpha=0.3, color='orange', label=label)
  1288. ax2.set_xlabel('Time (s)')
  1289. ax2.set_ylabel('Velocity (m/s)')
  1290. ax2.set_title('Slam Brake Event Detection - Vehicle Speed')
  1291. ax2.grid(True)
  1292. ax2.legend()
  1293. # 保存图像
  1294. chart_filename = os.path.join(output_dir, f"slam_brake_chart.png")
  1295. plt.savefig(chart_filename, dpi=300)
  1296. plt.close()
  1297. logger.info(f"Slam brake chart saved to: {chart_filename}")
  1298. return chart_filename
  1299. except Exception as e:
  1300. logger.error(f"Failed to generate slam brake chart: {str(e)}", exc_info=True)
  1301. return None
  1302. def generate_slam_accelerate_chart(comfort_calculator, output_dir: str) -> Optional[str]:
  1303. """
  1304. Generate slam accelerate metric chart with orange background for slam accelerate events.
  1305. This version first saves data to CSV, then uses the CSV to generate the chart.
  1306. Args:
  1307. comfort_calculator: ComfortCalculator instance
  1308. output_dir: Output directory
  1309. Returns:
  1310. str: Chart file path, or None if generation fails
  1311. """
  1312. logger = LogManager().get_logger()
  1313. try:
  1314. # 获取数据
  1315. df = comfort_calculator.ego_df.copy()
  1316. slam_accel_events = comfort_calculator.discomfort_df[
  1317. (comfort_calculator.discomfort_df['type'] == 'slam_accel')
  1318. ].copy()
  1319. if df.empty:
  1320. logger.warning("Cannot generate slam accelerate chart: empty data")
  1321. return None
  1322. # 生成时间戳
  1323. # 保存 CSV 数据(第一步)
  1324. csv_filename = os.path.join(output_dir, f"slam_accel_data.csv")
  1325. # 获取加速度阈值(如果存在)
  1326. accel_threshold = df.get('ip_acc', pd.Series([None] * len(df)))
  1327. df_csv = pd.DataFrame({
  1328. 'simTime': df['simTime'],
  1329. 'lon_acc': df['lon_acc'],
  1330. 'v': df['v'],
  1331. 'min_threshold': 0.0, # 加速度最小阈值设为0
  1332. 'max_threshold': accel_threshold # 急加速阈值
  1333. })
  1334. df_csv.to_csv(csv_filename, index=False)
  1335. logger.info(f"Slam accelerate data saved to: {csv_filename}")
  1336. # 第二步:从 CSV 读取(可验证保存数据无误)
  1337. df = pd.read_csv(csv_filename)
  1338. # 创建图表(第三步)
  1339. plt.figure(figsize=(12, 8), constrained_layout=True)
  1340. # 图 1:纵向加速度
  1341. ax1 = plt.subplot(2, 1, 1)
  1342. ax1.plot(df['simTime'], df['lon_acc'], 'b-', label='Longitudinal Acceleration')
  1343. # 添加加速度阈值线
  1344. if 'max_threshold' in df.columns and not df['max_threshold'].isnull().all():
  1345. ax1.plot(df['simTime'], df['max_threshold'], 'r--', label='Acceleration Threshold')
  1346. # 添加橙色背景标识急加速事件
  1347. for idx, event in slam_accel_events.iterrows():
  1348. label = 'Slam Accelerate Event' if idx == 0 else None
  1349. ax1.axvspan(event['start_time'], event['end_time'],
  1350. alpha=0.3, color='orange', label=label)
  1351. ax1.set_xlabel('Time (s)')
  1352. ax1.set_ylabel('Acceleration (m/s²)')
  1353. ax1.set_title('Slam Accelerate Event Detection - Longitudinal Acceleration')
  1354. ax1.grid(True)
  1355. ax1.legend()
  1356. # 图 2:速度
  1357. ax2 = plt.subplot(2, 1, 2)
  1358. ax2.plot(df['simTime'], df['v'], 'g-', label='Velocity')
  1359. # 添加橙色背景标识急加速事件
  1360. for idx, event in slam_accel_events.iterrows():
  1361. label = 'Slam Accelerate Event' if idx == 0 else None
  1362. ax2.axvspan(event['start_time'], event['end_time'],
  1363. alpha=0.3, color='orange', label=label)
  1364. ax2.set_xlabel('Time (s)')
  1365. ax2.set_ylabel('Velocity (m/s)')
  1366. ax2.set_title('Slam Accelerate Event Detection - Vehicle Speed')
  1367. ax2.grid(True)
  1368. ax2.legend()
  1369. # 保存图像
  1370. chart_filename = os.path.join(output_dir, f"slam_accel_chart.png")
  1371. plt.savefig(chart_filename, dpi=300)
  1372. plt.close()
  1373. logger.info(f"Slam accelerate chart saved to: {chart_filename}")
  1374. return chart_filename
  1375. except Exception as e:
  1376. logger.error(f"Failed to generate slam accelerate chart: {str(e)}", exc_info=True)
  1377. return None
  1378. def get_metric_thresholds(calculator, metric_name: str) -> dict:
  1379. """
  1380. 从配置文件中获取指标的阈值
  1381. Args:
  1382. calculator: Calculator instance (FunctionCalculator, SafetyCalculator, ComfortCalculator, EfficientCalculator, TrafficCalculator)
  1383. metric_name: 指标名称
  1384. Returns:
  1385. dict: 包含min和max阈值的字典
  1386. """
  1387. logger = LogManager().get_logger()
  1388. thresholds = {"min": None, "max": None}
  1389. try:
  1390. # 根据计算器类型获取配置
  1391. if hasattr(calculator, 'data_processed'):
  1392. # 检查安全性指标配置
  1393. if hasattr(calculator.data_processed,
  1394. 'safety_config') and 'safety' in calculator.data_processed.safety_config:
  1395. config = calculator.data_processed.safety_config['safety']
  1396. metric_type = 'safety'
  1397. # 检查舒适性指标配置
  1398. elif hasattr(calculator.data_processed,
  1399. 'comfort_config') and 'comfort' in calculator.data_processed.comfort_config:
  1400. config = calculator.data_processed.comfort_config['comfort']
  1401. metric_type = 'comfort'
  1402. # 检查功能性指标配置
  1403. elif hasattr(calculator.data_processed,
  1404. 'function_config') and 'function' in calculator.data_processed.function_config:
  1405. config = calculator.data_processed.function_config['function']
  1406. metric_type = 'function'
  1407. # 检查高效性指标配置
  1408. elif hasattr(calculator.data_processed,
  1409. 'efficient_config') and 'efficient' in calculator.data_processed.efficient_config:
  1410. config = calculator.data_processed.efficient_config['efficient']
  1411. metric_type = 'efficient'
  1412. # 检查交通性指标配置
  1413. elif hasattr(calculator.data_processed,
  1414. 'traffic_config') and 'traffic' in calculator.data_processed.traffic_config:
  1415. config = calculator.data_processed.traffic_config['traffic']
  1416. metric_type = 'traffic'
  1417. else:
  1418. # 直接检查calculator是否有function_config属性(针对FunctionCalculator)
  1419. if hasattr(calculator, 'function_config') and 'function' in calculator.function_config:
  1420. config = calculator.function_config['function']
  1421. metric_type = 'function'
  1422. else:
  1423. logger.warning(f"无法找到{metric_name}的配置信息")
  1424. return thresholds
  1425. else:
  1426. # 直接检查calculator是否有function_config属性(针对FunctionCalculator)
  1427. if hasattr(calculator, 'function_config') and 'function' in calculator.function_config:
  1428. config = calculator.function_config['function']
  1429. metric_type = 'function'
  1430. else:
  1431. logger.warning(f"计算器没有data_processed属性或function_config属性")
  1432. return thresholds
  1433. # 递归查找指标配置
  1434. def find_metric_config(node, target_name):
  1435. if isinstance(node, dict):
  1436. if 'name' in node and node['name'].lower() == target_name.lower() and 'min' in node and 'max' in node:
  1437. return node
  1438. for key, value in node.items():
  1439. result = find_metric_config(value, target_name)
  1440. if result:
  1441. return result
  1442. return None
  1443. # 查找指标配置
  1444. metric_config = find_metric_config(config, metric_name)
  1445. if metric_config:
  1446. thresholds["min"] = metric_config.get("min")
  1447. thresholds["max"] = metric_config.get("max")
  1448. logger.info(f"找到{metric_name}的阈值: min={thresholds['min']}, max={thresholds['max']}")
  1449. else:
  1450. logger.warning(f"在{metric_type}配置中未找到{metric_name}的阈值信息")
  1451. except Exception as e:
  1452. logger.error(f"获取{metric_name}阈值时出错: {str(e)}", exc_info=True)
  1453. return thresholds
  1454. def generate_safety_chart_data(safety_calculator, metric_name: str, output_dir: Optional[str] = None) -> Optional[str]:
  1455. """
  1456. Generate chart data for safety metrics
  1457. Args:
  1458. safety_calculator: SafetyCalculator instance
  1459. metric_name: Metric name
  1460. output_dir: Output directory
  1461. Returns:
  1462. str: Chart file path, or None if generation fails
  1463. """
  1464. logger = LogManager().get_logger()
  1465. try:
  1466. # 确保输出目录存在
  1467. if output_dir:
  1468. os.makedirs(output_dir, exist_ok=True)
  1469. else:
  1470. output_dir = os.getcwd()
  1471. # 根据指标名称选择不同的图表生成方法
  1472. if metric_name.lower() == 'ttc':
  1473. return generate_ttc_chart(safety_calculator, output_dir)
  1474. elif metric_name.lower() == 'mttc':
  1475. return generate_mttc_chart(safety_calculator, output_dir)
  1476. elif metric_name.lower() == 'thw':
  1477. return generate_thw_chart(safety_calculator, output_dir)
  1478. elif metric_name.lower() == 'lonsd':
  1479. return generate_lonsd_chart(safety_calculator, output_dir)
  1480. elif metric_name.lower() == 'latsd':
  1481. return generate_latsd_chart(safety_calculator, output_dir)
  1482. elif metric_name.lower() == 'btn':
  1483. return generate_btn_chart(safety_calculator, output_dir)
  1484. elif metric_name.lower() == 'collisionrisk':
  1485. return generate_collision_risk_chart(safety_calculator, output_dir)
  1486. elif metric_name.lower() == 'collisionseverity':
  1487. return generate_collision_severity_chart(safety_calculator, output_dir)
  1488. else:
  1489. logger.warning(f"Chart generation not implemented for metric [{metric_name}]")
  1490. return None
  1491. except Exception as e:
  1492. logger.error(f"Failed to generate chart data: {str(e)}", exc_info=True)
  1493. return None
  1494. def generate_ttc_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1495. """
  1496. Generate TTC metric chart with orange background for unsafe events.
  1497. This version first saves data to CSV, then uses the CSV to generate the chart.
  1498. Args:
  1499. safety_calculator: SafetyCalculator instance
  1500. output_dir: Output directory
  1501. Returns:
  1502. str: Chart file path, or None if generation fails
  1503. """
  1504. logger = LogManager().get_logger()
  1505. try:
  1506. # 获取数据
  1507. ttc_data = safety_calculator.ttc_data
  1508. if not ttc_data:
  1509. logger.warning("Cannot generate TTC chart: empty data")
  1510. return None
  1511. # 创建DataFrame
  1512. df = pd.DataFrame(ttc_data)
  1513. # 获取阈值
  1514. thresholds = get_metric_thresholds(safety_calculator, 'TTC')
  1515. min_threshold = thresholds.get('min')
  1516. max_threshold = thresholds.get('max')
  1517. # 生成时间戳
  1518. # 保存 CSV 数据(第一步)
  1519. csv_filename = os.path.join(output_dir, f"ttc_data.csv")
  1520. df_csv = pd.DataFrame({
  1521. 'simTime': df['simTime'],
  1522. 'simFrame': df['simFrame'],
  1523. 'TTC': df['TTC'],
  1524. 'min_threshold': min_threshold,
  1525. 'max_threshold': max_threshold
  1526. })
  1527. df_csv.to_csv(csv_filename, index=False)
  1528. logger.info(f"TTC data saved to: {csv_filename}")
  1529. # 第二步:从 CSV 读取(可验证保存数据无误)
  1530. df = pd.read_csv(csv_filename)
  1531. # 检测超阈值事件
  1532. unsafe_events = []
  1533. if min_threshold is not None:
  1534. # 对于TTC,小于最小阈值视为不安全
  1535. unsafe_condition = df['TTC'] < min_threshold
  1536. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1537. for _, group in df[unsafe_condition].groupby(event_groups):
  1538. if len(group) >= 2: # 至少2帧才算一次事件
  1539. start_time = group['simTime'].iloc[0]
  1540. end_time = group['simTime'].iloc[-1]
  1541. duration = end_time - start_time
  1542. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1543. unsafe_events.append({
  1544. 'start_time': start_time,
  1545. 'end_time': end_time,
  1546. 'start_frame': group['simFrame'].iloc[0],
  1547. 'end_frame': group['simFrame'].iloc[-1],
  1548. 'duration': duration,
  1549. 'min_ttc': group['TTC'].min()
  1550. })
  1551. # 创建图表(第三步)
  1552. plt.figure(figsize=(12, 8))
  1553. plt.plot(df['simTime'], df['TTC'], 'b-', label='TTC')
  1554. # 添加阈值线
  1555. if min_threshold is not None:
  1556. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  1557. if max_threshold is not None:
  1558. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold})')
  1559. # 添加橙色背景标识不安全事件
  1560. for idx, event in enumerate(unsafe_events):
  1561. label = 'Unsafe TTC Event' if idx == 0 else None
  1562. plt.axvspan(event['start_time'], event['end_time'],
  1563. alpha=0.3, color='orange', label=label)
  1564. plt.xlabel('Time (s)')
  1565. plt.ylabel('TTC (s)')
  1566. plt.title('Time To Collision (TTC) Trend')
  1567. plt.grid(True)
  1568. plt.legend()
  1569. # 保存图像
  1570. chart_filename = os.path.join(output_dir, f"ttc_chart.png")
  1571. plt.savefig(chart_filename, dpi=300)
  1572. plt.close()
  1573. # 记录不安全事件信息
  1574. if unsafe_events:
  1575. logger.info(f"检测到 {len(unsafe_events)} 个TTC不安全事件")
  1576. for i, event in enumerate(unsafe_events):
  1577. logger.info(
  1578. f"TTC不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最小TTC={event['min_ttc']:.2f}s")
  1579. logger.info(f"TTC chart saved to: {chart_filename}")
  1580. return chart_filename
  1581. except Exception as e:
  1582. logger.error(f"Failed to generate TTC chart: {str(e)}", exc_info=True)
  1583. return None
  1584. def generate_mttc_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1585. """
  1586. Generate MTTC metric chart with orange background for unsafe events
  1587. Args:
  1588. safety_calculator: SafetyCalculator instance
  1589. output_dir: Output directory
  1590. Returns:
  1591. str: Chart file path, or None if generation fails
  1592. """
  1593. logger = LogManager().get_logger()
  1594. try:
  1595. # 获取数据
  1596. mttc_data = safety_calculator.mttc_data
  1597. if not mttc_data:
  1598. logger.warning("Cannot generate MTTC chart: empty data")
  1599. return None
  1600. # 创建DataFrame
  1601. df = pd.DataFrame(mttc_data)
  1602. # 获取阈值
  1603. thresholds = get_metric_thresholds(safety_calculator, 'MTTC')
  1604. min_threshold = thresholds.get('min')
  1605. max_threshold = thresholds.get('max')
  1606. # 检测超阈值事件
  1607. unsafe_events = []
  1608. if min_threshold is not None:
  1609. # 对于MTTC,小于最小阈值视为不安全
  1610. unsafe_condition = df['MTTC'] < min_threshold
  1611. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1612. for _, group in df[unsafe_condition].groupby(event_groups):
  1613. if len(group) >= 2: # 至少2帧才算一次事件
  1614. start_time = group['simTime'].iloc[0]
  1615. end_time = group['simTime'].iloc[-1]
  1616. duration = end_time - start_time
  1617. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1618. unsafe_events.append({
  1619. 'start_time': start_time,
  1620. 'end_time': end_time,
  1621. 'start_frame': group['simFrame'].iloc[0],
  1622. 'end_frame': group['simFrame'].iloc[-1],
  1623. 'duration': duration,
  1624. 'min_mttc': group['MTTC'].min()
  1625. })
  1626. # 创建图表
  1627. plt.figure(figsize=(12, 6))
  1628. plt.plot(df['simTime'], df['MTTC'], 'g-', label='MTTC')
  1629. # 添加阈值线
  1630. if min_threshold is not None:
  1631. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  1632. if max_threshold is not None:
  1633. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold})')
  1634. # 添加橙色背景标识不安全事件
  1635. for idx, event in enumerate(unsafe_events):
  1636. label = 'Unsafe MTTC Event' if idx == 0 else None
  1637. plt.axvspan(event['start_time'], event['end_time'],
  1638. alpha=0.3, color='orange', label=label)
  1639. plt.xlabel('Time (s)')
  1640. plt.ylabel('MTTC (s)')
  1641. plt.title('Modified Time To Collision (MTTC) Trend')
  1642. plt.grid(True)
  1643. plt.legend()
  1644. # 保存图表
  1645. chart_filename = os.path.join(output_dir, f"mttc_chart.png")
  1646. plt.savefig(chart_filename, dpi=300)
  1647. plt.close()
  1648. # 保存CSV数据,包含阈值信息
  1649. csv_filename = os.path.join(output_dir, f"mttc_data.csv")
  1650. df_csv = df.copy()
  1651. df_csv['min_threshold'] = min_threshold
  1652. df_csv['max_threshold'] = max_threshold
  1653. df_csv.to_csv(csv_filename, index=False)
  1654. # 记录不安全事件信息
  1655. if unsafe_events:
  1656. logger.info(f"检测到 {len(unsafe_events)} 个MTTC不安全事件")
  1657. for i, event in enumerate(unsafe_events):
  1658. logger.info(
  1659. f"MTTC不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最小MTTC={event['min_mttc']:.2f}s")
  1660. logger.info(f"MTTC chart saved to: {chart_filename}")
  1661. logger.info(f"MTTC data saved to: {csv_filename}")
  1662. return chart_filename
  1663. except Exception as e:
  1664. logger.error(f"Failed to generate MTTC chart: {str(e)}", exc_info=True)
  1665. return None
  1666. def generate_thw_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1667. """
  1668. Generate THW metric chart with orange background for unsafe events
  1669. Args:
  1670. safety_calculator: SafetyCalculator instance
  1671. output_dir: Output directory
  1672. Returns:
  1673. str: Chart file path, or None if generation fails
  1674. """
  1675. logger = LogManager().get_logger()
  1676. try:
  1677. # 获取数据
  1678. thw_data = safety_calculator.thw_data
  1679. if not thw_data:
  1680. logger.warning("Cannot generate THW chart: empty data")
  1681. return None
  1682. # 创建DataFrame
  1683. df = pd.DataFrame(thw_data)
  1684. # 获取阈值
  1685. thresholds = get_metric_thresholds(safety_calculator, 'THW')
  1686. min_threshold = thresholds.get('min')
  1687. max_threshold = thresholds.get('max')
  1688. # 检测超阈值事件
  1689. unsafe_events = []
  1690. if min_threshold is not None:
  1691. # 对于THW,小于最小阈值视为不安全
  1692. unsafe_condition = df['THW'] < min_threshold
  1693. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1694. for _, group in df[unsafe_condition].groupby(event_groups):
  1695. if len(group) >= 2: # 至少2帧才算一次事件
  1696. start_time = group['simTime'].iloc[0]
  1697. end_time = group['simTime'].iloc[-1]
  1698. duration = end_time - start_time
  1699. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1700. unsafe_events.append({
  1701. 'start_time': start_time,
  1702. 'end_time': end_time,
  1703. 'start_frame': group['simFrame'].iloc[0],
  1704. 'end_frame': group['simFrame'].iloc[-1],
  1705. 'duration': duration,
  1706. 'min_thw': group['THW'].min()
  1707. })
  1708. # 创建图表
  1709. plt.figure(figsize=(12, 10))
  1710. plt.plot(df['simTime'], df['THW'], 'c-', label='THW')
  1711. # 添加阈值线
  1712. if min_threshold is not None:
  1713. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}s)')
  1714. if max_threshold is not None:
  1715. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold})')
  1716. # 添加橙色背景标识不安全事件
  1717. for idx, event in enumerate(unsafe_events):
  1718. label = 'Unsafe THW Event' if idx == 0 else None
  1719. plt.axvspan(event['start_time'], event['end_time'],
  1720. alpha=0.3, color='orange', label=label)
  1721. plt.xlabel('Time (s)')
  1722. plt.ylabel('THW (s)')
  1723. plt.title('Time Headway (THW) Trend')
  1724. plt.grid(True)
  1725. plt.legend()
  1726. # 保存图表
  1727. chart_filename = os.path.join(output_dir, f"thw_chart.png")
  1728. plt.savefig(chart_filename, dpi=300)
  1729. plt.close()
  1730. # 保存CSV数据,包含阈值信息
  1731. csv_filename = os.path.join(output_dir, f"thw_data.csv")
  1732. df_csv = df.copy()
  1733. df_csv['min_threshold'] = min_threshold
  1734. df_csv['max_threshold'] = max_threshold
  1735. df_csv.to_csv(csv_filename, index=False)
  1736. # 记录不安全事件信息
  1737. if unsafe_events:
  1738. logger.info(f"检测到 {len(unsafe_events)} 个THW不安全事件")
  1739. for i, event in enumerate(unsafe_events):
  1740. logger.info(
  1741. f"THW不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最小THW={event['min_thw']:.2f}s")
  1742. logger.info(f"THW chart saved to: {chart_filename}")
  1743. logger.info(f"THW data saved to: {csv_filename}")
  1744. return chart_filename
  1745. except Exception as e:
  1746. logger.error(f"Failed to generate THW chart: {str(e)}", exc_info=True)
  1747. return None
  1748. def generate_lonsd_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1749. """
  1750. Generate Longitudinal Safe Distance metric chart
  1751. Args:
  1752. safety_calculator: SafetyCalculator instance
  1753. output_dir: Output directory
  1754. Returns:
  1755. str: Chart file path, or None if generation fails
  1756. """
  1757. logger = LogManager().get_logger()
  1758. try:
  1759. # 获取数据
  1760. lonsd_data = safety_calculator.lonsd_data
  1761. if not lonsd_data:
  1762. logger.warning("Cannot generate Longitudinal Safe Distance chart: empty data")
  1763. return None
  1764. # 创建DataFrame
  1765. df = pd.DataFrame(lonsd_data)
  1766. # 获取阈值
  1767. thresholds = get_metric_thresholds(safety_calculator, 'LonSD')
  1768. min_threshold = thresholds.get('min')
  1769. max_threshold = thresholds.get('max')
  1770. # 创建图表
  1771. plt.figure(figsize=(12, 6))
  1772. plt.plot(df['simTime'], df['LonSD'], 'm-', label='Longitudinal Safe Distance')
  1773. # 添加阈值线
  1774. if min_threshold is not None:
  1775. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  1776. if max_threshold is not None:
  1777. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  1778. plt.xlabel('Time (s)')
  1779. plt.ylabel('Distance (m)')
  1780. plt.title('Longitudinal Safe Distance (LonSD) Trend')
  1781. plt.grid(True)
  1782. plt.legend()
  1783. # 保存图表
  1784. chart_filename = os.path.join(output_dir, f"lonsd_chart.png")
  1785. plt.savefig(chart_filename, dpi=300)
  1786. plt.close()
  1787. # 保存CSV数据,包含阈值信息
  1788. csv_filename = os.path.join(output_dir, f"lonsd_data.csv")
  1789. df_csv = df.copy()
  1790. df_csv['min_threshold'] = min_threshold
  1791. df_csv['max_threshold'] = max_threshold
  1792. df_csv.to_csv(csv_filename, index=False)
  1793. logger.info(f"Longitudinal Safe Distance chart saved to: {chart_filename}")
  1794. logger.info(f"Longitudinal Safe Distance data saved to: {csv_filename}")
  1795. return chart_filename
  1796. except Exception as e:
  1797. logger.error(f"Failed to generate Longitudinal Safe Distance chart: {str(e)}", exc_info=True)
  1798. return None
  1799. def generate_latsd_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1800. """
  1801. Generate Lateral Safe Distance metric chart with orange background for unsafe events
  1802. Args:
  1803. safety_calculator: SafetyCalculator instance
  1804. output_dir: Output directory
  1805. Returns:
  1806. str: Chart file path, or None if generation fails
  1807. """
  1808. logger = LogManager().get_logger()
  1809. try:
  1810. # 获取数据
  1811. latsd_data = safety_calculator.latsd_data
  1812. if not latsd_data:
  1813. logger.warning("Cannot generate Lateral Safe Distance chart: empty data")
  1814. return None
  1815. # 创建DataFrame
  1816. df = pd.DataFrame(latsd_data)
  1817. # 获取阈值
  1818. thresholds = get_metric_thresholds(safety_calculator, 'LatSD')
  1819. min_threshold = thresholds.get('min')
  1820. max_threshold = thresholds.get('max')
  1821. # 检测超阈值事件
  1822. unsafe_events = []
  1823. if min_threshold is not None:
  1824. # 对于LatSD,小于最小阈值视为不安全
  1825. unsafe_condition = df['LatSD'] < min_threshold
  1826. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1827. for _, group in df[unsafe_condition].groupby(event_groups):
  1828. if len(group) >= 2: # 至少2帧才算一次事件
  1829. start_time = group['simTime'].iloc[0]
  1830. end_time = group['simTime'].iloc[-1]
  1831. duration = end_time - start_time
  1832. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1833. unsafe_events.append({
  1834. 'start_time': start_time,
  1835. 'end_time': end_time,
  1836. 'start_frame': group['simFrame'].iloc[0],
  1837. 'end_frame': group['simFrame'].iloc[-1],
  1838. 'duration': duration,
  1839. 'min_latsd': group['LatSD'].min()
  1840. })
  1841. # 创建图表
  1842. plt.figure(figsize=(12, 6))
  1843. plt.plot(df['simTime'], df['LatSD'], 'y-', label='Lateral Safe Distance')
  1844. # 添加阈值线
  1845. if min_threshold is not None:
  1846. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}m)')
  1847. if max_threshold is not None:
  1848. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold}m)')
  1849. # 添加橙色背景标识不安全事件
  1850. for idx, event in enumerate(unsafe_events):
  1851. label = 'Unsafe LatSD Event' if idx == 0 else None
  1852. plt.axvspan(event['start_time'], event['end_time'],
  1853. alpha=0.3, color='orange', label=label)
  1854. plt.xlabel('Time (s)')
  1855. plt.ylabel('Distance (m)')
  1856. plt.title('Lateral Safe Distance (LatSD) Trend')
  1857. plt.grid(True)
  1858. plt.legend()
  1859. # 保存图表
  1860. chart_filename = os.path.join(output_dir, f"latsd_chart.png")
  1861. plt.savefig(chart_filename, dpi=300)
  1862. plt.close()
  1863. # 保存CSV数据,包含阈值信息
  1864. csv_filename = os.path.join(output_dir, f"latsd_data.csv")
  1865. df_csv = df.copy()
  1866. df_csv['min_threshold'] = min_threshold
  1867. df_csv['max_threshold'] = max_threshold
  1868. df_csv.to_csv(csv_filename, index=False)
  1869. # 记录不安全事件信息
  1870. if unsafe_events:
  1871. logger.info(f"检测到 {len(unsafe_events)} 个LatSD不安全事件")
  1872. for i, event in enumerate(unsafe_events):
  1873. logger.info(
  1874. f"LatSD不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最小LatSD={event['min_latsd']:.2f}m")
  1875. logger.info(f"Lateral Safe Distance chart saved to: {chart_filename}")
  1876. logger.info(f"Lateral Safe Distance data saved to: {csv_filename}")
  1877. return chart_filename
  1878. except Exception as e:
  1879. logger.error(f"Failed to generate Lateral Safe Distance chart: {str(e)}", exc_info=True)
  1880. return None
  1881. def generate_btn_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1882. """
  1883. Generate Brake Threat Number metric chart with orange background for unsafe events
  1884. Args:
  1885. safety_calculator: SafetyCalculator instance
  1886. output_dir: Output directory
  1887. Returns:
  1888. str: Chart file path, or None if generation fails
  1889. """
  1890. logger = LogManager().get_logger()
  1891. try:
  1892. # 获取数据
  1893. btn_data = safety_calculator.btn_data
  1894. if not btn_data:
  1895. logger.warning("Cannot generate Brake Threat Number chart: empty data")
  1896. return None
  1897. # 创建DataFrame
  1898. df = pd.DataFrame(btn_data)
  1899. # 获取阈值
  1900. thresholds = get_metric_thresholds(safety_calculator, 'BTN')
  1901. min_threshold = thresholds.get('min')
  1902. max_threshold = thresholds.get('max')
  1903. # 检测超阈值事件
  1904. unsafe_events = []
  1905. if max_threshold is not None:
  1906. # 对于BTN,大于最大阈值视为不安全
  1907. unsafe_condition = df['BTN'] > max_threshold
  1908. event_groups = (unsafe_condition != unsafe_condition.shift()).cumsum()
  1909. for _, group in df[unsafe_condition].groupby(event_groups):
  1910. if len(group) >= 2: # 至少2帧才算一次事件
  1911. start_time = group['simTime'].iloc[0]
  1912. end_time = group['simTime'].iloc[-1]
  1913. duration = end_time - start_time
  1914. if duration >= 0.1: # 只记录持续时间超过0.1秒的事件
  1915. unsafe_events.append({
  1916. 'start_time': start_time,
  1917. 'end_time': end_time,
  1918. 'start_frame': group['simFrame'].iloc[0],
  1919. 'end_frame': group['simFrame'].iloc[-1],
  1920. 'duration': duration,
  1921. 'max_btn': group['BTN'].max()
  1922. })
  1923. # 创建图表
  1924. plt.figure(figsize=(12, 6))
  1925. plt.plot(df['simTime'], df['BTN'], 'r-', label='Brake Threat Number')
  1926. # 添加阈值线
  1927. if min_threshold is not None:
  1928. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold})')
  1929. if max_threshold is not None:
  1930. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold})')
  1931. # 添加橙色背景标识不安全事件
  1932. for idx, event in enumerate(unsafe_events):
  1933. label = 'Unsafe BTN Event' if idx == 0 else None
  1934. plt.axvspan(event['start_time'], event['end_time'],
  1935. alpha=0.3, color='orange', label=label)
  1936. plt.xlabel('Time (s)')
  1937. plt.ylabel('BTN')
  1938. plt.title('Brake Threat Number (BTN) Trend')
  1939. plt.grid(True)
  1940. plt.legend()
  1941. # 保存图表
  1942. chart_filename = os.path.join(output_dir, f"btn_chart.png")
  1943. plt.savefig(chart_filename, dpi=300)
  1944. plt.close()
  1945. # 保存CSV数据,包含阈值信息
  1946. csv_filename = os.path.join(output_dir, f"btn_data.csv")
  1947. df_csv = df.copy()
  1948. df_csv['min_threshold'] = min_threshold
  1949. df_csv['max_threshold'] = max_threshold
  1950. df_csv.to_csv(csv_filename, index=False)
  1951. # 记录不安全事件信息
  1952. if unsafe_events:
  1953. logger.info(f"检测到 {len(unsafe_events)} 个BTN不安全事件")
  1954. for i, event in enumerate(unsafe_events):
  1955. logger.info(
  1956. f"BTN不安全事件 #{i + 1}: 开始时间={event['start_time']:.2f}s, 结束时间={event['end_time']:.2f}s, 持续时间={event['duration']:.2f}s, 最大BTN={event['max_btn']:.2f}")
  1957. logger.info(f"Brake Threat Number chart saved to: {chart_filename}")
  1958. logger.info(f"Brake Threat Number data saved to: {csv_filename}")
  1959. return chart_filename
  1960. except Exception as e:
  1961. logger.error(f"Failed to generate Brake Threat Number chart: {str(e)}", exc_info=True)
  1962. return None
  1963. def generate_collision_risk_chart(safety_calculator, output_dir: str) -> Optional[str]:
  1964. """
  1965. Generate Collision Risk metric chart
  1966. Args:
  1967. safety_calculator: SafetyCalculator instance
  1968. output_dir: Output directory
  1969. Returns:
  1970. str: Chart file path, or None if generation fails
  1971. """
  1972. logger = LogManager().get_logger()
  1973. try:
  1974. # 获取数据
  1975. risk_data = safety_calculator.collision_risk_data
  1976. if not risk_data:
  1977. logger.warning("Cannot generate Collision Risk chart: empty data")
  1978. return None
  1979. # 创建DataFrame
  1980. df = pd.DataFrame(risk_data)
  1981. # 获取阈值
  1982. thresholds = get_metric_thresholds(safety_calculator, 'collisionRisk')
  1983. min_threshold = thresholds.get('min')
  1984. max_threshold = thresholds.get('max')
  1985. # 创建图表
  1986. plt.figure(figsize=(12, 6))
  1987. plt.plot(df['simTime'], df['collisionRisk'], 'r-', label='Collision Risk')
  1988. # 添加阈值线
  1989. if min_threshold is not None:
  1990. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}%)')
  1991. if max_threshold is not None:
  1992. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold}%)')
  1993. plt.xlabel('Time (s)')
  1994. plt.ylabel('Risk Value (%)')
  1995. plt.title('Collision Risk (collisionRisk) Trend')
  1996. plt.grid(True)
  1997. plt.legend()
  1998. # 保存图表
  1999. chart_filename = os.path.join(output_dir, f"collision_risk_chart.png")
  2000. plt.savefig(chart_filename, dpi=300)
  2001. plt.close()
  2002. # 保存CSV数据,包含阈值信息
  2003. csv_filename = os.path.join(output_dir, f"collisionrisk_data.csv")
  2004. df_csv = df.copy()
  2005. df_csv['min_threshold'] = min_threshold
  2006. df_csv['max_threshold'] = max_threshold
  2007. df_csv.to_csv(csv_filename, index=False)
  2008. logger.info(f"Collision Risk chart saved to: {chart_filename}")
  2009. logger.info(f"Collision Risk data saved to: {csv_filename}")
  2010. return chart_filename
  2011. except Exception as e:
  2012. logger.error(f"Failed to generate Collision Risk chart: {str(e)}", exc_info=True)
  2013. return None
  2014. def generate_collision_severity_chart(safety_calculator, output_dir: str) -> Optional[str]:
  2015. """
  2016. Generate Collision Severity metric chart
  2017. Args:
  2018. safety_calculator: SafetyCalculator instance
  2019. output_dir: Output directory
  2020. Returns:
  2021. str: Chart file path, or None if generation fails
  2022. """
  2023. logger = LogManager().get_logger()
  2024. try:
  2025. # 获取数据
  2026. severity_data = safety_calculator.collision_severity_data
  2027. if not severity_data:
  2028. logger.warning("Cannot generate Collision Severity chart: empty data")
  2029. return None
  2030. # 创建DataFrame
  2031. df = pd.DataFrame(severity_data)
  2032. # 获取阈值
  2033. thresholds = get_metric_thresholds(safety_calculator, 'collisionSeverity')
  2034. min_threshold = thresholds.get('min')
  2035. max_threshold = thresholds.get('max')
  2036. # 创建图表
  2037. plt.figure(figsize=(12, 6))
  2038. plt.plot(df['simTime'], df['collisionSeverity'], 'r-', label='Collision Severity')
  2039. # 添加阈值线
  2040. if min_threshold is not None:
  2041. plt.axhline(y=min_threshold, color='r', linestyle='--', label=f'Min Threshold ({min_threshold}%)')
  2042. if max_threshold is not None:
  2043. plt.axhline(y=max_threshold, color='g', linestyle='--', label=f'Max Threshold ({max_threshold}%)')
  2044. plt.xlabel('Time (s)')
  2045. plt.ylabel('Severity (%)')
  2046. plt.title('Collision Severity (collisionSeverity) Trend')
  2047. plt.grid(True)
  2048. plt.legend()
  2049. # 保存图表
  2050. chart_filename = os.path.join(output_dir, f"collision_severity_chart.png")
  2051. plt.savefig(chart_filename, dpi=300)
  2052. plt.close()
  2053. # 保存CSV数据,包含阈值信息
  2054. csv_filename = os.path.join(output_dir, f"collisionseverity_data.csv")
  2055. df_csv = df.copy()
  2056. df_csv['min_threshold'] = min_threshold
  2057. df_csv['max_threshold'] = max_threshold
  2058. df_csv.to_csv(csv_filename, index=False)
  2059. logger.info(f"Collision Severity chart saved to: {chart_filename}")
  2060. logger.info(f"Collision Severity data saved to: {csv_filename}")
  2061. return chart_filename
  2062. except Exception as e:
  2063. logger.error(f"Failed to generate Collision Severity chart: {str(e)}", exc_info=True)
  2064. return None
  2065. def generate_traffic_chart_data(traffic_calculator, metric_name: str, output_dir: Optional[str] = None) -> Optional[
  2066. str]:
  2067. """Generate chart data for traffic metrics"""
  2068. # 待实现
  2069. return None
  2070. def calculate_distance(ego_df, correctwarning):
  2071. """计算预警距离"""
  2072. dist = ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['relative_dist']
  2073. return dist
  2074. def calculate_relative_speed(ego_df, correctwarning):
  2075. """计算相对速度"""
  2076. return ego_df[(ego_df['ifwarning'] == correctwarning) & (ego_df['ifwarning'].notna())]['composite_v']
  2077. # 使用function.py中已实现的scenario_sign_dict
  2078. from modules.metric.function import scenario_sign_dict
  2079. if __name__ == "__main__":
  2080. # 测试代码
  2081. print("Metrics visualization utilities loaded.")