""" 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}