File size: 8,681 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
"""AnyGrasp SDK bridge for ATEC Task E.

AnyGrasp predicts grasp candidates from RGB-D point clouds in the camera frame.
For Task E we keep the same execution contract as the TunTun/GraspNet adapter:
use the model for contact centre, jaw yaw, score and width, then hand a
top-down-friendly world-frame ``TaskEGrasp`` to the existing Piper primitive.
"""

from __future__ import annotations

from functools import lru_cache
from pathlib import Path
import ctypes
import os
import sys

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

from scripts.graspnet_task_e.tuntun_adapter import TaskEGrasp, camera_arrays


REPO_ROOT = Path(__file__).resolve().parents[2]
ANYGRASP_ROOT = REPO_ROOT / "third_party" / "anygrasp_sdk"
DETECTION_ROOT = ANYGRASP_ROOT / "grasp_detection"
CHECKPOINT_PATH = DETECTION_ROOT / "log" / "checkpoint_detection.tar"
SSL11_DIR = Path(
    "/home/ubuntu/projects/manipdojo2026/micromamba/envs/genmanip-sim/lib/python3.10/site-packages/"
    "isaacsim/exts/omni.isaac.ros2_bridge/humble/lib"
)
TOOLS_DIR = REPO_ROOT / "tools" / "anygrasp"


def _ensure_anygrasp_paths() -> None:
    det = str(DETECTION_ROOT)
    if det not in sys.path:
        sys.path.insert(0, det)
    tools = str(TOOLS_DIR)
    old_path = os.environ.get("PATH", "")
    if TOOLS_DIR.exists() and tools not in old_path.split(":"):
        os.environ["PATH"] = f"{tools}:{old_path}" if old_path else tools
    ssl = str(SSL11_DIR)
    old_ld = os.environ.get("LD_LIBRARY_PATH", "")
    if SSL11_DIR.exists() and ssl not in old_ld.split(":"):
        os.environ["LD_LIBRARY_PATH"] = f"{ssl}:{old_ld}" if old_ld else ssl
    # lib_cxx.so is linked against OpenSSL 1.1.  In long-running Isaac Python
    # processes, changing LD_LIBRARY_PATH after startup is not enough, so load
    # the exact libraries by absolute path before importing gsnet/lib_cxx.
    for name in ("libcrypto.so.1.1", "libssl.so.1.1"):
        path = SSL11_DIR / name
        if path.exists():
            ctypes.CDLL(str(path), mode=ctypes.RTLD_GLOBAL)


def _check_anygrasp_files() -> None:
    missing = []
    for path in [
        DETECTION_ROOT / "gsnet.so",
        DETECTION_ROOT / "lib_cxx.so",
        DETECTION_ROOT / "license" / "licenseCfg.json",
        CHECKPOINT_PATH,
    ]:
        if not path.exists():
            missing.append(str(path))
    if missing:
        raise FileNotFoundError("AnyGrasp SDK is not fully installed:\n" + "\n".join(missing))


@lru_cache(maxsize=1)
def _load_anygrasp_detector():
    _ensure_anygrasp_paths()
    _check_anygrasp_files()
    from argparse import Namespace
    from gsnet import AnyGrasp

    cfg = Namespace(
        checkpoint_path=str(CHECKPOINT_PATH),
        max_gripper_width=0.085,
        gripper_height=0.03,
        top_down_grasp=True,
        debug=False,
    )
    detector = AnyGrasp(cfg)
    detector.load_net()
    return detector


def _points_from_rgbd(
    rgb: np.ndarray,
    depth: np.ndarray,
    mask: np.ndarray,
    K: np.ndarray,
    *,
    expand_px: int = 0,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    use_mask = mask > 0
    if expand_px > 0 and np.any(use_mask):
        ys0, xs0 = np.where(use_mask)
        y1 = max(int(ys0.min()) - expand_px, 0)
        y2 = min(int(ys0.max()) + expand_px + 1, mask.shape[0])
        x1 = max(int(xs0.min()) - expand_px, 0)
        x2 = min(int(xs0.max()) + expand_px + 1, mask.shape[1])
        use_mask = np.zeros_like(use_mask, dtype=bool)
        use_mask[y1:y2, x1:x2] = True
    valid = use_mask & np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)
    ys, xs = np.where(valid)
    if len(xs) == 0:
        raise RuntimeError("No valid masked depth points for AnyGrasp.")

    z = depth[ys, xs].astype(np.float32)
    x = (xs.astype(np.float32) - float(K[0, 2])) / float(K[0, 0]) * z
    y = (ys.astype(np.float32) - float(K[1, 2])) / float(K[1, 1]) * z
    points = np.stack([x, y, z], axis=1).astype(np.float32)
    colors = (rgb[ys, xs, :3].astype(np.float32) / 255.0).astype(np.float32)
    return points, colors, np.stack([ys, xs], axis=1)


def _lims_for_points(points: np.ndarray, pad: float = 0.04) -> list[float]:
    lo = points.min(axis=0)
    hi = points.max(axis=0)
    return [
        float(lo[0] - pad),
        float(hi[0] + pad),
        float(lo[1] - pad),
        float(hi[1] + pad),
        float(max(0.0, lo[2] - pad)),
        float(hi[2] + pad),
    ]


def _select_anygrasp_candidate(gg, points_cam: np.ndarray):
    if gg is None or len(gg) == 0:
        raise RuntimeError("AnyGrasp returned no grasps after filtering.")
    gg = gg.nms().sort_by_score()
    grasps = list(gg)
    if not grasps:
        raise RuntimeError("AnyGrasp returned no grasps after filtering.")

    center = np.median(points_cam, axis=0)
    spread = float(np.linalg.norm(np.percentile(points_cam, 90, axis=0) - np.percentile(points_cam, 10, axis=0)))
    spread = max(spread, 1e-3)

    def rank(g) -> float:
        dist = float(np.linalg.norm(np.asarray(g.translation, dtype=np.float64) - center))
        # Keep score dominant, but reject edge candidates that are far from the
        # segmented object core. This mirrors the proven GraspNet selector.
        return float(g.score) * 0.65 + max(0.0, 1.0 - dist / spread) * 0.35

    return max(grasps[:128], key=rank)


def infer_anygrasp_from_camera(camera, mask: np.ndarray) -> TaskEGrasp:
    """Run AnyGrasp SDK and convert the selected grasp to Task-E world pose."""
    rgb, depth, K, pos_w, quat_wxyz_ros = camera_arrays(camera)
    detector = _load_anygrasp_detector()
    attempts = [
        (0, 0.04, True, False, True),
        (0, 0.08, False, False, False),
        (24, 0.08, False, False, False),
    ]
    last_error: Exception | None = None
    points_cam = colors = None
    grasp = None
    for expand_px, lim_pad, apply_object_mask, dense_grasp, collision_detection in attempts:
        try:
            points_cam, colors, _pixels = _points_from_rgbd(rgb, depth, mask, K, expand_px=expand_px)
            if len(points_cam) < 64:
                raise RuntimeError(f"Too few masked points for AnyGrasp: {len(points_cam)}")
            lims = _lims_for_points(points_cam, pad=lim_pad)
            print(
                "[ANYGRASP] "
                f"points={len(points_cam)} expand_px={expand_px} lim_pad={lim_pad:.3f} "
                f"object_mask={apply_object_mask} dense={dense_grasp} collision={collision_detection}",
                flush=True,
            )
            gg, _cloud = detector.get_grasp(
                points_cam,
                colors,
                lims=lims,
                apply_object_mask=apply_object_mask,
                dense_grasp=dense_grasp,
                collision_detection=collision_detection,
            )
            grasp = _select_anygrasp_candidate(gg, points_cam)
            break
        except Exception as exc:
            last_error = exc
            print(f"[ANYGRASP] attempt failed: {exc}", flush=True)
    if grasp is None or points_cam is None:
        raise RuntimeError(f"AnyGrasp failed for all attempts: {last_error}")

    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

    pts_w = (rot_w_cam @ points_cam.astype(np.float64).T).T + pos_w
    z_gate = float(np.percentile(pts_w[:, 2], 70))
    upper = pts_w[pts_w[:, 2] >= z_gate]
    if len(upper) > 16:
        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))

    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,
    )