lst.py 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  1. import zipfile
  2. import sqlite3
  3. import csv
  4. import tempfile
  5. from pathlib import Path
  6. from typing import List, Dict, Tuple, Optional, Any, NamedTuple
  7. import cantools
  8. import os
  9. import subprocess
  10. import numpy as np
  11. import pandas as pd
  12. from collections import Counter
  13. from datetime import datetime
  14. import argparse
  15. import sys
  16. from pyproj import Proj
  17. from bagpy.bagreader import bagreader
  18. import shutil
  19. import json
  20. from dataclasses import dataclass, field
  21. # --- Constants ---
  22. PLAYER_ID_EGO = int(1)
  23. PLAYER_ID_OBJ = int(2)
  24. DEFAULT_TYPE = int(1)
  25. OUTPUT_CSV_OBJSTATE = "ObjState.csv"
  26. OUTPUT_CSV_TEMP_OBJSTATE = "ObjState_temp_intermediate.csv" # Should be eliminated
  27. OUTPUT_CSV_EGOSTATE = "EgoState.csv" # Not used in final merge? Check logic if needed.
  28. OUTPUT_CSV_MERGED = "merged_ObjState.csv"
  29. OUTPUT_CSV_OBU = "OBUdata.csv"
  30. OUTPUT_CSV_LANEMAP = "LaneMap.csv"
  31. OUTPUT_CSV_EGOMAP = "EgoMap.csv"
  32. OUTPUT_CSV_FUNCTION = "Function.csv"
  33. ROADMARK_CSV = "RoadMark.csv"
  34. # --- Configuration Class ---
  35. @dataclass
  36. class Config:
  37. """Holds configuration paths and settings."""
  38. zip_path: Path
  39. output_path: Path
  40. json_path: Optional[Path] # Make json_path optional
  41. dbc_path: Optional[Path] = None
  42. engine_path: Optional[Path] = None
  43. map_path: Optional[Path] = None
  44. utm_zone: int = 51 # Example UTM zone
  45. x_offset: float = 0.0
  46. y_offset: float = 0.0
  47. # Derived paths
  48. output_dir: Path = field(init=False)
  49. def __post_init__(self):
  50. # Use output_path directly as output_dir to avoid nested directories
  51. self.output_dir = self.output_path
  52. self.output_dir.mkdir(parents=True, exist_ok=True)
  53. # --- Zip/CSV Processing ---
  54. class ZipCSVProcessor:
  55. """Processes DB files within a ZIP archive to generate CSV data."""
  56. # Define column mappings more clearly
  57. EGO_COLS_NEW = [
  58. "simTime", "simFrame", "playerId", "v", "speedX", "speedY",
  59. "posH", "speedH", "posX", "posY", "accelX", "accelY",
  60. "travelDist", "composite_v", "relative_dist", "type" # Added type
  61. ]
  62. OBJ_COLS_OLD_SUFFIXED = [
  63. "v_obj", "speedX_obj", "speedY_obj", "posH_obj", "speedH_obj",
  64. "posX_obj", "posY_obj", "accelX_obj", "accelY_obj", "travelDist_obj"
  65. ]
  66. OBJ_COLS_MAPPING = {old: new for old, new in
  67. zip(OBJ_COLS_OLD_SUFFIXED, EGO_COLS_NEW[3:13])} # Map suffixed cols to standard names
  68. def __init__(self, config: Config):
  69. self.config = config
  70. self.dbc = self._load_dbc(config.dbc_path)
  71. self.projection = Proj(proj='utm', zone=config.utm_zone, ellps='WGS84', preserve_units='m')
  72. self._init_table_config()
  73. self._init_keyword_mapping()
  74. def _load_dbc(self, dbc_path: Optional[Path]) -> Optional[cantools.db.Database]:
  75. if not dbc_path or not dbc_path.exists():
  76. print("DBC path not provided or file not found.")
  77. return None
  78. try:
  79. return cantools.db.load_file(dbc_path)
  80. except Exception as e:
  81. print(f"DBC loading failed: {e}")
  82. return None
  83. def _init_table_config(self):
  84. """Initializes configurations for different table types."""
  85. self.table_config = {
  86. "gnss_table": self._get_gnss_config(),
  87. "can_table": self._get_can_config()
  88. }
  89. def _get_gnss_config(self):
  90. # Keep relevant columns, adjust mapping as needed
  91. return {
  92. "output_columns": self.EGO_COLS_NEW, # Use the standard ego columns + type
  93. "mapping": { # Map output columns to source DB columns/signals
  94. "simTime": ("second", "usecond"),
  95. "simFrame": "ID",
  96. "v": "speed",
  97. "speedY": "y_speed",
  98. "speedX": "x_speed",
  99. "posH": "yaw",
  100. "speedH": "yaw_rate",
  101. "posX": "latitude_dd", # Source before projection
  102. "posY": "longitude_dd", # Source before projection
  103. "accelX": "x_acceleration",
  104. "accelY": "y_acceleration",
  105. "travelDist": "total_distance",
  106. # composite_v/relative_dist might not be direct fields in GNSS, handle later if needed
  107. "composite_v": "speed", # Placeholder, adjust if needed
  108. "relative_dist": None, # Placeholder, likely not in GNSS data
  109. "type": None # Will be set later
  110. },
  111. "db_columns": ["ID", "second", "usecond", "speed", "y_speed", "x_speed",
  112. "yaw", "yaw_rate", "latitude_dd", "longitude_dd",
  113. "x_acceleration", "y_acceleration", "total_distance"] # Actual cols to SELECT
  114. }
  115. def _get_can_config(self):
  116. # Define columns needed from DB/CAN signals for both EGO and OBJ
  117. return {
  118. "mapping": { # Map unified output columns to CAN signals or direct fields
  119. # EGO mappings (VUT = Vehicle Under Test)
  120. "v": "VUT_Speed_mps",
  121. "speedX": "VUT_Speed_x_mps",
  122. "speedY": "VUT_Speed_y_mps",
  123. "speedH": "VUT_Yaw_Rate",
  124. "posX": "VUT_GPS_Latitude", # Source before projection
  125. "posY": "VUT_GPS_Longitude", # Source before projection
  126. "posH": "VUT_Heading",
  127. "accelX": "VUT_Acc_X",
  128. "accelY": "VUT_Acc_Y",
  129. # OBJ mappings (UFO = Unidentified Flying Object / Other Vehicle)
  130. "v_obj": "Speed_mps",
  131. "speedX_obj": "UFO_Speed_x_mps",
  132. "speedY_obj": "UFO_Speed_y_mps",
  133. "speedH_obj": "Yaw_Rate",
  134. "posX_obj": "GPS_Latitude", # Source before projection
  135. "posY_obj": "GPS_Longitude", # Source before projection
  136. "posH_obj": "Heading",
  137. "accelX_obj": "Acc_X",
  138. "accelY_obj": "Acc_Y",
  139. # Relative Mappings
  140. "composite_v": "VUT_Rel_speed_long_mps",
  141. "relative_dist": "VUT_Dist_MRP_Abs",
  142. # travelDist often calculated, not direct CAN signal
  143. "travelDist": None, # Placeholder
  144. "travelDist_obj": None # Placeholder
  145. },
  146. "db_columns": ["ID", "second", "usecond", "timestamp", "canid", "len", "frame"] # Core DB columns
  147. }
  148. def _init_keyword_mapping(self):
  149. """Maps keywords in filenames to table configurations and output CSV names."""
  150. self.keyword_mapping = {
  151. "gnss": ("gnss_table", OUTPUT_CSV_OBJSTATE),
  152. # GNSS likely represents ego, writing to ObjState first? Revisit logic if needed.
  153. "can2": ("can_table", OUTPUT_CSV_OBJSTATE), # Process CAN data into the combined ObjState file
  154. }
  155. def process_zip(self) -> None:
  156. """Extracts and processes DB files from the configured ZIP path."""
  157. print(f"Processing ZIP: {self.config.zip_path}")
  158. output_dir = self.config.output_dir # Already created in Config
  159. try:
  160. with zipfile.ZipFile(self.config.zip_path, "r") as zip_ref:
  161. db_files_to_process = []
  162. for file_info in zip_ref.infolist():
  163. # Check if it's a DB file in the CANdata directory
  164. if 'CANdata/' in file_info.filename and file_info.filename.endswith('.db'):
  165. # Check if the filename contains any of the keywords
  166. match = self._match_keyword(file_info.filename)
  167. if match:
  168. table_type, csv_name = match
  169. db_files_to_process.append((file_info, table_type, csv_name))
  170. if not db_files_to_process:
  171. print("No relevant DB files found in CANdata/ matching keywords.")
  172. return
  173. # Process matched DB files
  174. with tempfile.TemporaryDirectory() as tmp_dir_str:
  175. tmp_dir = Path(tmp_dir_str)
  176. for file_info, table_type, csv_name in db_files_to_process:
  177. print(f"Processing DB: {file_info.filename} for table type {table_type}")
  178. extracted_path = tmp_dir / Path(file_info.filename).name
  179. try:
  180. # Extract the specific DB file
  181. with zip_ref.open(file_info.filename) as source, open(extracted_path, "wb") as target:
  182. shutil.copyfileobj(source, target)
  183. # Process the extracted DB file
  184. self._process_db_file(extracted_path, output_dir, table_type, csv_name)
  185. except (sqlite3.Error, pd.errors.EmptyDataError, FileNotFoundError, KeyError) as e:
  186. print(f"Error processing DB file {file_info.filename}: {e}")
  187. except Exception as e:
  188. print(f"Unexpected error processing DB file {file_info.filename}: {e}")
  189. finally:
  190. if extracted_path.exists():
  191. extracted_path.unlink() # Clean up extracted file
  192. except zipfile.BadZipFile:
  193. print(f"Error: Bad ZIP file: {self.config.zip_path}")
  194. except FileNotFoundError:
  195. print(f"Error: ZIP file not found: {self.config.zip_path}")
  196. except Exception as e:
  197. print(f"An error occurred during ZIP processing: {e}")
  198. def _match_keyword(self, filename: str) -> Optional[Tuple[str, str]]:
  199. """Finds the first matching keyword configuration for a filename."""
  200. for keyword, (table_type, csv_name) in self.keyword_mapping.items():
  201. if keyword in filename:
  202. return table_type, csv_name
  203. return None
  204. def _process_db_file(
  205. self, db_path: Path, output_dir: Path, table_type: str, csv_name: str
  206. ) -> None:
  207. """Connects to SQLite DB and processes the specified table type."""
  208. output_csv_path = output_dir / csv_name
  209. try:
  210. # Use URI for read-only connection
  211. conn_str = f"file:{db_path}?mode=ro"
  212. with sqlite3.connect(conn_str, uri=True) as conn:
  213. cursor = conn.cursor()
  214. if not self._check_table_exists(cursor, table_type):
  215. print(f"Table '{table_type}' does not exist in {db_path.name}. Skipping.")
  216. return
  217. if self._check_table_empty(cursor, table_type):
  218. print(f"Table '{table_type}' in {db_path.name} is empty. Skipping.")
  219. return
  220. print(f"Exporting data from table '{table_type}' to {output_csv_path}")
  221. if table_type == "can_table":
  222. self._process_can_table_optimized(cursor, output_csv_path)
  223. elif table_type == "gnss_table":
  224. # Pass output_path directly, avoid intermediate steps
  225. self._process_gnss_table(cursor, output_csv_path)
  226. else:
  227. print(f"Warning: No specific processor for table type '{table_type}'. Skipping.")
  228. except sqlite3.OperationalError as e:
  229. print(f"Database operational error for {db_path.name}: {e}. Check file integrity/permissions.")
  230. except sqlite3.DatabaseError as e:
  231. print(f"Database error connecting to {db_path.name}: {e}")
  232. except Exception as e:
  233. print(f"Unexpected error processing DB {db_path.name}: {e}")
  234. def _check_table_exists(self, cursor, table_name: str) -> bool:
  235. """Checks if a table exists in the database."""
  236. try:
  237. cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?;", (table_name,))
  238. return cursor.fetchone() is not None
  239. except sqlite3.Error as e:
  240. print(f"Error checking existence of table {table_name}: {e}")
  241. return False # Assume not exists on error
  242. def _check_table_empty(self, cursor, table_name: str) -> bool:
  243. """Checks if a table is empty."""
  244. try:
  245. cursor.execute(f"SELECT COUNT(*) FROM {table_name}") # Use COUNT(*) for efficiency
  246. count = cursor.fetchone()[0]
  247. return count == 0
  248. except sqlite3.Error as e:
  249. # If error occurs (e.g., table doesn't exist after check - race condition?), treat as problematic/empty
  250. print(f"Error checking if table {table_name} is empty: {e}")
  251. return True
  252. def _process_gnss_table(self, cursor, output_path: Path) -> None:
  253. """Processes gnss_table data and writes directly to CSV."""
  254. config = self.table_config["gnss_table"]
  255. db_columns = config["db_columns"]
  256. output_columns = config["output_columns"]
  257. mapping = config["mapping"]
  258. try:
  259. cursor.execute(f"SELECT {', '.join(db_columns)} FROM gnss_table")
  260. rows = cursor.fetchall()
  261. if not rows:
  262. print("No data found in gnss_table.")
  263. return
  264. processed_data = []
  265. for row in rows:
  266. row_dict = dict(zip(db_columns, row))
  267. record = {}
  268. # Calculate simTime
  269. record["simTime"] = round(row_dict.get("second", 0) + row_dict.get("usecond", 0) / 1e6, 2)
  270. # Map other columns
  271. for out_col in output_columns:
  272. if out_col == "simTime": continue # Already handled
  273. if out_col == "playerId":
  274. record[out_col] = PLAYER_ID_EGO # Assuming GNSS is ego
  275. continue
  276. if out_col == "type":
  277. record[out_col] = DEFAULT_TYPE
  278. continue
  279. source_info = mapping.get(out_col)
  280. if source_info is None:
  281. record[out_col] = 0.0 # Or np.nan if preferred
  282. elif isinstance(source_info, tuple):
  283. # This case was only for simTime, handled above
  284. record[out_col] = 0.0
  285. else: # Direct mapping from db_columns
  286. raw_value = row_dict.get(source_info)
  287. if raw_value is not None:
  288. # Handle projection for position columns
  289. if out_col == "posX":
  290. # Assuming source_info = "latitude_dd"
  291. lat = row_dict.get(mapping["posX"])
  292. lon = row_dict.get(mapping["posY"])
  293. if lat is not None and lon is not None:
  294. proj_x, _ = self.projection(lon, lat)
  295. record[out_col] = round(proj_x, 6)
  296. else:
  297. record[out_col] = 0.0
  298. elif out_col == "posY":
  299. # Assuming source_info = "longitude_dd"
  300. lat = row_dict.get(mapping["posX"])
  301. lon = row_dict.get(mapping["posY"])
  302. if lat is not None and lon is not None:
  303. _, proj_y = self.projection(lon, lat)
  304. record[out_col] = round(proj_y, 6)
  305. else:
  306. record[out_col] = 0.0
  307. elif out_col in ["composite_v", "relative_dist"]:
  308. # Handle these based on source if available, else default
  309. record[out_col] = round(float(raw_value), 3) if source_info else 0.0
  310. else:
  311. # General case: round numeric values
  312. try:
  313. record[out_col] = round(float(raw_value), 3)
  314. except (ValueError, TypeError):
  315. record[out_col] = raw_value # Keep as is if not numeric
  316. else:
  317. record[out_col] = 0.0 # Default for missing source data
  318. processed_data.append(record)
  319. if processed_data:
  320. df_final = pd.DataFrame(processed_data)[output_columns].iloc[::4].reset_index(drop=True) # Ensure column order
  321. df_final['simFrame'] = np.arange(1, len(df_final) + 1)
  322. df_final.to_csv(output_path, index=False, encoding="utf-8")
  323. print(f"Successfully wrote GNSS data to {output_path}")
  324. else:
  325. print("No processable records found in gnss_table.")
  326. except sqlite3.Error as e:
  327. print(f"SQL error during GNSS processing: {e}")
  328. except Exception as e:
  329. print(f"Unexpected error during GNSS processing: {e}")
  330. def _process_can_table_optimized(self, cursor, output_path: Path) -> None:
  331. """Processes CAN data directly into the final merged DataFrame format."""
  332. config = self.table_config["can_table"]
  333. db_columns = config["db_columns"]
  334. mapping = config["mapping"]
  335. try:
  336. cursor.execute(f"SELECT {', '.join(db_columns)} FROM can_table")
  337. rows = cursor.fetchall()
  338. if not rows:
  339. print("No data found in can_table.")
  340. return
  341. all_records = []
  342. for row in rows:
  343. row_dict = dict(zip(db_columns, row))
  344. # Decode CAN frame if DBC is available
  345. decoded_signals = self._decode_can_frame(row_dict)
  346. # Create a unified record combining DB fields and decoded signals
  347. record = self._create_unified_can_record(row_dict, decoded_signals, mapping)
  348. if record: # Only add if parsing was successful
  349. all_records.append(record)
  350. if not all_records:
  351. print("No CAN records could be successfully processed.")
  352. return
  353. # Convert raw records to DataFrame for easier manipulation
  354. df_raw = pd.DataFrame(all_records)
  355. # Separate EGO and OBJ data based on available columns
  356. df_ego = self._extract_vehicle_data(df_raw, PLAYER_ID_EGO)
  357. df_obj = self._extract_vehicle_data(df_raw, PLAYER_ID_OBJ)
  358. # Project coordinates
  359. df_ego = self._project_coordinates(df_ego, 'posX', 'posY')
  360. df_obj = self._project_coordinates(df_obj, 'posX', 'posY') # Use same column names after extraction
  361. # Add calculated/default columns
  362. df_ego['type'] = DEFAULT_TYPE
  363. df_obj['type'] = DEFAULT_TYPE
  364. # Note: travelDist is often calculated later or not available directly
  365. # Ensure both have the same columns before merging
  366. final_columns = self.EGO_COLS_NEW # Target columns
  367. df_ego = df_ego.reindex(columns=final_columns).iloc[::4]
  368. df_obj = df_obj.reindex(columns=final_columns).iloc[::4]
  369. # Reindex simFrame of ego and obj
  370. df_ego['simFrame'] = np.arange(1, len(df_ego)+1)
  371. df_obj['simFrame'] = np.arange(1, len(df_obj)+1)
  372. # Merge EGO and OBJ dataframes
  373. df_merged = pd.concat([df_ego, df_obj], ignore_index=True)
  374. # Sort and clean up
  375. df_merged.sort_values(by=["simTime", "simFrame", "playerId"], inplace=True)
  376. df_merged.reset_index(drop=True, inplace=True)
  377. # Fill potential NaNs introduced by reindexing or missing data
  378. # Choose appropriate fill strategy (e.g., 0, forward fill, or leave as NaN)
  379. # df_merged.fillna(0.0, inplace=True) # Example: fill with 0.0
  380. # Save the final merged DataFrame
  381. df_merged.to_csv(output_path, index=False, encoding="utf-8")
  382. print(f"Successfully processed CAN data and wrote merged output to {output_path}")
  383. except sqlite3.Error as e:
  384. print(f"SQL error during CAN processing: {e}")
  385. except KeyError as e:
  386. print(f"Key error during CAN processing - mapping issue? Missing key: {e}")
  387. except Exception as e:
  388. print(f"Unexpected error during CAN processing: {e}")
  389. import traceback
  390. traceback.print_exc() # Print detailed traceback for debugging
  391. def _decode_can_frame(self, row_dict: Dict) -> Dict[str, Any]:
  392. """Decodes CAN frame using DBC file if available."""
  393. decoded_signals = {}
  394. if self.dbc and 'canid' in row_dict and 'frame' in row_dict and 'len' in row_dict:
  395. can_id = row_dict['canid']
  396. frame_bytes = bytes(row_dict['frame'][:row_dict['len']]) # Ensure correct length
  397. try:
  398. message_def = self.dbc.get_message_by_frame_id(can_id)
  399. decoded_signals = message_def.decode(frame_bytes, decode_choices=False,
  400. allow_truncated=True) # Allow truncated
  401. except KeyError:
  402. # Optional: print(f"Warning: CAN ID 0x{can_id:X} not found in DBC.")
  403. pass # Ignore unknown IDs silently
  404. except ValueError as e:
  405. print(
  406. f"Warning: Decoding ValueError for CAN ID 0x{can_id:X} (length {row_dict['len']}, data: {frame_bytes.hex()}): {e}")
  407. except Exception as e:
  408. print(f"Warning: Error decoding CAN ID 0x{can_id:X}: {e}")
  409. return decoded_signals
  410. def _create_unified_can_record(self, row_dict: Dict, decoded_signals: Dict, mapping: Dict) -> Optional[
  411. Dict[str, Any]]:
  412. """Creates a single record combining DB fields and decoded signals based on mapping."""
  413. record = {}
  414. try:
  415. # Handle time and frame ID first
  416. record["simTime"] = round(row_dict.get("second", 0) + row_dict.get("usecond", 0) / 1e6, 2)
  417. record["simFrame"] = row_dict.get("ID")
  418. record["canid"] = f"0x{row_dict.get('canid'):X}" # Store CAN ID if needed
  419. # Populate record using the mapping config
  420. for target_col, source_info in mapping.items():
  421. if target_col in ["simTime", "simFrame", "canid"]: continue # Already handled
  422. if isinstance(source_info, tuple): continue # Should only be time
  423. # source_info is now the signal name (or None)
  424. signal_name = source_info
  425. if signal_name and signal_name in decoded_signals:
  426. # Value from decoded CAN signal
  427. raw_value = decoded_signals[signal_name]
  428. try:
  429. # Apply scaling/offset if needed (cantools handles this)
  430. # Round appropriately, especially for floats
  431. if isinstance(raw_value, (int, float)):
  432. # Be cautious with lat/lon precision before projection
  433. if "Latitude" in target_col or "Longitude" in target_col:
  434. record[target_col] = float(raw_value) # Keep precision for projection
  435. else:
  436. record[target_col] = round(float(raw_value), 6)
  437. else:
  438. record[target_col] = raw_value # Keep non-numeric as is (e.g., enums)
  439. except (ValueError, TypeError):
  440. record[target_col] = raw_value # Assign raw value if conversion fails
  441. # If signal not found or source_info is None, leave it empty for now
  442. # Will be filled later or during DataFrame processing
  443. return record
  444. except Exception as e:
  445. print(f"Error creating unified record for row {row_dict.get('ID')}: {e}")
  446. return None
  447. def _extract_vehicle_data(self, df_raw: pd.DataFrame, player_id: int) -> pd.DataFrame:
  448. """Extracts and renames columns for a specific vehicle (EGO or OBJ)."""
  449. df_vehicle = pd.DataFrame()
  450. # df_vehicle["simTime"] = df_raw["simTime"].drop_duplicates().sort_values().reset_index(drop=True)
  451. # df_vehicle["simFrame"] = np.arange(1, len(df_vehicle) + 1)
  452. # df_vehicle["playerId"] = int(player_id)
  453. df_vehicle_temps_ego = pd.DataFrame()
  454. df_vehicle_temps_obj = pd.DataFrame()
  455. if player_id == PLAYER_ID_EGO:
  456. # Select EGO columns (not ending in _obj) + relative columns
  457. ego_cols = {target: source for target, source in self.table_config['can_table']['mapping'].items()
  458. if source and not isinstance(source, tuple) and not target.endswith('_obj')}
  459. rename_map = {}
  460. select_cols_raw = []
  461. for target_col, source_info in ego_cols.items():
  462. if source_info: # Mapped signal/field name in df_raw
  463. select_cols_raw.append(target_col) # Column names in df_raw are already target names
  464. rename_map[target_col] = target_col # No rename needed here
  465. # Include relative speed and distance for ego frame
  466. relative_cols = ["composite_v", "relative_dist"]
  467. select_cols_raw.extend(relative_cols)
  468. for col in relative_cols:
  469. rename_map[col] = col
  470. # Select and rename
  471. df_vehicle_temp = df_raw[list(set(select_cols_raw) & set(df_raw.columns))] # Select available columns
  472. for col in df_vehicle_temp.columns:
  473. df_vehicle_temps_ego[col] = df_vehicle_temp[col].dropna().reset_index(drop=True)
  474. df_vehicle = pd.concat([df_vehicle, df_vehicle_temps_ego], axis=1)
  475. elif player_id == PLAYER_ID_OBJ:
  476. # Select OBJ columns (ending in _obj)
  477. obj_cols = {target: source for target, source in self.table_config['can_table']['mapping'].items()
  478. if source and not isinstance(source, tuple) and target.endswith('_obj')}
  479. rename_map = {}
  480. select_cols_raw = []
  481. for target_col, source_info in obj_cols.items():
  482. if source_info:
  483. select_cols_raw.append(target_col) # Original _obj column name
  484. # Map from VUT_XXX_obj -> VUT_XXX
  485. rename_map[target_col] = self.OBJ_COLS_MAPPING.get(target_col,
  486. target_col) # Rename to standard name
  487. # Select and rename
  488. df_vehicle_temp = df_raw[list(set(select_cols_raw) & set(df_raw.columns))] # Select available columns
  489. df_vehicle_temp.rename(columns=rename_map, inplace=True)
  490. for col in df_vehicle_temp.columns:
  491. df_vehicle_temps_obj[col] = df_vehicle_temp[col].dropna().reset_index(drop=True)
  492. df_vehicle = pd.concat([df_vehicle, df_vehicle_temps_obj], axis=1)
  493. # Copy relative speed/distance from ego calculation (assuming it's relative *to* ego)
  494. if "composite_v" in df_raw.columns:
  495. df_vehicle["composite_v"] = df_raw["composite_v"].dropna().reset_index(drop=True)
  496. if "relative_dist" in df_raw.columns:
  497. df_vehicle["relative_dist"] = df_raw["relative_dist"].dropna().reset_index(drop=True)
  498. # Drop rows where essential position data might be missing after selection/renaming
  499. # Adjust required columns as necessary
  500. # required_pos = ['posX', 'posY', 'posH']
  501. # df_vehicle.dropna(subset=[col for col in required_pos if col in df_vehicle.columns], inplace=True)
  502. try:
  503. df_vehicle["simTime"] = np.round(np.linspace(df_raw["simTime"].tolist()[0], df_raw["simTime"].tolist()[0] + 0.01*(len(df_vehicle)), len(df_vehicle)), 2)
  504. df_vehicle["simFrame"] = np.arange(1, len(df_vehicle) + 1)
  505. df_vehicle["playerId"] = int(player_id)
  506. df_vehicle['playerId'] = pd.to_numeric(df_vehicle['playerId']).astype(int)
  507. except ValueError as ve:
  508. print(f"{ve}")
  509. except TypeError as te:
  510. print(f"{te}")
  511. except Exception as Ee:
  512. print(f"{Ee}")
  513. return df_vehicle
  514. def _project_coordinates(self, df: pd.DataFrame, lat_col: str, lon_col: str) -> pd.DataFrame:
  515. """Applies UTM projection to latitude and longitude columns."""
  516. if lat_col in df.columns and lon_col in df.columns:
  517. # Ensure data is numeric and handle potential errors/missing values
  518. lat = pd.to_numeric(df[lat_col], errors='coerce')
  519. lon = pd.to_numeric(df[lon_col], errors='coerce')
  520. valid_coords = lat.notna() & lon.notna()
  521. if valid_coords.any():
  522. x, y = self.projection(lon[valid_coords].values, lat[valid_coords].values)
  523. # Update DataFrame, assign NaN where original coords were invalid
  524. df.loc[valid_coords, lat_col] = np.round(x, 6) # Overwrite latitude col with X
  525. df.loc[valid_coords, lon_col] = np.round(y, 6) # Overwrite longitude col with Y
  526. df.loc[~valid_coords, [lat_col, lon_col]] = np.nan # Set invalid coords to NaN
  527. else:
  528. # No valid coordinates found, set columns to NaN or handle as needed
  529. df[lat_col] = np.nan
  530. df[lon_col] = np.nan
  531. # Rename columns AFTER projection for clarity
  532. df.rename(columns={lat_col: 'posX', lon_col: 'posY'}, inplace=True)
  533. else:
  534. # Ensure columns exist even if projection didn't happen
  535. if 'posX' not in df.columns: df['posX'] = np.nan
  536. if 'posY' not in df.columns: df['posY'] = np.nan
  537. print(f"Warning: Latitude ('{lat_col}') or Longitude ('{lon_col}') columns not found for projection.")
  538. return df
  539. # --- Polynomial Fitting (Largely unchanged, minor cleanup) ---
  540. class PolynomialCurvatureFitting:
  541. """Calculates curvature and its derivative using polynomial fitting."""
  542. def __init__(self, lane_map_path: Path, degree: int = 3):
  543. self.lane_map_path = lane_map_path
  544. self.degree = degree
  545. self.data = self._load_data()
  546. if self.data is not None:
  547. self.points = self.data[["centerLine_x", "centerLine_y"]].values
  548. self.x_data, self.y_data = self.points[:, 0], self.points[:, 1]
  549. else:
  550. self.points = np.empty((0, 2))
  551. self.x_data, self.y_data = np.array([]), np.array([])
  552. def _load_data(self) -> Optional[pd.DataFrame]:
  553. """Loads lane map data safely."""
  554. if not self.lane_map_path.exists() or self.lane_map_path.stat().st_size == 0:
  555. print(f"Warning: LaneMap file not found or empty: {self.lane_map_path}")
  556. return None
  557. try:
  558. return pd.read_csv(self.lane_map_path)
  559. except pd.errors.EmptyDataError:
  560. print(f"Warning: LaneMap file is empty: {self.lane_map_path}")
  561. return None
  562. except Exception as e:
  563. print(f"Error reading LaneMap file {self.lane_map_path}: {e}")
  564. return None
  565. def curvature(self, coefficients: np.ndarray, x: float) -> float:
  566. """Computes curvature of the polynomial at x."""
  567. if len(coefficients) < 3: # Need at least degree 2 for curvature
  568. return 0.0
  569. first_deriv_coeffs = np.polyder(coefficients)
  570. second_deriv_coeffs = np.polyder(first_deriv_coeffs)
  571. dy_dx = np.polyval(first_deriv_coeffs, x)
  572. d2y_dx2 = np.polyval(second_deriv_coeffs, x)
  573. denominator = (1 + dy_dx ** 2) ** 1.5
  574. return np.abs(d2y_dx2) / denominator if denominator != 0 else np.inf
  575. def curvature_derivative(self, coefficients: np.ndarray, x: float) -> float:
  576. """Computes the derivative of curvature with respect to x."""
  577. if len(coefficients) < 4: # Need at least degree 3 for derivative of curvature
  578. return 0.0
  579. first_deriv_coeffs = np.polyder(coefficients)
  580. second_deriv_coeffs = np.polyder(first_deriv_coeffs)
  581. third_deriv_coeffs = np.polyder(second_deriv_coeffs)
  582. dy_dx = np.polyval(first_deriv_coeffs, x)
  583. d2y_dx2 = np.polyval(second_deriv_coeffs, x)
  584. d3y_dx3 = np.polyval(third_deriv_coeffs, x)
  585. denominator = (1 + dy_dx ** 2) ** 2.5 # Note the power is 2.5 or 5/2
  586. if denominator == 0:
  587. return np.inf
  588. numerator = d3y_dx3 * (1 + dy_dx ** 2) - 3 * dy_dx * d2y_dx2 * d2y_dx2 # Corrected term order? Verify formula
  589. # Standard formula: (d3y_dx3*(1 + dy_dx**2) - 3*dy_dx*(d2y_dx2**2)) / ((1 + dy_dx**2)**(5/2)) * sign(d2y_dx2)
  590. # Let's stick to the provided calculation logic but ensure denominator is correct
  591. # The provided formula in the original code seems to be for dk/ds (arc length), not dk/dx.
  592. # Re-implementing dk/dx based on standard calculus:
  593. term1 = d3y_dx3 * (1 + dy_dx ** 2) ** (3 / 2)
  594. term2 = d2y_dx2 * (3 / 2) * (1 + dy_dx ** 2) ** (1 / 2) * (2 * dy_dx * d2y_dx2) # Chain rule
  595. numerator_dk_dx = term1 - term2
  596. denominator_dk_dx = (1 + dy_dx ** 2) ** 3
  597. if denominator_dk_dx == 0:
  598. return np.inf
  599. # Take absolute value or not? Original didn't. Let's omit abs() for derivative.
  600. return numerator_dk_dx / denominator_dk_dx
  601. # dk_dx = (d3y_dx3 * (1 + dy_dx ** 2) - 3 * dy_dx * d2y_dx2 ** 2) / (
  602. # (1 + dy_dx ** 2) ** (5/2) # Original had power 3 ?? Double check this formula source
  603. # ) * np.sign(d2y_dx2) # Need sign of curvature
  604. # return dk_dx
  605. def polynomial_fit(
  606. self, x_window: np.ndarray, y_window: np.ndarray
  607. ) -> Tuple[Optional[np.ndarray], Optional[np.poly1d]]:
  608. """Performs polynomial fitting, handling potential rank warnings."""
  609. if len(x_window) <= self.degree:
  610. print(f"Warning: Window size {len(x_window)} is <= degree {self.degree}. Cannot fit.")
  611. return None, None
  612. try:
  613. # Use warnings context manager if needed, but RankWarning often indicates insufficient data variability
  614. # with warnings.catch_warnings():
  615. # warnings.filterwarnings('error', category=np.RankWarning) # Or ignore
  616. coefficients = np.polyfit(x_window, y_window, self.degree)
  617. return coefficients, np.poly1d(coefficients)
  618. except np.RankWarning:
  619. print(f"Warning: Rank deficient fitting for window. Check data variability.")
  620. # Attempt lower degree fit? Or return None? For now, return None.
  621. # try:
  622. # coefficients = np.polyfit(x_window, y_window, len(x_window) - 1)
  623. # return coefficients, np.poly1d(coefficients)
  624. # except:
  625. return None, None
  626. except Exception as e:
  627. print(f"Error during polynomial fit: {e}")
  628. return None, None
  629. def find_best_window(self, point: Tuple[float, float], window_size: int) -> Optional[int]:
  630. """Finds the start index of the window whose center is closest to the point."""
  631. if len(self.x_data) < window_size:
  632. print("Warning: Not enough data points for the specified window size.")
  633. return None
  634. x_point, y_point = point
  635. min_dist_sq = np.inf
  636. best_start_index = -1
  637. # Calculate window centers more efficiently
  638. # Use rolling mean if window_size is large, otherwise simple loop is fine
  639. num_windows = len(self.x_data) - window_size + 1
  640. if num_windows <= 0: return None
  641. for start in range(num_windows):
  642. x_center = np.mean(self.x_data[start: start + window_size])
  643. y_center = np.mean(self.y_data[start: start + window_size])
  644. dist_sq = (x_point - x_center) ** 2 + (y_point - y_center) ** 2
  645. if dist_sq < min_dist_sq:
  646. min_dist_sq = dist_sq
  647. best_start_index = start
  648. return best_start_index if best_start_index != -1 else None
  649. def find_projection(
  650. self,
  651. x_target: float,
  652. y_target: float,
  653. polynomial: np.poly1d,
  654. x_range: Tuple[float, float],
  655. search_points: int = 100, # Number of points instead of step size
  656. ) -> Optional[Tuple[float, float, float]]:
  657. """Finds the approximate closest point on the polynomial within the x_range."""
  658. if x_range[1] <= x_range[0]: return None # Invalid range
  659. x_values = np.linspace(x_range[0], x_range[1], search_points)
  660. y_values = polynomial(x_values)
  661. distances_sq = (x_target - x_values) ** 2 + (y_target - y_values) ** 2
  662. if len(distances_sq) == 0: return None
  663. min_idx = np.argmin(distances_sq)
  664. min_distance = np.sqrt(distances_sq[min_idx])
  665. return x_values[min_idx], y_values[min_idx], min_distance
  666. def fit_and_project(
  667. self, points: np.ndarray, window_size: int
  668. ) -> List[Dict[str, Any]]:
  669. """Fits polynomial and calculates curvature for each point in the input array."""
  670. if self.data is None or len(self.x_data) < window_size:
  671. print("Insufficient LaneMap data for fitting.")
  672. # Return default values for all points
  673. return [
  674. {
  675. "projection": (np.nan, np.nan),
  676. "curvHor": np.nan,
  677. "curvHorDot": np.nan,
  678. "laneOffset": np.nan,
  679. }
  680. ] * len(points)
  681. results = []
  682. if points.ndim != 2 or points.shape[1] != 2:
  683. raise ValueError("Input points must be a 2D numpy array with shape (n, 2).")
  684. for x_target, y_target in points:
  685. result = { # Default result
  686. "projection": (np.nan, np.nan),
  687. "curvHor": np.nan,
  688. "curvHorDot": np.nan,
  689. "laneOffset": np.nan,
  690. }
  691. best_start = self.find_best_window((x_target, y_target), window_size)
  692. if best_start is None:
  693. results.append(result)
  694. continue
  695. x_window = self.x_data[best_start: best_start + window_size]
  696. y_window = self.y_data[best_start: best_start + window_size]
  697. coefficients, polynomial = self.polynomial_fit(x_window, y_window)
  698. if coefficients is None or polynomial is None:
  699. results.append(result)
  700. continue
  701. x_min, x_max = np.min(x_window), np.max(x_window)
  702. projection_result = self.find_projection(
  703. x_target, y_target, polynomial, (x_min, x_max)
  704. )
  705. if projection_result is None:
  706. results.append(result)
  707. continue
  708. proj_x, proj_y, min_distance = projection_result
  709. curv_hor = self.curvature(coefficients, proj_x)
  710. curv_hor_dot = self.curvature_derivative(coefficients, proj_x)
  711. result = {
  712. "projection": (round(proj_x, 6), round(proj_y, 6)),
  713. "curvHor": round(curv_hor, 6),
  714. "curvHorDot": round(curv_hor_dot, 6),
  715. "laneOffset": round(min_distance, 6),
  716. }
  717. results.append(result)
  718. return results
  719. # --- Data Quality Analyzer (Optimized) ---
  720. class DataQualityAnalyzer:
  721. """Analyzes data quality metrics, focusing on frame loss."""
  722. def __init__(self, df: Optional[pd.DataFrame] = None):
  723. self.df = df if df is not None and not df.empty else pd.DataFrame() # Ensure df is DataFrame
  724. def analyze_frame_loss(self) -> Dict[str, Any]:
  725. """Analyzes frame loss characteristics."""
  726. metrics = {
  727. "total_frames_data": 0,
  728. "unique_frames_count": 0,
  729. "min_frame": np.nan,
  730. "max_frame": np.nan,
  731. "expected_frames": 0,
  732. "dropped_frames_count": 0,
  733. "loss_rate": np.nan,
  734. "max_consecutive_loss": 0,
  735. "max_loss_start_frame": np.nan,
  736. "max_loss_end_frame": np.nan,
  737. "loss_intervals_distribution": {},
  738. "valid": False, # Indicate if analysis was possible
  739. "message": ""
  740. }
  741. if self.df.empty or 'simFrame' not in self.df.columns:
  742. metrics["message"] = "DataFrame is empty or 'simFrame' column is missing."
  743. return metrics
  744. # Drop rows with NaN simFrame and ensure integer type
  745. frames_series = self.df['simFrame'].dropna().astype(int)
  746. metrics["total_frames_data"] = len(frames_series)
  747. if frames_series.empty:
  748. metrics["message"] = "No valid 'simFrame' data found after dropping NaN."
  749. return metrics
  750. unique_frames = sorted(frames_series.unique())
  751. metrics["unique_frames_count"] = len(unique_frames)
  752. if metrics["unique_frames_count"] < 2:
  753. metrics["message"] = "Less than two unique frames; cannot analyze loss."
  754. metrics["valid"] = True # Data exists, just not enough to analyze loss
  755. if metrics["unique_frames_count"] == 1:
  756. metrics["min_frame"] = unique_frames[0]
  757. metrics["max_frame"] = unique_frames[0]
  758. metrics["expected_frames"] = 1
  759. return metrics
  760. metrics["min_frame"] = unique_frames[0]
  761. metrics["max_frame"] = unique_frames[-1]
  762. metrics["expected_frames"] = metrics["max_frame"] - metrics["min_frame"] + 1
  763. # Calculate differences between consecutive unique frames
  764. frame_diffs = np.diff(unique_frames)
  765. # Gaps are where diff > 1. The number of lost frames in a gap is diff - 1.
  766. gaps = frame_diffs[frame_diffs > 1]
  767. lost_frames_in_gaps = gaps - 1
  768. metrics["dropped_frames_count"] = int(lost_frames_in_gaps.sum())
  769. if metrics["expected_frames"] > 0:
  770. metrics["loss_rate"] = round(metrics["dropped_frames_count"] / metrics["expected_frames"], 4)
  771. else:
  772. metrics["loss_rate"] = 0.0 # Avoid division by zero if min_frame == max_frame (already handled)
  773. if len(lost_frames_in_gaps) > 0:
  774. metrics["max_consecutive_loss"] = int(lost_frames_in_gaps.max())
  775. # Find where the max loss occurred
  776. max_loss_indices = np.where(frame_diffs == metrics["max_consecutive_loss"] + 1)[0]
  777. # Get the first occurrence start/end frames
  778. max_loss_idx = max_loss_indices[0]
  779. metrics["max_loss_start_frame"] = unique_frames[max_loss_idx]
  780. metrics["max_loss_end_frame"] = unique_frames[max_loss_idx + 1]
  781. # Count distribution of loss interval lengths
  782. loss_counts = Counter(lost_frames_in_gaps)
  783. metrics["loss_intervals_distribution"] = {int(k): int(v) for k, v in loss_counts.items()}
  784. else:
  785. metrics["max_consecutive_loss"] = 0
  786. metrics["valid"] = True
  787. metrics["message"] = "Frame loss analysis complete."
  788. return metrics
  789. def get_all_csv_files(path: Path) -> List[Path]:
  790. """Gets all CSV files in path, excluding specific ones."""
  791. excluded_files = {OUTPUT_CSV_LANEMAP, ROADMARK_CSV}
  792. return [
  793. file_path
  794. for file_path in path.rglob("*.csv") # Recursive search
  795. if file_path.is_file() and file_path.name not in excluded_files
  796. ]
  797. def run_frame_loss_analysis_on_folder(path: Path) -> Dict[str, Dict[str, Any]]:
  798. """Runs frame loss analysis on all relevant CSV files in a folder."""
  799. analysis_results = {}
  800. csv_files = get_all_csv_files(path)
  801. if not csv_files:
  802. print(f"No relevant CSV files found in {path}")
  803. return analysis_results
  804. for file_path in csv_files:
  805. file_name = file_path.name
  806. if file_name in {OUTPUT_CSV_FUNCTION, OUTPUT_CSV_OBU}: # Skip specific files if needed
  807. print(f"Skipping frame analysis for: {file_name}")
  808. continue
  809. print(f"Analyzing frame loss for: {file_name}")
  810. if file_path.stat().st_size == 0:
  811. print(f"File {file_name} is empty. Skipping analysis.")
  812. analysis_results[file_name] = {"valid": False, "message": "File is empty."}
  813. continue
  814. try:
  815. # Read only necessary column if possible, handle errors
  816. df = pd.read_csv(file_path, usecols=['simFrame'], index_col=False,
  817. on_bad_lines='warn') # 'warn' or 'skip'
  818. analyzer = DataQualityAnalyzer(df)
  819. metrics = analyzer.analyze_frame_loss()
  820. analysis_results[file_name] = metrics
  821. # Optionally print a summary here
  822. if metrics["valid"]:
  823. print(f" Loss Rate: {metrics.get('loss_rate', np.nan) * 100:.2f}%, "
  824. f"Dropped: {metrics.get('dropped_frames_count', 'N/A')}, "
  825. f"Max Gap: {metrics.get('max_consecutive_loss', 'N/A')}")
  826. else:
  827. print(f" Analysis failed: {metrics.get('message')}")
  828. except pd.errors.EmptyDataError:
  829. print(f"File {file_name} contains no data after reading.")
  830. analysis_results[file_name] = {"valid": False, "message": "Empty data after read."}
  831. except ValueError as ve: # Handle case where simFrame might not be present
  832. print(f"ValueError processing file {file_name}: {ve}. Is 'simFrame' column present?")
  833. analysis_results[file_name] = {"valid": False, "message": f"ValueError: {ve}"}
  834. except Exception as e:
  835. print(f"Unexpected error processing file {file_name}: {e}")
  836. analysis_results[file_name] = {"valid": False, "message": f"Unexpected error: {e}"}
  837. return analysis_results
  838. def data_precheck(output_dir: Path, max_allowed_loss_rate: float = 0.20) -> bool:
  839. """Checks data quality, focusing on frame loss rate."""
  840. print(f"--- Running Data Quality Precheck on: {output_dir} ---")
  841. if not output_dir.exists() or not output_dir.is_dir():
  842. print(f"Error: Output directory does not exist: {output_dir}")
  843. return False
  844. try:
  845. frame_loss_results = run_frame_loss_analysis_on_folder(output_dir)
  846. except Exception as e:
  847. print(f"Critical error during frame loss analysis: {e}")
  848. return False # Treat critical error as failure
  849. if not frame_loss_results:
  850. print("Warning: No files were analyzed for frame loss.")
  851. # Decide if this is a failure or just a warning. Let's treat it as OK for now.
  852. return True
  853. all_checks_passed = True
  854. for file_name, metrics in frame_loss_results.items():
  855. if metrics.get("valid", False):
  856. loss_rate = metrics.get("loss_rate", np.nan)
  857. if pd.isna(loss_rate):
  858. print(f" {file_name}: Loss rate could not be calculated.")
  859. # Decide if NaN loss rate is acceptable.
  860. elif loss_rate > max_allowed_loss_rate:
  861. print(
  862. f" FAIL: {file_name} - Frame loss rate ({loss_rate * 100:.2f}%) exceeds threshold ({max_allowed_loss_rate * 100:.1f}%).")
  863. all_checks_passed = False
  864. else:
  865. print(f" PASS: {file_name} - Frame loss rate ({loss_rate * 100:.2f}%) is acceptable.")
  866. else:
  867. print(
  868. f" WARN: {file_name} - Frame loss analysis could not be completed ({metrics.get('message', 'Unknown reason')}).")
  869. # Decide if inability to analyze is a failure. Let's allow it for now.
  870. print(f"--- Data Quality Precheck {'PASSED' if all_checks_passed else 'FAILED'} ---")
  871. return all_checks_passed
  872. # --- Final Preprocessing Step ---
  873. class FinalDataProcessor:
  874. """Merges processed CSVs, adds curvature, and handles traffic lights."""
  875. def __init__(self, config: Config):
  876. self.config = config
  877. self.output_dir = config.output_dir
  878. def process(self) -> bool:
  879. """执行最终数据合并和处理步骤。"""
  880. print("--- Starting Final Data Processing ---")
  881. try:
  882. # 1. Load main object state data
  883. obj_state_path = self.output_dir / OUTPUT_CSV_OBJSTATE
  884. lane_map_path = self.output_dir / OUTPUT_CSV_LANEMAP
  885. if not obj_state_path.exists():
  886. print(f"Error: Required input file not found: {obj_state_path}")
  887. return False
  888. # 处理交通灯数据并保存
  889. df_traffic = self._process_trafficlight_data()
  890. if not df_traffic.empty:
  891. traffic_csv_path = self.output_dir / "Traffic.csv"
  892. df_traffic.to_csv(traffic_csv_path, index=False, float_format='%.6f')
  893. print(f"Successfully created traffic light data file: {traffic_csv_path}")
  894. # Load and process data
  895. df_object = pd.read_csv(obj_state_path, dtype={"simTime": float}, low_memory=False)
  896. # Process and merge data
  897. df_merged = self._merge_optional_data(df_object)
  898. # Save final merged file directly to output directory
  899. merged_csv_path = self.output_dir / OUTPUT_CSV_MERGED
  900. print(f'merged_csv_path:{merged_csv_path}')
  901. df_merged.to_csv(merged_csv_path, index=False, float_format='%.6f')
  902. print(f"Successfully created final merged file: {merged_csv_path}")
  903. # Clean up intermediate files
  904. # if obj_state_path.exists():
  905. # obj_state_path.unlink()
  906. print("--- Final Data Processing Finished ---")
  907. return True
  908. except Exception as e:
  909. print(f"An unexpected error occurred during final data processing: {e}")
  910. import traceback
  911. traceback.print_exc()
  912. return False
  913. # def _merge_optional_data(self, df_object: pd.DataFrame) -> pd.DataFrame:
  914. # """加载和合并可选数据"""
  915. # df_merged = df_object.copy()
  916. # # 检查并删除重复列的函数
  917. # def clean_duplicate_columns(df):
  918. # # 查找带有 _x 或 _y 后缀的列
  919. # duplicate_cols = []
  920. # base_cols = {}
  921. # for col in df.columns:
  922. # if col.endswith('_x') or col.endswith('_y'):
  923. # base_name = col[:-2] # 去掉后缀
  924. # if base_name not in base_cols:
  925. # base_cols[base_name] = []
  926. # base_cols[base_name].append(col)
  927. # # 对于每组重复列,检查数据是否相同,如果相同则只保留一个
  928. # for base_name, cols in base_cols.items():
  929. # if len(cols) > 1:
  930. # # 检查这些列的数据是否相同
  931. # is_identical = True
  932. # first_col = cols[0]
  933. # for col in cols[1:]:
  934. # if not df[first_col].equals(df[col]):
  935. # is_identical = False
  936. # break
  937. # if is_identical:
  938. # # 数据相同,保留第一列并重命名为基本名称
  939. # df = df.rename(columns={first_col: base_name})
  940. # # 删除其他重复列
  941. # for col in cols[1:]:
  942. # duplicate_cols.append(col)
  943. # print(f"列 {cols} 数据相同,保留为 {base_name}")
  944. # else:
  945. # print(f"列 {cols} 数据不同,保留所有列")
  946. # # 删除重复列
  947. # if duplicate_cols:
  948. # df = df.drop(columns=duplicate_cols)
  949. # print(f"删除了重复列: {duplicate_cols}")
  950. # return df
  951. # # --- 合并 EgoMap ---
  952. # egomap_path = self.output_dir / OUTPUT_CSV_EGOMAP
  953. # if egomap_path.exists() and egomap_path.stat().st_size > 0:
  954. # try:
  955. # df_ego = pd.read_csv(egomap_path, dtype={"simTime": float})
  956. # # 删除 simFrame 列,因为使用主数据的 simFrame
  957. # if 'simFrame' in df_ego.columns:
  958. # df_ego = df_ego.drop(columns=['simFrame'])
  959. # # 按时间和ID排序
  960. # df_ego.sort_values(['simTime', 'playerId'], inplace=True)
  961. # df_merged.sort_values(['simTime', 'playerId'], inplace=True)
  962. # # 使用 merge_asof 进行就近合并,不包括 simFrame
  963. # df_merged = pd.merge_asof(
  964. # df_merged,
  965. # df_ego,
  966. # on='simTime',
  967. # by='playerId',
  968. # direction='nearest',
  969. # tolerance=0.01 # 10ms tolerance
  970. # )
  971. # print("EgoMap data merged.")
  972. # except Exception as e:
  973. # print(f"Warning: Could not merge EgoMap data from {egomap_path}: {e}")
  974. # # --- Merge Function ---
  975. # function_path = self.output_dir / OUTPUT_CSV_FUNCTION
  976. # if function_path.exists() and function_path.stat().st_size > 0:
  977. # try:
  978. # df_function = pd.read_csv(function_path, dtype={"timestamp": float}, low_memory=False).drop_duplicates()
  979. # # 删除 simFrame 列
  980. # if 'simFrame' in df_function.columns:
  981. # df_function = df_function.drop(columns=['simFrame'])
  982. # if 'simTime' in df_function.columns:
  983. # df_function['simTime'] = df_function['simTime'].round(2)
  984. # df_function['time'] = df_function['simTime'].round(2).astype(float)
  985. # df_merged['time'] = df_merged['simTime'].round(2).astype(float)
  986. # common_cols = list(set(df_merged.columns) & set(df_function.columns) - {'time'})
  987. # df_function.drop(columns=common_cols, inplace=True, errors='ignore')
  988. # df_merged = pd.merge(df_merged, df_function, on=["time"], how="left")
  989. # df_merged.drop(columns=['time'], inplace=True)
  990. # print("Function data merged.")
  991. # else:
  992. # print("Warning: 'simTime' column not found in Function.csv. Cannot merge.")
  993. # except Exception as e:
  994. # print(f"Warning: Could not merge Function data from {function_path}: {e}")
  995. # else:
  996. # print("Function data not found or empty, skipping merge.")
  997. # # --- Merge OBU ---
  998. # obu_path = self.output_dir / OUTPUT_CSV_OBU
  999. # if obu_path.exists() and obu_path.stat().st_size > 0:
  1000. # try:
  1001. # df_obu = pd.read_csv(obu_path, dtype={"simTime": float}, low_memory=False).drop_duplicates()
  1002. # # 删除 simFrame 列
  1003. # if 'simFrame' in df_obu.columns:
  1004. # df_obu = df_obu.drop(columns=['simFrame'])
  1005. # df_obu['time'] = df_obu['simTime'].round(2).astype(float)
  1006. # df_merged['time'] = df_merged['simTime'].round(2).astype(float)
  1007. # common_cols = list(set(df_merged.columns) & set(df_obu.columns) - {'time'})
  1008. # df_obu.drop(columns=common_cols, inplace=True, errors='ignore')
  1009. # df_merged = pd.merge(df_merged, df_obu, on=["time"], how="left")
  1010. # df_merged.drop(columns=['time'], inplace=True)
  1011. # print("OBU data merged.")
  1012. # except Exception as e:
  1013. # print(f"Warning: Could not merge OBU data from {obu_path}: {e}")
  1014. # else:
  1015. # print("OBU data not found or empty, skipping merge.")
  1016. # # 在所有合并完成后,清理重复列
  1017. # df_merged = clean_duplicate_columns(df_merged)
  1018. # return df_merged
  1019. def _merge_optional_data(self, df_object: pd.DataFrame) -> pd.DataFrame:
  1020. """加载和合并可选数据"""
  1021. df_merged = df_object.copy()
  1022. # 检查并删除重复列的函数
  1023. def clean_duplicate_columns(df):
  1024. # 查找带有 _x 或 _y 后缀的列
  1025. duplicate_cols = []
  1026. base_cols = {}
  1027. # 打印清理前的列名
  1028. print(f"清理重复列前的列名: {df.columns.tolist()}")
  1029. for col in df.columns:
  1030. if col.endswith('_x') or col.endswith('_y'):
  1031. base_name = col[:-2] # 去掉后缀
  1032. if base_name not in base_cols:
  1033. base_cols[base_name] = []
  1034. base_cols[base_name].append(col)
  1035. # 对于每组重复列,检查数据是否相同,如果相同则只保留一个
  1036. for base_name, cols in base_cols.items():
  1037. if len(cols) > 1:
  1038. # 检查这些列的数据是否相同
  1039. is_identical = True
  1040. first_col = cols[0]
  1041. for col in cols[1:]:
  1042. if not df[first_col].equals(df[col]):
  1043. is_identical = False
  1044. break
  1045. if is_identical:
  1046. # 数据相同,保留第一列并重命名为基本名称
  1047. df = df.rename(columns={first_col: base_name})
  1048. # 删除其他重复列
  1049. for col in cols[1:]:
  1050. duplicate_cols.append(col)
  1051. print(f"列 {cols} 数据相同,保留为 {base_name}")
  1052. else:
  1053. print(f"列 {cols} 数据不同,保留所有列")
  1054. # 如果是 simTime 相关列,确保保留一个
  1055. if base_name == 'simTime' and 'simTime' not in df.columns:
  1056. df = df.rename(columns={cols[0]: 'simTime'})
  1057. print(f"将 {cols[0]} 重命名为 simTime")
  1058. # 删除其他 simTime 相关列
  1059. for col in cols[1:]:
  1060. duplicate_cols.append(col)
  1061. # 删除重复列
  1062. if duplicate_cols:
  1063. # 确保不会删除 simTime 列
  1064. if 'simTime' not in df.columns and any(col.startswith('simTime_') for col in duplicate_cols):
  1065. # 找到一个 simTime 相关列保留
  1066. for col in duplicate_cols[:]:
  1067. if col.startswith('simTime_'):
  1068. df = df.rename(columns={col: 'simTime'})
  1069. duplicate_cols.remove(col)
  1070. print(f"将 {col} 重命名为 simTime")
  1071. break
  1072. df = df.drop(columns=duplicate_cols)
  1073. print(f"删除了重复列: {duplicate_cols}")
  1074. # 打印清理后的列名
  1075. print(f"清理重复列后的列名: {df.columns.tolist()}")
  1076. return df
  1077. # --- 合并 EgoMap ---
  1078. egomap_path = self.output_dir / OUTPUT_CSV_EGOMAP
  1079. if egomap_path.exists() and egomap_path.stat().st_size > 0:
  1080. try:
  1081. df_ego = pd.read_csv(egomap_path, dtype={"simTime": float})
  1082. # 删除 simFrame 列,因为使用主数据的 simFrame
  1083. if 'simFrame' in df_ego.columns:
  1084. df_ego = df_ego.drop(columns=['simFrame'])
  1085. # 打印合并前的列名
  1086. print(f"合并 EgoMap 前 df_merged 的列: {df_merged.columns.tolist()}")
  1087. print(f"df_ego 的列: {df_ego.columns.tolist()}")
  1088. # 按时间和ID排序
  1089. df_ego.sort_values(['simTime', 'playerId'], inplace=True)
  1090. df_merged.sort_values(['simTime', 'playerId'], inplace=True)
  1091. # 使用 merge_asof 进行就近合并,不包括 simFrame
  1092. df_merged = pd.merge_asof(
  1093. df_merged,
  1094. df_ego,
  1095. on='simTime',
  1096. by='playerId',
  1097. direction='nearest',
  1098. tolerance=0.01 # 10ms tolerance
  1099. )
  1100. # 打印合并后的列名
  1101. print(f"合并 EgoMap 后 df_merged 的列: {df_merged.columns.tolist()}")
  1102. # 确保 simTime 列存在
  1103. if 'simTime' not in df_merged.columns:
  1104. if 'simTime_x' in df_merged.columns:
  1105. df_merged.rename(columns={'simTime_x': 'simTime'}, inplace=True)
  1106. print("将 simTime_x 重命名为 simTime")
  1107. else:
  1108. print("警告: 合并 EgoMap 后找不到 simTime 列!")
  1109. print("EgoMap data merged.")
  1110. except Exception as e:
  1111. print(f"Warning: Could not merge EgoMap data from {egomap_path}: {e}")
  1112. import traceback
  1113. traceback.print_exc()
  1114. # 先处理可能的列名重复问题
  1115. df_merged = clean_duplicate_columns(df_merged)
  1116. # --- 合并 Traffic ---
  1117. traffic_path = self.output_dir / "Traffic.csv"
  1118. if traffic_path.exists() and traffic_path.stat().st_size > 0:
  1119. try:
  1120. df_traffic = pd.read_csv(traffic_path, dtype={"simTime": float}, low_memory=False).drop_duplicates()
  1121. # 删除 simFrame 列
  1122. if 'simFrame' in df_traffic.columns:
  1123. df_traffic = df_traffic.drop(columns=['simFrame'])
  1124. # 根据车辆航向角确定行驶方向并筛选对应的红绿灯
  1125. def get_direction_from_heading(heading):
  1126. # 将角度归一化到 -180 到 180 度范围
  1127. heading = heading % 360
  1128. if heading > 180:
  1129. heading -= 360
  1130. # 确定方向:北(N)、东(E)、南(S)、西(W)
  1131. if -45 <= heading <= 45: # 北向
  1132. return 'N'
  1133. elif 45 < heading <= 135: # 东向
  1134. return 'E'
  1135. elif -135 <= heading < -45: # 西向
  1136. return 'W'
  1137. else: # 南向 (135 < heading <= 180 或 -180 <= heading < -135)
  1138. return 'S'
  1139. # 检查posH列是否存在,如果不存在但posH_x存在,则使用posH_x
  1140. heading_col = 'posH'
  1141. if heading_col not in df_merged.columns:
  1142. if 'posH_x' in df_merged.columns:
  1143. heading_col = 'posH_x'
  1144. print(f"使用 {heading_col} 替代 posH")
  1145. else:
  1146. print(f"警告: 找不到航向角列 posH 或 posH_x")
  1147. return df_merged
  1148. # 添加方向列
  1149. df_merged['vehicle_direction'] = df_merged[heading_col].apply(get_direction_from_heading)
  1150. # 创建 phaseId 到方向的映射
  1151. phase_to_direction = {
  1152. 1: 'S', # 南直行
  1153. 2: 'W', # 西直行
  1154. 3: 'N', # 北直行
  1155. 4: 'E', # 东直行
  1156. 5: 'S', # 南行人
  1157. 6: 'W', # 西行人
  1158. 7: 'S', # 南左转
  1159. 8: 'W', # 西左转
  1160. 9: 'N', # 北左转
  1161. 10: 'E', # 东左转
  1162. 11: 'N', # 北行人
  1163. 12: 'E', # 东行人
  1164. 13: 'S', # 南右转
  1165. 14: 'W', # 西右转
  1166. 15: 'N', # 北右转
  1167. 16: 'E' # 东右转
  1168. }
  1169. # 创建 trafficlight_id 到方向的映射
  1170. trafficlight_to_direction = {
  1171. # 南向北方向的红绿灯
  1172. 48100017: 'S',
  1173. 48100038: 'S',
  1174. 48100043: 'S',
  1175. 48100030: 'S',
  1176. # 西向东方向的红绿灯
  1177. 48100021: 'W',
  1178. 48100039: 'W',
  1179. # 东向西方向的红绿灯
  1180. 48100041: 'E',
  1181. 48100019: 'E',
  1182. # 北向南方向的红绿灯
  1183. 48100033: 'N',
  1184. 48100018: 'N',
  1185. 48100022: 'N'
  1186. }
  1187. # 添加时间列用于合并
  1188. df_traffic['time'] = df_traffic['simTime'].round(2).astype(float)
  1189. # 检查 df_merged 中是否有 simTime 列
  1190. if 'simTime' not in df_merged.columns:
  1191. print("警告: 合并 Traffic 前 df_merged 中找不到 simTime 列!")
  1192. # 尝试查找 simTime_x 或其他可能的列
  1193. if 'simTime_x' in df_merged.columns:
  1194. df_merged.rename(columns={'simTime_x': 'simTime'}, inplace=True)
  1195. print("将 simTime_x 重命名为 simTime")
  1196. else:
  1197. print("严重错误: 无法找到任何 simTime 相关列,无法继续合并!")
  1198. return df_merged
  1199. df_merged['time'] = df_merged['simTime'].round(2).astype(float)
  1200. # 合并 Traffic 数据
  1201. df_merged = pd.merge(df_merged, df_traffic, on=["time"], how="left")
  1202. # 再次处理可能的列名重复问题
  1203. df_merged = clean_duplicate_columns(df_merged)
  1204. # 检查trafficlight_id列是否存在
  1205. trafficlight_col = 'trafficlight_id'
  1206. if trafficlight_col not in df_merged.columns:
  1207. if 'trafficlight_id_x' in df_merged.columns:
  1208. trafficlight_col = 'trafficlight_id_x'
  1209. print(f"使用 {trafficlight_col} 替代 trafficlight_id")
  1210. else:
  1211. print(f"警告: 找不到红绿灯ID列 trafficlight_id 或 trafficlight_id_x")
  1212. # 筛选与车辆行驶方向相关的红绿灯
  1213. def filter_relevant_traffic_light(row):
  1214. if 'phaseId' not in row or pd.isna(row['phaseId']):
  1215. return np.nan
  1216. # 获取 phaseId 对应的方向
  1217. phase_id = int(row['phaseId']) if not pd.isna(row['phaseId']) else None
  1218. if phase_id is None:
  1219. return np.nan
  1220. phase_direction = phase_to_direction.get(phase_id, None)
  1221. # 如果 phaseId 方向与车辆方向匹配
  1222. if phase_direction == row['vehicle_direction']:
  1223. # 查找该方向的所有红绿灯 ID
  1224. relevant_ids = [tid for tid, direction in trafficlight_to_direction.items()
  1225. if direction == phase_direction]
  1226. # 如果 trafficlight_id 在 EgoMap 中且方向匹配
  1227. if trafficlight_col in row and not pd.isna(row[trafficlight_col]) and row[trafficlight_col] in relevant_ids:
  1228. return row[trafficlight_col]
  1229. return np.nan
  1230. # 应用筛选函数
  1231. df_merged['filtered_trafficlight_id'] = df_merged.apply(filter_relevant_traffic_light, axis=1)
  1232. # 清理临时列
  1233. print(f"删除 time 列前 df_merged 的列: {df_merged.columns.tolist()}")
  1234. df_merged.drop(columns=['time'], inplace=True)
  1235. print(f"删除 time 列后 df_merged 的列: {df_merged.columns.tolist()}")
  1236. # 确保 simTime 列存在
  1237. if 'simTime' not in df_merged.columns:
  1238. if 'simTime_x' in df_merged.columns:
  1239. df_merged.rename(columns={'simTime_x': 'simTime'}, inplace=True)
  1240. print("将 simTime_x 重命名为 simTime")
  1241. else:
  1242. print("警告: 处理 Traffic 数据后找不到 simTime 列!")
  1243. print("Traffic light data merged and filtered.")
  1244. except Exception as e:
  1245. print(f"Warning: Could not merge Traffic data from {traffic_path}: {e}")
  1246. import traceback
  1247. traceback.print_exc()
  1248. else:
  1249. print("Traffic data not found or empty, skipping merge.")
  1250. # --- Merge Function ---
  1251. function_path = self.output_dir / OUTPUT_CSV_FUNCTION
  1252. if function_path.exists() and function_path.stat().st_size > 0:
  1253. try:
  1254. # 添加调试信息
  1255. print(f"正在读取 Function 数据: {function_path}")
  1256. df_function = pd.read_csv(function_path, low_memory=False).drop_duplicates()
  1257. print(f"Function 数据列名: {df_function.columns.tolist()}")
  1258. # 删除 simFrame 列
  1259. if 'simFrame' in df_function.columns:
  1260. df_function = df_function.drop(columns=['simFrame'])
  1261. # 确保 simTime 列存在并且是浮点型
  1262. if 'simTime' in df_function.columns:
  1263. # 安全地将 simTime 转换为浮点型
  1264. try:
  1265. df_function['simTime'] = pd.to_numeric(df_function['simTime'], errors='coerce')
  1266. df_function = df_function.dropna(subset=['simTime']) # 删除无法转换的行
  1267. df_function['time'] = df_function['simTime'].round(2)
  1268. # 安全地处理 df_merged 的 simTime 列
  1269. if 'simTime' in df_merged.columns:
  1270. print(f"df_merged['simTime'] 的类型: {df_merged['simTime'].dtype}")
  1271. print(f"df_merged['simTime'] 的前5个值: {df_merged['simTime'].head().tolist()}")
  1272. df_merged['time'] = pd.to_numeric(df_merged['simTime'], errors='coerce').round(2)
  1273. # 删除 time 列中的 NaN 值
  1274. nan_count = df_merged['time'].isna().sum()
  1275. if nan_count > 0:
  1276. print(f"警告: 转换后有 {nan_count} 个 NaN 值,将删除这些行")
  1277. df_merged = df_merged.dropna(subset=['time'])
  1278. # 确保两个 DataFrame 的 time 列类型一致
  1279. df_function['time'] = df_function['time'].astype(float)
  1280. df_merged['time'] = df_merged['time'].astype(float)
  1281. common_cols = list(set(df_merged.columns) & set(df_function.columns) - {'time'})
  1282. df_function.drop(columns=common_cols, inplace=True, errors='ignore')
  1283. # 合并数据
  1284. df_merged = pd.merge(df_merged, df_function, on=["time"], how="left")
  1285. df_merged.drop(columns=['time'], inplace=True)
  1286. print("Function 数据合并成功。")
  1287. else:
  1288. print("警告: df_merged 中找不到 'simTime' 列,无法合并 Function 数据。")
  1289. # 打印所有列名以便调试
  1290. print(f"df_merged 的所有列: {df_merged.columns.tolist()}")
  1291. except Exception as e:
  1292. print(f"警告: 处理 Function.csv 中的 simTime 列时出错: {e}")
  1293. import traceback
  1294. traceback.print_exc()
  1295. else:
  1296. print(f"警告: Function.csv 中找不到 'simTime' 列。可用的列: {df_function.columns.tolist()}")
  1297. except Exception as e:
  1298. print(f"警告: 无法合并 Function 数据: {e}")
  1299. import traceback
  1300. traceback.print_exc()
  1301. else:
  1302. print(f"Function 数据文件不存在或为空: {function_path}")
  1303. # --- Merge OBU ---
  1304. obu_path = self.output_dir / OUTPUT_CSV_OBU
  1305. if obu_path.exists() and obu_path.stat().st_size > 0:
  1306. try:
  1307. # 添加调试信息
  1308. print(f"正在读取 OBU 数据: {obu_path}")
  1309. df_obu = pd.read_csv(obu_path, low_memory=False).drop_duplicates()
  1310. print(f"OBU 数据列名: {df_obu.columns.tolist()}")
  1311. # 删除 simFrame 列
  1312. if 'simFrame' in df_obu.columns:
  1313. df_obu = df_obu.drop(columns=['simFrame'])
  1314. # 确保 simTime 列存在并且是浮点型
  1315. if 'simTime' in df_obu.columns:
  1316. # 安全地将 simTime 转换为浮点型
  1317. try:
  1318. df_obu['simTime'] = pd.to_numeric(df_obu['simTime'], errors='coerce')
  1319. df_obu = df_obu.dropna(subset=['simTime']) # 删除无法转换的行
  1320. df_obu['time'] = df_obu['simTime'].round(2)
  1321. # 安全地处理 df_merged 的 simTime 列
  1322. if 'simTime' in df_merged.columns:
  1323. print(f"合并 OBU 前 df_merged['simTime'] 的类型: {df_merged['simTime'].dtype}")
  1324. print(f"合并 OBU 前 df_merged['simTime'] 的前5个值: {df_merged['simTime'].head().tolist()}")
  1325. df_merged['time'] = pd.to_numeric(df_merged['simTime'], errors='coerce').round(2)
  1326. # 删除 time 列中的 NaN 值
  1327. nan_count = df_merged['time'].isna().sum()
  1328. if nan_count > 0:
  1329. print(f"警告: 转换后有 {nan_count} 个 NaN 值,将删除这些行")
  1330. df_merged = df_merged.dropna(subset=['time'])
  1331. # 确保两个 DataFrame 的 time 列类型一致
  1332. df_obu['time'] = df_obu['time'].astype(float)
  1333. df_merged['time'] = df_merged['time'].astype(float)
  1334. common_cols = list(set(df_merged.columns) & set(df_obu.columns) - {'time'})
  1335. df_obu.drop(columns=common_cols, inplace=True, errors='ignore')
  1336. # 合并数据
  1337. df_merged = pd.merge(df_merged, df_obu, on=["time"], how="left")
  1338. df_merged.drop(columns=['time'], inplace=True)
  1339. print("OBU 数据合并成功。")
  1340. else:
  1341. print("警告: df_merged 中找不到 'simTime' 列,无法合并 OBU 数据。")
  1342. # 打印所有列名以便调试
  1343. print(f"df_merged 的所有列: {df_merged.columns.tolist()}")
  1344. except Exception as e:
  1345. print(f"警告: 处理 OBUdata.csv 中的 simTime 列时出错: {e}")
  1346. import traceback
  1347. traceback.print_exc()
  1348. else:
  1349. print(f"警告: OBUdata.csv 中找不到 'simTime' 列。可用的列: {df_obu.columns.tolist()}")
  1350. except Exception as e:
  1351. print(f"警告: 无法合并 OBU 数据: {e}")
  1352. import traceback
  1353. traceback.print_exc()
  1354. else:
  1355. print(f"OBU 数据文件不存在或为空: {obu_path}")
  1356. # 在所有合并完成后,再次清理重复列
  1357. df_merged = clean_duplicate_columns(df_merged)
  1358. return df_merged
  1359. def _process_trafficlight_data(self) -> pd.DataFrame:
  1360. """Processes traffic light JSON data if available."""
  1361. # Check if json_path is provided and exists
  1362. if not self.config.json_path:
  1363. print("No traffic light JSON file provided. Skipping traffic light processing.")
  1364. return pd.DataFrame()
  1365. if not self.config.json_path.exists():
  1366. print("Traffic light JSON file not found. Skipping traffic light processing.")
  1367. return pd.DataFrame()
  1368. print(f"Processing traffic light data from: {self.config.json_path}")
  1369. valid_trafficlights = []
  1370. try:
  1371. with open(self.config.json_path, 'r', encoding='utf-8') as f:
  1372. # Read the whole file, assuming it's a JSON array or JSON objects per line
  1373. try:
  1374. # Attempt to read as a single JSON array
  1375. raw_data = json.load(f)
  1376. if not isinstance(raw_data, list):
  1377. raw_data = [raw_data] # Handle case of single JSON object
  1378. except json.JSONDecodeError:
  1379. # If fails, assume JSON objects per line
  1380. f.seek(0) # Reset file pointer
  1381. raw_data = [json.loads(line) for line in f if line.strip()]
  1382. for entry in raw_data:
  1383. # Normalize entry if it's a string containing JSON
  1384. if isinstance(entry, str):
  1385. try:
  1386. entry = json.loads(entry)
  1387. except json.JSONDecodeError:
  1388. print(f"Warning: Skipping invalid JSON string in traffic light data: {entry[:100]}...")
  1389. continue
  1390. # Safely extract data using .get()
  1391. intersections = entry.get('intersections', [])
  1392. if not isinstance(intersections, list): continue # Skip if not a list
  1393. for intersection in intersections:
  1394. if not isinstance(intersection, dict): continue
  1395. timestamp_ms = intersection.get('intersectionTimestamp', 0)
  1396. sim_time = round(int(timestamp_ms) / 1000, 2) # Convert ms to s and round
  1397. phases = intersection.get('phases', [])
  1398. if not isinstance(phases, list): continue
  1399. for phase in phases:
  1400. if not isinstance(phase, dict): continue
  1401. phase_id = phase.get('phaseId', 0)
  1402. phase_states = phase.get('phaseStates', [])
  1403. if not isinstance(phase_states, list): continue
  1404. for phase_state in phase_states:
  1405. if not isinstance(phase_state, dict): continue
  1406. # Check for startTime == 0 as per original logic
  1407. if phase_state.get('startTime') == 0:
  1408. light_state = phase_state.get('light', 0) # Extract light state
  1409. data = {
  1410. 'simTime': sim_time,
  1411. 'phaseId': phase_id,
  1412. 'stateMask': light_state,
  1413. # Add playerId for merging - assume applies to ego
  1414. 'playerId': PLAYER_ID_EGO
  1415. }
  1416. valid_trafficlights.append(data)
  1417. if not valid_trafficlights:
  1418. print("No valid traffic light states (with startTime=0) found in JSON.")
  1419. return pd.DataFrame()
  1420. df_trafficlights = pd.DataFrame(valid_trafficlights)
  1421. # Drop duplicates based on relevant fields
  1422. df_trafficlights.drop_duplicates(subset=['simTime', 'playerId', 'phaseId', 'stateMask'], keep='first',
  1423. inplace=True)
  1424. print(f"Processed {len(df_trafficlights)} unique traffic light state entries.")
  1425. # 按时间升序排序 - 修复倒序问题
  1426. df_trafficlights = df_trafficlights.sort_values('simTime', ascending=True)
  1427. # 添加调试信息
  1428. print(f"交通灯数据时间范围: {df_trafficlights['simTime'].min()} 到 {df_trafficlights['simTime'].max()}")
  1429. print(f"交通灯数据前5行时间: {df_trafficlights['simTime'].head().tolist()}")
  1430. print(f"交通灯数据后5行时间: {df_trafficlights['simTime'].tail().tolist()}")
  1431. return df_trafficlights
  1432. except json.JSONDecodeError as e:
  1433. print(f"Error decoding traffic light JSON file {self.config.json_path}: {e}")
  1434. return pd.DataFrame()
  1435. except Exception as e:
  1436. print(f"Unexpected error processing traffic light data: {e}")
  1437. return pd.DataFrame()
  1438. # --- Rosbag Processing ---
  1439. class RosbagProcessor:
  1440. """Extracts data from Rosbag files within a ZIP archive."""
  1441. # Mapping from filename parts to rostopics
  1442. ROSTOPIC_MAP = {
  1443. ('V2I', 'HazardousLocationW'): "/HazardousLocationWarning",
  1444. ('V2C', 'OtherVehicleRedLightViolationW'): "/c2v/GoThroughRadLight",
  1445. ('V2I', 'LeftTurnAssist'): "/LeftTurnAssistant",
  1446. ('V2V', 'LeftTurnAssist'): "/V2VLeftTurnAssistant",
  1447. ('V2I', 'RedLightViolationW'): "/SignalViolationWarning",
  1448. ('V2C', 'AbnormalVehicleW'): "/c2v/AbnormalVehicleWarnning",
  1449. ('V2C', 'SignalLightReminder'): "/c2v/TrafficLightInfo",
  1450. ('V2C', 'VulnerableRoadUserCollisionW'): "/c2v/VulnerableObject",
  1451. ('V2C', 'EmergencyVehiclesPriority'): "/c2v/EmergencyVehiclesPriority",
  1452. ('V2C', 'LitterW'): "/c2v/RoadSpillageWarning",
  1453. ('V2V', 'ForwardCollisionW'): "/V2VForwardCollisionWarning",
  1454. ('V2C', 'VisibilityW'): "/c2v/VisibilityWarinning",
  1455. ('V2V', 'EmergencyBrakeW'): "/V2VEmergencyBrakeWarning",
  1456. ('V2I', 'GreenLightOptimalSpeedAdvisory'): "/GreenLightOptimalSpeedAdvisory", # Check exact topic name
  1457. ('V2C', 'DynamicSpeedLimitingInformation'): "/c2v/DynamicSpeedLimit",
  1458. ('V2C', 'TrafficJamW'): "/c2v/TrafficJam",
  1459. ('V2C', 'DrivingLaneRecommendation'): "/c2v/LaneGuidance",
  1460. ('V2C', 'RampMerge'): "/c2v/RampMerging",
  1461. ('V2I', 'CooperativeIntersectionPassing'): "/CooperativeIntersectionPassing",
  1462. ('V2I', 'IntersectionCollisionW'): "/IntersectionCollisionWarning",
  1463. ('V2V', 'IntersectionCollisionW'): "/V2VIntersectionCollisionWarning",
  1464. ('V2V', 'BlindSpotW'): "/V2VBlindSpotWarning",
  1465. ('V2I', 'SpeedLimitW'): "/SpeedLimit",
  1466. ('V2I', 'VulnerableRoadUserCollisionW'): "/VulnerableRoadUserCollisionWarning",
  1467. ('V2I', 'CooperativeLaneChange'): "/CooperativeLaneChange",
  1468. ('V2V', 'CooperativeLaneChange'): "/V2VCooperativeLaneChange",
  1469. ('V2I', 'CooperativeVehicleMerge'): "/CooperativeVehicleMerge",
  1470. ('V2V', 'AbnormalVehicleW'): "/V2VAbnormalVehicleWarning",
  1471. ('V2V', 'ControlLossW'): "/V2VVehicleLossControlWarning",
  1472. ('V2V', 'EmergencyVehicleW'): '/V2VEmergencyVehicleWarning',
  1473. ('V2I', 'InVehicleSignage'): "/InVehicleSign",
  1474. ('V2V', 'DoNotPassW'): "/V2VDoNotPassWarning",
  1475. ('V2I', 'TrafficJamW'): "/TrafficJamWarning",
  1476. # Add more mappings as needed
  1477. }
  1478. def __init__(self, config: Config):
  1479. self.config = config
  1480. self.output_dir = config.output_dir
  1481. def _get_target_rostopic(self, zip_filename: str) -> Optional[str]:
  1482. """Determines the target rostopic based on keywords in the filename."""
  1483. for (kw1, kw2), topic in self.ROSTOPIC_MAP.items():
  1484. if kw1 in zip_filename and kw2 in zip_filename:
  1485. print(f"Identified target topic '{topic}' for {zip_filename}")
  1486. return topic
  1487. print(f"Warning: No specific rostopic mapping found for {zip_filename}.")
  1488. return None
  1489. def process_zip_for_rosbags(self) -> None:
  1490. """Finds, extracts, and processes rosbags from the ZIP file."""
  1491. print(f"--- Processing Rosbags in {self.config.zip_path} ---")
  1492. target_rostopic = self._get_target_rostopic(self.config.zip_path.stem)
  1493. if not target_rostopic:
  1494. print("Skipping Rosbag processing as no target topic was identified.")
  1495. with tempfile.TemporaryDirectory() as tmp_dir_str:
  1496. tmp_dir = Path(tmp_dir_str)
  1497. bag_files_extracted = []
  1498. try:
  1499. with zipfile.ZipFile(self.config.zip_path, 'r') as zip_ref:
  1500. for member in zip_ref.infolist():
  1501. # Extract Rosbag files
  1502. if 'Rosbag/' in member.filename and member.filename.endswith('.bag'):
  1503. try:
  1504. extracted_path = Path(zip_ref.extract(member, path=tmp_dir))
  1505. bag_files_extracted.append(extracted_path)
  1506. print(f"Extracted Rosbag: {extracted_path.name}")
  1507. except Exception as e:
  1508. print(f"Error extracting Rosbag {member.filename}: {e}")
  1509. # Extract HMIdata CSV files directly to output
  1510. elif 'HMIdata/' in member.filename and member.filename.endswith('.csv'):
  1511. try:
  1512. target_path = self.output_dir / Path(member.filename).name
  1513. with zip_ref.open(member) as source, open(target_path, "wb") as target:
  1514. shutil.copyfileobj(source, target)
  1515. print(f"Extracted HMI data: {target_path.name}")
  1516. except Exception as e:
  1517. print(f"Error extracting HMI data {member.filename}: {e}")
  1518. except zipfile.BadZipFile:
  1519. print(f"Error: Bad ZIP file provided: {self.config.zip_path}")
  1520. return
  1521. except FileNotFoundError:
  1522. print(f"Error: ZIP file not found: {self.config.zip_path}")
  1523. return
  1524. if not bag_files_extracted:
  1525. print("No Rosbag files found in the archive.")
  1526. # Attempt extraction of HMI/RDB anyway if needed (already done above)
  1527. return
  1528. # Process extracted bag files
  1529. for bag_path in bag_files_extracted:
  1530. print(f"Processing bag file: {bag_path.name}")
  1531. self._convert_bag_topic_to_csv(bag_path, target_rostopic)
  1532. print("--- Rosbag Processing Finished ---")
  1533. def _convert_bag_topic_to_csv(self, bag_file_path: Path, target_topic: str) -> None:
  1534. """Converts a specific topic from a single bag file to CSV."""
  1535. output_csv_path = self.output_dir / OUTPUT_CSV_OBU # Standard name for OBU data
  1536. try:
  1537. # Check if bagpy can handle Path object, else convert to str
  1538. bag_reader = bagreader(str(bag_file_path), verbose=False)
  1539. # Check if topic exists
  1540. available_topics = bag_reader.topic_table['Topics'].tolist() if hasattr(bag_reader,
  1541. 'topic_table') and bag_reader.topic_table is not None else []
  1542. if target_topic not in available_topics:
  1543. print(f"Target topic '{target_topic}' not found in {bag_file_path.name}. Available: {available_topics}")
  1544. # Clean up temporary bagpy-generated files if possible
  1545. df = pd.DataFrame(columns=['simTime', 'event_Type'])
  1546. if hasattr(bag_reader, 'data_folder') and Path(bag_reader.data_folder).exists():
  1547. shutil.rmtree(bag_reader.data_folder, ignore_errors=True)
  1548. else:
  1549. # Extract message data to a temporary CSV created by bagpy
  1550. temp_csv_path_str = bag_reader.message_by_topic(target_topic)
  1551. temp_csv_path = Path(temp_csv_path_str)
  1552. if not temp_csv_path.exists() or temp_csv_path.stat().st_size == 0:
  1553. print(
  1554. f"Warning: Bagpy generated an empty or non-existent CSV for topic '{target_topic}' from {bag_file_path.name}.")
  1555. return # Skip if empty
  1556. # Read the temporary CSV, process, and save to final location
  1557. df = pd.read_csv(temp_csv_path)
  1558. if df.empty:
  1559. print(f"Warning: Bagpy CSV for topic '{target_topic}' is empty after reading.")
  1560. return
  1561. # Clean columns: Drop 'Time', rename '*timestamp' -> 'simTime'
  1562. if 'Time' in df.columns:
  1563. df.drop(columns=['Time'], inplace=True)
  1564. rename_dict = {}
  1565. for col in df.columns:
  1566. if col.endswith('.timestamp'): # More specific match
  1567. rename_dict[col] = 'simTime'
  1568. elif col.endswith('event_type'): # As per original code
  1569. rename_dict[col] = 'event_Type'
  1570. # Add other renames if necessary
  1571. df.rename(columns=rename_dict, inplace=True)
  1572. # Ensure simTime is float and rounded (optional, do if needed for merging)
  1573. if 'simTime' in df.columns:
  1574. df['simTime'] = pd.to_numeric(df['simTime'], errors='coerce').round(2) # Example rounding
  1575. # Save processed data
  1576. df.to_csv(output_csv_path, index=False, float_format='%.6f')
  1577. print(f"Saved processed OBU data to: {output_csv_path}")
  1578. except ValueError as ve:
  1579. # Catch potential Bagpy internal errors if topic doesn't contain messages
  1580. print(
  1581. f"ValueError processing bag {bag_file_path.name} (Topic: {target_topic}): {ve}. Topic might be empty.")
  1582. except ImportError as ie:
  1583. print(
  1584. f"ImportError during bag processing: {ie}. Ensure all ROS dependencies are installed if needed by bagpy.")
  1585. except Exception as e:
  1586. print(f"Error processing bag file {bag_file_path.name} (Topic: {target_topic}): {e}")
  1587. import traceback
  1588. traceback.print_exc() # More details on unexpected errors
  1589. finally:
  1590. # Clean up temporary files/folders created by bagpy
  1591. if 'temp_csv_path' in locals() and temp_csv_path.exists():
  1592. try:
  1593. temp_csv_path.unlink() # Delete the specific CSV
  1594. except OSError as ose:
  1595. print(f"Warning: Could not delete bagpy temp csv {temp_csv_path}: {ose}")
  1596. if 'bag_reader' in locals() and hasattr(bag_reader, 'data_folder'):
  1597. bagpy_folder = Path(bag_reader.data_folder)
  1598. if bagpy_folder.exists() and bagpy_folder.is_dir():
  1599. try:
  1600. shutil.rmtree(bagpy_folder, ignore_errors=True) # Delete the folder bagpy made
  1601. except OSError as ose:
  1602. print(f"Warning: Could not delete bagpy temp folder {bagpy_folder}: {ose}")
  1603. # --- Utility Functions ---
  1604. def get_base_path() -> Path:
  1605. """Gets the base path of the script or executable."""
  1606. if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
  1607. # Running in a PyInstaller bundle
  1608. return Path(sys._MEIPASS)
  1609. else:
  1610. # Running as a normal script
  1611. return Path(__file__).parent.resolve()
  1612. def run_cpp_engine(config: Config):
  1613. """Runs the external C++ preprocessing engine."""
  1614. if not config.engine_path or not config.map_path:
  1615. print("C++ engine path or map path not configured. Skipping C++ engine execution.")
  1616. return True # Return True assuming it's optional or handled elsewhere
  1617. engine_cmd = [
  1618. str(config.engine_path),
  1619. str(config.map_path),
  1620. str(config.output_dir),
  1621. str(config.x_offset),
  1622. str(config.y_offset)
  1623. ]
  1624. print(f"--- Running C++ Preprocessing Engine ---")
  1625. print(f"Command: {' '.join(engine_cmd)}")
  1626. try:
  1627. result = subprocess.run(
  1628. engine_cmd,
  1629. check=True, # Raise exception on non-zero exit code
  1630. capture_output=True, # Capture stdout/stderr
  1631. text=True, # Decode output as text
  1632. cwd=config.engine_path.parent # Run from the engine's directory? Or script's? Adjust if needed.
  1633. )
  1634. print("C++ Engine Output:")
  1635. print(result.stdout)
  1636. if result.stderr:
  1637. print("C++ Engine Error Output:")
  1638. print(result.stderr)
  1639. print("--- C++ Engine Finished Successfully ---")
  1640. return True
  1641. except FileNotFoundError:
  1642. print(f"Error: C++ engine executable not found at {config.engine_path}.")
  1643. return False
  1644. except subprocess.CalledProcessError as e:
  1645. print(f"Error: C++ engine failed with exit code {e.returncode}.")
  1646. print("C++ Engine Output (stdout):")
  1647. print(e.stdout)
  1648. print("C++ Engine Output (stderr):")
  1649. print(e.stderr)
  1650. return False
  1651. except Exception as e:
  1652. print(f"An unexpected error occurred while running the C++ engine: {e}")
  1653. return False
  1654. if __name__ == "__main__":
  1655. pass