lst.py 81 KB

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