Download chess-sim/code/sim/grasp_geometry.py from Machanize/playful: direct link, hf CLI and curl.
- Browser
- Download file 8.53 kB
-
https://huggingface.co/datasets/Machanize/playful/resolve/main/chess-sim/code/sim/grasp_geometry.py
- Command line
-
hf download hf://datasets/Machanize/playful/chess-sim/code/sim/grasp_geometry.py
-
curl -L -o grasp_geometry.py https://huggingface.co/datasets/Machanize/playful/resolve/main/chess-sim/code/sim/grasp_geometry.py
8.53 kB
| """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 | |
| 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()) | |
| 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) | |
| 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])) | |