File size: 8,531 Bytes
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Jaw and piece profiles, cut from the collision meshes the physics actually uses.

The SO-101 fingers form a V that opens upward: the inner faces lean outward by a
few degrees. Pointing down with the fingertips just below a piece's head, the jaws
close on the head, the way a person pinches a piece. If the squeeze slips, the head
still rests on the tips, because the tip gap is narrower than the head.

All lengths in metres. Gripper frame: -z toward the fingertips, +x from the fixed
jaw toward the moving jaw, y across the finger width.
"""
from __future__ import annotations

from dataclasses import dataclass

import mujoco
import numpy as np

STEP = 0.0005            # profile sample spacing along the height
FINGER_BAND = 0.0045     # half-width of the finger strip that must clear the piece


def _triangles(m, d, geom_ids, frame_body):
    """Collision triangles (N, 3, 3) of `geom_ids`, in `frame_body`'s frame."""
    R = d.xmat[frame_body].reshape(3, 3)
    out = []
    for g in geom_ids:
        mid = m.geom_dataid[g]
        v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]].astype(float)
        f = m.mesh_face[m.mesh_faceadr[mid]:m.mesh_faceadr[mid] + m.mesh_facenum[mid]]
        w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g]
        out.append(((w - d.xpos[frame_body]) @ R)[f])
    return np.concatenate(out)


def section_extent(tris, heights, along, across, band):
    """Min and max of `along`·p over each horizontal section, restricted to |across·p| < band.

    Exact for the triangle soup: every triangle crossing a plane gives a segment,
    which is clipped to the band. Returns (lo, hi) arrays, NaN where empty.
    """
    lo = np.full(len(heights), np.nan)
    hi = np.full(len(heights), np.nan)
    z = tris[:, :, 2]
    zmin, zmax = z.min(1), z.max(1)
    for i, h in enumerate(heights):
        t = tris[(zmin <= h) & (zmax > h)]
        if not len(t):
            continue
        pts = []
        for a, b in ((0, 1), (1, 2), (2, 0)):
            pa, pb = t[:, a], t[:, b]
            cross = (pa[:, 2] - h) * (pb[:, 2] - h) < 0
            s = np.where(cross, (h - pa[:, 2]) / np.where(cross, pb[:, 2] - pa[:, 2], 1), np.nan)
            pts.append(pa[:, :2] + (pb[:, :2] - pa[:, :2]) * s[:, None])
        pts = np.stack(pts, 1)                          # (n, 3 edges, 2)
        ok = ~np.isnan(pts[:, :, 0])
        keep = ok.sum(1) == 2
        segs = pts[keep][ok[keep]].reshape(-1, 2, 2)    # (n, 2 endpoints, xy)
        u = segs @ along                                # (n, 2)
        w = segs @ across
        # Clip each segment to |w| <= band.
        w0, w1, u0, u1 = w[:, 0], w[:, 1], u[:, 0], u[:, 1]
        dw = np.where(np.abs(w1 - w0) < 1e-12, 1e-12, w1 - w0)
        ta = np.clip((-band - w0) / dw, 0, 1)
        tb = np.clip((band - w0) / dw, 0, 1)
        t0, t1 = np.minimum(ta, tb), np.maximum(ta, tb)
        inside = (t1 > t0) | ((np.abs(w0) <= band) & (np.abs(w1) <= band))
        t0 = np.where(np.abs(w1 - w0) < 1e-12, 0, t0)
        t1 = np.where(np.abs(w1 - w0) < 1e-12, 1, t1)
        if not inside.any():
            continue
        ua = u0 + (u1 - u0) * t0
        ub = u0 + (u1 - u0) * t1
        vals = np.concatenate([ua[inside], ub[inside]])
        lo[i], hi[i] = vals.min(), vals.max()
    return lo, hi


@dataclass
class Jaws:
    tip_z: float              # lowest fixed-fingertip point, gripper frame
    heights: np.ndarray       # sample heights above the tip
    fixed_inner: np.ndarray   # max x of the fixed finger (its inner face)
    fixed_outer: np.ndarray   # min x of the fixed finger
    jaw_tris: np.ndarray      # moving-jaw collision triangles, moving-jaw frame
    jaw_pos: np.ndarray       # moving-jaw frame origin in the gripper frame (q = 0)
    jaw_rot: np.ndarray
    jaw_axis: np.ndarray      # hinge axis, moving-jaw frame

    def moving_tris(self, q: float) -> np.ndarray:
        a = self.jaw_axis
        K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]])
        Rq = np.eye(3) + np.sin(q) * K + (1 - np.cos(q)) * K @ K
        return (self.jaw_tris @ Rq.T) @ self.jaw_rot.T + self.jaw_pos

    def moving_profile(self, q: float, heights=None):
        """(inner, outer) x of the moving finger per height above the tip."""
        h = self.heights if heights is None else heights
        lo, hi = section_extent(self.moving_tris(q), self.tip_z + h,
                                np.array([1.0, 0]), np.array([0, 1.0]), FINGER_BAND)
        return lo, hi


def measure_jaws(m: mujoco.MjModel, top=0.06) -> Jaws:
    d = mujoco.MjData(m)
    gid = m.joint("gripper").id
    mujoco.mj_kinematics(m, d)
    gb, jb = m.body("gripper").id, m.body("moving_jaw_so101_v1").id
    fixed_geoms = [g for g in range(m.ngeom) if m.geom_bodyid[g] == gb and m.geom_group[g] == 3
                   and m.mesh(m.geom_dataid[g]).name.startswith("wrist_roll_follower")]
    jaw_geoms = [g for g in range(m.ngeom) if m.geom_bodyid[g] == jb and m.geom_group[g] == 3]
    fixed = _triangles(m, d, fixed_geoms, gb)
    jaw = _triangles(m, d, jaw_geoms, jb)
    Rg = d.xmat[gb].reshape(3, 3)
    # Express the moving jaw at q = 0 regardless of the model's default gripper angle.
    q0 = d.qpos[m.jnt_qposadr[gid]]
    a = m.jnt_axis[gid]
    K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]])
    Rq0 = np.eye(3) + np.sin(q0) * K + (1 - np.cos(q0)) * K @ K
    jaw_rot = Rg.T @ d.xmat[jb].reshape(3, 3) @ Rq0.T
    jaw_pos = Rg.T @ (d.xpos[jb] - d.xpos[gb])
    tip_z = fixed[:, :, 2].min()
    heights = np.arange(STEP / 2, top, STEP)
    lo, hi = section_extent(fixed, tip_z + heights, np.array([1.0, 0]), np.array([0, 1.0]), FINGER_BAND)
    return Jaws(tip_z=tip_z, heights=heights, fixed_inner=hi, fixed_outer=lo,
                jaw_tris=jaw, jaw_pos=jaw_pos, jaw_rot=jaw_rot, jaw_axis=a.copy())


@dataclass
class PieceProfile:
    heights: np.ndarray      # sample heights above the base
    lo: np.ndarray           # min coordinate along the closing direction (NaN = no material)
    hi: np.ndarray           # max coordinate along the closing direction
    height: float


def piece_triangles(m: mujoco.MjModel, body: str) -> np.ndarray:
    """Collision triangles of a piece body in its own frame (base at z=0)."""
    d = mujoco.MjData(m)
    mujoco.mj_kinematics(m, d)
    bid = m.body(body).id
    geoms = [g for g in range(m.ngeom) if m.geom_bodyid[g] == bid and m.geom_group[g] == 3]
    return _triangles(m, d, geoms, bid)


def piece_profile(tris: np.ndarray, closing_dir) -> PieceProfile:
    """What the jaws see of a piece closing along `closing_dir` (unit xy, piece frame)."""
    u = np.asarray(closing_dir, float)
    v = np.array([-u[1], u[0]])
    height = float(tris[:, :, 2].max())
    heights = np.arange(STEP / 2, height, STEP)
    lo, hi = section_extent(tris, heights, u, v, FINGER_BAND)
    return PieceProfile(heights=heights, lo=lo, hi=hi, height=height)


@dataclass
class Grasp:
    tip_height: float        # fingertip height above the piece base
    center_x: float          # piece axis x in the gripper frame
    open_q: float            # gripper angle that clears the piece by the margin
    contact_q: float         # predicted gripper angle at first contact
    contact_height: float    # height above the base of first moving-jaw contact


def plan_grasp(jaws: Jaws, piece: PieceProfile, tip_height: float,
               fixed_gap=0.0008, open_margin=0.003) -> Grasp:
    """Put the piece `fixed_gap` off the fixed finger and find the jaw angles."""
    z = piece.heights
    sel = (z >= tip_height) & ~np.isnan(piece.hi)
    rel = z[sel] - tip_height
    fixed = np.interp(rel, jaws.heights, jaws.fixed_inner)
    center = float(np.max(fixed - piece.lo[sel]) + fixed_gap)
    right = center + piece.hi[sel]

    def clearance(q):
        inner, _ = jaws.moving_profile(q, rel)
        gap = np.where(np.isnan(inner), np.inf, inner - right)   # no finger at that height
        return float(gap.min()), int(gap.argmin())

    lo, hi = -0.25, 1.2
    for _ in range(30):
        mid = (lo + hi) / 2
        lo, hi = (lo, mid) if clearance(mid)[0] > 0 else (mid, hi)
    contact_q = hi
    at = clearance(contact_q)[1]
    lo, hi = contact_q, 1.2
    for _ in range(30):
        mid = (lo + hi) / 2
        lo, hi = (lo, mid) if clearance(mid)[0] > open_margin else (mid, hi)
    return Grasp(tip_height=tip_height, center_x=center, open_q=hi, contact_q=contact_q,
                 contact_height=float(z[sel][at]))