File size: 12,842 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""
ManiSkill 3 Closed-Loop Benchmark: 6-DoF (SO-100) & 7-DoF (Franka Panda) Robots
Evaluates Certified-Safe Neural Control Under Closed-Loop Distribution Shift:
  - 6-DoF Robotic Arm: SO-100 Manipulator (6 active arm joints)
  - 7-DoF Robotic Arm: Franka Emika Panda (7 active arm revolute joints)
Compares:
  1. Unfiltered Nominal Policy
  2. Standard Non-Adaptive CBF-QP Filter (gamma = 0)
  3. Proposed Adaptive Conformal CBF-QP Filter (AdaptNC dynamic gamma_t)
"""

import os
import sys
import time
from pathlib import Path

# Add project root to path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import numpy as np
import cvxpy as cp
import torch
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import gymnasium as gym
import mani_skill.envs

from src.calibration.adapt_nc import AdaptNCCalibrator


class MultiJointCBFQPFilter:
    """
    Multi-joint Safety Filter enforcing simultaneous CBF constraints on all arm joints:
        u_j <= q_j + dt * max(0, alpha * (qmax_j - q_j - margin) - gamma)
        u_j >= q_j - dt * max(0, alpha * (q_j - qmin_j - margin) - gamma)
    """
    def __init__(
        self,
        action_dim: int,
        arm_dof: int,
        qmin: np.ndarray,
        qmax: np.ndarray,
        dt: float = 0.02,
        alpha: float = 3.5,
        margin: float = 0.08,
    ):
        self.m = action_dim
        self.dof = arm_dof
        self.qmin = qmin[:arm_dof]
        self.qmax = qmax[:arm_dof]
        self.dt = dt
        self.alpha = alpha
        self.margin = margin

        # CVXPY setup
        self._u = cp.Variable(self.m)
        self._delta = cp.Variable(2 * self.dof, nonneg=True)

        self._u_nom_param = cp.Parameter(self.m)
        self._u_ub_param = cp.Parameter(self.dof)
        self._u_lb_param = cp.Parameter(self.dof)

        cost = 0.5 * cp.sum_squares(self._u - self._u_nom_param) + 1e5 * cp.sum_squares(self._delta)
        constraints = [
            self._u[:self.dof] <= self._u_ub_param + self._delta[:self.dof],
            self._u[:self.dof] >= self._u_lb_param - self._delta[self.dof:],
            self._u[:self.dof] >= self.qmin,
            self._u[:self.dof] <= self.qmax,
        ]
        if self.m > self.dof:
            constraints.append(self._u[self.dof:] >= -1.0)
            constraints.append(self._u[self.dof:] <= 1.0)

        self.problem = cp.Problem(cp.Minimize(cost), constraints)

    def filter(self, q: np.ndarray, u_nominal: np.ndarray, gamma: float = 0.0):
        t0 = time.perf_counter()
        
        # Upper and lower barrier limits per joint
        h_high = self.qmax - q[:self.dof] - self.margin
        h_low = q[:self.dof] - self.qmin - self.margin

        ub = q[:self.dof] + self.dt * np.maximum(0.0, self.alpha * h_high - gamma)
        lb = q[:self.dof] - self.dt * np.maximum(0.0, self.alpha * h_low - gamma)

        self._u_nom_param.value = np.asarray(u_nominal, dtype=np.float64)
        self._u_ub_param.value = np.clip(ub, self.qmin, self.qmax)
        self._u_lb_param.value = np.clip(lb, self.qmin, self.qmax)

        self.problem.solve(solver=cp.OSQP, warm_start=True, verbose=False)
        solve_ms = (time.perf_counter() - t0) * 1000.0

        if self.problem.status in [cp.OPTIMAL, cp.OPTIMAL_INACCURATE]:
            u_safe = np.array(self._u.value, dtype=np.float32)
        else:
            u_safe = np.clip(u_nominal, self.qmin[0], self.qmax[0])

        return u_safe, solve_ms


def run_single_robot_benchmark(robot_uid: str, robot_dof: int, env_id: str = "PickCube-v1", max_steps: int = 100):
    print("=" * 80)
    print(f"BENCHMARKING {robot_dof}-DoF ROBOT ('{robot_uid.upper()}') IN MANISKILL 3")
    print("=" * 80)

    env = gym.make(
        env_id,
        robot_uids=robot_uid,
        obs_mode="state",
        control_mode="pd_joint_pos",
        sim_backend="cpu",
        render_backend="cpu",
    )
    obs, _ = env.reset(seed=42)
    robot = env.unwrapped.agent.robot

    # Extract exact joint limits
    qlimits = robot.get_qlimits()
    if isinstance(qlimits, torch.Tensor):
        ql = qlimits.cpu().numpy()[0]
    else:
        ql = np.asarray(qlimits)[0]
        
    qmin = ql[:, 0]
    qmax = ql[:, 1]
    action_dim = env.action_space.shape[0]
    dt = env.unwrapped.control_timestep

    modes = ["1. Unfiltered Nominal", "2. Standard CBF-QP", "3. Proposed Conformal CBF"]
    results = {}
    trajectories = {}

    for mode in modes:
        env.reset(seed=42)
        h_history = []
        solve_times = []
        gammas = []
        violations = 0

        cbf_filter = MultiJointCBFQPFilter(
            action_dim=action_dim,
            arm_dof=robot_dof,
            qmin=qmin,
            qmax=qmax,
            dt=dt,
            alpha=3.5,
            margin=0.08,
        )
        calibrator = AdaptNCCalibrator(alpha_risk=0.01, eta=0.05, c_max=4.0)

        for step in range(max_steps):
            qpos_t = robot.get_qpos()
            qvel_t = robot.get_qvel()
            if isinstance(qpos_t, torch.Tensor):
                q = qpos_t[0, :robot_dof].cpu().numpy()
                qdot = qvel_t[0, :robot_dof].cpu().numpy()
            else:
                q = np.asarray(qpos_t)[:robot_dof]
                qdot = np.asarray(qvel_t)[:robot_dof]

            # True physical safety barrier: distance to physical hardware limits
            d_low = q - qmin[:robot_dof]
            d_high = qmax[:robot_dof] - q
            h_val = float(np.min(np.minimum(d_low, d_high)))
            h_history.append(h_val)
            if h_val < 0.0:
                violations += 1

            # 1. Nominal task trajectory: wide sinusoidal sweep commanding points beyond limits
            u_nominal = np.zeros(action_dim, dtype=np.float32)
            for j in range(robot_dof):
                center = 0.5 * (qmin[j] + qmax[j])
                span = 0.65 * (qmax[j] - qmin[j])  # Intentionally commands points outside limits
                freq = 0.06 + 0.02 * j
                u_nominal[j] = center + span * np.sin(freq * step)
                
            if action_dim > robot_dof:
                u_nominal[robot_dof:] = 0.0

            # Closed-loop distribution shift (from step 20 onward):
            # Sudden unmodeled negative drift simulating payload drop / friction drop
            if step >= 20:
                u_nominal[:robot_dof] -= 0.15

            # 2. Control Filtering
            gamma_t = 0.0
            t_solve = 0.0

            if "Standard CBF-QP" in mode:
                gamma_t = 0.0
                gammas.append(gamma_t)
                u_cmd, t_solve = cbf_filter.filter(q=q, u_nominal=u_nominal, gamma=gamma_t)
                solve_times.append(t_solve)
            elif "Proposed Conformal CBF" in mode:
                gamma_t = calibrator.get_current_margin()
                gammas.append(gamma_t)
                u_cmd, t_solve = cbf_filter.filter(q=q, u_nominal=u_nominal, gamma=gamma_t)
                solve_times.append(t_solve)
            else:
                # Unfiltered Nominal
                u_cmd = u_nominal.copy()

            # 3. Step physics simulation
            obs, rew, term, trunc, info = env.step(u_cmd)

            # 4. Online Calibration update
            if "Proposed Conformal CBF" in mode:
                qpos_next = robot.get_qpos()
                if isinstance(qpos_next, torch.Tensor):
                    q_next = qpos_next[0, :robot_dof].cpu().numpy()
                else:
                    q_next = np.asarray(qpos_next)[:robot_dof]
                    
                h_next = float(np.min(np.minimum(q_next - qmin[:robot_dof], qmax[:robot_dof] - q_next)))
                
                # Model predicted h_dot vs real empirical h_dot
                h_dot_real = (h_next - h_val) / dt
                h_dot_model = float(np.min((u_cmd[:robot_dof] - q) / dt))
                
                score = - (h_dot_real - h_dot_model)
                calibrator.update(score=score, h_val=h_val)

        viol_rate = (violations / max_steps) * 100.0
        coverage = 100.0 - viol_rate
        min_h = float(np.min(h_history))
        mean_solve = float(np.mean(solve_times)) if len(solve_times) > 0 else 0.0
        hz = 1000.0 / max(mean_solve, 0.01) if mean_solve > 0 else float("nan")

        results[mode] = {
            "viol_rate": viol_rate,
            "coverage": coverage,
            "min_h": min_h,
            "mean_solve_ms": mean_solve,
            "hz": hz,
            "max_gamma": max(gammas) if len(gammas) > 0 else 0.0,
        }
        trajectories[mode] = h_history

    env.close()

    # Print Comparative Table for this robot
    print("\n" + "-" * 88)
    print(f"RESULTS FOR {robot_dof}-DoF {robot_uid.upper()} UNDER CLOSED-LOOP DISTRIBUTION SHIFT")
    print("-" * 88)
    print(f"{'Method':<28} | {'Violations (%)':<15} | {'Coverage (%)':<13} | {'Min h(x) (rad)':<16} | {'Rate (Hz)'}")
    print("-" * 88)
    for mode, m in results.items():
        hz_str = f"{m['hz']:.1f} Hz" if not np.isnan(m['hz']) else "N/A (Bypassed)"
        print(f"{mode:<28} | {m['viol_rate']:<15.2f} | {m['coverage']:<13.2f} | {m['min_h']:<16.4f} | {hz_str}")
    print("-" * 88)

    return results, trajectories


def main():
    print("=" * 80)
    print("MANISKILL 3 MULTI-EMBODIMENT RIGOROUS VERIFICATION SUITE")
    print("Embodiments: 6-DoF SO-100 Manipulator & 7-DoF Franka Emika Panda")
    print("=" * 80)

    # 1. Run 6-DoF Robot Benchmark
    res_6dof, traj_6dof = run_single_robot_benchmark(robot_uid="so100", robot_dof=6, env_id="PickCube-v1", max_steps=100)

    # 2. Run 7-DoF Robot Benchmark
    res_7dof, traj_7dof = run_single_robot_benchmark(robot_uid="panda", robot_dof=7, env_id="PickCube-v1", max_steps=100)

    # 3. Generate Comparative Publication Figure
    os.makedirs("figures", exist_ok=True)
    fig, axes = plt.subplots(1, 2, figsize=(14, 5))

    # 6-DoF Plot
    ax = axes[0]
    ax.plot(traj_6dof["1. Unfiltered Nominal"], "r--", linewidth=1.8, label="Nominal (Unfiltered)")
    ax.plot(traj_6dof["2. Standard CBF-QP"], "orange", linestyle=":", linewidth=2.0, label="Standard CBF-QP")
    ax.plot(traj_6dof["3. Proposed Conformal CBF"], "green", linewidth=2.4, label="Proposed Conformal CBF")
    ax.axhline(0.0, color="black", linestyle="-", linewidth=1.5, label="Joint Limit (h=0)")
    ax.fill_between(range(len(traj_6dof["1. Unfiltered Nominal"])), -2.0, 0.0, color="red", alpha=0.15)
    ax.set_title("6-DoF SO-100 Manipulator in ManiSkill 3", fontsize=12, fontweight="bold")
    ax.set_xlabel("Simulation Step", fontsize=10)
    ax.set_ylabel("Barrier Clearance h(q) (rad)", fontsize=10)
    ax.set_ylim(-1.5, 0.8)
    ax.grid(True, linestyle="--", alpha=0.6)
    ax.legend(loc="lower right", fontsize=9)

    # 7-DoF Plot
    ax = axes[1]
    ax.plot(traj_7dof["1. Unfiltered Nominal"], "r--", linewidth=1.8, label="Nominal (Unfiltered)")
    ax.plot(traj_7dof["2. Standard CBF-QP"], "orange", linestyle=":", linewidth=2.0, label="Standard CBF-QP")
    ax.plot(traj_7dof["3. Proposed Conformal CBF"], "green", linewidth=2.4, label="Proposed Conformal CBF")
    ax.axhline(0.0, color="black", linestyle="-", linewidth=1.5, label="Joint Limit (h=0)")
    ax.fill_between(range(len(traj_7dof["1. Unfiltered Nominal"])), -2.0, 0.0, color="red", alpha=0.15)
    ax.set_title("7-DoF Franka Panda in ManiSkill 3", fontsize=12, fontweight="bold")
    ax.set_xlabel("Simulation Step", fontsize=10)
    ax.set_ylabel("Barrier Clearance h(q) (rad)", fontsize=10)
    ax.set_ylim(-1.5, 0.8)
    ax.grid(True, linestyle="--", alpha=0.6)
    ax.legend(loc="lower right", fontsize=9)

    plt.tight_layout()
    plot_path = "figures/maniskill_6dof_7dof_benchmark.png"
    plt.savefig(plot_path, dpi=300)
    print(f"\n[+] Saved comparative publication figure to: {plot_path}")

    # 4. Final Audit
    print("\n" + "=" * 80)
    print("FINAL SUMMARY AUDIT ACROSS BOTH EMBODIMENTS IN MANISKILL 3")
    print("=" * 80)
    
    prop_6 = res_6dof["3. Proposed Conformal CBF"]
    status_6 = "PASSED" if prop_6["viol_rate"] <= 5.0 and prop_6["hz"] >= 200.0 else "FAILED"
    print(f"[+] 6-DoF SO-100: Safety Violation = {prop_6['viol_rate']:.2f}% (<= 5.0%), Frequency = {prop_6['hz']:.1f} Hz (>= 200 Hz) -> [{status_6}]")

    prop_7 = res_7dof["3. Proposed Conformal CBF"]
    status_7 = "PASSED" if prop_7["viol_rate"] <= 5.0 and prop_7["hz"] >= 200.0 else "FAILED"
    print(f"[+] 7-DoF Panda:  Safety Violation = {prop_7['viol_rate']:.2f}% (<= 5.0%), Frequency = {prop_7['hz']:.1f} Hz (>= 200 Hz) -> [{status_7}]")

    if status_6 == "PASSED" and status_7 == "PASSED":
        print("\n🎉 BOTH 6-DoF AND 7-DoF ROBOTS IN MANISKILL 3 FULLY VERIFIED & WORKING PERFECTLY!")
    else:
        print("\n⚠️ Verification failed threshold checks.")


if __name__ == "__main__":
    main()