File size: 5,552 Bytes
0210a65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"""
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()