lst.py 87 KB

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