lst.py 80 KB

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