lst.py 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  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 = 1
  23. PLAYER_ID_OBJ = 2
  24. DEFAULT_TYPE = 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 zip(OBJ_COLS_OLD_SUFFIXED, EGO_COLS_NEW[3:13])} # Map suffixed cols to standard names
  67. def __init__(self, config: Config):
  68. self.config = config
  69. self.dbc = self._load_dbc(config.dbc_path)
  70. self.projection = Proj(proj='utm', zone=config.utm_zone, ellps='WGS84', preserve_units='m')
  71. self._init_table_config()
  72. self._init_keyword_mapping()
  73. def _load_dbc(self, dbc_path: Optional[Path]) -> Optional[cantools.db.Database]:
  74. if not dbc_path or not dbc_path.exists():
  75. print("DBC path not provided or file not found.")
  76. return None
  77. try:
  78. return cantools.db.load_file(dbc_path)
  79. except Exception as e:
  80. print(f"DBC loading failed: {e}")
  81. return None
  82. def _init_table_config(self):
  83. """Initializes configurations for different table types."""
  84. self.table_config = {
  85. "gnss_table": self._get_gnss_config(),
  86. "can_table": self._get_can_config()
  87. }
  88. def _get_gnss_config(self):
  89. # Keep relevant columns, adjust mapping as needed
  90. return {
  91. "output_columns": self.EGO_COLS_NEW, # Use the standard ego columns + type
  92. "mapping": { # Map output columns to source DB columns/signals
  93. "simTime": ("second", "usecond"),
  94. "simFrame": "ID",
  95. "v": "speed",
  96. "speedY": "y_speed",
  97. "speedX": "x_speed",
  98. "posH": "yaw",
  99. "speedH": "yaw_rate",
  100. "posX": "latitude_dd", # Source before projection
  101. "posY": "longitude_dd", # Source before projection
  102. "accelX": "x_acceleration",
  103. "accelY": "y_acceleration",
  104. "travelDist": "total_distance",
  105. # composite_v/relative_dist might not be direct fields in GNSS, handle later if needed
  106. "composite_v": "speed", # Placeholder, adjust if needed
  107. "relative_dist": None, # Placeholder, likely not in GNSS data
  108. "type": None # Will be set later
  109. },
  110. "db_columns": ["ID", "second", "usecond", "speed", "y_speed", "x_speed",
  111. "yaw", "yaw_rate", "latitude_dd", "longitude_dd",
  112. "x_acceleration", "y_acceleration", "total_distance"] # Actual cols to SELECT
  113. }
  114. def _get_can_config(self):
  115. # Define columns needed from DB/CAN signals for both EGO and OBJ
  116. return {
  117. "mapping": { # Map unified output columns to CAN signals or direct fields
  118. # EGO mappings (VUT = Vehicle Under Test)
  119. "simTime": ("second", "usecond"),
  120. "simFrame": "ID",
  121. "canid": "canid", # Keep CAN ID for reference if needed
  122. "v": "VUT_Speed_mps",
  123. "speedX": "VUT_Speed_x_mps",
  124. "speedY": "VUT_Speed_y_mps",
  125. "speedH": "VUT_Yaw_Rate",
  126. "posX": "VUT_GPS_Latitude", # Source before projection
  127. "posY": "VUT_GPS_Longitude", # Source before projection
  128. "posH": "VUT_Heading",
  129. "accelX": "VUT_Acc_X",
  130. "accelY": "VUT_Acc_Y",
  131. # OBJ mappings (UFO = Unidentified Flying Object / Other Vehicle)
  132. "v_obj": "Speed_mps",
  133. "speedX_obj": "UFO_Speed_x_mps",
  134. "speedY_obj": "UFO_Speed_y_mps",
  135. "speedH_obj": "Yaw_Rate",
  136. "posX_obj": "GPS_Latitude", # Source before projection
  137. "posY_obj": "GPS_Longitude", # Source before projection
  138. "posH_obj": "Heading",
  139. "accelX_obj": "Acc_X",
  140. "accelY_obj": "Acc_Y",
  141. # Relative Mappings
  142. "composite_v": "VUT_Rel_speed_long_mps",
  143. "relative_dist": "VUT_Dist_MRP_Abs",
  144. # travelDist often calculated, not direct CAN signal
  145. "travelDist": None, # Placeholder
  146. "travelDist_obj": None # Placeholder
  147. },
  148. "db_columns": ["ID", "second", "usecond", "timestamp", "canid", "len", "frame"] # Core DB columns
  149. }
  150. def _init_keyword_mapping(self):
  151. """Maps keywords in filenames to table configurations and output CSV names."""
  152. self.keyword_mapping = {
  153. "gnss": ("gnss_table", OUTPUT_CSV_OBJSTATE), # GNSS likely represents ego, writing to ObjState first? Revisit logic if needed.
  154. "can2": ("can_table", OUTPUT_CSV_OBJSTATE), # Process CAN data into the combined ObjState file
  155. }
  156. def process_zip(self) -> None:
  157. """Extracts and processes DB files from the configured ZIP path."""
  158. print(f"Processing ZIP: {self.config.zip_path}")
  159. output_dir = self.config.output_dir # Already created in Config
  160. try:
  161. with zipfile.ZipFile(self.config.zip_path, "r") as zip_ref:
  162. db_files_to_process = []
  163. for file_info in zip_ref.infolist():
  164. # Check if it's a DB file in the CANdata directory
  165. if 'CANdata/' in file_info.filename and file_info.filename.endswith('.db'):
  166. # Check if the filename contains any of the keywords
  167. match = self._match_keyword(file_info.filename)
  168. if match:
  169. table_type, csv_name = match
  170. db_files_to_process.append((file_info, table_type, csv_name))
  171. if not db_files_to_process:
  172. print("No relevant DB files found in CANdata/ matching keywords.")
  173. return
  174. # Process matched DB files
  175. with tempfile.TemporaryDirectory() as tmp_dir_str:
  176. tmp_dir = Path(tmp_dir_str)
  177. for file_info, table_type, csv_name in db_files_to_process:
  178. print(f"Processing DB: {file_info.filename} for table type {table_type}")
  179. extracted_path = tmp_dir / Path(file_info.filename).name
  180. try:
  181. # Extract the specific DB file
  182. with zip_ref.open(file_info.filename) as source, open(extracted_path, "wb") as target:
  183. shutil.copyfileobj(source, target)
  184. # Process the extracted DB file
  185. self._process_db_file(extracted_path, output_dir, table_type, csv_name)
  186. except (sqlite3.Error, pd.errors.EmptyDataError, FileNotFoundError, KeyError) as e:
  187. print(f"Error processing DB file {file_info.filename}: {e}")
  188. except Exception as e:
  189. print(f"Unexpected error processing DB file {file_info.filename}: {e}")
  190. finally:
  191. if extracted_path.exists():
  192. extracted_path.unlink() # Clean up extracted file
  193. except zipfile.BadZipFile:
  194. print(f"Error: Bad ZIP file: {self.config.zip_path}")
  195. except FileNotFoundError:
  196. print(f"Error: ZIP file not found: {self.config.zip_path}")
  197. except Exception as e:
  198. print(f"An error occurred during ZIP processing: {e}")
  199. def _match_keyword(self, filename: str) -> Optional[Tuple[str, str]]:
  200. """Finds the first matching keyword configuration for a filename."""
  201. for keyword, (table_type, csv_name) in self.keyword_mapping.items():
  202. if keyword in filename:
  203. return table_type, csv_name
  204. return None
  205. def _process_db_file(
  206. self, db_path: Path, output_dir: Path, table_type: str, csv_name: str
  207. ) -> None:
  208. """Connects to SQLite DB and processes the specified table type."""
  209. output_csv_path = output_dir / csv_name
  210. try:
  211. # Use URI for read-only connection
  212. conn_str = f"file:{db_path}?mode=ro"
  213. with sqlite3.connect(conn_str, uri=True) as conn:
  214. cursor = conn.cursor()
  215. if not self._check_table_exists(cursor, table_type):
  216. print(f"Table '{table_type}' does not exist in {db_path.name}. Skipping.")
  217. return
  218. if self._check_table_empty(cursor, table_type):
  219. print(f"Table '{table_type}' in {db_path.name} is empty. Skipping.")
  220. return
  221. print(f"Exporting data from table '{table_type}' to {output_csv_path}")
  222. if table_type == "can_table":
  223. self._process_can_table_optimized(cursor, output_csv_path)
  224. elif table_type == "gnss_table":
  225. # Pass output_path directly, avoid intermediate steps
  226. self._process_gnss_table(cursor, output_csv_path)
  227. else:
  228. print(f"Warning: No specific processor for table type '{table_type}'. Skipping.")
  229. except sqlite3.OperationalError as e:
  230. print(f"Database operational error for {db_path.name}: {e}. Check file integrity/permissions.")
  231. except sqlite3.DatabaseError as e:
  232. print(f"Database error connecting to {db_path.name}: {e}")
  233. except Exception as e:
  234. print(f"Unexpected error processing DB {db_path.name}: {e}")
  235. def _check_table_exists(self, cursor, table_name: str) -> bool:
  236. """Checks if a table exists in the database."""
  237. try:
  238. cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?;", (table_name,))
  239. return cursor.fetchone() is not None
  240. except sqlite3.Error as e:
  241. print(f"Error checking existence of table {table_name}: {e}")
  242. return False # Assume not exists on error
  243. def _check_table_empty(self, cursor, table_name: str) -> bool:
  244. """Checks if a table is empty."""
  245. try:
  246. cursor.execute(f"SELECT COUNT(*) FROM {table_name}") # Use COUNT(*) for efficiency
  247. count = cursor.fetchone()[0]
  248. return count == 0
  249. except sqlite3.Error as e:
  250. # If error occurs (e.g., table doesn't exist after check - race condition?), treat as problematic/empty
  251. print(f"Error checking if table {table_name} is empty: {e}")
  252. return True
  253. def _process_gnss_table(self, cursor, output_path: Path) -> None:
  254. """Processes gnss_table data and writes directly to CSV."""
  255. config = self.table_config["gnss_table"]
  256. db_columns = config["db_columns"]
  257. output_columns = config["output_columns"]
  258. mapping = config["mapping"]
  259. try:
  260. cursor.execute(f"SELECT {', '.join(db_columns)} FROM gnss_table")
  261. rows = cursor.fetchall()
  262. if not rows:
  263. print("No data found in gnss_table.")
  264. return
  265. processed_data = []
  266. for row in rows:
  267. row_dict = dict(zip(db_columns, row))
  268. record = {}
  269. # Calculate simTime
  270. record["simTime"] = round(row_dict.get("second", 0) + row_dict.get("usecond", 0) / 1e6, 2)
  271. # Map other columns
  272. for out_col in output_columns:
  273. if out_col == "simTime": continue # Already handled
  274. if out_col == "playerId":
  275. record[out_col] = PLAYER_ID_EGO # Assuming GNSS is ego
  276. continue
  277. if out_col == "type":
  278. record[out_col] = DEFAULT_TYPE
  279. continue
  280. source_info = mapping.get(out_col)
  281. if source_info is None:
  282. record[out_col] = 0.0 # Or np.nan if preferred
  283. elif isinstance(source_info, tuple):
  284. # This case was only for simTime, handled above
  285. record[out_col] = 0.0
  286. else: # Direct mapping from db_columns
  287. raw_value = row_dict.get(source_info)
  288. if raw_value is not None:
  289. # Handle projection for position columns
  290. if out_col == "posX":
  291. # Assuming source_info = "latitude_dd"
  292. lat = row_dict.get(mapping["posX"])
  293. lon = row_dict.get(mapping["posY"])
  294. if lat is not None and lon is not None:
  295. proj_x, _ = self.projection(lon, lat)
  296. record[out_col] = round(proj_x, 6)
  297. else:
  298. record[out_col] = 0.0
  299. elif out_col == "posY":
  300. # Assuming source_info = "longitude_dd"
  301. lat = row_dict.get(mapping["posX"])
  302. lon = row_dict.get(mapping["posY"])
  303. if lat is not None and lon is not None:
  304. _, proj_y = self.projection(lon, lat)
  305. record[out_col] = round(proj_y, 6)
  306. else:
  307. record[out_col] = 0.0
  308. elif out_col in ["composite_v", "relative_dist"]:
  309. # Handle these based on source if available, else default
  310. record[out_col] = round(float(raw_value), 3) if source_info else 0.0
  311. else:
  312. # General case: round numeric values
  313. try:
  314. record[out_col] = round(float(raw_value), 3)
  315. except (ValueError, TypeError):
  316. record[out_col] = raw_value # Keep as is if not numeric
  317. else:
  318. record[out_col] = 0.0 # Default for missing source data
  319. processed_data.append(record)
  320. if processed_data:
  321. df_final = pd.DataFrame(processed_data)[output_columns] # Ensure column order
  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)
  368. df_obj = df_obj.reindex(columns=final_columns)
  369. # Merge EGO and OBJ dataframes
  370. df_merged = pd.concat([df_ego, df_obj], ignore_index=True)
  371. # Sort and clean up
  372. df_merged.sort_values(by=["simTime", "simFrame", "playerId"], inplace=True)
  373. df_merged.reset_index(drop=True, inplace=True)
  374. # Fill potential NaNs introduced by reindexing or missing data
  375. # Choose appropriate fill strategy (e.g., 0, forward fill, or leave as NaN)
  376. df_merged.fillna(0.0, inplace=True) # Example: fill with 0.0
  377. # Save the final merged DataFrame
  378. df_merged.to_csv(output_path, index=False, encoding="utf-8")
  379. print(f"Successfully processed CAN data and wrote merged output to {output_path}")
  380. except sqlite3.Error as e:
  381. print(f"SQL error during CAN processing: {e}")
  382. except KeyError as e:
  383. print(f"Key error during CAN processing - mapping issue? Missing key: {e}")
  384. except Exception as e:
  385. print(f"Unexpected error during CAN processing: {e}")
  386. import traceback
  387. traceback.print_exc() # Print detailed traceback for debugging
  388. def _decode_can_frame(self, row_dict: Dict) -> Dict[str, Any]:
  389. """Decodes CAN frame using DBC file if available."""
  390. decoded_signals = {}
  391. if self.dbc and 'canid' in row_dict and 'frame' in row_dict and 'len' in row_dict:
  392. can_id = row_dict['canid']
  393. frame_bytes = bytes(row_dict['frame'][:row_dict['len']]) # Ensure correct length
  394. try:
  395. message_def = self.dbc.get_message_by_frame_id(can_id)
  396. decoded_signals = message_def.decode(frame_bytes, decode_choices=False, allow_truncated=True) # Allow truncated
  397. except KeyError:
  398. # Optional: print(f"Warning: CAN ID 0x{can_id:X} not found in DBC.")
  399. pass # Ignore unknown IDs silently
  400. except ValueError as e:
  401. print(f"Warning: Decoding ValueError for CAN ID 0x{can_id:X} (length {row_dict['len']}, data: {frame_bytes.hex()}): {e}")
  402. except Exception as e:
  403. print(f"Warning: Error decoding CAN ID 0x{can_id:X}: {e}")
  404. return decoded_signals
  405. def _create_unified_can_record(self, row_dict: Dict, decoded_signals: Dict, mapping: Dict) -> Optional[Dict[str, Any]]:
  406. """Creates a single record combining DB fields and decoded signals based on mapping."""
  407. record = {}
  408. try:
  409. # Handle time and frame ID first
  410. record["simTime"] = round(row_dict.get("second", 0) + row_dict.get("usecond", 0) / 1e6, 2)
  411. record["simFrame"] = row_dict.get("ID")
  412. record["canid"] = f"0x{row_dict.get('canid', 0):X}" # Store CAN ID if needed
  413. # Populate record using the mapping config
  414. for target_col, source_info in mapping.items():
  415. if target_col in ["simTime", "simFrame", "canid"]: continue # Already handled
  416. if isinstance(source_info, tuple): continue # Should only be time
  417. # source_info is now the signal name (or None)
  418. signal_name = source_info
  419. if signal_name and signal_name in decoded_signals:
  420. # Value from decoded CAN signal
  421. raw_value = decoded_signals[signal_name]
  422. try:
  423. # Apply scaling/offset if needed (cantools handles this)
  424. # Round appropriately, especially for floats
  425. if isinstance(raw_value, (int, float)):
  426. # Be cautious with lat/lon precision before projection
  427. if "Latitude" in target_col or "Longitude" in target_col:
  428. record[target_col] = float(raw_value) # Keep precision for projection
  429. else:
  430. record[target_col] = round(float(raw_value), 6)
  431. else:
  432. record[target_col] = raw_value # Keep non-numeric as is (e.g., enums)
  433. except (ValueError, TypeError):
  434. record[target_col] = raw_value # Assign raw value if conversion fails
  435. # If signal not found or source_info is None, leave it empty for now
  436. # Will be filled later or during DataFrame processing
  437. return record
  438. except Exception as e:
  439. print(f"Error creating unified record for row {row_dict.get('ID')}: {e}")
  440. return None
  441. def _extract_vehicle_data(self, df_raw: pd.DataFrame, player_id: int) -> pd.DataFrame:
  442. """Extracts and renames columns for a specific vehicle (EGO or OBJ)."""
  443. df_vehicle = pd.DataFrame()
  444. df_vehicle["simTime"] = df_raw["simTime"]
  445. df_vehicle["simFrame"] = df_raw["simFrame"]
  446. df_vehicle["playerId"] = player_id
  447. if player_id == PLAYER_ID_EGO:
  448. # Select EGO columns (not ending in _obj) + relative columns
  449. ego_cols = {target: source for target, source in self.table_config['can_table']['mapping'].items()
  450. if source and not isinstance(source, tuple) and not target.endswith('_obj')}
  451. rename_map = {}
  452. select_cols_raw = []
  453. for target_col, source_info in ego_cols.items():
  454. if source_info: # Mapped signal/field name in df_raw
  455. select_cols_raw.append(target_col) # Column names in df_raw are already target names
  456. rename_map[target_col] = target_col # No rename needed here
  457. # Include relative speed and distance for ego frame
  458. relative_cols = ["composite_v", "relative_dist"]
  459. select_cols_raw.extend(relative_cols)
  460. for col in relative_cols:
  461. rename_map[col] = col
  462. # Select and rename
  463. df_vehicle_temp = df_raw[list(set(select_cols_raw) & set(df_raw.columns))] # Select available columns
  464. df_vehicle = pd.concat([df_vehicle, df_vehicle_temp], axis=1)
  465. elif player_id == PLAYER_ID_OBJ:
  466. # Select OBJ columns (ending in _obj)
  467. obj_cols = {target: source for target, source in self.table_config['can_table']['mapping'].items()
  468. if source and not isinstance(source, tuple) and target.endswith('_obj')}
  469. rename_map = {}
  470. select_cols_raw = []
  471. for target_col, source_info in obj_cols.items():
  472. if source_info:
  473. select_cols_raw.append(target_col) # Original _obj column name
  474. # Map from VUT_XXX_obj -> VUT_XXX
  475. rename_map[target_col] = self.OBJ_COLS_MAPPING.get(target_col, target_col) # Rename to standard name
  476. # Select and rename
  477. df_vehicle_temp = df_raw[list(set(select_cols_raw) & set(df_raw.columns))] # Select available columns
  478. df_vehicle_temp.rename(columns=rename_map, inplace=True)
  479. df_vehicle = pd.concat([df_vehicle, df_vehicle_temp], axis=1)
  480. # Copy relative speed/distance from ego calculation (assuming it's relative *to* ego)
  481. if "composite_v" in df_raw.columns:
  482. df_vehicle["composite_v"] = df_raw["composite_v"]
  483. if "relative_dist" in df_raw.columns:
  484. df_vehicle["relative_dist"] = df_raw["relative_dist"]
  485. # Drop rows where essential position data might be missing after selection/renaming
  486. # Adjust required columns as necessary
  487. required_pos = ['posX', 'posY', 'posH']
  488. df_vehicle.dropna(subset=[col for col in required_pos if col in df_vehicle.columns], inplace=True)
  489. return df_vehicle
  490. def _project_coordinates(self, df: pd.DataFrame, lat_col: str, lon_col: str) -> pd.DataFrame:
  491. """Applies UTM projection to latitude and longitude columns."""
  492. if lat_col in df.columns and lon_col in df.columns:
  493. # Ensure data is numeric and handle potential errors/missing values
  494. lat = pd.to_numeric(df[lat_col], errors='coerce')
  495. lon = pd.to_numeric(df[lon_col], errors='coerce')
  496. valid_coords = lat.notna() & lon.notna()
  497. if valid_coords.any():
  498. x, y = self.projection(lon[valid_coords].values, lat[valid_coords].values)
  499. # Update DataFrame, assign NaN where original coords were invalid
  500. df.loc[valid_coords, lat_col] = np.round(x, 6) # Overwrite latitude col with X
  501. df.loc[valid_coords, lon_col] = np.round(y, 6) # Overwrite longitude col with Y
  502. df.loc[~valid_coords, [lat_col, lon_col]] = np.nan # Set invalid coords to NaN
  503. else:
  504. # No valid coordinates found, set columns to NaN or handle as needed
  505. df[lat_col] = np.nan
  506. df[lon_col] = np.nan
  507. # Rename columns AFTER projection for clarity
  508. df.rename(columns={lat_col: 'posX', lon_col: 'posY'}, inplace=True)
  509. else:
  510. # Ensure columns exist even if projection didn't happen
  511. if 'posX' not in df.columns: df['posX'] = np.nan
  512. if 'posY' not in df.columns: df['posY'] = np.nan
  513. print(f"Warning: Latitude ('{lat_col}') or Longitude ('{lon_col}') columns not found for projection.")
  514. return df
  515. # --- Polynomial Fitting (Largely unchanged, minor cleanup) ---
  516. class PolynomialCurvatureFitting:
  517. """Calculates curvature and its derivative using polynomial fitting."""
  518. def __init__(self, lane_map_path: Path, degree: int = 3):
  519. self.lane_map_path = lane_map_path
  520. self.degree = degree
  521. self.data = self._load_data()
  522. if self.data is not None:
  523. self.points = self.data[["centerLine_x", "centerLine_y"]].values
  524. self.x_data, self.y_data = self.points[:, 0], self.points[:, 1]
  525. else:
  526. self.points = np.empty((0, 2))
  527. self.x_data, self.y_data = np.array([]), np.array([])
  528. def _load_data(self) -> Optional[pd.DataFrame]:
  529. """Loads lane map data safely."""
  530. if not self.lane_map_path.exists() or self.lane_map_path.stat().st_size == 0:
  531. print(f"Warning: LaneMap file not found or empty: {self.lane_map_path}")
  532. return None
  533. try:
  534. return pd.read_csv(self.lane_map_path)
  535. except pd.errors.EmptyDataError:
  536. print(f"Warning: LaneMap file is empty: {self.lane_map_path}")
  537. return None
  538. except Exception as e:
  539. print(f"Error reading LaneMap file {self.lane_map_path}: {e}")
  540. return None
  541. def curvature(self, coefficients: np.ndarray, x: float) -> float:
  542. """Computes curvature of the polynomial at x."""
  543. if len(coefficients) < 3: # Need at least degree 2 for curvature
  544. return 0.0
  545. first_deriv_coeffs = np.polyder(coefficients)
  546. second_deriv_coeffs = np.polyder(first_deriv_coeffs)
  547. dy_dx = np.polyval(first_deriv_coeffs, x)
  548. d2y_dx2 = np.polyval(second_deriv_coeffs, x)
  549. denominator = (1 + dy_dx**2)**1.5
  550. return np.abs(d2y_dx2) / denominator if denominator != 0 else np.inf
  551. def curvature_derivative(self, coefficients: np.ndarray, x: float) -> float:
  552. """Computes the derivative of curvature with respect to x."""
  553. if len(coefficients) < 4: # Need at least degree 3 for derivative of curvature
  554. return 0.0
  555. first_deriv_coeffs = np.polyder(coefficients)
  556. second_deriv_coeffs = np.polyder(first_deriv_coeffs)
  557. third_deriv_coeffs = np.polyder(second_deriv_coeffs)
  558. dy_dx = np.polyval(first_deriv_coeffs, x)
  559. d2y_dx2 = np.polyval(second_deriv_coeffs, x)
  560. d3y_dx3 = np.polyval(third_deriv_coeffs, x)
  561. denominator = (1 + dy_dx**2)**2.5 # Note the power is 2.5 or 5/2
  562. if denominator == 0:
  563. return np.inf
  564. numerator = d3y_dx3 * (1 + dy_dx**2) - 3 * dy_dx * d2y_dx2 * d2y_dx2 # Corrected term order? Verify formula
  565. # Standard formula: (d3y_dx3*(1 + dy_dx**2) - 3*dy_dx*(d2y_dx2**2)) / ((1 + dy_dx**2)**(5/2)) * sign(d2y_dx2)
  566. # Let's stick to the provided calculation logic but ensure denominator is correct
  567. # The provided formula in the original code seems to be for dk/ds (arc length), not dk/dx.
  568. # Re-implementing dk/dx based on standard calculus:
  569. term1 = d3y_dx3 * (1 + dy_dx**2)**(3/2)
  570. term2 = d2y_dx2 * (3/2) * (1 + dy_dx**2)**(1/2) * (2 * dy_dx * d2y_dx2) # Chain rule
  571. numerator_dk_dx = term1 - term2
  572. denominator_dk_dx = (1 + dy_dx**2)**3
  573. if denominator_dk_dx == 0:
  574. return np.inf
  575. # Take absolute value or not? Original didn't. Let's omit abs() for derivative.
  576. return numerator_dk_dx / denominator_dk_dx
  577. # dk_dx = (d3y_dx3 * (1 + dy_dx ** 2) - 3 * dy_dx * d2y_dx2 ** 2) / (
  578. # (1 + dy_dx ** 2) ** (5/2) # Original had power 3 ?? Double check this formula source
  579. # ) * np.sign(d2y_dx2) # Need sign of curvature
  580. # return dk_dx
  581. def polynomial_fit(
  582. self, x_window: np.ndarray, y_window: np.ndarray
  583. ) -> Tuple[Optional[np.ndarray], Optional[np.poly1d]]:
  584. """Performs polynomial fitting, handling potential rank warnings."""
  585. if len(x_window) <= self.degree:
  586. print(f"Warning: Window size {len(x_window)} is <= degree {self.degree}. Cannot fit.")
  587. return None, None
  588. try:
  589. # Use warnings context manager if needed, but RankWarning often indicates insufficient data variability
  590. # with warnings.catch_warnings():
  591. # warnings.filterwarnings('error', category=np.RankWarning) # Or ignore
  592. coefficients = np.polyfit(x_window, y_window, self.degree)
  593. return coefficients, np.poly1d(coefficients)
  594. except np.RankWarning:
  595. print(f"Warning: Rank deficient fitting for window. Check data variability.")
  596. # Attempt lower degree fit? Or return None? For now, return None.
  597. # try:
  598. # coefficients = np.polyfit(x_window, y_window, len(x_window) - 1)
  599. # return coefficients, np.poly1d(coefficients)
  600. # except:
  601. return None, None
  602. except Exception as e:
  603. print(f"Error during polynomial fit: {e}")
  604. return None, None
  605. def find_best_window(self, point: Tuple[float, float], window_size: int) -> Optional[int]:
  606. """Finds the start index of the window whose center is closest to the point."""
  607. if len(self.x_data) < window_size:
  608. print("Warning: Not enough data points for the specified window size.")
  609. return None
  610. x_point, y_point = point
  611. min_dist_sq = np.inf
  612. best_start_index = -1
  613. # Calculate window centers more efficiently
  614. # Use rolling mean if window_size is large, otherwise simple loop is fine
  615. num_windows = len(self.x_data) - window_size + 1
  616. if num_windows <= 0: return None
  617. for start in range(num_windows):
  618. x_center = np.mean(self.x_data[start : start + window_size])
  619. y_center = np.mean(self.y_data[start : start + window_size])
  620. dist_sq = (x_point - x_center)**2 + (y_point - y_center)**2
  621. if dist_sq < min_dist_sq:
  622. min_dist_sq = dist_sq
  623. best_start_index = start
  624. return best_start_index if best_start_index != -1 else None
  625. def find_projection(
  626. self,
  627. x_target: float,
  628. y_target: float,
  629. polynomial: np.poly1d,
  630. x_range: Tuple[float, float],
  631. search_points: int = 100, # Number of points instead of step size
  632. ) -> Optional[Tuple[float, float, float]]:
  633. """Finds the approximate closest point on the polynomial within the x_range."""
  634. if x_range[1] <= x_range[0]: return None # Invalid range
  635. x_values = np.linspace(x_range[0], x_range[1], search_points)
  636. y_values = polynomial(x_values)
  637. distances_sq = (x_target - x_values)**2 + (y_target - y_values)**2
  638. if len(distances_sq) == 0: return None
  639. min_idx = np.argmin(distances_sq)
  640. min_distance = np.sqrt(distances_sq[min_idx])
  641. return x_values[min_idx], y_values[min_idx], min_distance
  642. def fit_and_project(
  643. self, points: np.ndarray, window_size: int
  644. ) -> List[Dict[str, Any]]:
  645. """Fits polynomial and calculates curvature for each point in the input array."""
  646. if self.data is None or len(self.x_data) < window_size:
  647. print("Insufficient LaneMap data for fitting.")
  648. # Return default values for all points
  649. return [
  650. {
  651. "projection": (np.nan, np.nan),
  652. "curvHor": np.nan,
  653. "curvHorDot": np.nan,
  654. "laneOffset": np.nan,
  655. }
  656. ] * len(points)
  657. results = []
  658. if points.ndim != 2 or points.shape[1] != 2:
  659. raise ValueError("Input points must be a 2D numpy array with shape (n, 2).")
  660. for x_target, y_target in points:
  661. result = { # Default result
  662. "projection": (np.nan, np.nan),
  663. "curvHor": np.nan,
  664. "curvHorDot": np.nan,
  665. "laneOffset": np.nan,
  666. }
  667. best_start = self.find_best_window((x_target, y_target), window_size)
  668. if best_start is None:
  669. results.append(result)
  670. continue
  671. x_window = self.x_data[best_start : best_start + window_size]
  672. y_window = self.y_data[best_start : best_start + window_size]
  673. coefficients, polynomial = self.polynomial_fit(x_window, y_window)
  674. if coefficients is None or polynomial is None:
  675. results.append(result)
  676. continue
  677. x_min, x_max = np.min(x_window), np.max(x_window)
  678. projection_result = self.find_projection(
  679. x_target, y_target, polynomial, (x_min, x_max)
  680. )
  681. if projection_result is None:
  682. results.append(result)
  683. continue
  684. proj_x, proj_y, min_distance = projection_result
  685. curv_hor = self.curvature(coefficients, proj_x)
  686. curv_hor_dot = self.curvature_derivative(coefficients, proj_x)
  687. result = {
  688. "projection": (round(proj_x, 6), round(proj_y, 6)),
  689. "curvHor": round(curv_hor, 6),
  690. "curvHorDot": round(curv_hor_dot, 6),
  691. "laneOffset": round(min_distance, 6),
  692. }
  693. results.append(result)
  694. return results
  695. # --- Data Quality Analyzer (Optimized) ---
  696. class DataQualityAnalyzer:
  697. """Analyzes data quality metrics, focusing on frame loss."""
  698. def __init__(self, df: Optional[pd.DataFrame] = None):
  699. self.df = df if df is not None and not df.empty else pd.DataFrame() # Ensure df is DataFrame
  700. def analyze_frame_loss(self) -> Dict[str, Any]:
  701. """Analyzes frame loss characteristics."""
  702. metrics = {
  703. "total_frames_data": 0,
  704. "unique_frames_count": 0,
  705. "min_frame": np.nan,
  706. "max_frame": np.nan,
  707. "expected_frames": 0,
  708. "dropped_frames_count": 0,
  709. "loss_rate": np.nan,
  710. "max_consecutive_loss": 0,
  711. "max_loss_start_frame": np.nan,
  712. "max_loss_end_frame": np.nan,
  713. "loss_intervals_distribution": {},
  714. "valid": False, # Indicate if analysis was possible
  715. "message": ""
  716. }
  717. if self.df.empty or 'simFrame' not in self.df.columns:
  718. metrics["message"] = "DataFrame is empty or 'simFrame' column is missing."
  719. return metrics
  720. # Drop rows with NaN simFrame and ensure integer type
  721. frames_series = self.df['simFrame'].dropna().astype(int)
  722. metrics["total_frames_data"] = len(frames_series)
  723. if frames_series.empty:
  724. metrics["message"] = "No valid 'simFrame' data found after dropping NaN."
  725. return metrics
  726. unique_frames = sorted(frames_series.unique())
  727. metrics["unique_frames_count"] = len(unique_frames)
  728. if metrics["unique_frames_count"] < 2:
  729. metrics["message"] = "Less than two unique frames; cannot analyze loss."
  730. metrics["valid"] = True # Data exists, just not enough to analyze loss
  731. if metrics["unique_frames_count"] == 1:
  732. metrics["min_frame"] = unique_frames[0]
  733. metrics["max_frame"] = unique_frames[0]
  734. metrics["expected_frames"] = 1
  735. return metrics
  736. metrics["min_frame"] = unique_frames[0]
  737. metrics["max_frame"] = unique_frames[-1]
  738. metrics["expected_frames"] = metrics["max_frame"] - metrics["min_frame"] + 1
  739. # Calculate differences between consecutive unique frames
  740. frame_diffs = np.diff(unique_frames)
  741. # Gaps are where diff > 1. The number of lost frames in a gap is diff - 1.
  742. gaps = frame_diffs[frame_diffs > 1]
  743. lost_frames_in_gaps = gaps - 1
  744. metrics["dropped_frames_count"] = int(lost_frames_in_gaps.sum())
  745. if metrics["expected_frames"] > 0:
  746. metrics["loss_rate"] = round(metrics["dropped_frames_count"] / metrics["expected_frames"], 4)
  747. else:
  748. metrics["loss_rate"] = 0.0 # Avoid division by zero if min_frame == max_frame (already handled)
  749. if len(lost_frames_in_gaps) > 0:
  750. metrics["max_consecutive_loss"] = int(lost_frames_in_gaps.max())
  751. # Find where the max loss occurred
  752. max_loss_indices = np.where(frame_diffs == metrics["max_consecutive_loss"] + 1)[0]
  753. # Get the first occurrence start/end frames
  754. max_loss_idx = max_loss_indices[0]
  755. metrics["max_loss_start_frame"] = unique_frames[max_loss_idx]
  756. metrics["max_loss_end_frame"] = unique_frames[max_loss_idx + 1]
  757. # Count distribution of loss interval lengths
  758. loss_counts = Counter(lost_frames_in_gaps)
  759. metrics["loss_intervals_distribution"] = {int(k): int(v) for k, v in loss_counts.items()}
  760. else:
  761. metrics["max_consecutive_loss"] = 0
  762. metrics["valid"] = True
  763. metrics["message"] = "Frame loss analysis complete."
  764. return metrics
  765. def get_all_csv_files(path: Path) -> List[Path]:
  766. """Gets all CSV files in path, excluding specific ones."""
  767. excluded_files = {OUTPUT_CSV_LANEMAP, ROADMARK_CSV}
  768. return [
  769. file_path
  770. for file_path in path.rglob("*.csv") # Recursive search
  771. if file_path.is_file() and file_path.name not in excluded_files
  772. ]
  773. def run_frame_loss_analysis_on_folder(path: Path) -> Dict[str, Dict[str, Any]]:
  774. """Runs frame loss analysis on all relevant CSV files in a folder."""
  775. analysis_results = {}
  776. csv_files = get_all_csv_files(path)
  777. if not csv_files:
  778. print(f"No relevant CSV files found in {path}")
  779. return analysis_results
  780. for file_path in csv_files:
  781. file_name = file_path.name
  782. if file_name in {OUTPUT_CSV_FUNCTION, OUTPUT_CSV_OBU}: # Skip specific files if needed
  783. print(f"Skipping frame analysis for: {file_name}")
  784. continue
  785. print(f"Analyzing frame loss for: {file_name}")
  786. if file_path.stat().st_size == 0:
  787. print(f"File {file_name} is empty. Skipping analysis.")
  788. analysis_results[file_name] = {"valid": False, "message": "File is empty."}
  789. continue
  790. try:
  791. # Read only necessary column if possible, handle errors
  792. df = pd.read_csv(file_path, usecols=['simFrame'], index_col=False,
  793. on_bad_lines='warn') # 'warn' or 'skip'
  794. analyzer = DataQualityAnalyzer(df)
  795. metrics = analyzer.analyze_frame_loss()
  796. analysis_results[file_name] = metrics
  797. # Optionally print a summary here
  798. if metrics["valid"]:
  799. print(f" Loss Rate: {metrics.get('loss_rate', np.nan)*100:.2f}%, "
  800. f"Dropped: {metrics.get('dropped_frames_count', 'N/A')}, "
  801. f"Max Gap: {metrics.get('max_consecutive_loss', 'N/A')}")
  802. else:
  803. print(f" Analysis failed: {metrics.get('message')}")
  804. except pd.errors.EmptyDataError:
  805. print(f"File {file_name} contains no data after reading.")
  806. analysis_results[file_name] = {"valid": False, "message": "Empty data after read."}
  807. except ValueError as ve: # Handle case where simFrame might not be present
  808. print(f"ValueError processing file {file_name}: {ve}. Is 'simFrame' column present?")
  809. analysis_results[file_name] = {"valid": False, "message": f"ValueError: {ve}"}
  810. except Exception as e:
  811. print(f"Unexpected error processing file {file_name}: {e}")
  812. analysis_results[file_name] = {"valid": False, "message": f"Unexpected error: {e}"}
  813. return analysis_results
  814. def data_precheck(output_dir: Path, max_allowed_loss_rate: float = 0.20) -> bool:
  815. """Checks data quality, focusing on frame loss rate."""
  816. print(f"--- Running Data Quality Precheck on: {output_dir} ---")
  817. if not output_dir.exists() or not output_dir.is_dir():
  818. print(f"Error: Output directory does not exist: {output_dir}")
  819. return False
  820. try:
  821. frame_loss_results = run_frame_loss_analysis_on_folder(output_dir)
  822. except Exception as e:
  823. print(f"Critical error during frame loss analysis: {e}")
  824. return False # Treat critical error as failure
  825. if not frame_loss_results:
  826. print("Warning: No files were analyzed for frame loss.")
  827. # Decide if this is a failure or just a warning. Let's treat it as OK for now.
  828. return True
  829. all_checks_passed = True
  830. for file_name, metrics in frame_loss_results.items():
  831. if metrics.get("valid", False):
  832. loss_rate = metrics.get("loss_rate", np.nan)
  833. if pd.isna(loss_rate):
  834. print(f" {file_name}: Loss rate could not be calculated.")
  835. # Decide if NaN loss rate is acceptable.
  836. elif loss_rate > max_allowed_loss_rate:
  837. print(f" FAIL: {file_name} - Frame loss rate ({loss_rate*100:.2f}%) exceeds threshold ({max_allowed_loss_rate*100:.1f}%).")
  838. all_checks_passed = False
  839. else:
  840. print(f" PASS: {file_name} - Frame loss rate ({loss_rate*100:.2f}%) is acceptable.")
  841. else:
  842. print(f" WARN: {file_name} - Frame loss analysis could not be completed ({metrics.get('message', 'Unknown reason')}).")
  843. # Decide if inability to analyze is a failure. Let's allow it for now.
  844. print(f"--- Data Quality Precheck {'PASSED' if all_checks_passed else 'FAILED'} ---")
  845. return all_checks_passed
  846. # --- Final Preprocessing Step ---
  847. class FinalDataProcessor:
  848. """Merges processed CSVs, adds curvature, and handles traffic lights."""
  849. def __init__(self, config: Config):
  850. self.config = config
  851. self.output_dir = config.output_dir
  852. def process(self) -> bool:
  853. """执行最终数据合并和处理步骤。"""
  854. print("--- Starting Final Data Processing ---")
  855. try:
  856. # 1. Load main object state data
  857. obj_state_path = self.output_dir / OUTPUT_CSV_OBJSTATE
  858. lane_map_path = self.output_dir / OUTPUT_CSV_LANEMAP
  859. if not obj_state_path.exists():
  860. print(f"Error: Required input file not found: {obj_state_path}")
  861. return False
  862. # Load and process data
  863. df_object = pd.read_csv(obj_state_path, dtype={"simTime": float}, low_memory=False)
  864. # Process and merge data
  865. df_merged = self._merge_optional_data(df_object)
  866. # Save final merged file directly to output directory
  867. merged_csv_path = self.output_dir / OUTPUT_CSV_MERGED
  868. print(f'merged_csv_path:{merged_csv_path}')
  869. df_merged.to_csv(merged_csv_path, index=False, float_format='%.6f')
  870. print(f"Successfully created final merged file: {merged_csv_path}")
  871. # Clean up intermediate files
  872. if obj_state_path.exists():
  873. obj_state_path.unlink()
  874. print("--- Final Data Processing Finished ---")
  875. return True
  876. except Exception as e:
  877. print(f"An unexpected error occurred during final data processing: {e}")
  878. import traceback
  879. traceback.print_exc()
  880. return False
  881. def _merge_optional_data(self, df_object: pd.DataFrame) -> pd.DataFrame:
  882. """加载和合并可选数据"""
  883. df_merged = df_object.copy()
  884. # --- 合并 EgoMap ---
  885. egomap_path = self.output_dir / OUTPUT_CSV_EGOMAP
  886. if egomap_path.exists() and egomap_path.stat().st_size > 0:
  887. try:
  888. df_ego = pd.read_csv(egomap_path, dtype={"simTime": float})
  889. # 删除 simFrame 列,因为使用主数据的 simFrame
  890. if 'simFrame' in df_ego.columns:
  891. df_ego = df_ego.drop(columns=['simFrame'])
  892. # 按时间和ID排序
  893. df_ego.sort_values(['simTime', 'playerId'], inplace=True)
  894. df_merged.sort_values(['simTime', 'playerId'], inplace=True)
  895. # 使用 merge_asof 进行就近合并,不包括 simFrame
  896. df_merged = pd.merge_asof(
  897. df_merged,
  898. df_ego,
  899. on='simTime',
  900. by='playerId',
  901. direction='nearest',
  902. tolerance=0.01 # 10ms tolerance
  903. )
  904. print("EgoMap data merged.")
  905. except Exception as e:
  906. print(f"Warning: Could not merge EgoMap data from {egomap_path}: {e}")
  907. # --- Merge Function ---
  908. function_path = self.output_dir / OUTPUT_CSV_FUNCTION
  909. if function_path.exists() and function_path.stat().st_size > 0:
  910. try:
  911. df_function = pd.read_csv(function_path, dtype={"timestamp": float}, low_memory=False).drop_duplicates()
  912. # 删除 simFrame 列
  913. if 'simFrame' in df_function.columns:
  914. df_function = df_function.drop(columns=['simFrame'])
  915. if 'simTime' in df_function.columns:
  916. df_function['simTime'] = df_function['simTime'].round(2)
  917. common_cols = list(set(df_merged.columns) & set(df_function.columns) - {'simTime'})
  918. df_function.drop(columns=common_cols, inplace=True, errors='ignore')
  919. df_merged = pd.merge(df_merged, df_function, on=["simTime"], how="left")
  920. print("Function data merged.")
  921. else:
  922. print("Warning: 'simTime' column not found in Function.csv. Cannot merge.")
  923. except Exception as e:
  924. print(f"Warning: Could not merge Function data from {function_path}: {e}")
  925. else:
  926. print("Function data not found or empty, skipping merge.")
  927. # --- Merge OBU ---
  928. obu_path = self.output_dir / OUTPUT_CSV_OBU
  929. if obu_path.exists() and obu_path.stat().st_size > 0:
  930. try:
  931. df_obu = pd.read_csv(obu_path, dtype={"simTime": float}, low_memory=False).drop_duplicates()
  932. # 删除 simFrame 列
  933. if 'simFrame' in df_obu.columns:
  934. df_obu = df_obu.drop(columns=['simFrame'])
  935. df_obu['simTime'] = df_obu['simTime'].round(2)
  936. common_cols = list(set(df_merged.columns) & set(df_obu.columns) - {'simTime'})
  937. df_obu.drop(columns=common_cols, inplace=True, errors='ignore')
  938. df_merged = pd.merge(df_merged, df_obu, on=["simTime"], how="left")
  939. print("OBU data merged.")
  940. except Exception as e:
  941. print(f"Warning: Could not merge OBU data from {obu_path}: {e}")
  942. else:
  943. print("OBU data not found or empty, skipping merge.")
  944. return df_merged
  945. def _process_trafficlight_data(self) -> pd.DataFrame:
  946. """Processes traffic light JSON data if available."""
  947. # Check if json_path is provided and exists
  948. if not self.config.json_path:
  949. print("No traffic light JSON file provided. Skipping traffic light processing.")
  950. return pd.DataFrame()
  951. if not self.config.json_path.exists():
  952. print("Traffic light JSON file not found. Skipping traffic light processing.")
  953. return pd.DataFrame()
  954. print(f"Processing traffic light data from: {self.config.json_path}")
  955. valid_trafficlights = []
  956. try:
  957. with open(self.config.json_path, 'r', encoding='utf-8') as f:
  958. # Read the whole file, assuming it's a JSON array or JSON objects per line
  959. try:
  960. # Attempt to read as a single JSON array
  961. raw_data = json.load(f)
  962. if not isinstance(raw_data, list):
  963. raw_data = [raw_data] # Handle case of single JSON object
  964. except json.JSONDecodeError:
  965. # If fails, assume JSON objects per line
  966. f.seek(0) # Reset file pointer
  967. raw_data = [json.loads(line) for line in f if line.strip()]
  968. for entry in raw_data:
  969. # Normalize entry if it's a string containing JSON
  970. if isinstance(entry, str):
  971. try:
  972. entry = json.loads(entry)
  973. except json.JSONDecodeError:
  974. print(f"Warning: Skipping invalid JSON string in traffic light data: {entry[:100]}...")
  975. continue
  976. # Safely extract data using .get()
  977. intersections = entry.get('intersections', [])
  978. if not isinstance(intersections, list): continue # Skip if not a list
  979. for intersection in intersections:
  980. if not isinstance(intersection, dict): continue
  981. timestamp_ms = intersection.get('intersectionTimestamp', 0)
  982. sim_time = round(int(timestamp_ms) / 1000, 2) # Convert ms to s and round
  983. phases = intersection.get('phases', [])
  984. if not isinstance(phases, list): continue
  985. for phase in phases:
  986. if not isinstance(phase, dict): continue
  987. phase_id = phase.get('phaseId', 0)
  988. phase_states = phase.get('phaseStates', [])
  989. if not isinstance(phase_states, list): continue
  990. for phase_state in phase_states:
  991. if not isinstance(phase_state, dict): continue
  992. # Check for startTime == 0 as per original logic
  993. if phase_state.get('startTime') == 0:
  994. light_state = phase_state.get('light', 0) # Extract light state
  995. data = {
  996. 'simTime': sim_time,
  997. 'phaseId': phase_id,
  998. 'stateMask': light_state,
  999. # Add playerId for merging - assume applies to ego
  1000. 'playerId': PLAYER_ID_EGO
  1001. }
  1002. valid_trafficlights.append(data)
  1003. if not valid_trafficlights:
  1004. print("No valid traffic light states (with startTime=0) found in JSON.")
  1005. return pd.DataFrame()
  1006. df_trafficlights = pd.DataFrame(valid_trafficlights)
  1007. # Drop duplicates based on relevant fields
  1008. df_trafficlights.drop_duplicates(subset=['simTime', 'playerId', 'phaseId', 'stateMask'], keep='first', inplace=True)
  1009. print(f"Processed {len(df_trafficlights)} unique traffic light state entries.")
  1010. return df_trafficlights
  1011. except json.JSONDecodeError as e:
  1012. print(f"Error decoding traffic light JSON file {self.config.json_path}: {e}")
  1013. return pd.DataFrame()
  1014. except Exception as e:
  1015. print(f"Unexpected error processing traffic light data: {e}")
  1016. return pd.DataFrame()
  1017. # --- Rosbag Processing ---
  1018. class RosbagProcessor:
  1019. """Extracts data from Rosbag files within a ZIP archive."""
  1020. # Mapping from filename parts to rostopics
  1021. ROSTOPIC_MAP = {
  1022. ('V2I', 'HazardousLocationW'): "/HazardousLocationWarning",
  1023. ('V2C', 'OtherVehicleRedLightViolationW'): "/c2v/GoThroughRadLight",
  1024. ('V2I', 'LeftTurnAssist'): "/LeftTurnAssistant",
  1025. ('V2V', 'LeftTurnAssist'): "/V2VLeftTurnAssistant",
  1026. ('V2I', 'RedLightViolationW'): "/SignalViolationWarning",
  1027. ('V2C', 'AbnormalVehicleW'): "/c2v/AbnormalVehicleWarnning",
  1028. ('V2C', 'SignalLightReminder'): "/c2v/TrafficLightInfo",
  1029. ('V2C', 'VulnerableRoadUserCollisionW'): "/c2v/VulnerableObject",
  1030. ('V2C', 'EmergencyVehiclesPriority'): "/c2v/EmergencyVehiclesPriority",
  1031. ('V2C', 'LitterW'): "/c2v/RoadSpillageWarning",
  1032. ('V2V', 'ForwardCollisionW'): "/V2VForwardCollisionWarning",
  1033. ('V2C', 'VisibilityW'): "/c2v/VisibilityWarinning",
  1034. ('V2V', 'EmergencyBrakeW'): "/V2VEmergencyBrakeWarning",
  1035. ('V2I', 'GreenLightOptimalSpeedAdvisory'): "/GreenLightOptimalSpeedAdvisory", # Check exact topic name
  1036. ('V2C', 'DynamicSpeedLimitingInformation'): "/c2v/DynamicSpeedLimit",
  1037. ('V2C', 'TrafficJamW'): "/c2v/TrafficJam",
  1038. ('V2C', 'DrivingLaneRecommendation'): "/c2v/LaneGuidance",
  1039. ('V2C', 'RampMerge'): "/c2v/RampMerging",
  1040. ('V2I', 'CooperativeIntersectionPassing'): "/CooperativeIntersectionPassing",
  1041. ('V2I', 'IntersectionCollisionW'): "/IntersectionCollisionWarning",
  1042. ('V2V', 'IntersectionCollisionW'): "/V2VIntersectionCollisionWarning",
  1043. ('V2V', 'BlindSpotW'): "/V2VBlindSpotWarning",
  1044. ('V2I', 'SpeedLimitW'): "/SpeedLimit",
  1045. ('V2I', 'VulnerableRoadUserCollisionW'): "/VulnerableRoadUserCollisionWarning",
  1046. ('V2I', 'CooperativeLaneChange'): "/CooperativeLaneChange",
  1047. ('V2V', 'CooperativeLaneChange'): "/V2VCooperativeLaneChange",
  1048. ('V2I', 'CooperativeVehicleMerge'): "/CooperativeVehicleMerge",
  1049. ('V2V', 'AbnormalVehicleW'): "/V2VAbnormalVehicleWarning",
  1050. ('V2V', 'ControlLossW'): "/V2VVehicleLossControlWarning",
  1051. ('V2V', 'EmergencyVehicleW'): '/V2VEmergencyVehicleWarning',
  1052. ('V2I', 'InVehicleSignage'): "/InVehicleSign",
  1053. ('V2V', 'DoNotPassW'): "/V2VDoNotPassWarning",
  1054. ('V2I', 'TrafficJamW'): "/TrafficJamWarning",
  1055. # Add more mappings as needed
  1056. }
  1057. def __init__(self, config: Config):
  1058. self.config = config
  1059. self.output_dir = config.output_dir
  1060. def _get_target_rostopic(self, zip_filename: str) -> Optional[str]:
  1061. """Determines the target rostopic based on keywords in the filename."""
  1062. for (kw1, kw2), topic in self.ROSTOPIC_MAP.items():
  1063. if kw1 in zip_filename and kw2 in zip_filename:
  1064. print(f"Identified target topic '{topic}' for {zip_filename}")
  1065. return topic
  1066. print(f"Warning: No specific rostopic mapping found for {zip_filename}.")
  1067. return None
  1068. def process_zip_for_rosbags(self) -> None:
  1069. """Finds, extracts, and processes rosbags from the ZIP file."""
  1070. print(f"--- Processing Rosbags in {self.config.zip_path} ---")
  1071. target_rostopic = self._get_target_rostopic(self.config.zip_path.stem)
  1072. if not target_rostopic:
  1073. print("Skipping Rosbag processing as no target topic was identified.")
  1074. return
  1075. with tempfile.TemporaryDirectory() as tmp_dir_str:
  1076. tmp_dir = Path(tmp_dir_str)
  1077. bag_files_extracted = []
  1078. try:
  1079. with zipfile.ZipFile(self.config.zip_path, 'r') as zip_ref:
  1080. for member in zip_ref.infolist():
  1081. # Extract Rosbag files
  1082. if 'Rosbag/' in member.filename and member.filename.endswith('.bag'):
  1083. try:
  1084. extracted_path = Path(zip_ref.extract(member, path=tmp_dir))
  1085. bag_files_extracted.append(extracted_path)
  1086. print(f"Extracted Rosbag: {extracted_path.name}")
  1087. except Exception as e:
  1088. print(f"Error extracting Rosbag {member.filename}: {e}")
  1089. # Extract HMIdata CSV files directly to output
  1090. elif 'HMIdata/' in member.filename and member.filename.endswith('.csv'):
  1091. try:
  1092. target_path = self.output_dir / Path(member.filename).name
  1093. with zip_ref.open(member) as source, open(target_path, "wb") as target:
  1094. shutil.copyfileobj(source, target)
  1095. print(f"Extracted HMI data: {target_path.name}")
  1096. except Exception as e:
  1097. print(f"Error extracting HMI data {member.filename}: {e}")
  1098. except zipfile.BadZipFile:
  1099. print(f"Error: Bad ZIP file provided: {self.config.zip_path}")
  1100. return
  1101. except FileNotFoundError:
  1102. print(f"Error: ZIP file not found: {self.config.zip_path}")
  1103. return
  1104. if not bag_files_extracted:
  1105. print("No Rosbag files found in the archive.")
  1106. # Attempt extraction of HMI/RDB anyway if needed (already done above)
  1107. return
  1108. # Process extracted bag files
  1109. for bag_path in bag_files_extracted:
  1110. print(f"Processing bag file: {bag_path.name}")
  1111. self._convert_bag_topic_to_csv(bag_path, target_rostopic)
  1112. print("--- Rosbag Processing Finished ---")
  1113. def _convert_bag_topic_to_csv(self, bag_file_path: Path, target_topic: str) -> None:
  1114. """Converts a specific topic from a single bag file to CSV."""
  1115. output_csv_path = self.output_dir / OUTPUT_CSV_OBU # Standard name for OBU data
  1116. try:
  1117. # Check if bagpy can handle Path object, else convert to str
  1118. bag_reader = bagreader(str(bag_file_path), verbose=False)
  1119. # Check if topic exists
  1120. available_topics = bag_reader.topic_table['Topics'].tolist() if hasattr(bag_reader, 'topic_table') and bag_reader.topic_table is not None else []
  1121. if target_topic not in available_topics:
  1122. print(f"Target topic '{target_topic}' not found in {bag_file_path.name}. Available: {available_topics}")
  1123. # Clean up temporary bagpy-generated files if possible
  1124. if hasattr(bag_reader, 'data_folder') and Path(bag_reader.data_folder).exists():
  1125. shutil.rmtree(bag_reader.data_folder, ignore_errors=True)
  1126. return
  1127. # Extract message data to a temporary CSV created by bagpy
  1128. temp_csv_path_str = bag_reader.message_by_topic(target_topic)
  1129. temp_csv_path = Path(temp_csv_path_str)
  1130. if not temp_csv_path.exists() or temp_csv_path.stat().st_size == 0:
  1131. print(f"Warning: Bagpy generated an empty or non-existent CSV for topic '{target_topic}' from {bag_file_path.name}.")
  1132. return # Skip if empty
  1133. # Read the temporary CSV, process, and save to final location
  1134. df = pd.read_csv(temp_csv_path)
  1135. if df.empty:
  1136. print(f"Warning: Bagpy CSV for topic '{target_topic}' is empty after reading.")
  1137. return
  1138. # Clean columns: Drop 'Time', rename '*timestamp' -> 'simTime'
  1139. if 'Time' in df.columns:
  1140. df.drop(columns=['Time'], inplace=True)
  1141. rename_dict = {}
  1142. for col in df.columns:
  1143. if col.endswith('.timestamp'): # More specific match
  1144. rename_dict[col] = 'simTime'
  1145. elif col.endswith('event_type'): # As per original code
  1146. rename_dict[col] = 'event_Type'
  1147. # Add other renames if necessary
  1148. df.rename(columns=rename_dict, inplace=True)
  1149. # Ensure simTime is float and rounded (optional, do if needed for merging)
  1150. if 'simTime' in df.columns:
  1151. df['simTime'] = pd.to_numeric(df['simTime'], errors='coerce').round(2) # Example rounding
  1152. # Save processed data
  1153. df.to_csv(output_csv_path, index=False, float_format='%.6f')
  1154. print(f"Saved processed OBU data to: {output_csv_path}")
  1155. except ValueError as ve:
  1156. # Catch potential Bagpy internal errors if topic doesn't contain messages
  1157. print(f"ValueError processing bag {bag_file_path.name} (Topic: {target_topic}): {ve}. Topic might be empty.")
  1158. except ImportError as ie:
  1159. print(f"ImportError during bag processing: {ie}. Ensure all ROS dependencies are installed if needed by bagpy.")
  1160. except Exception as e:
  1161. print(f"Error processing bag file {bag_file_path.name} (Topic: {target_topic}): {e}")
  1162. import traceback
  1163. traceback.print_exc() # More details on unexpected errors
  1164. finally:
  1165. # Clean up temporary files/folders created by bagpy
  1166. if 'temp_csv_path' in locals() and temp_csv_path.exists():
  1167. try:
  1168. temp_csv_path.unlink() # Delete the specific CSV
  1169. except OSError as ose:
  1170. print(f"Warning: Could not delete bagpy temp csv {temp_csv_path}: {ose}")
  1171. if 'bag_reader' in locals() and hasattr(bag_reader, 'data_folder'):
  1172. bagpy_folder = Path(bag_reader.data_folder)
  1173. if bagpy_folder.exists() and bagpy_folder.is_dir():
  1174. try:
  1175. shutil.rmtree(bagpy_folder, ignore_errors=True) # Delete the folder bagpy made
  1176. except OSError as ose:
  1177. print(f"Warning: Could not delete bagpy temp folder {bagpy_folder}: {ose}")
  1178. # --- Utility Functions ---
  1179. def get_base_path() -> Path:
  1180. """Gets the base path of the script or executable."""
  1181. if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
  1182. # Running in a PyInstaller bundle
  1183. return Path(sys._MEIPASS)
  1184. else:
  1185. # Running as a normal script
  1186. return Path(__file__).parent.resolve()
  1187. def run_cpp_engine(config: Config):
  1188. """Runs the external C++ preprocessing engine."""
  1189. if not config.engine_path or not config.map_path:
  1190. print("C++ engine path or map path not configured. Skipping C++ engine execution.")
  1191. return True # Return True assuming it's optional or handled elsewhere
  1192. engine_cmd = [
  1193. str(config.engine_path),
  1194. str(config.map_path),
  1195. str(config.output_dir),
  1196. str(config.x_offset),
  1197. str(config.y_offset)
  1198. ]
  1199. print(f"--- Running C++ Preprocessing Engine ---")
  1200. print(f"Command: {' '.join(engine_cmd)}")
  1201. try:
  1202. result = subprocess.run(
  1203. engine_cmd,
  1204. check=True, # Raise exception on non-zero exit code
  1205. capture_output=True, # Capture stdout/stderr
  1206. text=True, # Decode output as text
  1207. cwd=config.engine_path.parent # Run from the engine's directory? Or script's? Adjust if needed.
  1208. )
  1209. print("C++ Engine Output:")
  1210. print(result.stdout)
  1211. if result.stderr:
  1212. print("C++ Engine Error Output:")
  1213. print(result.stderr)
  1214. print("--- C++ Engine Finished Successfully ---")
  1215. return True
  1216. except FileNotFoundError:
  1217. print(f"Error: C++ engine executable not found at {config.engine_path}.")
  1218. return False
  1219. except subprocess.CalledProcessError as e:
  1220. print(f"Error: C++ engine failed with exit code {e.returncode}.")
  1221. print("C++ Engine Output (stdout):")
  1222. print(e.stdout)
  1223. print("C++ Engine Output (stderr):")
  1224. print(e.stderr)
  1225. return False
  1226. except Exception as e:
  1227. print(f"An unexpected error occurred while running the C++ engine: {e}")
  1228. return False
  1229. if __name__ == "__main__":
  1230. pass