File size: 7,759 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env python3
"""SONIC walks to the WalkGrab object on a planner reference, then reaches.

The action term tracks the GEAR planner clip in SONIC's ``g1`` mode and hands
over to wrist teleop by itself, so this script just holds a neutral action
while it walks and then runs the same reach / close / lift schedule as the
standing manip smoke.

Generate the reference first (matched to the object xy):

  ./jobs/gen_walk_reference.sh --target 1.5 -0.35
  ./jobs/sonic_walkgrab_play.sh --headless --video
"""

from __future__ import annotations

import argparse
import os
import pathlib
import sys
import traceback

_PROJECT = pathlib.Path(__file__).resolve().parents[2]
_SIM_SRC = _PROJECT / "simulation" / "source"
if str(_SIM_SRC) not in sys.path:
    sys.path.insert(0, str(_SIM_SRC))

from isaaclab.app import AppLauncher

parser = argparse.ArgumentParser(
    description="SONIC whole-body walk to the WalkGrab object, then wrist reach."
)
parser.add_argument("--task", default="V2D-G1-SonicWalkGrab-Play-v0")
parser.add_argument(
    "--clip",
    default="20200709_141754_836212060125",
    help="reconstruction/runs/<clip> whose exported object.urdf goes on the table.",
)
parser.add_argument("--num_envs", type=int, default=1)
parser.add_argument("--max_steps", type=int, default=0, help="0 = one full episode.")
parser.add_argument("--video", action="store_true")
parser.add_argument(
    "--video_length",
    type=int,
    default=0,
    help="Recorded steps; 0 = whole run. Used when --video is set.",
)
parser.add_argument(
    "--reach-xy",
    type=float,
    default=None,
    help="Override the pelvis-object xy range at which the term stops tracking the "
    "planner reference and hands over to the wrist.",
)
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()
os.environ["V2D_SONIC_WALKGRAB_CLIP"] = args_cli.clip
if args_cli.video:
    args_cli.enable_cameras = True

app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app

import gymnasium as gym  # noqa: E402
import torch  # noqa: E402
from isaaclab.utils.dict import print_dict  # noqa: E402
from isaaclab_tasks.utils import parse_env_cfg  # noqa: E402

import v2d_sim.tasks.g1_sonic_walkgrab  # noqa: E402, F401

_GRAV, _WRIST, _OBJ, _DELTA = (
    slice(0, 3),
    slice(3, 6),
    slice(6, 9),
    slice(9, 12),
)


def _t(x):
    return x.torch if hasattr(x, "torch") else x


def main() -> None:
    env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=args_cli.num_envs)
    if args_cli.reach_xy is not None:
        env_cfg.actions.wrist.arrive_xy = args_cli.reach_xy
    env = gym.make(
        args_cli.task,
        cfg=env_cfg,
        render_mode="rgb_array" if args_cli.video else None,
    )

    episode_steps = int(env.unwrapped.max_episode_length)
    n = args_cli.max_steps or episode_steps
    video_length = args_cli.video_length or n
    print(
        f"[sonic-walkgrab] task={args_cli.task} clip={args_cli.clip} "
        f"episode={episode_steps} running={n} recording={video_length}",
        flush=True,
    )
    print(
        "[sonic-walkgrab] SONIC g1 mode tracks the GEAR planner walk reference, then "
        f"hands over to wrist teleop inside {env_cfg.actions.wrist.arrive_xy:.2f} m pelvis xy.",
        flush=True,
    )

    if args_cli.video:
        out_dir = _PROJECT / "simulation" / "runs" / "sonic_walkgrab" / args_cli.clip
        out_dir.mkdir(parents=True, exist_ok=True)
        video_kwargs = {
            "video_folder": str(out_dir),
            "step_trigger": lambda step: step == 0,
            "video_length": video_length,
            "disable_logger": True,
        }
        print("[sonic-walkgrab] recording video", flush=True)
        print_dict(video_kwargs, nesting=4)
        env = gym.wrappers.RecordVideo(env, **video_kwargs)

    inner = env.unwrapped
    wrist_term = inner.action_manager.get_term("wrist")
    acfg = env_cfg.actions.wrist
    lo = torch.tensor(
        [acfg.wrist_x[0], acfg.wrist_y[0], acfg.wrist_z[0]], device=inner.device
    )
    hi = torch.tensor(
        [acfg.wrist_x[1], acfg.wrist_y[1], acfg.wrist_z[1]], device=inner.device
    )
    center, half = (lo + hi) / 2.0, (hi - lo) / 2.0

    obs_dict, _ = env.reset()
    obs = obs_dict["policy"]
    robot = inner.scene["robot"]
    obj = inner.scene["object"]
    rest_z = float(env_cfg.scene.object.init_state.pos[2])
    n_env = inner.num_envs
    reach_start = torch.full((n_env,), -1, device=inner.device, dtype=torch.long)

    min_root_z = float("inf")
    min_hand_obj = float("inf")
    max_root_x = float("-inf")
    max_lift = 0.0
    settle = 10
    obj_z0 = rest_z

    hold = torch.zeros(n_env, 4, device=inner.device)
    hold[:, 2] = 1.0
    hold[:, 3] = -1.0

    for step in range(n):
        if not simulation_app.is_running():
            break
        obj_xy = torch.linalg.norm(obs[:, _OBJ][:, :2], dim=1)
        # The action term owns the handover; mirror it so the reach schedule
        # starts on the same step SONIC switches out of g1 mode.
        arrived = torch.as_tensor(~wrist_term.walking, device=inner.device)
        reach_start[(reach_start < 0) & arrived] = step
        in_reach = reach_start >= 0
        action = hold.clone()
        if bool(in_reach.any()):
            local = (step - reach_start.clamp(min=0)).float()
            horizon = max(1.0, float(n - int(reach_start[in_reach].min())))
            frac = (local / horizon).clamp(0.0, 1.0)
            want = obs[:, _OBJ].clone()
            want[:, 2] = want[:, 2] + 0.06 * (1.0 - frac)
            want[:, 2] = want[:, 2] + torch.where(
                frac > 0.60, 0.12 * (frac - 0.60) / 0.40, torch.zeros_like(frac)
            )
            grip = torch.where(
                frac < 0.45,
                torch.full_like(frac, -1.0),
                torch.where(
                    frac < 0.60,
                    -1.0 + 2.0 * (frac - 0.45) / 0.15,
                    torch.ones_like(frac),
                ),
            )
            a = torch.clamp((want - center) / half, -1.0, 1.0)
            reach_action = torch.cat([a, grip.unsqueeze(-1)], dim=1)
            action[in_reach] = reach_action[in_reach]
        obs_dict, _, terminated, truncated, _ = env.step(action)
        obs = obs_dict["policy"]

        root = _t(robot.data.root_pos_w)[0]
        obj_pos = _t(obj.data.root_pos_w)[0]
        min_root_z = min(min_root_z, float(root[2]))
        max_root_x = max(max_root_x, float(root[0]))
        if step == settle:
            obj_z0 = float(obj_pos[2])
        max_lift = max(max_lift, float(obj_pos[2]) - obj_z0)
        hand_obj = float(torch.linalg.norm(obs[0, _DELTA]))
        min_hand_obj = min(min_hand_obj, hand_obj)
        if step % 50 == 0 or step == n - 1:
            mode = "reach" if bool(in_reach[0]) else "walk"
            print(
                f"  step {step}/{n}  {mode}  root_xy=({float(root[0]):.3f},{float(root[1]):.3f}) "
                f"root_z={float(root[2]):.3f}  object_xy=({float(obj_pos[0]):.3f},{float(obj_pos[1]):.3f}) "
                f"pelvis-obj_xy={float(obj_xy[0]):.3f}  hand-obj={hand_obj:.3f}  "
                f"done={int(bool(terminated[0] or truncated[0]))}",
                flush=True,
            )

    print(f"[sonic-walkgrab] min root_z={min_root_z:.3f}  max root_x={max_root_x:.3f}", flush=True)
    print(f"[sonic-walkgrab] min hand-object (pelvis frame)={min_hand_obj:.3f} m", flush=True)
    print(f"[sonic-walkgrab] peak object lift above rest={max_lift:+.3f} m", flush=True)
    env.close()


if __name__ == "__main__":
    code = 0
    try:
        main()
    except Exception:
        traceback.print_exc()
        code = 1
    finally:
        simulation_app.close()
    os._exit(code)