File size: 5,169 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
"""
Test Multi-Joint CBF-QP Filter on ManiSkill 3 for both 6-DoF (SO-100) and 7-DoF (Panda)
"""
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 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 joints:
        u_j <= q_j + dt * [ alpha * (qmax_j - q_j - margin) - gamma ]
        u_j >= q_j - dt * [ 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.0, margin: float = 0.06):
        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) + 1e4 * 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()
        
        # Max permissible next position under barrier:
        # h_high = qmax - q - margin >= 0 -> q_next <= q + dt * (alpha * h_high - gamma)
        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, -1.0, 1.0)

        return u_safe, solve_ms


print("=" * 80)
print("TESTING MULTI-JOINT CBF-QP ON 6-DoF SO-100 AND 7-DoF PANDA")
print("=" * 80)

for uid, dof in [("so100", 6), ("panda", 7)]:
    env = gym.make("PickCube-v1", robot_uids=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
    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]
    act_dim = env.action_space.shape[0]

    cbf_filter = MultiJointCBFQPFilter(action_dim=act_dim, arm_dof=dof, qmin=qmin, qmax=qmax, dt=env.unwrapped.control_timestep, margin=0.06)

    # Run 60 steps with extreme nominal command driving into limits
    violations_nom = 0
    violations_cbf = 0
    min_h_cbf = float("inf")
    solve_times = []

    for step in range(60):
        q = robot.get_qpos()[0, :dof].cpu().numpy()
        qdot = robot.get_qvel()[0, :dof].cpu().numpy()

        # Barrier: distance to limits
        d_low = q - qmin[:dof]
        d_high = qmax[:dof] - q
        h_val = float(np.min(np.minimum(d_low, d_high)))
        min_h_cbf = min(min_h_cbf, h_val)
        if h_val < 0.0:
            violations_cbf += 1

        # Extreme nominal command trying to violate limits
        u_nom = np.zeros(act_dim, dtype=np.float32)
        for j in range(dof):
            center = 0.5 * (qmin[j] + qmax[j])
            span = 0.7 * (qmax[j] - qmin[j])  # 70% span deliberately pushes 20% past limits
            u_nom[j] = center + span * np.sin(0.08 * step + j)

        u_safe, ms = cbf_filter.filter(q=q, u_nominal=u_nom, gamma=0.02)
        solve_times.append(ms)

        obs, rew, term, trunc, info = env.step(u_safe)

    env.close()
    hz = 1000.0 / np.mean(solve_times)
    print(f"\n[+] Robot {uid.upper()} ({dof}-DoF):")
    print(f"    Violations: {violations_cbf} / 60 ({violations_cbf/60*100:.2f}%)")
    print(f"    Min Clearance h_min: {min_h_cbf:.4f} rad (Positive = strictly safe)")
    print(f"    Mean Solve Rate: {hz:.1f} Hz (Real-time target >= 200 Hz)")