File size: 5,039 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 | """
Phase 4: Quadrotor Neural CBF Training Script
Trains a compact MLP barrier h_theta(x) for the 12D Quadrotor to enforce 3D cylindrical keep-outs and altitude limits.
"""
import sys
import os
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import numpy as np
import torch
import torch.optim as optim
from src.dynamics.quadrotor_6dof import Quadrotor6DoFSystem
from src.cbf.network import NeuralCBF
from src.cbf.loss import CBFLoss
def generate_quadrotor_data(num_samples: int = 6000):
obs_center = np.array([1.5, 1.5, 1.5], dtype=np.float32)
obs_radius = 0.8
z_min, z_max = 0.2, 3.5
# Sample 12D states: [px, py, pz, vx, vy, vz, phi, theta, psi, p, q, r]
px = np.random.uniform(0.0, 3.5, size=(num_samples, 1))
py = np.random.uniform(0.0, 3.5, size=(num_samples, 1))
pz = np.random.uniform(0.1, 3.8, size=(num_samples, 1))
vel = np.random.uniform(-1.5, 1.5, size=(num_samples, 3))
angles = np.random.uniform(-0.4, 0.4, size=(num_samples, 3))
ang_vel = np.random.uniform(-1.0, 1.0, size=(num_samples, 3))
states = np.hstack([px, py, pz, vel, angles, ang_vel]).astype(np.float32)
# Calculate Higher-Order barrier taking velocity stopping distance into account
xy_dist_vec = states[:, :2] - obs_center[:2]
xy_dist = np.linalg.norm(xy_dist_vec, axis=1)
# Radial velocity: dot(v_xy, d_xy / ||d_xy||)
unit_xy = xy_dist_vec / np.maximum(xy_dist[:, None], 1e-4)
v_radial = np.sum(states[:, 3:5] * unit_xy, axis=1)
# Barrier value = (dist - radius) + tau * v_radial
tau = 0.8
h_xy = (xy_dist - obs_radius) + tau * v_radial
z_val = states[:, 2]
vz = states[:, 5]
h_z_low = (z_val - z_min) + 0.5 * vz
h_z_high = (z_max - z_val) - 0.5 * vz
h_total = np.minimum(h_xy, np.minimum(h_z_low, h_z_high))
safe_mask = h_total > 0.25
unsafe_mask = h_total < -0.10
boundary_mask = (h_total >= -0.15) & (h_total <= 0.30)
x_safe = torch.tensor(states[safe_mask], dtype=torch.float32)
x_unsafe = torch.tensor(states[unsafe_mask], dtype=torch.float32)
x_boundary = torch.tensor(states[boundary_mask], dtype=torch.float32)
return x_safe, x_unsafe, x_boundary
def main():
print("=" * 60)
print("PHASE 4: TRAINING QUADROTOR NEURAL CBF (12D SE(3) System)")
print("=" * 60)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"[+] Training Device: {device}")
quad = Quadrotor6DoFSystem(dt=0.01)
cbf_model = NeuralCBF(state_dim=12, hidden_dims=[64, 64], activation="tanh").to(device)
loss_fn = CBFLoss(
alpha_cbf=1.5,
margin=0.1,
weight_safe=1.0,
weight_unsafe=2.0,
weight_cbf=2.0,
weight_reg=1e-4,
)
optimizer = optim.Adam(cbf_model.parameters(), lr=1e-3)
x_safe, x_unsafe, x_boundary = generate_quadrotor_data(num_samples=8000)
print(f"[+] Dataset: {len(x_safe)} Safe | {len(x_unsafe)} Unsafe | {len(x_boundary)} Boundary samples")
x_safe = x_safe.to(device)
x_unsafe = x_unsafe.to(device)
x_boundary = x_boundary.to(device)
batch_b = len(x_boundary)
f_b_list = [quad.f(x_boundary[i].detach().cpu().numpy()) for i in range(batch_b)]
g_b_list = [quad.g(x_boundary[i].detach().cpu().numpy()) for i in range(batch_b)]
f_boundary = torch.tensor(np.array(f_b_list), dtype=torch.float32, device=device)
g_boundary = torch.tensor(np.array(g_b_list), dtype=torch.float32, device=device)
u_hover = torch.full((batch_b, 4), float((quad.m * quad.gravity) / 4.0), dtype=torch.float32, device=device)
epochs = 60
batch_size = 256
print("\n[*] Starting Quadrotor CBF Training Loop...")
for epoch in range(1, epochs + 1):
cbf_model.train()
optimizer.zero_grad()
idx_s = torch.randperm(len(x_safe))[:batch_size]
idx_u = torch.randperm(len(x_unsafe))[:batch_size]
idx_b = torch.randperm(len(x_boundary))[:batch_size]
loss_dict = loss_fn(
model=cbf_model,
x_safe=x_safe[idx_s],
x_unsafe=x_unsafe[idx_u],
x_boundary=x_boundary[idx_b],
f_boundary=f_boundary[idx_b],
g_boundary=g_boundary[idx_b],
u_nominal=u_hover[idx_b],
)
total_loss = loss_dict["total_loss"]
total_loss.backward()
optimizer.step()
if epoch % 10 == 0 or epoch == epochs:
print(
f"Epoch [{epoch:02d}/{epochs}] | "
f"Total: {total_loss.item():.4f} | "
f"Safe: {loss_dict['loss_safe'].item():.4f} | "
f"Unsafe: {loss_dict['loss_unsafe'].item():.4f} | "
f"CBF Ineq: {loss_dict['loss_cbf'].item():.4f}"
)
os.makedirs("checkpoints", exist_ok=True)
checkpoint_path = "checkpoints/cbf_quadrotor.pt"
torch.save(cbf_model.state_dict(), checkpoint_path)
print(f"\n[+] Quadrotor Checkpoint saved: {checkpoint_path}")
if __name__ == "__main__":
main()
|