Download code/case2/rom_batch.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 6.91 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/rom_batch.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case2/rom_batch.py
-
curl -L -o rom_batch.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/rom_batch.py
6.91 kB
| """Batched reduced-order model (ROM) for nominal and test-randomized (TR) evaluation. Sim2Sim only. | |
| Plant = release GoalEnv.step (util-free copy): kinematic bicycle with car_length=1.0 m, steering scale 0.7 rad, | |
| motor torque map with tau0/omega0, speed clipped to [0, 5] m/s, dt = 0.1 s, state cast to float32 each step. | |
| Success = first post-step distance < 3 m; time = (step index + 1) * 0.1 s (release logger is one step early). | |
| Each episode carries its own perturbation parameters (one row in `params`). Nominal ROM = all defaults. | |
| Command path for every step: policy -> steering-rate limiter -> actuation delay -> start hold -> additive noise -> plant. | |
| Common random numbers: all policies see the same params and noise for the same episode index. | |
| """ | |
| import numpy as np | |
| import torch | |
| from common import DT, MAX_STEPS, GOAL_RADIUS | |
| DEFAULTS = dict( | |
| tau0=1000.0, omega0=2600.0, # powertrain (release nominal) | |
| sig_thr=0.0, sig_steer=0.0, # per-step additive Gaussian sd on normalized throttle/steering | |
| delay=0, # actuation delay (control steps of 0.1 s) | |
| steer_rate=np.inf, # max |change| of normalized steering per control step | |
| hold=0, # start hold (control steps with zero command and zero speed) | |
| wheelbase=1.0, # ROM car_length (m) | |
| vmax=5.0, # ROM speed cap (m/s) | |
| x0=0.0, y0=0.0, yaw0=0.0, v0=0.0, # initial state | |
| gx_scale=1.0, g_rot=0.0, # goal radius scale and bearing rotation (rad), applied to the base goal | |
| obs_pos_sig=0.0, # sd of observation noise on relative goal position (m), per step | |
| ) | |
| R_WHEEL, I_WHEEL, GAMMA, C1, C0, STEER_SCALE = 0.47, 6.69, 1.0 / 3.0, 1e-4, 0.02, 0.7 | |
| def default_params(n): | |
| return {k: np.full(n, v, dtype=np.float64) for k, v in DEFAULTS.items()} | |
| def simulate(actor, goals_xy, params, noise_seed, device='cpu', max_steps=MAX_STEPS, keep_traj=False): | |
| """Run len(goals_xy) episodes for one policy. Returns dict of per-episode arrays. | |
| goals_xy: (N,2) base goals. params: dict name -> (N,) arrays (missing keys use defaults). | |
| noise_seed: seed of the per-step noise stream (same seed -> same noise for every policy). | |
| """ | |
| n = len(goals_xy) | |
| P = default_params(n) | |
| for k, v in params.items(): | |
| P[k] = np.broadcast_to(np.asarray(v, dtype=np.float64), (n,)).copy() | |
| t = lambda a: torch.as_tensor(a, dtype=torch.float64, device=device) | |
| tau0, omega0, wb, vmax = t(P['tau0']), t(P['omega0']), t(P['wheelbase']), t(P['vmax']) | |
| sig = torch.stack([t(P['sig_thr']), t(P['sig_steer'])], 1) | |
| rate = t(P['steer_rate']) | |
| hold = torch.as_tensor(P['hold'].astype(np.int64), device=device) | |
| delay = P['delay'].astype(np.int64) | |
| dmax = int(delay.max()) if n else 0 | |
| # goal perturbation (radius scale and bearing rotation about the start point) | |
| g = np.asarray(goals_xy, dtype=np.float64) | |
| c, s = np.cos(P['g_rot']), np.sin(P['g_rot']) | |
| gx = P['gx_scale'] * (c * g[:, 0] - s * g[:, 1]) | |
| gy = P['gx_scale'] * (s * g[:, 0] + c * g[:, 1]) | |
| gx, gy = t(gx), t(gy) | |
| f32 = lambda a: a.to(torch.float32).to(torch.float64) | |
| x, y, yaw, v = f32(t(P['x0'])), f32(t(P['y0'])), f32(t(P['yaw0'])), f32(t(P['v0'])) | |
| gen = torch.Generator(device=device).manual_seed(int(noise_seed)) | |
| obs_sig = t(P['obs_pos_sig']) | |
| prev_steer = torch.zeros(n, dtype=torch.float64, device=device) | |
| buf = torch.zeros((dmax + 1, n, 2), dtype=torch.float64, device=device) # ring buffer for delay | |
| didx = torch.as_tensor(delay, device=device) | |
| done = torch.zeros(n, dtype=torch.bool, device=device) | |
| hit_step = torch.full((n,), -1, dtype=torch.int64, device=device) | |
| min_d = torch.full((n,), np.inf, dtype=torch.float64, device=device) | |
| traj = [] if keep_traj else None | |
| ar = torch.arange(n, device=device) | |
| for k in range(max_steps): | |
| # observation (release relative_state_to_goal), optional position noise | |
| cth, sth = torch.cos(yaw), torch.sin(yaw) | |
| dx, dy = gx - x, gy - y | |
| rx, ry = cth * dx + sth * dy, -sth * dx + cth * dy | |
| if bool((obs_sig > 0).any()): | |
| rx = rx + obs_sig * torch.randn(n, generator=gen, device=device, dtype=torch.float64) | |
| ry = ry + obs_sig * torch.randn(n, generator=gen, device=device, dtype=torch.float64) | |
| obs = torch.stack([rx, ry, torch.atan2(ry, rx), v], 1).to(torch.float32) | |
| a = actor(obs).to(torch.float64) | |
| # steering-rate limiter (as in the release Chrono loop) | |
| d = a[:, 1] - prev_steer | |
| lim = torch.where(d.abs() > rate, prev_steer + rate * torch.sign(d), a[:, 1]) | |
| prev_steer = lim | |
| cmd = torch.stack([a[:, 0], lim], 1) | |
| # actuation delay: write at slot k, read slot k - delay (zeros before the first command) | |
| buf[k % (dmax + 1)] = cmd | |
| cmd_d = buf[(k - didx) % (dmax + 1), ar] | |
| cmd_d = torch.where((k - didx >= 0)[:, None], cmd_d, torch.zeros_like(cmd_d)) | |
| # start hold: zero command and braked vehicle | |
| held = k < hold | |
| cmd_d = torch.where(held[:, None], torch.zeros_like(cmd_d), cmd_d) | |
| # additive noise (release: added after the policy, not clipped again); drawn for all episodes every step | |
| z = torch.randn((n, 2), generator=gen, device=device, dtype=torch.float64) | |
| alpha, beta = (cmd_d + sig * z).unbind(1) | |
| # plant (release GoalEnv.step) | |
| omega_m = v / (R_WHEEL * GAMMA) | |
| T = alpha * (-tau0 * omega_m / omega0 + tau0) - C1 * omega_m - C0 | |
| v_dot = T * GAMMA / I_WHEEL * R_WHEEL | |
| nx = x + torch.cos(yaw) * v * DT | |
| ny = y + torch.sin(yaw) * v * DT | |
| nyaw = yaw + v * torch.tan(beta * STEER_SCALE) / wb * DT | |
| nv = torch.clamp(v + v_dot * DT, min=torch.zeros_like(vmax), max=vmax) | |
| nv = torch.where(held, torch.zeros_like(nv), nv) | |
| nx, ny, nyaw, nv = f32(nx), f32(ny), f32(nyaw), f32(nv) | |
| live = ~done | |
| x, y, yaw, v = (torch.where(live, nx, x), torch.where(live, ny, y), torch.where(live, nyaw, yaw), torch.where(live, nv, v)) | |
| dist = torch.sqrt((x - gx) ** 2 + (y - gy) ** 2) | |
| min_d = torch.where(live, torch.minimum(min_d, dist), min_d) | |
| newhit = live & (dist < GOAL_RADIUS) | |
| hit_step = torch.where(newhit, torch.full_like(hit_step, k), hit_step) | |
| done = done | newhit | |
| if keep_traj: | |
| traj.append(torch.stack([x, y, yaw, v], 1).cpu().numpy().astype(np.float32)) | |
| if bool(done.all()): | |
| break | |
| hs = hit_step.cpu().numpy() | |
| out = dict(success=hs >= 0, time_s=np.where(hs >= 0, (hs + 1) * DT, np.nan), | |
| terminal_distance_m=torch.sqrt((x - gx) ** 2 + (y - gy) ** 2).cpu().numpy(), | |
| min_distance_m=min_d.cpu().numpy()) | |
| if keep_traj: | |
| out['traj'] = np.stack(traj, 1) | |
| return out | |