main
Drew Owens Publish Microgoose Rev A full-stack hardware, CAD, datasheet, and 7-stage RL stack e843249
#!/usr/bin/env python3
"""Standalone CPU ONNX Runtime + MuJoCo Sim-to-Sim Evaluator & Video Renderer.

Evaluates rl/checkpoints/policy.onnx purely on CPUExecutionProvider (no PyTorch)
inside MuJoCo 4.0.1 with the full BAM XL330 actuator model:
  - Reflected armature inertia, Coulomb stiction, viscous damping, backlash deadzone
  - 1-step (2 ms) Spine MCU TTL UART communication delay
  - 5.0 V Spine bus sag & quadrant torque-speed saturation
  - Mid-walk lateral velocity push disturbance at t = 4.0 s

Verifies 10-second survival, tilt < 0.45 rad, positive forward displacement tracking
vx_cmd, and zero NaNs. Writes:
  - rl/checkpoints/sim2sim_report.json
  - docs/videos/microgoose-walk-sim2sim.mp4 (1280x720 @ 30 fps H.264)
  - docs/rl/sim2sim_walk_strip.png (6-frame progression strip)
"""

from __future__ import annotations

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

import json
import math
from pathlib import Path
from typing import Any, Dict, List

import imageio.v2 as iio
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import mujoco
import numpy as np
import onnxruntime as ort
from PIL import Image, ImageDraw, ImageFont

from microgoose_mj_env import (
    CONTROL_DT,
    MAX_EPISODE_STEPS,
    OBS_DIM,
    MicrogooseMjEnv,
)


ROOT_DIR = Path(__file__).resolve().parents[1]
ONNX_PATH = ROOT_DIR / "rl" / "checkpoints" / "policy.onnx"
REPORT_PATH = ROOT_DIR / "rl" / "checkpoints" / "sim2sim_report.json"
VIDEO_PATH = ROOT_DIR / "docs" / "videos" / "microgoose-walk-sim2sim.mp4"
STRIP_PATH = ROOT_DIR / "docs" / "rl" / "sim2sim_walk_strip.png"


def draw_hud_overlay(frame: np.ndarray, tele: Dict[str, Any]) -> np.ndarray:
    """Render a subtle semi-transparent dark telemetry HUD card in top-left corner."""
    img = Image.fromarray(frame).convert("RGBA")
    overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)

    # HUD card background (#0d1317 alpha + #3b3894 border)
    box = (24, 22, 428, 178)
    draw.rounded_rectangle(box, radius=10, fill=(13, 19, 23, 208), outline=(59, 56, 148, 235), width=2)

    try:
        font_title = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 16)
        font_mono = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 14)
    except Exception:
        font_title = ImageFont.load_default()
        font_mono = ImageFont.load_default()

    draw.text((38, 32), "MICROGOOSE SIM-TO-SIM (CPU ONNX)", fill=(56, 189, 248, 255), font=font_title)

    t_s = tele["t_sec"]
    vx = tele["vx"]
    vx_cmd = tele["vx_cmd"]
    dist_x = tele["x_m"]
    tilt_deg = math.degrees(tele["tilt_rad"])
    v_bus = tele["v_bus"]
    l_c, r_c = tele["contacts"]

    lines = [
        f"Time:  {t_s:5.2f} s   Dist X: {dist_x:+5.2f} m",
        f"Vel X: {vx:+5.2f} / {vx_cmd:+5.2f} m/s",
        f"Tilt:  {tilt_deg:5.1f} deg  5V Bus: {v_bus:4.2f} V",
        f"Feet:  L [{'ON ' if l_c > 0.5 else 'AIR'}]   R [{'ON ' if r_c > 0.5 else 'AIR'}]",
    ]
    y = 60
    for ln in lines:
        draw.text((38, y), ln, fill=(237, 240, 242, 255), font=font_mono)
        y += 24

    # Highlight mid-walk lateral impulse window (t = 4.0s to 4.7s)
    if 4.00 <= t_s <= 4.75:
        badge = (448, 22, 818, 64)
        draw.rounded_rectangle(badge, radius=8, fill=(180, 62, 28, 225), outline=(251, 146, 60, 255), width=2)
        draw.text(
            (464, 34),
            "LATERAL PUSH IMPULSE (+0.18 m/s)",
            fill=(255, 247, 237, 255),
            font=font_title,
        )

    out = Image.alpha_composite(img, overlay).convert("RGB")
    return np.asarray(out, dtype=np.uint8)


def save_walk_strip(strip_frames: List[Tuple[str, np.ndarray]], out_path: Path) -> None:
    out_path.parent.mkdir(parents=True, exist_ok=True)
    bg = "#0d1317"
    fg = "#edf0f2"
    border = "#3b3894"
    sky = "#38bdf8"

    fig, axes = plt.subplots(2, 3, figsize=(15.0, 6.2), dpi=140, facecolor=bg)
    fig.subplots_adjust(hspace=0.18, wspace=0.06, top=0.88, bottom=0.03, left=0.02, right=0.98)
    fig.suptitle(
        "Microgoose 10s CPU ONNX Sim-to-Sim Rollout (BAM Friction + 2ms Delay + t=4.0s Lateral Push)",
        color=fg,
        fontsize=13.5,
        fontweight="bold",
        y=0.96,
    )

    for ax, (caption, rgb) in zip(axes.flat, strip_frames):
        # Center-crop 16:9 frame slightly for closer detail on robot gait
        h, w, _ = rgb.shape
        crop = rgb[int(h * 0.08) : int(h * 0.94), int(w * 0.14) : int(w * 0.86)]
        ax.imshow(crop)
        ax.set_title(caption, color=sky if "Push" not in caption else "#fb923c", fontsize=10.5, fontweight="bold", pad=5)
        ax.set_xticks([])
        ax.set_yticks([])
        for sp in ax.spines.values():
            sp.set_visible(True)
            sp.set_color(border)
            sp.set_linewidth(1.5)

    fig.savefig(out_path, facecolor=bg)
    plt.close(fig)


def main() -> None:
    if not ONNX_PATH.exists():
        raise FileNotFoundError(f"ONNX policy not found at {ONNX_PATH}")

    sess = ort.InferenceSession(str(ONNX_PATH), providers=["CPUExecutionProvider"])

    vx_cmd = 0.16
    push_step = 200  # t = 4.00 s at 50 Hz
    push_dvy = 0.18  # +0.18 m/s lateral torso impulse

    env = MicrogooseMjEnv(
        seed=2026,
        domain_rand=False,
        obs_noise=False,
        enable_pushes=False,
        max_episode_steps=MAX_EPISODE_STEPS,
    )
    env.set_command(vx=vx_cmd, vy=0.0, wz=0.0, stand_flag=0.0)
    obs = env.reset(fixed_stand_pose=True)

    renderer = mujoco.Renderer(env.model, height=720, width=1280)
    scene_opt = mujoco.MjvOption()
    scene_opt.flags[mujoco.mjtVisFlag.mjVIS_RANGEFINDER] = False
    VIDEO_PATH.parent.mkdir(parents=True, exist_ok=True)
    writer = iio.get_writer(
        str(VIDEO_PATH),
        fps=30,
        codec="libx264",
        quality=8,
        pixelformat="yuv420p",
        macro_block_size=16,
    )

    # 50 Hz control (500 steps = 10.0s) -> 300 video frames at 30 fps
    render_steps = set(np.round(np.linspace(0, MAX_EPISODE_STEPS - 1, 300)).astype(int).tolist())
    strip_targets = {
        25: "t = 0.5s | Gait Spin-Up",
        110: "t = 2.2s | Steady Stride",
        200: "t = 4.0s | Lateral Push (+0.18 m/s)",
        225: "t = 4.5s | Balance Recovery",
        350: "t = 7.0s | Cruise Tracking",
        490: "t = 9.8s | Full 10s Completion",
    }
    strip_frames: List[Tuple[str, np.ndarray]] = []

    vx_trace: List[float] = []
    tilt_trace: List[float] = []
    vbus_trace: List[float] = []
    foot_l_z_trace: List[float] = []
    foot_r_z_trace: List[float] = []
    nan_count = 0
    fell = False
    steps_completed = 0

    start_pos = env.data.qpos[0:3].copy()

    try:
        for step in range(MAX_EPISODE_STEPS):
            if step == push_step:
                env.apply_planar_push(0.0, push_dvy)

            # Open hinged orange beak briefly in a reactive honk right after push!
            if 200 <= step <= 222:
                env.beak_target_rad = 0.48
            else:
                env.beak_target_rad = env.beak_default

            obs_in = obs.reshape(1, OBS_DIM).astype(np.float32)
            actions = sess.run(["actions"], {"obs": obs_in})[0][0]
            if not np.isfinite(actions).all():
                nan_count += int(np.sum(~np.isfinite(actions)))
                actions = np.nan_to_num(actions, nan=0.0)

            obs, _, term, trunc, info = env.step(actions)
            if not np.isfinite(obs).all():
                nan_count += int(np.sum(~np.isfinite(obs)))

            steps_completed = step + 1
            vx_trace.append(info["vx_body"])
            tilt_trace.append(info["tilt_rad"])
            vbus_trace.append(info["v_bus"])
            foot_l_z_trace.append(info["foot_z_lr"][0])
            foot_r_z_trace.append(info["foot_z_lr"][1])

            need_video = step in render_steps
            need_strip = step in strip_targets
            if need_video or need_strip:
                renderer.update_scene(env.data, camera="track_cam", scene_option=scene_opt)
                raw_rgb = renderer.render()
                if need_strip:
                    strip_frames.append((strip_targets[step], raw_rgb.copy()))
                if need_video:
                    tele = {
                        "t_sec": (step + 1) * CONTROL_DT,
                        "vx": info["vx_body"],
                        "vx_cmd": vx_cmd,
                        "x_m": float(env.data.qpos[0] - start_pos[0]),
                        "tilt_rad": info["tilt_rad"],
                        "v_bus": info["v_bus"],
                        "contacts": (float(env.last_foot_contacts[0]), float(env.last_foot_contacts[1])),
                    }
                    hud_rgb = draw_hud_overlay(raw_rgb, tele)
                    writer.append_data(hud_rgb)

            if term:
                fell = True
                break
    finally:
        writer.close()
        renderer.close()

    end_pos = env.data.qpos[0:3].copy()
    forward_disp_m = float(end_pos[0] - start_pos[0])
    lateral_disp_m = float(end_pos[1] - start_pos[1])
    total_planar_disp_m = float(np.linalg.norm(end_pos[0:2] - start_pos[0:2]))
    max_tilt_rad = float(np.max(tilt_trace))
    mean_tilt_rad = float(np.mean(tilt_trace))
    steady_vx = vx_trace[40:] if len(vx_trace) > 40 else vx_trace
    mean_steady_vx = float(np.mean(steady_vx))
    steady_vx_mae = float(np.mean(np.abs(np.asarray(steady_vx) - vx_cmd)))

    if len(strip_frames) == 6:
        save_walk_strip(strip_frames, STRIP_PATH)

    report = {
        "schema": "microgoose-sim2sim-report/v1",
        "onnx_policy": str(ONNX_PATH),
        "execution_provider": "CPUExecutionProvider",
        "episode_steps": steps_completed,
        "episode_duration_sec": round(steps_completed * CONTROL_DT, 2),
        "survived_full_10s": bool((not fell) and steps_completed == MAX_EPISODE_STEPS),
        "nan_count": nan_count,
        "vx_cmd_mps": vx_cmd,
        "mean_steady_vx_mps": round(mean_steady_vx, 4),
        "steady_vx_mae_mps": round(steady_vx_mae, 4),
        "forward_displacement_x_m": round(forward_disp_m, 4),
        "lateral_displacement_y_m": round(lateral_disp_m, 4),
        "planar_displacement_m": round(total_planar_disp_m, 4),
        "max_tilt_rad": round(max_tilt_rad, 4),
        "max_tilt_deg": round(math.degrees(max_tilt_rad), 2),
        "mean_tilt_rad": round(mean_tilt_rad, 4),
        "peak_foot_clearance_mm": {
            "left": round(float(np.max(foot_l_z_trace)) * 1000.0, 2),
            "right": round(float(np.max(foot_r_z_trace)) * 1000.0, 2),
        },
        "min_spine_5v_bus_v": round(float(np.min(vbus_trace)), 3),
        "mid_walk_push": {
            "time_sec": round(push_step * CONTROL_DT, 2),
            "dvy_mps": push_dvy,
            "recovered_without_fall": bool(not fell),
        },
        "artifacts": {
            "video_mp4": str(VIDEO_PATH),
            "walk_strip_png": str(STRIP_PATH),
        },
    }
    REPORT_PATH.parent.mkdir(parents=True, exist_ok=True)
    with open(REPORT_PATH, "w", encoding="utf-8") as f:
        json.dump(report, f, indent=2)

    print("Sim-to-sim verification summary:")
    print(json.dumps(report, indent=2))

    assert not fell and steps_completed == MAX_EPISODE_STEPS, "Robot fell before completing 10s rollout!"
    assert max_tilt_rad < 0.45, f"Max tilt {max_tilt_rad:.3f} rad exceeded 0.45 rad limit!"
    assert forward_disp_m > 0.85, f"Forward displacement {forward_disp_m:.3f} m too low for vx_cmd={vx_cmd}!"
    assert nan_count == 0, f"Detected {nan_count} NaNs during sim-to-sim rollout!"


if __name__ == "__main__":
    main()