ββββββββββββ ββββββ βββββββ ββββ ββββ ββββββ ββββββ
βββββββββββββ ββββββββββββββ βββββ βββββββββββββββββββββ
ββββββ ββββββ βββββββββ βββββββββββββββββββββββββββββββ
ββββββ ββββββββββββββββ ββββββββββββββββββββββββββββββ
βββββββββββ βββββββββββββββββββββ βββ ββββββ ββββββ βββ
βββββββββββ ββββββββ βββββββ βββ ββββββ ββββββ βββ
Phase 3.2 Β· Temporal Transformer Β· GMM Β· MC Dropout Β· Hard Shield AEB Β· ROS2
π¨ 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.
ENIGMAA is live and accessible at:
π enigmaa.space.z.ai
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 |
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 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| 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 |
All test case driving scenarios in ENIGMAA are simulated using the open-source
highway-envlibrary.
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
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-envrepository.
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
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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)
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 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
All scenarios below are simulated using the open-source
highway-envlibrary β 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 |
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.
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)
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
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.pyThe bridge is compatible with any controller: another Python process, a ROS2 node, a remote machine, or a custom RL training loop.
test_case_ros2.py provides a production-ready SafeTrajectoryNode that bridges ENIGMAA's Bayesian MPC agent directly to real ROS2 vehicle hardware.
| 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/observationssource with your real LiDAR / camera feature extractor pipeline in production.
# 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_ros2Expected log output:
[INFO] [safe_trajectory_ai]: Initializing SafeTrajectory AI ROS2 Node...
[INFO] [safe_trajectory_ai]: Successfully loaded Temporal Transformer weights.
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.
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
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.
cd env/HighwayEnv
python eval.pyEval Episode 1 Survived for: 423 steps
Eval Episode 2 Survived for: 389 steps
Eval Episode 3 Survived for: 461 steps
AVERAGE_STEPS: 424.33
python eval_report.pyRuns 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.
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.
- Python 3.9 β 3.13
- pip
- (Optional) ROS2 Humble or later for
test_case_ros2.py
git clone https://github.com/your-username/enigmaa-highway
cd enigmaa-highwaycd env/HighwayEnv
pip install -e .pip install torch captum filelockdependencies = [
"gymnasium >= 1.0.0a2",
"farama-notifications >= 0.0.1",
"numpy >= 1.23.0",
"pygame >= 2.0.2",
"matplotlib",
"pandas",
"scipy",
"torch",
"captum",
"filelock",
]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.pyAll 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 |
| 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 |
|
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