Skip to content

Latest commit

Β 

History

7 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•—   β–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•—   β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— 
β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ–ˆβ–ˆβ•—  β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β•β• β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—
β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—  β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘
β–ˆβ–ˆβ•”β•β•β•  β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘
β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β•šβ•β• β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ•‘
β•šβ•β•β•β•β•β•β•β•šβ•β•  β•šβ•β•β•β•β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β•     β•šβ•β•β•šβ•β•  β•šβ•β•β•šβ•β•  β•šβ•β•

Bayesian MPC Predictive Agent for Autonomous Highway Driving

Phase 3.2 Β· Temporal Transformer Β· GMM Β· MC Dropout Β· Hard Shield AEB Β· ROS2


Python PyTorch Gymnasium ROS2 License: MIT


highway-env Captum FileLock


Live Demo


🚨 Test Case Simulation Notice

All driving scenarios used in test cases are simulated using highway-env β€” a free, open-source autonomous driving environment by Γ‰douard Leurent, maintained by the Farama Foundation under the MIT License. We use a modified fork with custom patches for intersection logic, coordinate encoding, and distributed training support.


πŸ“Œ Table of Contents

# Section
1 🌐 Live Deployment
2 πŸ”­ Project Overview
3 πŸ—οΈ Open-Source Simulation Foundation
4 πŸ—‚οΈ Repository Structure
5 🧠 System Architecture
6 ⚑ Test Scenarios
7 πŸ›‘οΈ Hard Shield β€” AEB Safety System
8 πŸ›°οΈ Server / Client Bridge
9 πŸ€– ROS2 Deployment
10 πŸ”„ Continuous Online Learning
11 πŸ”§ Patch System
12 πŸ§ͺ Evaluation & Benchmarks
13 πŸ”¬ Explainability (XAI)
14 πŸ“¦ Installation
15 πŸš€ Quick Start
16 βš™οΈ Configuration Reference
17 πŸ“Š Model Files
18 πŸ™ Acknowledgements

🌐 Live Deployment

ENIGMAA is live and accessible at:

The deployed instance runs the full ENIGMAA stack β€” Bayesian MPC agent, Hard Shield AEB, and the multi-environment evaluation suite β€” accessible directly from your browser without any local setup.

Detail Info
🌍 URL https://enigmaa.space.z.ai
🧠 Agent Bayesian Trajectory Predictor (Phase 3.2)
πŸ›‘οΈ Safety Hard Shield AEB active
🌐 Environments highway-v0, intersection-v0, two-way-v0

πŸ”­ Project Overview

ENIGMAA is a research grade Bayesian Model Predictive Control (MPC) agent for safe autonomous driving in complex, dynamic traffic environments. It wraps a neural trajectory predictor inside a physics-level safety guardrail, enabling confident action selection with quantified uncertainty at every timestep.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        ENIGMAA PHASE 3.2                             β”‚
β”‚                                                                      β”‚
β”‚  Observation ──▢ Feature Extraction ──▢ Temporal Transformer         β”‚
β”‚                                               β”‚                      β”‚
β”‚                                    GMM Trajectory Prediction         β”‚
β”‚                                    (3 modes Γ— 30-step horizon)       β”‚
β”‚                                               β”‚                      β”‚
β”‚                                     MPC Action Selection             β”‚
β”‚                                               β”‚                      β”‚
β”‚                                   Hard Shield AEB Override           β”‚
β”‚                                               β”‚                      β”‚
β”‚                                        Environment Step              β”‚
β”‚                                               β”‚                      β”‚
β”‚                                    Online Model Fine-tuning          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Core Capabilities

Capability Technology
Sequence modeling Temporal Transformer Encoder (2L, nhead=3)
Multi-modal prediction Gaussian Mixture Model head (3 modes)
Uncertainty quantification MC Dropout β€” epistemic + aleatoric
Rule-based safety Hard Shield AEB (physics proximity checks)
Explainability Captum Integrated Gradients
Continuous learning File-locked background fine-tuning
Real-robot bridge ROS2 node (/vehicle/cmd_vel)
Remote control TCP socket server/client protocol

πŸ—οΈ Open-Source Simulation Foundation

All test case driving scenarios in ENIGMAA are simulated using the open-source highway-env library.

What is highway-env?

highway-env is a free, open-source collection of environments for autonomous driving and tactical decision-making, originally developed by Γ‰douard Leurent and now maintained by the Farama Foundation as part of the Gymnasium ecosystem.

It provides:

  • Kinematic vehicle simulation with realistic lane/road geometry
  • Multi-agent NPC traffic with configurable spawn rates and behaviors
  • Observation spaces: kinematics, occupancy grids, grayscale frames
  • Action spaces: discrete (lane change/speed) and continuous (steering/acceleration)
  • Multiple pre-built environments covering highway, intersection, roundabout, parking, and racetrack scenarios

Our modifications on top of the base library:

highway-env (upstream, MIT)
        β”‚
        β”œβ”€β”€ patch_intersection.py      β†’ intersection-v0 AEB logic + action remapping
        β”œβ”€β”€ patch_coordinates.py       β†’ relative ego-coordinate trajectory encoding
        β”œβ”€β”€ patch_data_architecture.py β†’ per-scenario isolated .npz data files
        └── patch_files.py             β†’ FileLock-safe concurrent training support

Environments Used

highway-env Environment ENIGMAA Scenario
highway-v0 Cruising, Braking, Overtake, Lane Selection, Gap Change, Cluster, Marginal Gap
intersection-v0 Urban intersection crossing with yielding
two-way-v0 Oncoming traffic head-on avoidance

⭐ If you use this project, please also star and cite the original highway-env repository.


πŸ—‚οΈ Repository Structure

env/
β”‚
β”œβ”€β”€ πŸ“¦ bayesian_model.pt                ← Root pre-trained Bayesian Transformer
β”œβ”€β”€ πŸ“Š live_calib_data.npz              ← Shared live calibration dataset
β”œβ”€β”€ πŸ“Š live_calib_data_oncoming.npz     ← Oncoming-specific calibration buffer
β”‚
└── πŸ“ HighwayEnv/
    β”‚
    β”œβ”€β”€ πŸ“ highway_env/                 ← Modified fork of highway-env (open-source base)
    β”‚   β”œβ”€β”€ envs/                       ← Environment definitions (highway, intersection…)
    β”‚   β”‚   β”œβ”€β”€ highway_env.py
    β”‚   β”‚   β”œβ”€β”€ intersection_env.py
    β”‚   β”‚   β”œβ”€β”€ two_way_env.py
    β”‚   β”‚   β”œβ”€β”€ roundabout_env.py
    β”‚   β”‚   β”œβ”€β”€ parking_env.py
    β”‚   β”‚   └── common/                 ← Observation, action, abstract, graphics
    β”‚   β”œβ”€β”€ road/                       ← Lane, road, graphics, spline, regulation
    β”‚   └── vehicle/                    ← Kinematics, behavior, controller, uncertainty
    β”‚
    β”œβ”€β”€ πŸ“ test_cases/                  ← ENIGMAA scenario-specific agents
    β”‚   β”œβ”€β”€ test_case_mpc.py            ← Baseline MPC (highway cruising)
    β”‚   β”œβ”€β”€ test_case_braking.py        ← Emergency braking
    β”‚   β”œβ”€β”€ test_case_overtake.py       ← Safe overtaking
    β”‚   β”œβ”€β”€ test_case_lane_selection.py ← Lane selection & merging
    β”‚   β”œβ”€β”€ test_case_gap_change.py     ← Dynamic gap exploitation
    β”‚   β”œβ”€β”€ test_case_cluster.py        ← Dense cluster navigation
    β”‚   β”œβ”€β”€ test_case_marginal_gap.py   ← Marginal gap acceptance
    β”‚   β”œβ”€β”€ test_case_intersection.py   ← Urban intersection crossing
    β”‚   β”œβ”€β”€ test_case_oncoming.py       ← Head-on collision avoidance
    β”‚   └── test_case_ros2.py           ← ROS2 deployment node
    β”‚
    β”œβ”€β”€ πŸ–₯️  server_env.py               ← TCP socket environment server
    β”œβ”€β”€ πŸ”Œ  client_script.py            ← TCP socket agent client
    β”œβ”€β”€ πŸ“ˆ  eval.py                     ← Quick 3-episode evaluation
    β”œβ”€β”€ πŸ“‹  eval_report.py              ← Multi-environment benchmark
    β”‚
    β”œβ”€β”€ πŸ”§  patch_files.py              ← FileLock + shared model patching
    β”œβ”€β”€ πŸ”§  patch_intersection.py       ← Intersection-v0 adaptation
    β”œβ”€β”€ πŸ”§  patch_data_architecture.py  ← Per-scenario data isolation
    β”œβ”€β”€ πŸ”§  patch_coordinates.py        ← Relative coordinate encoding fix
    β”‚
    β”œβ”€β”€ πŸ“¦  bayesian_model.pt           ← Working checkpoint (online-updated)
    β”œβ”€β”€ πŸ“¦  bayesian_model_oncoming.pt  ← Oncoming-specific weights
    β”œβ”€β”€ πŸ“Š  data_test_case_*.npz        ← Per-scenario training datasets
    β”œβ”€β”€ πŸ”’  training.lock               ← FileLock for concurrent safety
    β”‚
    β”œβ”€β”€ pyproject.toml                  ← Package metadata & deps
    └── setup.py                        ← Legacy setuptools entry

🧠 System Architecture

Bayesian Trajectory Predictor

 ╔══════════════════════════════════════════════════════════════╗
 β•‘                  BayesianTrajectoryPredictor                 β•‘
 ╠══════════════════════════════════════════════════════════════╣
 β•‘                                                              β•‘
 β•‘  Input:  (batch, seq_len=3, 69-dim)                          β•‘
 β•‘           └── 64-dim kinematics + 5-dim one-hot action       β•‘
 β•‘                                                              β•‘
 β•‘  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β•‘
 β•‘  β”‚       Temporal Transformer Encoder                   β”‚    β•‘
 β•‘  β”‚   2 layers Β· nhead=3 Β· d_ff=128 Β· dropout=0.2        β”‚    β•‘
 β•‘  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β•‘
 β•‘                        β”‚  last-timestep token                β•‘
 β•‘               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”                            β•‘
 β•‘               β”‚  Linear + ReLU  β”‚  (β†’ 128-dim hidden)        β•‘
 β•‘               β”‚  + MC Dropout   β”‚  (p=0.2, active at infer)  β•‘
 β•‘               β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜                            β•‘
 β•‘        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                     β•‘
 β•‘        β–Ό               β–Ό               β–Ό                     β•‘
 β•‘   mean_head       logvar_head     weight_head                 β•‘
 β•‘  (3Γ—30Γ—2 ΞΌ)      (3Γ—30Γ—2 σ²)    (3,) softmax                 β•‘
 β•‘        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                     β•‘
 β•‘               Gaussian Mixture Model                          β•‘
 β•‘               3 modes Β· 30-step horizon Β· (x,y) coords       β•‘
 β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

MC Dropout remains active during inference. Each forward pass samples a different trajectory distribution, and N passes are aggregated to estimate:

  • Epistemic uncertainty β€” what the model doesn't know (reducible with more data)
  • Aleatoric uncertainty β€” inherent observation noise (irreducible)

MPC Action Selection Loop

 For each timestep t:
 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚  1. Extract 64-dim features from obs_t                   β”‚
 β”‚  2. Append to 3-frame temporal buffer                    β”‚
 β”‚                                                          β”‚
 β”‚  For each candidate action a ∈ {0,1,2,3,4}:             β”‚
 β”‚    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
 β”‚    β”‚  Concat one-hot(a) β†’ temporal sequence           β”‚  β”‚
 β”‚    β”‚  Run N MC forward passes through Transformer     β”‚  β”‚
 β”‚    β”‚  Compute GMM-weighted mean trajectory            β”‚  β”‚
 β”‚    β”‚  Compute epistemic std (uncertainty)             β”‚  β”‚
 β”‚    β”‚  Score = progress βˆ’ lateral_dev βˆ’ uncertainty    β”‚  β”‚
 β”‚    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
 β”‚                                                          β”‚
 β”‚  3. Select action with highest score (best_action)       β”‚
 β”‚  4. Apply Hard Shield AEB override if needed  πŸ›‘οΈ         β”‚
 β”‚  5. env.step(final_action) β†’ obs_{t+1}, reward           β”‚
 β”‚  6. Log (feature, true_future) for online training       β”‚
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⚑ Test Scenarios

All scenarios below are simulated using the open-source highway-env library β€” used exclusively for test case simulation.

Scenario Script Environment Challenge AEB Mode
πŸ›£οΈ Baseline Cruising test_case_mpc.py highway-v0 Maintain high speed in flowing traffic Lane-based
πŸ›‘ Emergency Braking test_case_braking.py highway-v0 Hard braking behind slow/stopped vehicle Lane-based
⬆️ Safe Overtake test_case_overtake.py highway-v0 Overtake slower vehicle without sideswipe Lane-based
πŸ”€ Lane Selection test_case_lane_selection.py highway-v0 Choose optimal lane under variable traffic Lane-based
πŸ”“ Gap Change test_case_gap_change.py highway-v0 Exploit dynamic gaps as they open/close Lane-based
🚦 Dense Cluster test_case_cluster.py highway-v0 Navigate through dense NPC clusters safely Lane-based
πŸ“ Marginal Gap test_case_marginal_gap.py highway-v0 Accept/reject tight gaps at decision threshold Lane-based
πŸ™οΈ Intersection test_case_intersection.py intersection-v0 Urban crossing with yielding + arrival reward Radial (8m)
πŸ”„ Oncoming Traffic test_case_oncoming.py two-way-v0 Head-on avoidance on two-lane road Lane-based
πŸ€– ROS2 Node test_case_ros2.py ROS2 Topics Real-robot deployment via pub/sub Both modes

πŸ›‘οΈ Hard Shield β€” AEB Safety System

The Hard Shield is a physics-level, rule-based safety override that executes after the neural network selects an action. It acts as a non-negotiable last-resort collision barrier β€” the neural policy is never solely responsible for collision avoidance.

Highway / Two-Way Mode (Lane-Based Geometry)

  Ego Vehicle ──▢ Check surrounding vehicles:

  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  crash_ahead   (|dy| < 2.0m,  0 < dx < 15.0m)  β†’  FRONT   β”‚
  β”‚  blocked_left  (-6.0m < dy ≀ -2.0m, |dx| < 10m) β†’  LEFT   β”‚
  β”‚  blocked_right  (2.0m ≀ dy < 6.0m,  |dx| < 10m) β†’  RIGHT  β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

  Decision Tree:
  crash_ahead + action ∈ {IDLE, FASTER}
      β”œβ”€β”€ NOT blocked_left  ──▢  action = LANE_LEFT   (evade)
      β”œβ”€β”€ NOT blocked_right ──▢  action = LANE_RIGHT  (evade)
      └── BOTH blocked      ──▢  action = SLOWER       (brake)

  action = LANE_LEFT  + blocked_left  ──▢  IDLE (or BRAKE if crash)
  action = LANE_RIGHT + blocked_right ──▢  IDLE (or BRAKE if crash)

Intersection Mode (Radial Proximity)

  For every NPC vehicle v:
    dist = sqrt[(v.x βˆ’ ego.x)Β² + (v.y βˆ’ ego.y)Β²]
    dist < 8.0m  ──▢  SLAM BRAKES  πŸ›‘  (action = SLOWER)

  Action remapping (NN 5-class β†’ intersection-v0 Discrete(3)):
    NN:  LEFT=0  IDLE=1  RIGHT=2  FASTER=3  SLOWER=4
    Env:   β†’1      β†’1      β†’1       β†’2         β†’0

πŸ›°οΈ Server / Client Bridge

ENIGMAA includes a TCP socket bridge that fully decouples the environment renderer from the agent controller, allowing any external process to drive the simulation.

 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”          TCP:5005         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚   server_env.py      │◄─────────────────────────►│  client_script.py    β”‚
 β”‚                      β”‚                            β”‚  (or any controller) β”‚
 β”‚  highway-env         β”‚  β‘  {"status": "ready"}    β”‚                      β”‚
 β”‚  pygame render loop  │─────────────────────────► β”‚                      β”‚
 β”‚                      β”‚  β‘‘ action integer (0-4)   β”‚                      β”‚
 β”‚                      │◄───────────────────────── β”‚                      β”‚
 β”‚                      β”‚  β‘’ {"reward":r,"done":d}  β”‚                      β”‚
 β”‚                      │─────────────────────────► β”‚                      β”‚
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Action Space:

Code Action
0 Lane Left
1 Idle
2 Lane Right
3 Faster
4 Slower
# Terminal 1 β€” Launch environment server (pygame window opens)
python server_env.py

# Terminal 2 β€” Connect your agent or test client
python client_script.py

The bridge is compatible with any controller: another Python process, a ROS2 node, a remote machine, or a custom RL training loop.


πŸ€– ROS2 Deployment

test_case_ros2.py provides a production-ready SafeTrajectoryNode that bridges ENIGMAA's Bayesian MPC agent directly to real ROS2 vehicle hardware.

Topics

Direction Topic Message Type Purpose
Subscribe /highway_env/observations Float32MultiArray Sensor feature vector input
Publish /vehicle/cmd_vel Twist Velocity commands to vehicle
Publish /explainability/rationale String Integrated Gradients per-step

πŸ’‘ Replace the /highway_env/observations source with your real LiDAR / camera feature extractor pipeline in production.

Launch

# 1. Source your ROS2 workspace
source /opt/ros/humble/setup.bash
source install/setup.bash

# 2. Copy model weights to working directory
cp env/HighwayEnv/bayesian_model.pt .

# 3. Run the node
ros2 run your_package test_case_ros2

Expected log output:

[INFO] [safe_trajectory_ai]: Initializing SafeTrajectory AI ROS2 Node...
[INFO] [safe_trajectory_ai]: Successfully loaded Temporal Transformer weights.

πŸ”„ Continuous Online Learning

ENIGMAA continuously improves its Bayesian model during inference using a background training thread with file-locked data access to prevent corruption across concurrent test cases.

Main Thread                          Background Thread
──────────────────────────────────   ──────────────────────────────────────────
Inference step t
  β”‚
  β”œβ”€β”€ extract features
  β”œβ”€β”€ predict trajectory
  β”œβ”€β”€ select action (+ AEB)
  β”œβ”€β”€ env.step()
  └── DataLogger.append(feat, future)

                                     Every N steps:
                                       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                       β”‚  FileLock(training.lock)         β”‚
                                       β”‚                                  β”‚
                                       β”‚  load  data_test_case_X.npz     β”‚
                                       β”‚  merge new + historical          β”‚
                                       β”‚  trim  β†’ max 10,000 rows         β”‚
                                       β”‚  save  data_test_case_X.npz     β”‚
                                       β”‚                                  β”‚
                                       β”‚  load  bayesian_model.pt         β”‚
                                       β”‚  fine-tune 2 epochs (bs=32)      β”‚
                                       β”‚  save  bayesian_model.pt         β”‚
                                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

The training.lock file acts as a mutex, preventing two simultaneously running test cases from writing to the same .npz or .pt file at the same time.


πŸ”§ Patch System

Rather than duplicating code across scenarios, ENIGMAA ships surgical patch scripts that transform a base test case to target a specific environment or architecture configuration.

Base test_case_mpc.py
        β”‚
        β”œβ”€β”€ patch_files.py              β†’ Add FileLock + shared MODEL_PATH
        β”‚
        β”œβ”€β”€ patch_data_architecture.py  β†’ Per-scenario isolated .npz data files
        β”‚                                 (data_test_case_braking.npz, etc.)
        β”‚
        β”œβ”€β”€ patch_coordinates.py        β†’ Fix ego position from env.unwrapped
        β”‚                                 Encode futures as relative (dx,dy) offsets
        β”‚
        └── patch_intersection.py       β†’ Switch to intersection-v0
                                          Radial AEB (8m threshold)
                                          Discrete(3) action remapping
                                          Arrival reward (+10) + spawn_probability

Running Patches

cd env/HighwayEnv

# Step 1 β€” Shared model + FileLock support
python patch_files.py

# Step 2 β€” Isolate per-scenario calibration data
python patch_data_architecture.py

# Step 3 β€” Fix ego coordinates + relative trajectory encoding
python patch_coordinates.py

# Step 4 β€” Only if running intersection scenario
python patch_intersection.py

⚠️ Run patches in the order listed above. Each patch assumes the previous one has already been applied.


πŸ§ͺ Evaluation & Benchmarks

Quick Evaluation (3 Episodes)

cd env/HighwayEnv
python eval.py
Eval Episode 1 Survived for: 423 steps
Eval Episode 2 Survived for: 389 steps
Eval Episode 3 Survived for: 461 steps
AVERAGE_STEPS: 424.33

Full Multi-Environment Benchmark

python eval_report.py

Runs the pre-trained model across three distinct highway-env environments:

Benchmark Environment Metric
Baseline MPC (Cruising) highway-v0 Steps survived
Two-Way Oncoming (Avoidance) two-way-v0 Steps survived
Urban Intersection (Yielding) intersection-v0 Steps survived

Both scripts use rgb_array render mode (headless) and cap episodes at 100–500 steps for repeatable benchmarking.


πŸ”¬ Explainability (XAI)

ENIGMAA uses Captum Integrated Gradients to trace every action decision back to the raw 69-dimensional input features β€” fulfilling safety and audit requirements in regulated deployments.

ModelWrapper(BayesianTrajectoryPredictor)
        β”‚
        └── IntegratedGradients.attribute(input_tensor)
                β”‚
                β–Ό
        Attribution scores per input feature
        (69 values: 64 kinematic dims + 5 action dims)
                β”‚
                β–Ό
        Published to /explainability/rationale  (ROS2)
        or logged inline in terminal output

The ModelWrapper reduces the multi-modal GMM output (3 modes Γ— 30 steps Γ— 2 coords) to a scalar score so that Integrated Gradients can compute gradients through the full prediction stack.

This enables safety engineers and regulators to audit why the agent selected a particular action at any timestep β€” a key requirement for ISO 26262 / SOTIF compliance in production AV systems.


πŸ“¦ Installation

Requirements

  • Python 3.9 – 3.13
  • pip
  • (Optional) ROS2 Humble or later for test_case_ros2.py

Step 1 β€” Clone

git clone https://github.com/your-username/enigmaa-highway
cd enigmaa-highway

Step 2 β€” Install the modified highway-env fork

cd env/HighwayEnv
pip install -e .

Step 3 β€” Install ENIGMAA dependencies

pip install torch captum filelock

Full dependency list (pyproject.toml)

dependencies = [
    "gymnasium >= 1.0.0a2",
    "farama-notifications >= 0.0.1",
    "numpy >= 1.23.0",
    "pygame >= 2.0.2",
    "matplotlib",
    "pandas",
    "scipy",
    "torch",
    "captum",
    "filelock",
]

πŸš€ Quick Start

cd env/HighwayEnv

# ── Option A: Run a scenario directly ──────────────────────────────────
python test_cases/test_case_mpc.py          # Highway baseline
python test_cases/test_case_braking.py      # Emergency braking
python test_cases/test_case_intersection.py # Urban intersection
python test_cases/test_case_oncoming.py     # Oncoming avoidance

# ── Option B: Server/Client split (decoupled renderer) ─────────────────
python server_env.py &       # Starts the pygame render server
python client_script.py      # Agent connects and sends actions

# ── Option C: Headless evaluation ──────────────────────────────────────
python eval.py               # Quick 3-episode benchmark
python eval_report.py        # Full 3-environment report

# ── Option D: Apply patches then run ───────────────────────────────────
python patch_files.py
python patch_data_architecture.py
python patch_coordinates.py
python test_cases/test_case_mpc.py

βš™οΈ Configuration Reference

All environments are configured by passing a config dict to gym.make():

env = gym.make("highway-v0", render_mode="human", config={
    "lanes_count": 2,
    "duration": 1_000_000,
    "simulation_frequency": 15,
    "collision_reward": -50,
    "high_speed_reward": 1,
    "right_lane_reward": 0.1,
    "reward_speed_range": [20, 30],
})
Parameter Type Default Description
lanes_count int 4 Number of highway lanes
duration int 40 Episode length in steps
simulation_frequency int 15 Simulation steps per second
collision_reward float -1 Penalty applied on collision
high_speed_reward float 0.4 Reward for high-speed travel
right_lane_reward float 0.1 Reward for right-lane preference
reward_speed_range list [20, 30] Speed range for full reward
spawn_probability float 0.6 NPC vehicle spawn rate (intersection)
arrived_reward float 1.0 Reward for completing intersection cross
manual_control bool False Enable keyboard control

πŸ“Š Model Files

File Location Size Description
bayesian_model.pt env/ ~167 KB Root pre-trained Bayesian Transformer
bayesian_model.pt env/HighwayEnv/ ~534 KB Working checkpoint (updated by online learning)
bayesian_model_oncoming.pt env/HighwayEnv/ ~534 KB Oncoming-scenario specialized weights
live_calib_data.npz env/ ~4.5 MB Shared live calibration buffer
live_calib_data.npz env/HighwayEnv/ ~10 MB Expanded working calibration buffer
live_calib_data_oncoming.npz env/HighwayEnv/ ~1.4 MB Oncoming-specific calibration buffer
data_test_case_*.npz env/HighwayEnv/ ~2 MB each Per-scenario isolated training data

πŸ™ Acknowledgements

The open-source driving simulation library powering all ENIGMAA test scenarios

By Γ‰douard Leurent Β· Maintained by Farama Foundation
Licensed under MIT
Gymnasium ecosystem maintenance and stewardship of open-source RL environments

gymnasium.farama.org
Model interpretability and explainability β€” Integrated Gradients XAI

By Meta Research Β· Open Source
Neural network backbone for the Temporal Transformer GMM architecture

By Meta AI Β· Open Source

ENIGMAA Phase 3.2 Β· MIT License Β· Built on open-source foundations

🌐 Deployed at enigmaa.space.z.ai

Test case simulation powered by highway-env

About

INNOVITUS 1.0 Hackathon

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages