lst.py 69 KB

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