File size: 5,268 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
"""
Closed-Loop Simulation and Evaluation Harness
Executes rollouts with plant dynamics, nominal policies, CBF-QP filtering,
and online non-exchangeable conformal calibration under injected distribution shifts.
"""

from typing import Callable, Optional, Dict, List, Any
import numpy as np
import torch

from src.dynamics.base import ControlAffineSystem
from src.cbf.network import NeuralCBF
from src.filter.cbf_qp import CBFQPSafetyFilter
from src.calibration.adapt_nc import AdaptNCCalibrator
from src.eval.metrics import calculate_run_metrics


class ClosedLoopHarness:
    """
    Simulation orchestrator executing rollouts under unannounced distribution shifts.
    """

    def __init__(
        self,
        system: ControlAffineSystem,
        cbf_net: Optional[NeuralCBF] = None,
        safety_filter: Optional[CBFQPSafetyFilter] = None,
        calibrator: Optional[AdaptNCCalibrator] = None,
        ground_truth_barrier_fn: Optional[Callable[[np.ndarray], float]] = None,
    ):
        self.system = system
        self.cbf_net = cbf_net
        self.safety_filter = safety_filter
        self.calibrator = calibrator
        self.gt_barrier_fn = ground_truth_barrier_fn

    def run_episode(
        self,
        x_init: np.ndarray,
        nominal_policy: Callable[[np.ndarray, int], np.ndarray],
        max_steps: int = 300,
        shift_step: Optional[int] = None,
        shift_disturbance_fn: Optional[Callable[[np.ndarray, int], np.ndarray]] = None,
        goal_check_fn: Optional[Callable[[np.ndarray], bool]] = None,
    ) -> Dict[str, Any]:
        """
        Executes a single closed-loop episode rollout.
        """
        history = []
        x = x_init.copy()
        goal_reached = False

        for t in range(max_steps):
            # 1. Compute nominal control action
            u_nom = nominal_policy(x, t)

            # 2. Safety filter intervention (if active)
            gamma = 0.0
            if self.calibrator is not None:
                gamma = self.calibrator.get_current_margin()

            h_val = 1.0
            Lf_h = 0.0
            Lg_h = np.zeros(self.system.control_dim, dtype=np.float32)
            u_safe = u_nom.copy()
            filter_info = {"solve_time_ms": 0.0, "slack": 0.0, "status": "bypassed"}

            if self.cbf_net is not None and self.safety_filter is not None:
                x_tensor = torch.tensor(x, dtype=torch.float32)
                h_val_t, grad_h_t = self.cbf_net.compute_h_and_jacobian(x_tensor)
                h_val = float(h_val_t.item())
                grad_h = grad_h_t.detach().cpu().numpy()

                f_val = self.system.f(x)
                g_val = self.system.g(x)

                Lf_h = float(np.dot(grad_h, f_val))
                Lg_h = grad_h @ g_val

                u_safe, filter_info = self.safety_filter.filter(
                    u_nominal=u_nom,
                    h_val=h_val,
                    Lf_h=Lf_h,
                    Lg_h=Lg_h,
                    gamma=gamma,
                )

            # 3. Injected distribution shift
            w_dist = None
            if shift_step is not None and t >= shift_step and shift_disturbance_fn is not None:
                w_dist = shift_disturbance_fn(x, t)

            # 4. Integrate system forward using RK4
            x_next = self.system.step_rk4(x, u_safe, disturbance=w_dist)

            # 5. Online Calibration step (if calibrator active)
            is_calib_viol = 0.0
            score = 0.0
            if self.calibrator is not None and self.cbf_net is not None:
                x_next_tensor = torch.tensor(x_next, dtype=torch.float32)
                h_next_val = float(self.cbf_net(x_next_tensor).item())

                score = self.calibrator.compute_nonconformity_score(
                    h_curr=h_val,
                    h_next=h_next_val,
                    Lf_h=Lf_h,
                    Lg_h=Lg_h,
                    u_executed=u_safe,
                    dt=self.system.dt,
                )
                calib_rec = self.calibrator.update(score=score, h_val=h_val)
                is_calib_viol = calib_rec["is_violation"]

            # 6. Evaluate ground-truth safety metric
            gt_barrier = 1.0
            if self.gt_barrier_fn is not None:
                gt_barrier = self.gt_barrier_fn(x)

            # 7. Check goal completion
            if goal_check_fn is not None and goal_check_fn(x):
                goal_reached = True

            # Record step telemetry
            step_record = {
                "step": t,
                "x": x.copy(),
                "u_nom": u_nom.copy(),
                "u_safe": u_safe.copy(),
                "h_val": h_val,
                "gamma": gamma,
                "score": score,
                "is_calib_violation": is_calib_viol,
                "ground_truth_barrier": gt_barrier,
                "solve_time_ms": filter_info["solve_time_ms"],
                "solver_status": filter_info["status"],
                "goal_reached": goal_reached,
            }
            history.append(step_record)

            x = x_next
            if goal_reached:
                break

        metrics = calculate_run_metrics(history)
        return {"history": history, "metrics": metrics}