File size: 6,446 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
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
"""Frozen SONIC v1.1 driving N robots at once from wrist targets.

``obs.pack_encoder`` builds one 1751-D vector per call from a full reference
clip. An RL rollout needs something different: many environments, no clip, and
a standing reference that never changes. Under those assumptions almost the
whole encoder vector is constant, so it is built once here and only the heading
(6) and the VR 3-point target (21) are rewritten each step.

The history buffers and the push ordering mirror ``scripts/play_sonic.py``
exactly -- history holds post-physics proprio together with the action that
produced it -- because SONIC is sensitive to that alignment.
"""

from __future__ import annotations

from pathlib import Path

import numpy as np

from .constants import (
    ACTION_CLIP,
    DECODER_DIM,
    DEFAULT_ANGLES,
    ENCODER_DIM,
    ENCODER_OFF,
    FUTURE_FRAMES,
    HIST_FRAMES,
    LOWER_BODY_ISAAC_IDX,
    MODE_IDS,
    NUM_JOINTS,
    TOKEN_DIM,
)
from .math_np import heading_rel_6d
from .policy import SonicOnnxAgent


class BatchedSonicController:
    """Wrist targets in, 29 joint-position targets out, for N environments.

    Teleop mode against a fixed standing reference: the legs are told to hold
    the default stance, so whatever the base does is SONIC reacting to the arm
    rather than commanded locomotion.
    """

    def __init__(
        self,
        checkpoint: str | Path,
        num_envs: int,
        *,
        agent: SonicOnnxAgent | None = None,
    ) -> None:
        self.num_envs = int(num_envs)
        self.agent = agent if agent is not None else SonicOnnxAgent(checkpoint, batched=True)
        self.default = np.asarray(DEFAULT_ANGLES, dtype=np.float64)

        self._enc = np.zeros((self.num_envs, ENCODER_DIM), dtype=np.float32)
        self._enc[:, ENCODER_OFF["encoder_mode_4"][0]] = float(MODE_IDS["teleop"])
        # Constant standing reference: every future frame clamps to the same
        # pose, so the lower-body block is one row tiled over the 10 frames and
        # the matching velocity block stays zero.
        lower = self.default[LOWER_BODY_ISAAC_IDX].astype(np.float32)
        a, b = ENCODER_OFF["motion_joint_positions_lowerbody_10frame_step5"]
        self._enc[:, a:b] = np.tile(lower, FUTURE_FRAMES)

        self._dec = np.zeros((self.num_envs, DECODER_DIM), dtype=np.float32)
        self._hist = {
            "ang_vel": np.zeros((self.num_envs, HIST_FRAMES, 3), dtype=np.float32),
            "q_rel": np.zeros((self.num_envs, HIST_FRAMES, NUM_JOINTS), dtype=np.float32),
            "dq": np.zeros((self.num_envs, HIST_FRAMES, NUM_JOINTS), dtype=np.float32),
            "action": np.zeros((self.num_envs, HIST_FRAMES, NUM_JOINTS), dtype=np.float32),
            "gravity": np.zeros((self.num_envs, HIST_FRAMES, 3), dtype=np.float32),
        }
        self._last_action = np.zeros((self.num_envs, NUM_JOINTS), dtype=np.float32)
        self._primed = np.zeros(self.num_envs, dtype=bool)

    def reset(self, env_ids: np.ndarray | None = None) -> None:
        """Forget history for these environments; the next step re-primes them."""
        if env_ids is None:
            self._primed[:] = False
            self._last_action[:] = 0.0
            return
        idx = np.asarray(env_ids, dtype=np.int64).reshape(-1)
        if idx.size:
            self._primed[idx] = False
            self._last_action[idx] = 0.0

    def step(
        self,
        *,
        joint_pos: np.ndarray,
        joint_vel: np.ndarray,
        ang_vel: np.ndarray,
        gravity: np.ndarray,
        root_quat_wxyz: np.ndarray,
        vr_pos: np.ndarray,
        vr_quat: np.ndarray,
    ) -> np.ndarray:
        """One 50 Hz control step for every environment.

        All arrays are batched over N. ``joint_pos`` / ``joint_vel`` are (N, 29)
        in Isaac Lab SONIC order, ``vr_pos`` is (N, 3, 3) and ``vr_quat``
        (N, 3, 4 wxyz), both in the pelvis frame in left-wrist, right-wrist,
        torso order. Returns the (N, 29) clipped network action; the caller
        scales it into joint targets.
        """
        q_rel = (np.asarray(joint_pos, dtype=np.float32) - self.default).astype(np.float32)
        dq = np.asarray(joint_vel, dtype=np.float32)
        ang = np.asarray(ang_vel, dtype=np.float32)
        grav = np.asarray(gravity, dtype=np.float32)

        self._record(ang, q_rel, dq, grav)

        quat = np.asarray(root_quat_wxyz, dtype=np.float64)
        ident = np.zeros_like(quat)
        ident[:, 0] = 1.0
        a, b = ENCODER_OFF["motion_anchor_orientation_heading"]
        self._enc[:, a:b] = heading_rel_6d(quat, ident).astype(np.float32)
        a, b = ENCODER_OFF["vr_3point_local_target"]
        self._enc[:, a:b] = np.asarray(vr_pos, dtype=np.float32).reshape(self.num_envs, 9)
        a, b = ENCODER_OFF["vr_3point_local_orn_target"]
        self._enc[:, a:b] = np.asarray(vr_quat, dtype=np.float32).reshape(self.num_envs, 12)

        self._dec[:, :TOKEN_DIM] = self.agent.encode(self._enc)
        i = TOKEN_DIM
        # PolicyCfg term order: base_ang_vel, joint_pos, joint_vel, actions, gravity_dir.
        for key in ("ang_vel", "q_rel", "dq", "action", "gravity"):
            buf = self._hist[key]
            n = buf.shape[1] * buf.shape[2]
            self._dec[:, i : i + n] = buf.reshape(self.num_envs, n)
            i += n
        if i != DECODER_DIM:
            raise RuntimeError(f"decoder pack {i} != {DECODER_DIM}")

        action = np.clip(self.agent.decode(self._dec), -ACTION_CLIP, ACTION_CLIP)
        self._last_action = action.astype(np.float32)
        return self._last_action

    def joint_targets(self, action: np.ndarray, scale: np.ndarray) -> np.ndarray:
        """``default + scale * action`` for the 29 SONIC joints."""
        return self.default + np.asarray(scale, dtype=np.float64) * np.asarray(action, dtype=np.float64)

    def _record(
        self, ang: np.ndarray, q_rel: np.ndarray, dq: np.ndarray, grav: np.ndarray
    ) -> None:
        """Append this frame, filling a freshly reset environment's whole window."""
        frame = {"ang_vel": ang, "q_rel": q_rel, "dq": dq, "action": self._last_action, "gravity": grav}
        fresh = ~self._primed
        for key, buf in self._hist.items():
            buf[:, :-1] = buf[:, 1:]
            buf[:, -1] = frame[key]
            if fresh.any():
                buf[fresh] = frame[key][fresh][:, None, :]
        self._primed[:] = True