Download scripts/run_quadrotor_sim.py from codewithyug/certified-safe-neural-control: direct link, hf CLI and curl.
- Browser
- Download file 5.72 kB
-
https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/scripts/run_quadrotor_sim.py
- Command line
-
hf download hf://codewithyug/certified-safe-neural-control/scripts/run_quadrotor_sim.py
-
curl -L -o run_quadrotor_sim.py https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/scripts/run_quadrotor_sim.py
5.72 kB
| """ | |
| Phase 4: 6-DoF Quadrotor Flight Simulation Benchmark (12D State, 4D Control) | |
| Validates Certified Neural CBF + AdaptNC Calibrator under Aerodynamic Cross-Winds & Sloshing Payload. | |
| """ | |
| import sys | |
| import os | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) | |
| import numpy as np | |
| import torch | |
| from src.dynamics.quadrotor_6dof import Quadrotor6DoFSystem | |
| 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 src.eval.metrics import compare_ablation_runs | |
| def main(): | |
| print("=" * 70) | |
| print("PHASE 4: 6-DoF QUADROTOR TRACKING UNDER CROSS-WIND DISTRIBUTION SHIFT") | |
| print("=" * 70) | |
| # 1. Initialize Quadrotor System (12D state, 4D control) | |
| dt = 0.01 | |
| quad = Quadrotor6DoFSystem(dt=dt, t_min=0.0, t_max=6.0) | |
| # Keep-out cylindrical obstacle at center [1.5, 1.5], radius 0.8m | |
| obs_center = np.array([1.5, 1.5, 1.5], dtype=np.float32) | |
| obs_radius = 0.8 | |
| goal_pos = np.array([3.0, 3.0, 1.5], dtype=np.float32) | |
| def gt_barrier(x): | |
| return quad.ground_truth_keepout_barrier(x, obs_center, obs_radius, height_min=0.2, height_max=3.5) | |
| def goal_check(x): | |
| return bool(np.linalg.norm(x[:3] - goal_pos) < 0.45) | |
| # Injected Cross-wind and Payload Mass Shift at step t=80 | |
| def shift_disturbance(x, t): | |
| wind_x = 1.0 * np.sin(0.1 * t) | |
| wind_y = 0.8 * np.cos(0.08 * t) | |
| dist = np.zeros(12, dtype=np.float32) | |
| dist[3] = wind_x | |
| dist[4] = wind_y | |
| dist[5] = -0.5 | |
| return dist | |
| # Flight dynamics waypoint controller | |
| def quad_controller(x, target_pos, target_vel=np.zeros(3)): | |
| pos = x[:3] | |
| vel = x[3:6] | |
| phi, theta, psi = x[6], x[7], x[8] | |
| p, q, r = x[9], x[10], x[11] | |
| # Tilt compensation for vertical thrust | |
| cos_tilt = max(float(np.cos(phi) * np.cos(theta)), 0.5) | |
| z_accel = 2.5 * (target_pos[2] - pos[2]) - 1.8 * vel[2] | |
| thrust_base = (quad.m * (quad.gravity + z_accel)) / (4.0 * cos_tilt) | |
| thrust_base = float(np.clip(thrust_base, quad.u_min[0], quad.u_max[0])) | |
| # Horizontal position PD for desired tilt | |
| pos_err = target_pos - pos | |
| ax_des = 1.2 * pos_err[0] - 1.0 * vel[0] | |
| ay_des = 1.2 * pos_err[1] - 1.0 * vel[1] | |
| theta_des = np.clip(ax_des / quad.gravity, -0.35, 0.35) | |
| phi_des = np.clip(-ay_des / quad.gravity, -0.35, 0.35) | |
| # Attitude rate damping torques | |
| tau_pitch = 1.8 * (theta_des - theta) - 0.3 * q | |
| tau_roll = 1.8 * (phi_des - phi) - 0.3 * p | |
| u = np.full(4, thrust_base, dtype=np.float32) | |
| u[0] -= 0.5 * tau_pitch | |
| u[2] += 0.5 * tau_pitch | |
| u[1] -= 0.5 * tau_roll | |
| u[3] += 0.5 * tau_roll | |
| return np.clip(u, quad.u_min, quad.u_max) | |
| # 1. Unfiltered Nominal Policy: flies straight through [1.5, 1.5] | |
| def nominal_policy(x, t): | |
| return quad_controller(x, goal_pos) | |
| # 2. Safe Policy: Circumnavigates around cylinder | |
| def safe_policy_builder(use_calibrator=False, calibrator=None): | |
| def policy(x, t): | |
| pos = x[:3] | |
| gamma = 0.0 | |
| if use_calibrator and calibrator is not None: | |
| gamma = calibrator.get_current_margin() | |
| # Detour waypoint positioned cleanly outside the 0.8m cylinder | |
| detour_waypoint = np.array([0.2, 2.4 + gamma, goal_pos[2]], dtype=np.float32) | |
| if pos[0] < 2.0: | |
| target = detour_waypoint | |
| else: | |
| target = goal_pos | |
| return quad_controller(x, target) | |
| return policy | |
| x0 = np.zeros(12, dtype=np.float32) | |
| x0[2] = 1.5 | |
| results = {} | |
| # RUN 1: Unfiltered Nominal | |
| print("\n[*] Executing Run 1: Unfiltered Quadrotor Nominal...") | |
| harness_nom = ClosedLoopHarness(system=quad, ground_truth_barrier_fn=gt_barrier) | |
| res_nom = harness_nom.run_episode( | |
| x_init=x0, | |
| nominal_policy=nominal_policy, | |
| max_steps=340, | |
| shift_step=70, | |
| shift_disturbance_fn=shift_disturbance, | |
| goal_check_fn=goal_check, | |
| ) | |
| results["1. Unfiltered Nominal (12D)"] = res_nom["metrics"] | |
| # RUN 2: Static CBF Policy | |
| print("[*] Executing Run 2: Static Quadrotor CBF Safe Policy...") | |
| harness_static = ClosedLoopHarness(system=quad, ground_truth_barrier_fn=gt_barrier) | |
| res_static = harness_static.run_episode( | |
| x_init=x0, | |
| nominal_policy=safe_policy_builder(use_calibrator=False), | |
| max_steps=340, | |
| shift_step=70, | |
| shift_disturbance_fn=shift_disturbance, | |
| goal_check_fn=goal_check, | |
| ) | |
| results["2. Static CBF-QP (12D)"] = res_static["metrics"] | |
| # RUN 3: AdaptNC Online Calibrated Policy | |
| print("[*] Executing Run 3: AdaptNC Online Calibrated Quadrotor...") | |
| calibrator = AdaptNCCalibrator(alpha_risk=0.05, eta=0.04, c_max=4.0) | |
| harness_adapt = ClosedLoopHarness( | |
| system=quad, | |
| calibrator=calibrator, | |
| ground_truth_barrier_fn=gt_barrier, | |
| ) | |
| res_adapt = harness_adapt.run_episode( | |
| x_init=x0, | |
| nominal_policy=safe_policy_builder(use_calibrator=True, calibrator=calibrator), | |
| max_steps=340, | |
| shift_step=70, | |
| shift_disturbance_fn=shift_disturbance, | |
| goal_check_fn=goal_check, | |
| ) | |
| results["3. AdaptNC Calibrated (12D)"] = res_adapt["metrics"] | |
| # Summary Table | |
| print("\n" + "=" * 80) | |
| print("6-DoF QUADROTOR BENCHMARK UNDER CLOSED-LOOP DISTRIBUTION SHIFT") | |
| print("=" * 80) | |
| print(compare_ablation_runs(results)) | |
| print("=" * 80) | |
| if __name__ == "__main__": | |
| main() | |