File size: 2,995 Bytes
3f4bb1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""GEAR planner walk clips resampled onto SONIC's control tick.

SONIC tracks a reference motion; it cannot generate one. GEAR's kinematic
planner (``motionbricks``) supplies that reference, and
``simulation/scripts/gen_walk_reference.py`` writes it out as MuJoCo ``qpos``
at the planner's own frame rate. This turns such a clip into what SONIC's
``g1`` encoder slots want: Isaac Lab joint order, 50 Hz, with velocities.

Kept free of Isaac Lab imports so it stays importable (and testable) outside a
running simulation app.
"""

from __future__ import annotations

from pathlib import Path

import numpy as np

from .constants import (
    FUTURE_FRAMES,
    G1_ISAACLAB_JOINT_NAMES,
    G1_MUJOCO_JOINT_NAMES,
    G1_STEP,
    NUM_JOINTS,
)

#: SONIC's control period. The g1 lookahead frames are G1_STEP of these apart.
SONIC_DT = 0.02


class PlannerReference:
    """A planner ``qpos`` clip, resampled and reindexed for SONIC."""

    def __init__(self, path: str | Path) -> None:
        path = Path(path)
        if not path.exists():
            raise FileNotFoundError(
                f"missing walk reference {path}\n"
                "generate it with: simulation/jobs/gen_walk_reference.sh --target X Y"
            )
        data = np.load(path)
        qpos = np.asarray(data["qpos"], dtype=np.float64)
        fps = float(data["fps"])
        self.target = np.asarray(data["target"], dtype=np.float64)

        src_t = np.arange(qpos.shape[0]) / fps
        dst_t = np.arange(0.0, src_t[-1] + 1e-9, SONIC_DT)

        order = [G1_MUJOCO_JOINT_NAMES.index(n) for n in G1_ISAACLAB_JOINT_NAMES]
        joints = qpos[:, 7:][:, order]
        self.q = np.stack(
            [np.interp(dst_t, src_t, joints[:, j]) for j in range(NUM_JOINTS)], axis=1
        )
        self.dq = np.gradient(self.q, SONIC_DT, axis=0)

        # Planner qpos stores the root as wxyz. Interpolating quaternions
        # componentwise needs them all on one hemisphere, or the lerp cuts
        # through the origin wherever the sign flips.
        quat = qpos[:, 3:7].copy()
        agree = np.sign(np.sum(quat[1:] * quat[:-1], axis=1) + 1e-12)
        quat[1:] *= np.cumprod(agree)[:, None]
        lerped = np.stack([np.interp(dst_t, src_t, quat[:, k]) for k in range(4)], axis=1)
        self.quat = lerped / np.linalg.norm(lerped, axis=1, keepdims=True)

        self.num_frames = int(self.q.shape[0])

    def horizon(self, frame: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """The 10-frame step-5 lookahead each env is currently looking at.

        ``frame`` is (N,). Returns joint positions (N, 10, 29), velocities
        (N, 10, 29) and root quaternions (N, 10, 4 wxyz). Envs past the end
        clamp to the final frame, which the planner leaves standing.
        """
        idx = np.asarray(frame, dtype=np.int64)[:, None] + np.arange(FUTURE_FRAMES) * G1_STEP
        idx = np.clip(idx, 0, self.num_frames - 1)
        return self.q[idx], self.dq[idx], self.quat[idx]