lst.py 81 KB

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