Download code/case2/chrono_runner.py from harryzhang1018/TestRandomization: direct link, hf CLI and curl.
- Browser
- Download file 7.26 kB
-
https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/chrono_runner.py
- Command line
-
hf download hf://datasets/harryzhang1018/TestRandomization/code/case2/chrono_runner.py
-
curl -L -o chrono_runner.py https://huggingface.co/datasets/harryzhang1018/TestRandomization/resolve/main/code/case2/chrono_runner.py
7.26 kB
| """Chrono HMMWV evaluation = high-fidelity truth for Case 2 (Sim2Sim). Copy of the release loop. | |
| Mirrors hmmwv_goal_reach/simulation/sim_testing.py: HMMWV_Full, NSC contact, SHAFTS engine, automatic shafts | |
| transmission, AWD, TMEASY tires, Bullet collision, 500 m x 500 m rigid patch, start at (0,0,0.9) with yaw 0, | |
| 1 ms step, 10 Hz policy, brake hold while t <= 1 s, normalized steering change limited to 0.1 per control step, | |
| success when the distance to the goal is < 3 m at a control step. Horizon 40 s (as in the ROM tests). | |
| Changes: no visualization, no CSV append (in-memory log), PyChrono 10 data-path call, actor = common.Actor. | |
| Usage: python chrono_runner.py jobs.jsonl out_dir --workers 10 | |
| (Resumes: episodes already in out_dir/episodes.jsonl are skipped. Use a new out_dir to re-run.) | |
| jobs.jsonl lines: {"policy": name, "policy_path": path, "goal_id": id, "x": gx, "y": gy} | |
| Output: out_dir/episodes.jsonl (one summary per episode), out_dir/traj/<policy>.npz (10 Hz trajectories). | |
| """ | |
| import argparse | |
| import json | |
| import math | |
| import multiprocessing as mp | |
| import os | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| HORIZON = 40.0 | |
| _ACTORS = {} | |
| def _setup(): | |
| import pychrono.core as chrono | |
| import pychrono.vehicle as veh | |
| import torch | |
| torch.set_num_threads(1) | |
| chrono.SetChronoDataPath(chrono.GetChronoDataPath()) | |
| veh.SetVehicleDataPath(chrono.GetChronoDataPath() + 'vehicle/') | |
| return chrono, veh | |
| def run_episode(job, horizon=HORIZON): | |
| from common import Actor, relative_obs | |
| chrono, veh = _setup() | |
| if job['policy_path'] not in _ACTORS: | |
| _ACTORS[job['policy_path']] = Actor(job['policy_path']) | |
| actor = _ACTORS[job['policy_path']] | |
| goal_x, goal_y = float(job['x']), float(job['y']) | |
| t_wall = time.time() | |
| contact_material = chrono.ChContactMaterialNSC() | |
| hmmwv = veh.HMMWV_Full() | |
| hmmwv.SetContactMethod(chrono.ChContactMethod_NSC) | |
| hmmwv.SetInitPosition(chrono.ChCoordsysd(chrono.ChVector3d(0.0, 0, 0.9), chrono.QuatFromAngleZ(0))) | |
| hmmwv.SetEngineType(veh.EngineModelType_SHAFTS) | |
| hmmwv.SetTransmissionType(veh.TransmissionModelType_AUTOMATIC_SHAFTS) | |
| hmmwv.SetDriveType(veh.DrivelineTypeWV_AWD) | |
| hmmwv.SetTireType(veh.TireModelType_TMEASY) | |
| hmmwv.Initialize() | |
| for f in ('SetChassisVisualizationType', 'SetSuspensionVisualizationType', 'SetSteeringVisualizationType', | |
| 'SetWheelVisualizationType', 'SetTireVisualizationType'): | |
| getattr(hmmwv, f)(chrono.VisualizationType_PRIMITIVES) | |
| hmmwv.GetSystem().SetCollisionSystemType(chrono.ChCollisionSystem.Type_BULLET) | |
| system = hmmwv.GetSystem() | |
| terrain = veh.RigidTerrain(system) | |
| terrain.AddPatch(contact_material, chrono.ChCoordsysd(chrono.ChVector3d(0, 0, 0), chrono.QUNIT), 500.0, 500.0) | |
| terrain.Initialize() | |
| goal_body = chrono.ChBodyEasyCylinder(chrono.ChAxis_Z, 0.75, 0.125, 40, True, False, contact_material) | |
| goal_body.SetPos(chrono.ChVector3d(goal_x, goal_y, 0.1)) | |
| goal_body.SetFixed(True) | |
| system.Add(goal_body) | |
| driver = veh.ChDriver(hmmwv.GetVehicle()) | |
| driver.Initialize() | |
| step_size = 1e-3 | |
| control_step = math.ceil(0.1 / step_size) | |
| prev_steering, step_number, t = 0.0, 0, 0.0 | |
| log, reached, hit_time = [], False, None | |
| vehicle = hmmwv.GetVehicle() | |
| while t < horizon: | |
| t = system.GetChTime() | |
| if step_number % control_step == 0: | |
| vx, vy = vehicle.GetPos().x, vehicle.GetPos().y | |
| yaw = vehicle.GetRot().GetCardanAnglesXYZ().z | |
| v = vehicle.GetSpeed() | |
| dist = math.sqrt((vx - goal_x) ** 2 + (vy - goal_y) ** 2) | |
| row = [t, vx, vy, yaw, v, np.nan, np.nan] | |
| if dist < 3.0: | |
| log.append(row) | |
| reached, hit_time = True, t | |
| break | |
| obs = relative_obs(vx, vy, yaw, v, goal_x, goal_y) | |
| throttle, steering = (float(u) for u in actor(obs[None])[0]) | |
| delta = steering - prev_steering | |
| prev_steering = prev_steering + 0.1 * delta / abs(delta) if abs(delta) > 0.1 else steering | |
| if t > 1.0: | |
| driver.SetSteering(prev_steering); driver.SetThrottle(throttle); driver.SetBraking(0.0) | |
| else: | |
| driver.SetSteering(0.0); driver.SetThrottle(0.0); driver.SetBraking(1.0) | |
| row[5], row[6] = throttle, prev_steering | |
| log.append(row) | |
| inputs = driver.GetInputs() | |
| driver.Synchronize(t); terrain.Synchronize(t); hmmwv.Synchronize(t, inputs, terrain) | |
| driver.Advance(step_size); terrain.Advance(step_size); hmmwv.Advance(step_size) | |
| step_number += 1 | |
| log = np.array(log, dtype=np.float64) | |
| d = np.hypot(log[:, 1] - goal_x, log[:, 2] - goal_y) | |
| summary = dict(policy=job['policy'], goal_id=job['goal_id'], x=goal_x, y=goal_y, success=reached, | |
| time_s=hit_time, terminal_distance_m=float(d[-1]), min_distance_m=float(d.min()), | |
| max_speed_mps=float(log[:, 4].max()), mean_throttle=float(np.nanmean(log[:, 5])) if len(log) > 1 else None, | |
| rows=len(log), finite=bool(np.isfinite(log[:, :5]).all()), wall_s=time.time() - t_wall) | |
| return summary, log.astype(np.float32) | |
| def _work(job): | |
| try: | |
| s, log = run_episode(job) | |
| return s, log | |
| except Exception as e: # runtime errors are recorded, never counted as controller failures | |
| import traceback | |
| return dict(policy=job['policy'], goal_id=job['goal_id'], status='runtime_error', error=traceback.format_exc()), None | |
| def main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument('jobs') | |
| p.add_argument('out') | |
| p.add_argument('--workers', type=int, default=10) | |
| a = p.parse_args() | |
| out = Path(a.out) | |
| (out / 'traj').mkdir(parents=True, exist_ok=True) | |
| jobs = [json.loads(l) for l in open(a.jobs)] | |
| done_path = out / 'episodes.jsonl' | |
| done = set() | |
| if done_path.exists(): | |
| for l in open(done_path): | |
| r = json.loads(l) | |
| if r.get('status') != 'runtime_error': | |
| done.add((r['policy'], r['goal_id'])) | |
| todo = [j for j in jobs if (j['policy'], j['goal_id']) not in done] | |
| print(f'{len(jobs)} jobs, {len(done)} done, {len(todo)} to run', flush=True) | |
| trajs = {} | |
| t0 = time.time() | |
| os.environ.setdefault('OMP_NUM_THREADS', '1') | |
| with mp.get_context('spawn').Pool(a.workers, maxtasksperchild=50) as pool, open(done_path, 'a') as f: | |
| for i, (s, log) in enumerate(pool.imap_unordered(_work, todo, chunksize=1)): | |
| s.setdefault('status', 'ok') | |
| f.write(json.dumps(s) + '\n'); f.flush() | |
| if log is not None: | |
| trajs.setdefault(s['policy'], {})[s['goal_id']] = log | |
| if (i + 1) % 50 == 0 or i + 1 == len(todo): | |
| print(f'{i + 1}/{len(todo)} elapsed {time.time() - t0:.0f}s', flush=True) | |
| if (i + 1) % 200 == 0: | |
| flush_traj(out, trajs) | |
| trajs = {} | |
| flush_traj(out, trajs) | |
| def flush_traj(out, trajs): | |
| for pol, d in trajs.items(): | |
| path = out / 'traj' / f'{pol}.npz' | |
| old = dict(np.load(path)) if path.exists() else {} | |
| old.update(d) | |
| np.savez_compressed(path, **old) | |
| if __name__ == '__main__': | |
| main() | |