Download scripts/run_simulation.py from codewithyug/certified-safe-neural-control: direct link, hf CLI and curl.
- Browser
- Download file 5.55 kB
-
https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/scripts/run_simulation.py
- Command line
-
hf download hf://codewithyug/certified-safe-neural-control/scripts/run_simulation.py
-
curl -L -o run_simulation.py https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/scripts/run_simulation.py
5.55 kB
| """ | |
| Turnkey Simulation and Baseline Comparison Script | |
| Demonstrates closed-loop performance under sudden distribution shift for: | |
| 1. Unfiltered Nominal Controller | |
| 2. Static Neural CBF-QP (Fixed margin gamma = 0) | |
| 3. Online Calibrated Neural CBF (AdaptNC Dynamic gamma_t) | |
| """ | |
| import sys | |
| import os | |
| from pathlib import Path | |
| # Add project root to sys.path for direct execution | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| import numpy as np | |
| import torch | |
| from src.dynamics.toy_nav import DubinsCarSystem | |
| from src.cbf.network import NeuralCBF | |
| from src.filter.cbf_qp import CBFQPSafetyFilter | |
| from src.calibration.adapt_nc import AdaptNCCalibrator | |
| from src.eval.harness import ClosedLoopHarness | |
| from src.eval.metrics import compare_ablation_runs | |
| def main(): | |
| print("=" * 70) | |
| print("CERTIFIED SAFE NEURAL CONTROL: CLOSED-LOOP DRIFT BENCHMARK") | |
| print("=" * 70) | |
| # 1. Initialize Dubins Car System | |
| dt = 0.02 | |
| sys = DubinsCarSystem(tau=0.5, K=1.0, dt=dt, omega_max=2.0, a_max=3.0) | |
| # Setup Obstacle and Goal | |
| obstacle_pos = np.array([2.5, 0.0], dtype=np.float32) | |
| obstacle_radius = 1.0 | |
| goal_pos = np.array([5.0, 0.0], dtype=np.float32) | |
| def gt_barrier(x): | |
| return sys.ground_truth_barrier(x, obstacle_pos, obstacle_radius, safety_margin=0.15) | |
| def goal_check(x): | |
| return bool(np.linalg.norm(x[:2] - goal_pos) < 0.4) | |
| # 2. Define Nominal Goal-Seeking Policy (Pure Pursuit P-controller) | |
| def nominal_policy(x, t): | |
| px, py, theta, v = x | |
| dx = goal_pos[0] - px | |
| dy = goal_pos[1] - py | |
| target_theta = np.arctan2(dy, dx) | |
| angle_err = np.arctan2(np.sin(target_theta - theta), np.cos(target_theta - theta)) | |
| omega_cmd = float(np.clip(2.5 * angle_err, -sys.u_max[0], sys.u_max[0])) | |
| a_cmd = float(np.clip(1.5 * (2.0 - v), -sys.u_max[1], sys.u_max[1])) | |
| return np.array([omega_cmd, a_cmd], dtype=np.float32) | |
| # 3. Create and Load Trained Neural CBF | |
| cbf_net = NeuralCBF(state_dim=4, hidden_dims=[64, 64], activation="tanh") | |
| ckpt_path = "checkpoints/cbf_dubins.pt" | |
| if os.path.exists(ckpt_path): | |
| cbf_net.load_state_dict(torch.load(ckpt_path, map_location="cpu", weights_only=True)) | |
| print(f"[+] Loaded trained Neural CBF from {ckpt_path}") | |
| else: | |
| print("[!] Warning: Checkpoint not found, using randomly initialized barrier.") | |
| # Injected Disturbance: Sudden cross-track drift & friction drop at t=80 | |
| def shift_disturbance(x, t): | |
| # Injected lateral drift force pushing car directly toward obstacle | |
| return np.array([0.0, -1.2, 0.3, -0.4], dtype=np.float32) | |
| x0 = np.array([0.0, 0.2, 0.0, 1.5], dtype=np.float32) | |
| results = {} | |
| # ------------------------------------------------------------- | |
| # RUN 1: Unfiltered Nominal Controller | |
| # ------------------------------------------------------------- | |
| print("\n[*] Executing Run 1: Unfiltered Nominal Controller...") | |
| harness_nom = ClosedLoopHarness(system=sys, ground_truth_barrier_fn=gt_barrier) | |
| res_nom = harness_nom.run_episode( | |
| x_init=x0, | |
| nominal_policy=nominal_policy, | |
| max_steps=220, | |
| shift_step=70, | |
| shift_disturbance_fn=shift_disturbance, | |
| goal_check_fn=goal_check, | |
| ) | |
| results["1. Unfiltered Nominal"] = res_nom["metrics"] | |
| # ------------------------------------------------------------- | |
| # RUN 2: Static CBF-QP (Fixed margin gamma = 0) | |
| # ------------------------------------------------------------- | |
| print("[*] Executing Run 2: Static Neural CBF-QP (Uncalibrated)...") | |
| qp_filter_static = CBFQPSafetyFilter( | |
| control_dim=2, | |
| u_min=sys.u_min, | |
| u_max=sys.u_max, | |
| alpha_cbf=1.5, | |
| slack_penalty=1e4, | |
| ) | |
| harness_static = ClosedLoopHarness( | |
| system=sys, | |
| cbf_net=cbf_net, | |
| safety_filter=qp_filter_static, | |
| ground_truth_barrier_fn=gt_barrier, | |
| ) | |
| res_static = harness_static.run_episode( | |
| x_init=x0, | |
| nominal_policy=nominal_policy, | |
| max_steps=220, | |
| shift_step=70, | |
| shift_disturbance_fn=shift_disturbance, | |
| goal_check_fn=goal_check, | |
| ) | |
| results["2. Static CBF-QP"] = res_static["metrics"] | |
| # ------------------------------------------------------------- | |
| # RUN 3: Online Calibrated Neural CBF (AdaptNC Dynamic gamma_t) | |
| # ------------------------------------------------------------- | |
| print("[*] Executing Run 3: Online Calibrated CBF (AdaptNC / ACI)...") | |
| qp_filter_adapt = CBFQPSafetyFilter( | |
| control_dim=2, | |
| u_min=sys.u_min, | |
| u_max=sys.u_max, | |
| alpha_cbf=1.5, | |
| slack_penalty=1e4, | |
| ) | |
| calibrator = AdaptNCCalibrator(alpha_risk=0.05, eta=0.04, c_max=4.0) | |
| harness_adapt = ClosedLoopHarness( | |
| system=sys, | |
| cbf_net=cbf_net, | |
| safety_filter=qp_filter_adapt, | |
| calibrator=calibrator, | |
| ground_truth_barrier_fn=gt_barrier, | |
| ) | |
| res_adapt = harness_adapt.run_episode( | |
| x_init=x0, | |
| nominal_policy=nominal_policy, | |
| max_steps=220, | |
| shift_step=70, | |
| shift_disturbance_fn=shift_disturbance, | |
| goal_check_fn=goal_check, | |
| ) | |
| results["3. AdaptNC Online Calibrated"] = res_adapt["metrics"] | |
| # 4. Print Comparative Table | |
| print("\n" + "=" * 80) | |
| print("BENCHMARK RESULTS SUMMARY UNDER CLOSED-LOOP DISTRIBUTION SHIFT") | |
| print("=" * 80) | |
| table_str = compare_ablation_runs(results) | |
| print(table_str) | |
| print("=" * 80) | |
| if __name__ == "__main__": | |
| main() | |