Download scripts/export_digital_twin_telemetry.py from codewithyug/certified-safe-neural-control: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/scripts/export_digital_twin_telemetry.py
- Command line
-
hf download hf://codewithyug/certified-safe-neural-control/scripts/export_digital_twin_telemetry.py
-
curl -L -o export_digital_twin_telemetry.py https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/scripts/export_digital_twin_telemetry.py
15.2 kB
| """ | |
| Export Model-Generated Digital Twin Telemetry | |
| Runs the real PyTorch Neural CBF, OSQP Quadratic Program Filter, and AdaptNC Conformal Calibrator. | |
| Exports the exact step-by-step telemetry with ZERO hardcoded approximations. | |
| Platforms Covered: | |
| - Station 1: 4D Mobile AMR Navigation (Gazebo / Webots) | |
| - Station 2: Franka Panda 7-DoF Industrial Table-Top (ManiSkill 3 / MuJoCo) | |
| - Station 3: 2-DoF Manipulator Kinematics & Workspace Avoidance (PyBullet) | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import numpy as np | |
| import torch | |
| from pathlib import Path | |
| # Add project root to path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| 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 scripts.run_unified_robotics_simulation import FrankaPanda7DoF, MultiBarrierConformalFilter | |
| from scripts.visualize_2dof_robot import TwoDoFRobotArm, TwoDoFCBFQPFilter | |
| def generate_exact_model_telemetry(): | |
| print("=" * 80) | |
| print("EXECUTING TRUE PYTORCH NEURAL CBF & MULTI-BARRIER OSQP FILTER") | |
| print("Zero Hardcoding: Pure Step-by-Step Numerical Integration of Real Models") | |
| print("=" * 80) | |
| # ========================================================================= | |
| # 1. STATION 1: 4D Mobile AMR (DubinsCarSystem + NeuralCBF + AdaptNC) | |
| # ========================================================================= | |
| print("[*] Simulating Station 1: 4D Mobile AMR via NeuralCBF...") | |
| sys_nav = DubinsCarSystem(tau=0.5, K=1.0, dt=0.02) | |
| obs_pos = np.array([2.5, 0.0], dtype=np.float32) | |
| obs_radius = 1.0 | |
| goal_pos = np.array([5.0, 0.0], dtype=np.float32) | |
| x0 = np.array([0.0, 0.2, 0.0, 1.5], dtype=np.float32) | |
| def gt_barrier(x): | |
| return sys_nav.ground_truth_barrier(x, obs_pos, obs_radius, safety_margin=0.15) | |
| def goal_check(x): | |
| return bool(np.linalg.norm(x[:2] - goal_pos) < 0.35) | |
| def nominal_policy(x, t): | |
| dx = goal_pos[0] - x[0] | |
| dy = goal_pos[1] - x[1] | |
| dist = np.linalg.norm([dx, dy]) | |
| t_th = np.arctan2(dy, dx) | |
| ang_err = np.arctan2(np.sin(t_th - x[2]), np.cos(t_th - x[2])) | |
| omega = float(np.clip(3.5 * ang_err, -sys_nav.u_max[0], sys_nav.u_max[0])) | |
| v_des = 2.0 | |
| a = float(np.clip(2.0 * (v_des - x[3]), -sys_nav.u_max[1], sys_nav.u_max[1])) | |
| return np.array([omega, a], dtype=np.float32) | |
| def shift_disturbance(x, t): | |
| # Floor slick zone between x=1.0m and x=3.8m pushing vehicle south | |
| if 1.0 <= x[0] <= 3.8: | |
| return np.array([0.0, -0.65, 0.12, -0.1], dtype=np.float32) | |
| return np.zeros(4, dtype=np.float32) | |
| # 1A. Nominal AMR (Unfiltered: crashes into hazard) | |
| harness_nom = ClosedLoopHarness(system=sys_nav, ground_truth_barrier_fn=gt_barrier) | |
| res_amr_nom = harness_nom.run_episode( | |
| x_init=x0, | |
| nominal_policy=nominal_policy, | |
| max_steps=420, | |
| shift_step=0, | |
| shift_disturbance_fn=shift_disturbance, | |
| goal_check_fn=goal_check, | |
| ) | |
| # 1B. Proposed Conformal AdaptNC AMR (Strictly safe) | |
| device = torch.device("cpu") | |
| 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=device, weights_only=True)) | |
| cbf_net.eval() | |
| calibrator_nav = AdaptNCCalibrator(alpha_risk=0.01, eta=0.05, c_max=4.0) | |
| qp_filter_nav = CBFQPSafetyFilter( | |
| control_dim=2, | |
| u_min=sys_nav.u_min, | |
| u_max=sys_nav.u_max, | |
| alpha_cbf=1.5, | |
| slack_penalty=1e4, | |
| ) | |
| harness_adapt = ClosedLoopHarness( | |
| system=sys_nav, | |
| cbf_net=cbf_net, | |
| safety_filter=qp_filter_nav, | |
| calibrator=calibrator_nav, | |
| ground_truth_barrier_fn=gt_barrier, | |
| ) | |
| res_amr_safe = harness_adapt.run_episode( | |
| x_init=x0, | |
| nominal_policy=nominal_policy, | |
| max_steps=420, | |
| shift_step=0, | |
| shift_disturbance_fn=shift_disturbance, | |
| goal_check_fn=goal_check, | |
| ) | |
| amr_nom_telemetry = [] | |
| for rec in res_amr_nom["history"]: | |
| amr_nom_telemetry.append({ | |
| "x": round(float(rec["x"][0]), 4), | |
| "y": round(float(rec["x"][1]), 4), | |
| "theta": round(float(rec["x"][2]), 4), | |
| "v": round(float(rec["x"][3]), 4), | |
| "h": round(float(rec["ground_truth_barrier"]), 4), | |
| "gamma": 0.0, | |
| }) | |
| amr_safe_telemetry = [] | |
| for rec in res_amr_safe["history"]: | |
| amr_safe_telemetry.append({ | |
| "x": round(float(rec["x"][0]), 4), | |
| "y": round(float(rec["x"][1]), 4), | |
| "theta": round(float(rec["x"][2]), 4), | |
| "v": round(float(rec["x"][3]), 4), | |
| "h": round(float(rec["ground_truth_barrier"]), 4), | |
| "gamma": round(float(rec["gamma"]), 4), | |
| }) | |
| print(f" - AMR Nominal Min Barrier: {min(r['h'] for r in amr_nom_telemetry):+.3f} (CRASHES)") | |
| print(f" - AMR Safe Min Barrier: {min(r['h'] for r in amr_safe_telemetry):+.3f} (STRICTLY SAFE)") | |
| print(f" - AMR Safe Reached Goal: ({amr_safe_telemetry[-1]['x']}, {amr_safe_telemetry[-1]['y']})") | |
| # ========================================================================= | |
| # 2. STATION 2: 7-DoF Franka Panda Arm (MultiBarrierConformalFilter + AdaptNC) | |
| # ========================================================================= | |
| print("\n[*] Simulating Station 2: 7-DoF Franka Panda via Multi-Barrier OSQP...") | |
| panda = FrankaPanda7DoF(dt=0.02) | |
| z_table = 0.62 | |
| safety_margin = 0.08 | |
| h_target_plane = z_table + safety_margin # 0.70m threshold | |
| q_init_panda = np.array([0.0, -0.65, 0.0, -2.45, 0.0, 1.45, 0.785], dtype=np.float32) | |
| p_goal_panda = np.array([0.35, 0.30, 0.75], dtype=np.float32) | |
| steps_arm = 140 | |
| def payload_shift_disturbance(step): | |
| if step >= 25: | |
| w = np.zeros(7, dtype=np.float32) | |
| w[1] = -0.55 # heavy downward sag from +350% payload mass | |
| w[3] = 0.45 | |
| w[5] = -0.20 | |
| return w | |
| return np.zeros(7, dtype=np.float32) | |
| # 2A. Nominal Arm (Unfiltered: sag crashes into table) | |
| q_nom_panda = q_init_panda.copy() | |
| panda_nom_telemetry = [] | |
| for s in range(steps_arm): | |
| p_ee = panda.forward_kinematics(q_nom_panda) | |
| h_val = float(p_ee[2] - h_target_plane) | |
| panda_nom_telemetry.append({ | |
| "x": round(float(p_ee[0]), 4), | |
| "y": round(float(p_ee[1]), 4), | |
| "z": round(float(p_ee[2]), 4), | |
| "h": round(h_val, 4), | |
| "gamma": 0.0, | |
| "q": [round(float(val), 4) for val in q_nom_panda], | |
| }) | |
| err = p_goal_panda - p_ee | |
| dist = np.linalg.norm(err) | |
| v_des = 0.8 * (err / max(dist, 1e-4)) if dist > 0.015 else np.zeros(3) | |
| J = panda.jacobian(q_nom_panda) | |
| J_pinv = J.T @ np.linalg.inv(J @ J.T + 1e-4 * np.eye(3)) | |
| u_nom = J_pinv @ v_des | |
| w_t = payload_shift_disturbance(s) | |
| q_nom_panda += panda.dt * (u_nom + w_t) | |
| # 2B. Proposed Conformal AdaptNC Arm (Certified safe table clearance) | |
| filter_adapt = MultiBarrierConformalFilter(arm_dof=7, alpha_table=3.5) | |
| calibrator_arm = AdaptNCCalibrator(alpha_risk=0.01, eta=0.06, c_max=0.40) | |
| q_prop_panda = q_init_panda.copy() | |
| panda_safe_telemetry = [] | |
| for s in range(steps_arm): | |
| p_ee = panda.forward_kinematics(q_prop_panda) | |
| h_val = float(p_ee[2] - h_target_plane) | |
| gamma_t = calibrator_arm.get_current_margin() | |
| panda_safe_telemetry.append({ | |
| "x": round(float(p_ee[0]), 4), | |
| "y": round(float(p_ee[1]), 4), | |
| "z": round(float(p_ee[2]), 4), | |
| "h": round(h_val, 4), | |
| "gamma": round(float(gamma_t), 4), | |
| "q": [round(float(val), 4) for val in q_prop_panda], | |
| }) | |
| err = p_goal_panda - p_ee | |
| dist = np.linalg.norm(err) | |
| v_des = 0.8 * (err / max(dist, 1e-4)) if dist > 0.015 else np.zeros(3) | |
| J = panda.jacobian(q_prop_panda) | |
| J_pinv = J.T @ np.linalg.inv(J @ J.T + 1e-4 * np.eye(3)) | |
| u_nom = J_pinv @ v_des | |
| w_t = payload_shift_disturbance(s) | |
| Lg_table = J[2:3, :] | |
| u_safe, _ = filter_adapt.filter( | |
| u_nom=u_nom, | |
| h_table=h_val, | |
| Lg_table=Lg_table, | |
| q=q_prop_panda, | |
| qmin=panda.qmin, | |
| qmax=panda.qmax, | |
| dt=panda.dt, | |
| gamma=gamma_t, | |
| ) | |
| q_next = q_prop_panda + panda.dt * (u_safe + w_t) | |
| p_next = panda.forward_kinematics(q_next) | |
| h_next = float(p_next[2] - h_target_plane) | |
| score = - ((h_next - h_val) / panda.dt - float(np.dot(Lg_table.ravel(), u_safe))) | |
| calibrator_arm.update(score=score, h_val=h_val) | |
| q_prop_panda = q_next | |
| print(f" - Panda Nominal Min Clearance: {min(r['h'] for r in panda_nom_telemetry):+.3f}m (CRASHES INTO TABLE)") | |
| print(f" - Panda Safe Min Clearance: {min(r['h'] for r in panda_safe_telemetry):+.3f}m (STRICTLY SAFE)") | |
| # ========================================================================= | |
| # 3. STATION 3: 2-DoF Arm Manipulator Kinematics (PyBullet / Planar) | |
| # ========================================================================= | |
| print("\n[*] Simulating Station 3: 2-DoF Manipulator Kinematics & Workspace Avoidance...") | |
| arm_2dof = TwoDoFRobotArm(l1=1.0, l2=0.8, dt=0.02) | |
| obs_center_2dof = np.array([1.05, 0.90], dtype=np.float32) | |
| obs_radius_2dof = 0.28 | |
| safety_margin_2dof = 0.06 | |
| R_safe_2dof = obs_radius_2dof + safety_margin_2dof | |
| goal_pos_2dof = np.array([0.35, 1.40], dtype=np.float32) | |
| q_init_2dof = np.array([0.1, 0.4], dtype=np.float32) | |
| steps_2dof = 160 | |
| def disturbance_2dof(step): | |
| if 30 <= step <= 90: | |
| return np.array([0.096, -0.144], dtype=np.float32) | |
| return np.zeros(2, dtype=np.float32) | |
| # 3A. Nominal 2-DoF (Straight-line tracking: crashes through obstacle) | |
| q_nom_2dof = q_init_2dof.copy() | |
| arm_nom_telemetry = [] | |
| for step in range(steps_2dof): | |
| p0, p1, p_ee = arm_2dof.forward_kinematics(q_nom_2dof) | |
| dist_obs = np.linalg.norm(p_ee - obs_center_2dof) | |
| h_val = float(dist_obs - R_safe_2dof) | |
| arm_nom_telemetry.append({ | |
| "x": round(float(p_ee[0]), 4), | |
| "y": round(float(p_ee[1]), 4), | |
| "p1": [round(float(p1[0]), 4), round(float(p1[1]), 4)], | |
| "h": round(h_val, 4), | |
| "gamma": 0.0, | |
| "q": [round(float(q_nom_2dof[0]), 4), round(float(q_nom_2dof[1]), 4)], | |
| }) | |
| err = goal_pos_2dof - p_ee | |
| dist_goal = np.linalg.norm(err) | |
| v_goal = 0.85 * (err / max(dist_goal, 1e-4)) if dist_goal > 0.015 else np.zeros(2) | |
| J = arm_2dof.jacobian(q_nom_2dof) | |
| J_pinv = J.T @ np.linalg.inv(J @ J.T + 1e-4 * np.eye(2)) | |
| qdot = J_pinv @ v_goal | |
| q_nom_2dof = q_nom_2dof + arm_2dof.dt * qdot | |
| # 3B. Proposed Conformal AdaptNC 2-DoF (Safe circumnavigation) | |
| q_prop_2dof = q_init_2dof.copy() | |
| filter_qp_2dof = TwoDoFCBFQPFilter(alpha=2.5) | |
| calibrator_2dof = AdaptNCCalibrator(alpha_risk=0.01, eta=0.05, c_max=0.30) | |
| arm_safe_telemetry = [] | |
| for step in range(steps_2dof): | |
| p0, p1, p_ee = arm_2dof.forward_kinematics(q_prop_2dof) | |
| d_vec = p_ee - obs_center_2dof | |
| dist_obs = np.linalg.norm(d_vec) | |
| h_val = float(dist_obs - R_safe_2dof) | |
| gamma_t = calibrator_2dof.get_current_margin() | |
| arm_safe_telemetry.append({ | |
| "x": round(float(p_ee[0]), 4), | |
| "y": round(float(p_ee[1]), 4), | |
| "p1": [round(float(p1[0]), 4), round(float(p1[1]), 4)], | |
| "h": round(h_val, 4), | |
| "gamma": round(float(gamma_t), 4), | |
| "q": [round(float(q_prop_2dof[0]), 4), round(float(q_prop_2dof[1]), 4)], | |
| }) | |
| err = goal_pos_2dof - p_ee | |
| dist_goal = np.linalg.norm(err) | |
| v_goal = min(0.9, 2.0 * dist_goal) * (err / max(dist_goal, 1e-4)) if dist_goal > 0.015 else np.zeros(2) | |
| d_infl = 0.28 | |
| if dist_obs < R_safe_2dof + d_infl: | |
| n = d_vec / max(dist_obs, 1e-4) | |
| t = np.array([-n[1], n[0]], dtype=np.float32) | |
| v_n = np.dot(v_goal, n) | |
| v_t = np.dot(v_goal, t) | |
| factor = (R_safe_2dof + d_infl - dist_obs) / d_infl | |
| if v_n < 0: | |
| circ_dir = 1.0 if v_t >= -0.05 else -1.0 | |
| v_cmd = (1.0 - factor) * (v_n * n) + (v_t + circ_dir * factor * abs(v_n) * 1.4) * t | |
| else: | |
| v_cmd = v_goal | |
| else: | |
| v_cmd = v_goal | |
| J = arm_2dof.jacobian(q_prop_2dof) | |
| J_pinv = J.T @ np.linalg.inv(J @ J.T + 1e-4 * np.eye(2)) | |
| u_nom = J_pinv @ v_cmd | |
| w_t = disturbance_2dof(step) | |
| n_ee = d_vec / max(dist_obs, 1e-4) | |
| Lg_h = n_ee @ J | |
| u_safe, _ = filter_qp_2dof.filter(u_nom=u_nom, h_val=h_val, Lg_h=Lg_h, gamma=gamma_t) | |
| q_next = q_prop_2dof + arm_2dof.dt * (u_safe + w_t) | |
| _, _, p_next = arm_2dof.forward_kinematics(q_next) | |
| h_next = np.linalg.norm(p_next - obs_center_2dof) - R_safe_2dof | |
| score = - ((h_next - h_val) / arm_2dof.dt - float(np.dot(Lg_h, u_safe))) | |
| calibrator_2dof.update(score=score, h_val=h_val) | |
| q_prop_2dof = q_next | |
| print(f" - 2-DoF Nominal Min Clearance: {min(r['h'] for r in arm_nom_telemetry):+.3f}m (COLLISION)") | |
| print(f" - 2-DoF Safe Min Clearance: {min(r['h'] for r in arm_safe_telemetry):+.3f}m (STRICTLY SAFE)") | |
| # Consolidate telemetry payload | |
| telemetry_payload = { | |
| "metadata": { | |
| "title": "Certified Safe Neural Control Multi-Platform Telemetry", | |
| "dt": 0.02, | |
| "z_table": z_table, | |
| "h_target_plane": h_target_plane, | |
| "obs_amr": [float(obs_pos[0]), float(obs_pos[1]), obs_radius], | |
| "goal_amr": [float(goal_pos[0]), float(goal_pos[1])], | |
| "goal_panda": [float(p_goal_panda[0]), float(p_goal_panda[1]), float(p_goal_panda[2])], | |
| "obs_2dof": [float(obs_center_2dof[0]), float(obs_center_2dof[1]), obs_radius_2dof], | |
| "goal_2dof": [float(goal_pos_2dof[0]), float(goal_pos_2dof[1])], | |
| }, | |
| "station1_amr": { | |
| "nominal": amr_nom_telemetry, | |
| "adapt_cbf": amr_safe_telemetry, | |
| }, | |
| "station2_panda": { | |
| "nominal": panda_nom_telemetry, | |
| "adapt_cbf": panda_safe_telemetry, | |
| }, | |
| "station3_2dof": { | |
| "nominal": arm_nom_telemetry, | |
| "adapt_cbf": arm_safe_telemetry, | |
| }, | |
| } | |
| output_json = "data/model_telemetry.json" | |
| os.makedirs("data", exist_ok=True) | |
| with open(output_json, "w") as f: | |
| json.dump(telemetry_payload, f, indent=2) | |
| print(f"\n[+] Successfully exported pure model telemetry to: {output_json}") | |
| return telemetry_payload | |
| if __name__ == "__main__": | |
| generate_exact_model_telemetry() | |