"""Inverse kinematics for the SO-101 with the gripper pointing straight down. The arm has five joints before the gripper: pan, lift, elbow, wrist flex, wrist roll. With the gripper vertical, those five set the pinch point's position (3) and the jaws' yaw on the table (1), and one more constraint (vertical) is met by wrist flex. So any reachable (point, yaw) pair has an exact solution. A tilt can be added for far reaches: the fingertips lean outward, away from the base, within the arm's own vertical plane (rotation about the shoulder-lift axis), which the five joints can still reach exactly. Near the edge of reach 10 degrees of tilt about doubles the height the pinch point can be lifted to. A negative tilt leans the fingertips inward, toward the base, which moves the hand's top (wrist and wrist camera) away from the shoulder when working close to the arm. Frames: the `gripper` body's -z axis runs from the wrist toward the fingertips and its +x axis is the closing direction, from the fixed jaw toward the moving jaw. """ from __future__ import annotations import mujoco import numpy as np ARM_JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll") GRIPPER_JOINT = "gripper" def yaw_rotation(yaw: float) -> np.ndarray: """Gripper-body orientation in the world: pointing down, closing along `yaw`.""" c, s = np.cos(yaw), np.sin(yaw) x = np.array([c, s, 0.0]) z = np.array([0.0, 0.0, 1.0]) # body +z points up, so the fingers point down return np.column_stack([x, np.cross(z, x), z]) class Kinematics: def __init__(self, model: mujoco.MjModel): self.m = model self.d = mujoco.MjData(model) self.qadr = np.array([model.jnt_qposadr[model.joint(j).id] for j in ARM_JOINTS]) self.vadr = np.array([model.jnt_dofadr[model.joint(j).id] for j in ARM_JOINTS]) self.lo = model.jnt_range[[model.joint(j).id for j in ARM_JOINTS], 0] self.hi = model.jnt_range[[model.joint(j).id for j in ARM_JOINTS], 1] self.body = model.body("gripper").id self.lift_joint = model.joint("shoulder_lift").id self._jp = np.zeros((3, model.nv)) self._jr = np.zeros((3, model.nv)) def _set(self, q): self.d.qpos[self.qadr] = q mujoco.mj_kinematics(self.m, self.d) mujoco.mj_comPos(self.m, self.d) def pose(self, q, offset=np.zeros(3)): """World position of a gripper-frame point, and the gripper rotation.""" self._set(q) R = self.d.xmat[self.body].reshape(3, 3).copy() return self.d.xpos[self.body] + R @ offset, R def target_rotation(self, target, yaw, tilt): """Gripper orientation for jaw `yaw`, fingertips tilted outward by `tilt` rad (inward, toward the base, if `tilt` is negative). Uses the shoulder-lift axis of the configuration last set (its pan).""" Rt = yaw_rotation(yaw) if tilt == 0.0: return Rt outward = tilt > 0 tilt = abs(tilt) a = self.d.xaxis[self.lift_joint].copy() a[2] = 0.0 a /= np.linalg.norm(a) out = np.asarray(target[:2]) - self.d.xanchor[self.lift_joint][:2] K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]]) for sign in (1.0, -1.0): Rtilt = np.eye(3) + np.sin(sign * tilt) * K + (1 - np.cos(sign * tilt)) * K @ K fingers = -Rtilt[:, 2] if (fingers[:2] @ out > 0) == outward: return Rtilt @ Rt return Rt def solve(self, target, yaw, offset, q0, iters=200, tol=2e-5, tilt=0.0): """Joint angles putting `offset` (gripper frame) at `target`, gripper down at `yaw` and leaning outward by `tilt`. Returns (q, position error m, orientation error rad). """ q = np.clip(np.asarray(q0, float).copy(), self.lo, self.hi) for _ in range(iters): p, R = self.pose(q, offset) Rt = self.target_rotation(target, yaw, tilt) e_pos = target - p e_rot = 0.5 * sum(np.cross(R[:, i], Rt[:, i]) for i in range(3)) if np.linalg.norm(e_pos) < tol and np.linalg.norm(e_rot) < tol * 20: break mujoco.mj_jac(self.m, self.d, self._jp, self._jr, p, self.body) J = np.vstack([self._jp[:, self.vadr], 0.05 * self._jr[:, self.vadr]]) e = np.concatenate([e_pos, 0.05 * e_rot]) dq = J.T @ np.linalg.solve(J @ J.T + 1e-8 * np.eye(6), e) step = np.max(np.abs(dq)) if step > 0.2: dq *= 0.2 / step q = np.clip(q + dq, self.lo, self.hi) p, R = self.pose(q, offset) Rt = self.target_rotation(target, yaw, tilt) e_rot = 0.5 * sum(np.cross(R[:, i], Rt[:, i]) for i in range(3)) return q, float(np.linalg.norm(target - p)), float(np.linalg.norm(e_rot)) def solve_global(self, target, yaw, offset, q0=None, tilt=0.0): """Multi-start solve for waypoints far from any known configuration.""" pan = np.arctan2(target[1], target[0]) starts = [] if q0 is None else [np.asarray(q0, float)] for lift, elbow, flex in ((0.0, 0.0, 1.5), (0.5, -0.2, 1.3), (-0.6, 0.9, 1.3), (-1.0, 1.3, 1.4)): for roll in np.linspace(-2.4, 2.4, 7): starts.append(np.array([pan, lift, elbow, flex, roll])) best = None for s in starts: q, ep, er = self.solve(target, yaw, offset, s, iters=150, tilt=tilt) score = ep + 0.02 * er if best is None or score < best[3]: best = (q, ep, er, score) if ep < 1e-4 and er < 2e-3: break return best[:3]