File size: 6,803 Bytes
153352c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/env python3
"""Verify the Phase-1 TartanDrive MuJoCo environment end-to-end.

Builds a TartanDriveEnv for one sequence, runs a scripted rollout, saves a
few rendered camera frames plus a top-down overlay of the sim trajectory vs.
the real GPS track (on the Gascola orthophoto), and optionally runs a fast
reset/step smoke-test. Success is qualitative for this PoC: the env should
reset/step without exceptions, observations must match observation_space,
and the vehicle should drive a plausible distance without tunneling through
terrain or diverging (NaNs) -- it is not expected to numerically retrace the
real GPS track.
"""
import argparse
import os
import subprocess
import sys

os.environ.setdefault("MUJOCO_GL", "egl")

from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

from metadata_utils.lidar_terrain import load_sequence_poses
from sim.env import TartanDriveEnv


def try_pull_atv_scan():
    scan_path = REPO_ROOT / "assets" / "vicky1_clean.pts"
    if scan_path.exists():
        return
    print("[verify_sim_env] assets/vicky1_clean.pts not found; attempting download "
          "(falls back to generic UTV dimensions in sim/vehicle_config.py if unreachable)...")
    try:
        subprocess.run([sys.executable, str(REPO_ROOT / "scripts" / "pull_atv_scan.py")],
                        cwd=REPO_ROOT, timeout=20, capture_output=True, check=True)
        print("[verify_sim_env] fetched vicky1_clean.pts")
    except Exception as e:
        print(f"[verify_sim_env] could not fetch vicky1_clean.pts ({e}); "
              f"using generic UTV approximation")


def run_smoke_test(env):
    obs, info = env.reset()
    assert env.observation_space.contains(obs), "reset() obs violates observation_space"
    assert env.action_space.shape == (2,)
    for _ in range(20):
        action = env.action_space.sample()
        obs, reward, terminated, truncated, info = env.step(action)
        assert env.observation_space.contains(obs), "step() obs violates observation_space"
        assert np.isfinite(obs["odom"]).all(), "odom contains NaN/inf"
        assert np.isfinite(obs["imu"]).all(), "imu contains NaN/inf"
        if terminated or truncated:
            obs, info = env.reset()
    print("[smoke-test] OK: reset/step observations match observation_space, no NaNs")


def rollout(env, steps, frame_every=50):
    obs, info = env.reset()
    xy = [env.data.qpos[env._free_qpos_adr:env._free_qpos_adr + 2].copy()]
    frames = [(0, obs["image"].copy())]
    ended_at = None
    for i in range(1, steps + 1):
        throttle, steer = 0.35, 0.25 * np.sin(i / 60.0)
        obs, reward, terminated, truncated, info = env.step(
            np.array([throttle, steer], dtype=np.float32))
        xy.append(env.data.qpos[env._free_qpos_adr:env._free_qpos_adr + 2].copy())
        if i % frame_every == 0:
            frames.append((i, obs["image"].copy()))
        if terminated or truncated:
            ended_at = i
            print(f"[rollout] episode ended at step {i} "
                  f"(terminated={terminated}, truncated={truncated})")
            break
    return np.array(xy), frames, ended_at


def save_frames(frames, out_dir):
    out_dir.mkdir(parents=True, exist_ok=True)
    for i, img in frames:
        Image.fromarray(img).save(out_dir / f"frame_{i:05d}.png")


def save_overlay(env, sim_xy, out_path):
    poses = load_sequence_poses(env.scene_dir)
    real_xy = poses.positions[:, :2]  # (easting, northing), relative to sequence start

    fig, ax = plt.subplots(figsize=(8, 8))
    try:
        import rasterio
        with rasterio.open(REPO_ROOT / "assets" / "gascola.tif") as ds:
            img = ds.read([1, 2, 3]).transpose(1, 2, 0)
            left, top = ds.transform * (0, 0)
            right, bottom = ds.transform * (ds.width, ds.height)
            utm0 = env.terrain.utm_origin
            extent = [left - utm0[0], right - utm0[0], bottom - utm0[1], top - utm0[1]]
            ax.imshow(img, extent=extent)
    except Exception as e:
        print(f"[overlay] could not load gascola.tif basemap ({e}); plotting trajectories only")

    ax.plot(real_xy[:, 0], real_xy[:, 1], "-", color="0.6", lw=1.0, label="real GPS track (full)")
    ax.plot(sim_xy[:, 0], sim_xy[:, 1], "-", color="tab:red", lw=2.0, label="sim rollout")
    ax.plot(0, 0, "k*", ms=14, label="sequence start")
    ax.set_xlabel("relative easting [m]")
    ax.set_ylabel("relative northing [m]")
    ax.legend(loc="best")
    ax.set_aspect("equal")
    margin = 15
    ax.set_xlim(sim_xy[:, 0].min() - margin, sim_xy[:, 0].max() + margin)
    ax.set_ylim(sim_xy[:, 1].min() - margin, sim_xy[:, 1].max() + margin)
    fig.tight_layout()
    fig.savefig(out_path, dpi=150)
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--sequence", default="2023-10-26-14-42-35_turnpike_afternoon_fall")
    parser.add_argument("--kitti-root", default=str(REPO_ROOT / "kitti_format"))
    parser.add_argument("--steps", type=int, default=350)
    parser.add_argument("--frame-stride", type=int, default=3,
                         help="use every Nth lidar frame when aggregating terrain")
    parser.add_argument("--frame-range-end", type=int, default=300,
                         help="restrict terrain aggregation to frames [0, this) for a fast PoC build")
    parser.add_argument("--cell-size", type=float, default=0.3)
    parser.add_argument("--out", default=str(REPO_ROOT / "sim_verify_out"))
    parser.add_argument("--smoke-test", action="store_true")
    args = parser.parse_args()

    try_pull_atv_scan()

    scene_dir = Path(args.kitti_root) / args.sequence
    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)
    cache_path = out_dir / f"{args.sequence}_terrain.npz"

    env = TartanDriveEnv(
        scene_dir=scene_dir, cache_path=cache_path,
        frame_stride=args.frame_stride, cell_size=args.cell_size,
        frame_range=(0, args.frame_range_end), max_episode_steps=args.steps + 1)

    if args.smoke_test:
        run_smoke_test(env)

    sim_xy, frames, ended_at = rollout(env, args.steps)
    save_frames(frames, out_dir / "frames")
    save_overlay(env, sim_xy, out_dir / "trajectory_overlay.png")
    env.close()

    distance = float(np.linalg.norm(sim_xy[-1] - sim_xy[0]))
    status = "SUCCESS" if ended_at is None else "ENDED EARLY (tilt/step limit)"
    print(f"[verify_sim_env] {status}: {len(sim_xy) - 1} steps, "
          f"net displacement {distance:.2f} m, {len(frames)} frames saved to {out_dir}")


if __name__ == "__main__":
    main()