"""SO-101 forward kinematics from the URDF (TheRobotStudio/SO-ARM100 at 141aea7, Simulation/SO101/so101_new_calib.urdf), surface points sampled on its visual meshes, and a pinhole camera. Used to find the gripper in the fixed camera's image (scripts/fit_camera.py) for form B referents on the real arm. Joint convention: LeRobot's recorded arm joints in degrees with zero at the middle of the range, which is the URDF's "new calibration" zero; gripper 0 (closed) to 100 (open), mapped linearly onto the URDF gripper limits. """ from __future__ import annotations import math import os import xml.etree.ElementTree as ET import numpy as np import torch ARM_JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper") def rpy_matrix(r, p, y): cr, sr, cp, sp, cy, sy = math.cos(r), math.sin(r), math.cos(p), math.sin(p), math.cos(y), math.sin(y) return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr], [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr], [-sp, cp * sr, cp * cr]]) def origin(el) -> np.ndarray: T = np.eye(4) if el is None: return T xyz = [float(v) for v in el.get("xyz", "0 0 0").split()] rpy = [float(v) for v in el.get("rpy", "0 0 0").split()] T[:3, :3] = rpy_matrix(*rpy) T[:3, 3] = xyz return T def read_stl(path: str) -> np.ndarray: """Binary STL -> (n, 3, 3) triangle vertices.""" with open(path, "rb") as f: f.seek(80) n = int(np.frombuffer(f.read(4), np.uint32)[0]) rec = np.frombuffer(f.read(50 * n), dtype=np.dtype([("nrm", " np.ndarray: a = 0.5 * np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1) k = rng.choice(len(tri), size=n, p=a / a.sum()) u, v = rng.random(n), rng.random(n) m = u + v > 1 u[m], v[m] = 1 - u[m], 1 - v[m] t = tri[k] return t[:, 0] + u[:, None] * (t[:, 1] - t[:, 0]) + v[:, None] * (t[:, 2] - t[:, 0]) class SO101: """Kinematic chain of the URDF. points(q) gives sampled surface points of every link in the base frame; tip(q) the origin of gripper_frame_link (between the fingertips).""" def __init__(self, urdf: str, points_per_link: int = 400, seed: int = 0, exclude: tuple = ()): root = ET.parse(urdf).getroot() base = os.path.dirname(urdf) rng = np.random.default_rng(seed) self.joints = {} for j in root.findall("joint"): self.joints[j.find("child").get("link")] = { "name": j.get("name"), "type": j.get("type"), "parent": j.find("parent").get("link"), "T": origin(j.find("origin")), "axis": np.array([float(v) for v in (j.find("axis").get("xyz") if j.find("axis") is not None else "0 0 1").split()]), "limit": (float(j.find("limit").get("lower")), float(j.find("limit").get("upper"))) if j.find("limit") is not None else None} self.links = [link.get("name") for link in root.findall("link")] self.base = [n for n in self.links if n not in self.joints][0] self.pts = {} for link in root.findall("link"): P = [] for vis in link.findall("visual"): mesh = vis.find("geometry/mesh") if mesh is None or any(x in mesh.get("filename") for x in exclude): continue tri = read_stl(os.path.join(base, mesh.get("filename"))) s = mesh.get("scale") if s: tri = tri * np.array([float(v) for v in s.split()]) p = sample_surface(tri, points_per_link, rng) T = origin(vis.find("origin")) P.append(p @ T[:3, :3].T + T[:3, 3]) if P: self.pts[link.get("name")] = np.concatenate(P) self.order = [] # links in an order where parents come first todo = [n for n in self.links] done = {self.base} while todo: for n in list(todo): if n == self.base: todo.remove(n) elif self.joints[n]["parent"] in done: self.order.append(n); done.add(n); todo.remove(n) def joint_angles(self, q: np.ndarray) -> dict: """q (N, 6): recorded values (degrees; gripper 0-100) -> joint name -> angle in radians (N,).""" out = {} for k, name in enumerate(ARM_JOINTS[:5]): out[name] = np.deg2rad(q[:, k]) lo, hi = [j for j in self.joints.values() if j["name"] == "gripper"][0]["limit"] out["gripper"] = lo + np.clip(q[:, 5], 0, 100) / 100.0 * (hi - lo) return out def link_poses(self, q: np.ndarray) -> dict: """link -> (N, 4, 4) pose in the base frame.""" N = len(q) ang = self.joint_angles(q) poses = {self.base: np.tile(np.eye(4), (N, 1, 1))} for n in self.order: j = self.joints[n] T = poses[j["parent"]] @ j["T"] if j["type"] in ("revolute", "continuous"): th = ang.get(j["name"], np.zeros(N)) R = np.stack([axis_angle(j["axis"], t) for t in th]) M = np.tile(np.eye(4), (N, 1, 1)); M[:, :3, :3] = R T = T @ M poses[n] = T return poses def points(self, q: np.ndarray) -> np.ndarray: """(N, P, 3) surface points in the base frame; the same point order for every frame.""" poses = self.link_poses(q) out = [np.einsum("nij,pj->npi", poses[n][:, :3, :3], p) + poses[n][:, None, :3, 3] for n, p in self.pts.items()] return np.concatenate(out, 1) def tip(self, q: np.ndarray) -> np.ndarray: return self.link_poses(q)["gripper_frame_link"][:, :3, 3] def axis_angle(axis: np.ndarray, t: float) -> np.ndarray: a = axis / np.linalg.norm(axis) K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]]) return np.eye(3) + math.sin(t) * K + (1 - math.cos(t)) * K @ K def rotvec_to_matrix(w: torch.Tensor) -> torch.Tensor: th = w.norm().clamp_min(1e-9) k = w / th K = torch.zeros(3, 3, dtype=w.dtype, device=w.device) K[0, 1], K[0, 2], K[1, 0], K[1, 2], K[2, 0], K[2, 1] = -k[2], k[1], k[2], -k[0], -k[1], k[0] return torch.eye(3, dtype=w.dtype, device=w.device) + torch.sin(th) * K + (1 - torch.cos(th)) * K @ K def project(X: torch.Tensor, cam: dict) -> tuple[torch.Tensor, torch.Tensor]: """X (..., 3) in the base frame -> pixel (..., 2) and depth (...). cam: rotvec (3), t (3) base->camera, f (2) focal lengths in pixels (x, y), c (2) principal point; OpenCV axes (x right, y down, z forward).""" R = rotvec_to_matrix(cam["rotvec"]) Y = X @ R.T + cam["t"] z = Y[..., 2] xy = Y[..., :2] / z.clamp_min(1e-3)[..., None] if "k1" in cam: # radial distortion on normalized coordinates (OpenCV k1, k2) r2 = (xy ** 2).sum(-1, keepdim=True) xy = xy * (1 + cam["k1"] * r2 + cam.get("k2", 0.0) * r2 ** 2) uv = xy * cam["f"] + cam["c"] return uv, z class SO101Torch(torch.nn.Module): """Differentiable forward kinematics of an SO101 model: surface points and tip in the base frame from recorded joints (degrees; gripper 0-100) plus per-joint offsets (degrees, learnable by the caller).""" def __init__(self, arm: SO101, device): super().__init__() self.chain = [] for n in arm.order: j = arm.joints[n] a = j["axis"] / np.linalg.norm(j["axis"]) if np.linalg.norm(j["axis"]) > 0 else np.array([0.0, 0.0, 1.0]) K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]]) k = ARM_JOINTS.index(j["name"]) if j["name"] in ARM_JOINTS else -1 self.chain.append({"link": n, "parent": j["parent"], "T": torch.tensor(j["T"], dtype=torch.float32, device=device), "K": torch.tensor(K, dtype=torch.float32, device=device), "k": k, "rev": j["type"] in ("revolute", "continuous")}) self.base = arm.base self.links = list(arm.pts) self.pts = {n: torch.tensor(p, dtype=torch.float32, device=device) for n, p in arm.pts.items()} lo, hi = [j for j in arm.joints.values() if j["name"] == "gripper"][0]["limit"] self.glim = (lo, hi) def poses(self, q: torch.Tensor, off: torch.Tensor) -> dict: N = q.shape[0] ang = torch.deg2rad(q[:, :5] + off[:5]) g = self.glim[0] + q[:, 5].clamp(0, 100) / 100.0 * (self.glim[1] - self.glim[0]) ang = torch.cat([ang, g[:, None]], 1) eye = torch.eye(4, device=q.device) P = {self.base: eye.expand(N, 4, 4)} for c in self.chain: T = P[c["parent"]] @ c["T"] if c["rev"] and c["k"] >= 0: th = ang[:, c["k"]][:, None, None] R = torch.eye(3, device=q.device) + torch.sin(th) * c["K"] + (1 - torch.cos(th)) * (c["K"] @ c["K"]) M = torch.zeros(N, 4, 4, device=q.device); M[:, :3, :3] = R; M[:, 3, 3] = 1 T = T @ M P[c["link"]] = T return P def points(self, q, off): P = self.poses(q, off) return torch.cat([torch.einsum("nij,pj->npi", P[n][:, :3, :3], p) + P[n][:, None, :3, 3] for n, p in self.pts.items()], 1) def tip(self, q, off): return self.poses(q, off)["gripper_frame_link"][:, :3, 3]