File size: 16,062 Bytes
21e1acb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
"""Small Task-E bridge around the TunTunClaw GraspNet API.

The GraspNet model predicts grasps in the camera/ROS frame.  Task E executes a
top-down Piper grasp in world frame, so this adapter intentionally uses
GraspNet for the contact centre and jaw yaw, then forces a stable top-down
orientation for the Piper gripper.
"""

from __future__ import annotations

from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
import os
import sys

import numpy as np
import torch
from scipy.spatial.transform import Rotation


REPO_ROOT = Path(__file__).resolve().parents[2]
TUNTUN_ROOT = REPO_ROOT / "third_party" / "tuntunclaw"
GRASPNET_ROOT = TUNTUN_ROOT / "graspnet-baseline"
CHECKPOINT_PATH = TUNTUN_ROOT / "temp" / "logs" / "log_rs" / "checkpoint-rs.tar"


def _ensure_tuntun_paths() -> None:
    paths = [
        GRASPNET_ROOT / "models",
        GRASPNET_ROOT / "dataset",
        GRASPNET_ROOT / "utils",
        GRASPNET_ROOT / "graspnetAPI",
        TUNTUN_ROOT / "manipulator_grasp",
    ]
    for path in paths:
        p = str(path)
        if p not in sys.path:
            sys.path.insert(0, p)


@dataclass(frozen=True)
class TaskEGrasp:
    translation_w: np.ndarray
    quat_wxyz_w: np.ndarray
    score: float
    width: float
    raw_translation_cam: np.ndarray


def camera_arrays(camera) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """Return RGB, depth, K, camera position and ROS-frame quaternion."""
    rgb = camera.data.output["rgb"][0].detach().cpu().numpy()[..., :3]
    depth = camera.data.output["depth"][0].detach().cpu().numpy()
    if depth.ndim == 3:
        depth = depth[..., 0]
    K = camera.data.intrinsic_matrices[0].detach().cpu().numpy()
    pos_w = camera.data.pos_w[0].detach().cpu().numpy()
    quat_wxyz_ros = camera.data.quat_w_ros[0].detach().cpu().numpy()
    return rgb, depth.astype(np.float32), K.astype(np.float32), pos_w.astype(np.float64), quat_wxyz_ros.astype(np.float64)


def project_world_points_to_image(points_w: np.ndarray, K: np.ndarray, pos_w: np.ndarray, quat_wxyz_ros: np.ndarray) -> np.ndarray:
    """Project world points into a ROS camera image."""
    rot_w_cam = Rotation.from_quat(
        [quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
    ).as_matrix()
    pts_cam = (rot_w_cam.T @ (points_w - pos_w).T).T
    z = np.clip(pts_cam[:, 2], 1e-6, None)
    u = K[0, 0] * pts_cam[:, 0] / z + K[0, 2]
    v = K[1, 1] * pts_cam[:, 1] / z + K[1, 2]
    return np.stack([u, v, pts_cam[:, 2]], axis=1)


def oracle_object_mask(env, camera, obj_idx: int, pad_px: int = 24) -> np.ndarray:
    """Create a temporary ROI mask by projecting the known simulated object bbox.

    This is for fast grasp primitive debugging.  Once the primitive is stable,
    replace this mask provider with RGB-D segmentation/VLM masks for submission.
    """
    from atec_rl_lab.tasks.task_e.env_cfg import OBJ_HALF_EXTENTS, TABLE_TOP_Z

    rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
    h, w = depth.shape[:2]
    obj = env.unwrapped.scene.rigid_objects[f"object_{obj_idx}"]
    center = obj.data.root_pos_w[0].detach().cpu().numpy().astype(np.float64)
    hx, hy = OBJ_HALF_EXTENTS[f"object_{obj_idx}"]
    z_lo = TABLE_TOP_Z + 0.005
    z_hi = max(center[2] + 0.16, TABLE_TOP_Z + 0.08)
    corners = np.array(
        [
            [center[0] + sx * hx, center[1] + sy * hy, z]
            for sx in (-1.0, 1.0)
            for sy in (-1.0, 1.0)
            for z in (z_lo, z_hi)
        ],
        dtype=np.float64,
    )
    uvz = project_world_points_to_image(corners, K, pos_w, quat_wxyz_ros)
    valid = uvz[:, 2] > 0.02
    mask = np.zeros((h, w), dtype=np.uint8)
    if not np.any(valid):
        return mask
    u = uvz[valid, 0]
    v = uvz[valid, 1]
    x1 = int(np.clip(np.floor(u.min()) - pad_px, 0, w - 1))
    y1 = int(np.clip(np.floor(v.min()) - pad_px, 0, h - 1))
    x2 = int(np.clip(np.ceil(u.max()) + pad_px, 0, w - 1))
    y2 = int(np.clip(np.ceil(v.max()) + pad_px, 0, h - 1))
    if x2 > x1 and y2 > y1:
        mask[y1 : y2 + 1, x1 : x2 + 1] = 255
        # Remove obvious background/table pixels while keeping the object surface.
        obj_depth = depth[mask > 0]
        obj_depth = obj_depth[np.isfinite(obj_depth) & (obj_depth > 0.0)]
        if obj_depth.size:
            d_min = float(np.percentile(obj_depth, 3))
            d_max = float(np.percentile(obj_depth, 70))
            mask[(depth < d_min - 0.03) | (depth > d_max + 0.06)] = 0
        # Debug oracle refinement: keep only RGB-D points whose reconstructed
        # world coordinates lie inside the selected object's AABB.  The first
        # rectangular ROI can include neighboring objects for banana/long
        # shapes, which shifts GraspNet's execution centre by tens of cm.
        ys, xs = np.where((mask > 0) & np.isfinite(depth) & (depth > 0.0))
        if len(xs) > 0:
            z = depth[ys, xs].astype(np.float64)
            x_cam = (xs.astype(np.float64) - float(K[0, 2])) / float(K[0, 0]) * z
            y_cam = (ys.astype(np.float64) - float(K[1, 2])) / float(K[1, 1]) * z
            pts_cam = np.stack([x_cam, y_cam, z], axis=1)
            rot_w_cam = Rotation.from_quat(
                [quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
            ).as_matrix()
            pts_w = (rot_w_cam @ pts_cam.T).T + pos_w
            keep = (
                (pts_w[:, 0] >= center[0] - hx - 0.025)
                & (pts_w[:, 0] <= center[0] + hx + 0.025)
                & (pts_w[:, 1] >= center[1] - hy - 0.025)
                & (pts_w[:, 1] <= center[1] + hy + 0.025)
                & (pts_w[:, 2] >= TABLE_TOP_Z - 0.010)
                & (pts_w[:, 2] <= center[2] + 0.180)
            )
            refined = np.zeros_like(mask)
            refined[ys[keep], xs[keep]] = 255
            if np.count_nonzero(refined) > 128:
                mask = refined
    return mask


_BAND_Z_LIMITS = {
    1: (0.035, 0.130),  # sugar box: reject table pixels and high gripper links
    2: (0.020, 0.190),  # mustard bottle
    3: (0.012, 0.095),  # banana
}


def rgbd_band_object_mask(camera, obj_idx: int, margin_y: float = 0.045) -> np.ndarray:
    """Segment a Task-E object from RGB-D using legal scene priors.

    The official randomizer keeps each object type in a distinct world-Y band.
    Reconstructing the video camera depth into world coordinates lets us isolate
    the object without reading simulator object state.  This is the intended
    replacement for ``oracle_object_mask`` in submission-style tests.
    """
    from scripts.act.task_e.config import OBJ_SPAWN_X_MIN, OBJ_SPAWN_X_MAX, OBJ_SPAWN_Y_BANDS
    from atec_rl_lab.tasks.task_e.env_cfg import TABLE_TOP_Z

    rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
    valid = np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
    ys, xs = np.where(valid)
    mask = np.zeros(depth.shape[:2], dtype=np.uint8)
    if len(xs) == 0:
        return mask

    z = depth[ys, xs].astype(np.float64)
    x_cam = (xs.astype(np.float64) - float(K[0, 2])) / float(K[0, 0]) * z
    y_cam = (ys.astype(np.float64) - float(K[1, 2])) / float(K[1, 1]) * z
    pts_cam = np.stack([x_cam, y_cam, z], axis=1)
    rot_w_cam = Rotation.from_quat(
        [quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
    ).as_matrix()
    pts_w = (rot_w_cam @ pts_cam.T).T + pos_w

    y0, y1 = OBJ_SPAWN_Y_BANDS[obj_idx]
    z_min_rel, z_max_rel = _BAND_Z_LIMITS.get(obj_idx, (0.006, 0.24))
    rgb_pts = rgb[ys, xs].astype(np.float32)
    maxc = rgb_pts.max(axis=1)
    minc = rgb_pts.min(axis=1)
    sat = maxc - minc
    non_gray = (sat > 18.0) | (maxc > 170.0)
    world_keep = (
        (pts_w[:, 0] >= OBJ_SPAWN_X_MIN - 0.08)
        & (pts_w[:, 0] <= OBJ_SPAWN_X_MAX + 0.08)
        & (pts_w[:, 1] >= y0 - margin_y)
        & (pts_w[:, 1] <= y1 + margin_y)
        & (pts_w[:, 2] >= TABLE_TOP_Z + z_min_rel)
        & (pts_w[:, 2] <= TABLE_TOP_Z + z_max_rel)
        & non_gray
    )
    mask[ys[world_keep], xs[world_keep]] = 255

    # Fill the component's rectangular holes lightly; GraspNet expects enough
    # depth samples and the box has large white low-saturation areas.
    if np.count_nonzero(mask) > 0:
        yy, xx = np.where(mask > 0)
        x1, x2 = int(xx.min()), int(xx.max())
        y1p, y2p = int(yy.min()), int(yy.max())
        roi = np.zeros_like(mask)
        roi[y1p : y2p + 1, x1 : x2 + 1] = 255
        fill_keep = roi[ys, xs] > 0
        fill_keep &= (
            (pts_w[:, 1] >= y0 - margin_y)
            & (pts_w[:, 1] <= y1 + margin_y)
            & (pts_w[:, 2] >= TABLE_TOP_Z + z_min_rel)
            & (pts_w[:, 2] <= TABLE_TOP_Z + z_max_rel)
        )
        mask[ys[fill_keep], xs[fill_keep]] = 255
    return mask


@lru_cache(maxsize=1)
def _load_graspnet_model():
    _ensure_tuntun_paths()
    if not CHECKPOINT_PATH.exists():
        raise FileNotFoundError(
            f"GraspNet checkpoint missing: {CHECKPOINT_PATH}. "
            "Download official checkpoint-rs.tar there first."
        )
    from graspnet import GraspNet

    net = GraspNet(
        input_feature_dim=0,
        num_view=300,
        num_angle=12,
        num_depth=4,
        cylinder_radius=0.05,
        hmin=-0.02,
        hmax_list=[0.01, 0.02, 0.03, 0.04],
        is_training=False,
    )
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    net.to(device)
    checkpoint = torch.load(CHECKPOINT_PATH, map_location=device)
    net.load_state_dict(checkpoint["model_state_dict"])
    net.eval()
    return net


def _run_graspnet(rgb: np.ndarray, depth: np.ndarray, mask: np.ndarray, K: np.ndarray):
    _ensure_tuntun_paths()
    import open3d as o3d
    from collision_detector import ModelFreeCollisionDetector
    from data_utils import CameraInfo, create_point_cloud_from_depth_image
    from graspnet import pred_decode
    from graspnetAPI import GraspGroup

    color = rgb.astype(np.float32) / 255.0
    height, width = depth.shape[:2]
    camera_info = CameraInfo(width, height, float(K[0, 0]), float(K[1, 1]), float(K[0, 2]), float(K[1, 2]), 1.0)
    cloud = create_point_cloud_from_depth_image(depth, camera_info, organized=True)

    valid = (mask > 0) & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
    cloud_masked = cloud[valid]
    color_masked = color[valid]
    if len(cloud_masked) == 0:
        raise RuntimeError("No valid masked depth points for GraspNet.")

    num_point = 5000
    if len(cloud_masked) >= num_point:
        idxs = np.random.choice(len(cloud_masked), num_point, replace=False)
    else:
        idxs = np.concatenate(
            [np.arange(len(cloud_masked)), np.random.choice(len(cloud_masked), num_point - len(cloud_masked), replace=True)]
        )
    cloud_sampled = torch.from_numpy(cloud_masked[idxs][None].astype(np.float32)).to(
        torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    )
    end_points = {"point_clouds": cloud_sampled, "cloud_colors": color_masked[idxs]}

    net = _load_graspnet_model()
    with torch.no_grad():
        end_points = net(end_points)
        grasp_preds = pred_decode(end_points)

    gg = GraspGroup(grasp_preds[0].detach().cpu().numpy()).nms().sort_by_score()
    if len(gg) > 128:
        gg = gg[:128]

    cloud_o3d = o3d.geometry.PointCloud()
    cloud_o3d.points = o3d.utility.Vector3dVector(cloud_masked.astype(np.float32))
    cloud_o3d.colors = o3d.utility.Vector3dVector(color_masked.astype(np.float32))
    try:
        detector = ModelFreeCollisionDetector(np.asarray(cloud_o3d.points, dtype=np.float32), voxel_size=0.01)
        collision_mask = detector.detect(gg, approach_dist=0.05, collision_thresh=0.01)
        gg = gg[~collision_mask]
    except Exception as exc:
        print(f"[graspnet] collision check skipped: {exc}")

    gg = gg.sort_by_score()
    grasps = list(gg)
    if not grasps:
        raise RuntimeError("No GraspNet candidates after filtering.")
    center = np.mean(cloud_masked, axis=0)
    # TunTunClaw's empirical selector: prefer grasps near the segmented object centre.
    max_dist = max(np.linalg.norm(g.translation - center) for g in grasps) or 1.0
    best = max(grasps, key=lambda g: float(g.score) * 0.1 + (1.0 - np.linalg.norm(g.translation - center) / max_dist) * 0.9)
    out = GraspGroup()
    out.add(best)
    return out


def _load_graspnet():
    _ensure_tuntun_paths()
    if not CHECKPOINT_PATH.exists():
        raise FileNotFoundError(
            f"GraspNet checkpoint missing: {CHECKPOINT_PATH}. "
            "Download official checkpoint-rs.tar there first."
        )
    return _run_graspnet


def infer_grasp_from_camera(camera, mask: np.ndarray) -> TaskEGrasp:
    """Run TunTunClaw GraspNet and convert the selected grasp to Task-E world pose."""
    rgb, depth, _K, pos_w, quat_wxyz_ros = camera_arrays(camera)
    run_grasp_inference = _load_graspnet()
    gg = run_grasp_inference(rgb, depth, mask, _K)
    if len(gg) == 0:
        raise RuntimeError("GraspNet returned no grasps.")
    grasp = list(gg)[0]

    rot_w_cam = Rotation.from_quat(
        [quat_wxyz_ros[1], quat_wxyz_ros[2], quat_wxyz_ros[3], quat_wxyz_ros[0]]
    ).as_matrix()
    t_cam = np.asarray(grasp.translation, dtype=np.float64)
    t_w = rot_w_cam @ t_cam + pos_w
    valid = (mask > 0) & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
    if np.any(valid):
        ys, xs = np.where(valid)
        z = depth[ys, xs].astype(np.float64)
        x = (xs.astype(np.float64) - float(_K[0, 2])) / float(_K[0, 0]) * z
        y = (ys.astype(np.float64) - float(_K[1, 2])) / float(_K[1, 1]) * z
        pts_cam = np.stack([x, y, z], axis=1)
        pts_w = (rot_w_cam @ pts_cam.T).T + pos_w
        # For top-down Piper execution, the upper object-surface cloud is more
        # stable than a single GraspNet seed point on box/bottle edges.  Keep
        # GraspNet's yaw/width/score, recenter only the execution target.
        z_gate = float(np.percentile(pts_w[:, 2], 70))
        upper = pts_w[pts_w[:, 2] >= z_gate]
        if len(upper) > 16:
            # The highest-score GraspNet seed often sits on a visible edge for
            # Task-E boxes/bottles.  Piper's parallel jaw is more reliable when
            # executed through the segmented object's robust surface centre.
            t_w[:2] = np.median(upper[:, :2], axis=0)
        else:
            t_w[:2] = np.median(pts_w[:, :2], axis=0)
        t_w[2] = float(np.percentile(pts_w[:, 2], 85))

    # GraspNet's first column is the approach axis.  We keep its jaw hint but
    # force the Piper tool z-axis downward because the Task-E IK/top-down setup
    # is much more stable than arbitrary 6-DoF wrist poses.
    R_cam_grasp = np.asarray(grasp.rotation_matrix, dtype=np.float64)
    jaw_hint_w = rot_w_cam @ R_cam_grasp[:, 1]
    jaw_xy = np.array([jaw_hint_w[0], jaw_hint_w[1], 0.0], dtype=np.float64)
    if np.linalg.norm(jaw_xy) < 1e-6:
        jaw_xy = np.array([0.0, 1.0, 0.0], dtype=np.float64)
    jaw_xy = jaw_xy / np.linalg.norm(jaw_xy)
    grip_z = np.array([0.0, 0.0, -1.0], dtype=np.float64)
    align_x = np.cross(jaw_xy, grip_z)
    align_x = align_x / max(np.linalg.norm(align_x), 1e-6)
    jaw_y = np.cross(grip_z, align_x)
    jaw_y = jaw_y / max(np.linalg.norm(jaw_y), 1e-6)
    R_w_tool = np.stack([align_x, jaw_y, grip_z], axis=1)
    quat_xyzw = Rotation.from_matrix(R_w_tool).as_quat()
    quat_wxyz = np.array([quat_xyzw[3], quat_xyzw[0], quat_xyzw[1], quat_xyzw[2]], dtype=np.float64)

    return TaskEGrasp(
        translation_w=t_w.astype(np.float64),
        quat_wxyz_w=quat_wxyz,
        score=float(grasp.score),
        width=float(grasp.width),
        raw_translation_cam=t_cam,
    )


def quat_wxyz_to_torch(quat_wxyz: np.ndarray, device: str) -> torch.Tensor:
    return torch.tensor([quat_wxyz], dtype=torch.float32, device=device)


def pos_to_torch(pos: np.ndarray, device: str) -> torch.Tensor:
    return torch.tensor([pos], dtype=torch.float32, device=device)