Picking a box off a table and placing it somewhere else with a 6-axis arm is, before any learned policy enters the picture, a handful of coordinate frames and a few matrix products. This post works through the minimum math for one pick-and-place cycle in NumPy, using the Universal Robots UR5e — which has a published DH table — and its MuJoCo Menagerie model as the reference. By the end you should know which frame each coordinate belongs in, what to compare forward and inverse kinematics results against, and where to look first when IK refuses to converge.
If MuJoCo is not installed yet, start with the MuJoCo and LeRobot version-matching install guide; if you are still choosing a simulator, the MuJoCo vs Isaac Lab vs PyBullet vs Genesis comparison is the better starting point. The code below targets the mujoco 3.17.0 Python package and NumPy 2.x.
The six frames in one pick-and-place cycle
Fix the frame names before writing any code. This post writes a transform as and reads it as “the pose of frame b seen from frame a”. With that convention, only works when the inner subscripts match, so ordering mistakes become visible on the page.
| Frame | Symbol | Defined by | Role in pick-and-place |
|---|---|---|---|
| World | world | Cell layout (e.g. a table corner) | Common reference tying robots and cameras together |
| Base | base | Where the robot is mounted | The frame IK targets are expressed in |
| Flange (end effector) | ee | Manufacturer’s DH table | Output of forward kinematics |
| Tool (TCP) | tcp | Gripper geometry | The point that actually touches the object; is constant |
| Camera | cam | Calibration result or MJCF | Reference for turning pixels into 3D points |
| Object | obj | Perception output | The grasp target |
The whole calculation reduces to two chains built from that table.
The first moves what the camera sees into the robot’s frame. The second answers “where must the flange be so that the TCP sits on the grasp pose above the object?” Turning that flange goal into joint angles is inverse kinematics.
Building and inverting homogeneous transforms in NumPy
A homogeneous transform packs a rotation and a translation into a 4×4 matrix. Rather than calling a general matrix inverse, use the structure directly: . It avoids accumulating numerical error, and it is exactly what TransInv in the Modern Robotics code library does.
import numpy as np
def make_T(R, p):
T = np.eye(4)
T[:3, :3] = R
T[:3, 3] = p
return T
def inv_T(T):
R, p = T[:3, :3], T[:3, 3]
return make_T(R.T, -R.T @ p)
def rot_z(theta):
c, s = np.cos(theta), np.sin(theta)
return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
# Assume the gripper TCP sits 0.15 m along the flange +Z axis
T_ee_tcp = make_T(np.eye(3), [0, 0, 0.15])
# Pre-grasp pose 10 cm above the object, TCP pointing down (180 deg about X)
R_down = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]])
T_obj_pregrasp = make_T(R_down, [0, 0, 0.10])
When writing a rotation such as R_down by hand, remember that its three columns are the child frame’s x, y and z axes expressed in the parent frame. Checking that the determinant is +1 (np.linalg.det(R_down)) catches an accidental left-handed frame immediately.
Forward kinematics from the official UR5e DH table
The Universal Robots DH parameter article publishes the values below for the UR5e/UR7e. It refers to the standard (classic) DH definition on Wikipedia and notes that UR’s a corresponds to Wikipedia’s r. The joint variable is not in the table; each joint angle goes in directly.
| Joint | a [m] | d [m] | α [rad] |
|---|---|---|---|
| 1 | 0 | 0.1625 | π/2 |
| 2 | -0.425 | 0 | 0 |
| 3 | -0.3922 | 0 | 0 |
| 4 | 0 | 0.1333 | π/2 |
| 5 | 0 | 0.0997 | -π/2 |
| 6 | 0 | 0.0996 | 0 |
In standard DH, one link contributes , and forward kinematics is the product .
import numpy as np
def dh(a, d, alpha, theta):
ct, st = np.cos(theta), np.sin(theta)
ca, sa = np.cos(alpha), np.sin(alpha)
return np.array([[ct, -st*ca, st*sa, a*ct],
[st, ct*ca, -ct*sa, a*st],
[0, sa, ca, d],
[0, 0, 0, 1]])
A = [0, -0.425, -0.3922, 0, 0, 0]
D = [0.1625, 0, 0, 0.1333, 0.0997, 0.0996]
ALPHA = [np.pi/2, 0, 0, np.pi/2, -np.pi/2, 0]
def fk(q):
T = np.eye(4)
for i in range(6):
T = T @ dh(A[i], D[i], ALPHA[i], q[i])
return T
np.set_printoptions(precision=4, suppress=True)
print(fk(np.zeros(6))[:3, 3]) # [-0.8172 -0.2329 0.0628]
home = np.array([-1.5708, -1.5708, 1.5708, -1.5708, -1.5708, 0])
print(fk(home)[:3, 3]) # [-0.1333 0.4919 0.4879]
With every joint at zero, x = -0.8172 m is simply , y = -0.2329 m is , and z = 0.0628 m is . Having one pose you can verify with mental arithmetic from the table is the quickest way to catch a sign error in the code.
Cross-checking FK against the MuJoCo Menagerie UR5e
The Menagerie UR5e is an MJCF model converted from the ros-industrial URDF, and it requires MuJoCo 2.3.3 or later. Its ur5e.xml explicitly sets compiler angle="radian", defines an attachment_site on the last link, and ships a home keyframe. The XML reference states that MJCF angles default to degrees, so check that attribute first whenever you bring in a different model.
- Clone the Menagerie repository and run from the directory above
universal_robots_ur5e(the meshes inassets/must be present for the model to load). - Write the joint angles into
qposand callmj_kinematicsto update body and site poses. - Read
site_xpos(nsite×3) andsite_xmat(nsite×9, a flattened 3×3 rotation) and compare them with the DH result.
import numpy as np
import mujoco
m = mujoco.MjModel.from_xml_path("universal_robots_ur5e/ur5e.xml")
d = mujoco.MjData(m)
site = m.site("attachment_site").id
for q in [np.zeros(6), np.array([-1.5708, -1.5708, 1.5708, -1.5708, -1.5708, 0])]:
d.qpos[:] = q
mujoco.mj_kinematics(m, d)
print(d.site_xpos[site], d.site_xmat[site].reshape(3, 3))
# zero pose: [-0.817 -0.234 0.063]
# home pose: [-0.134 0.492 0.488]
Both poses agree with the DH result to within about 1 mm, and the rotation matrices are identical. The remaining gap exists because the MJCF rounds link offsets differently from the DH table — pos="0 0 0.163" and pos="0 0 0.392" versus 0.1625 and 0.3922. The Menagerie base body also carries quat="0 0 0 -1" (a 180° turn about Z); the fact that results still match means that, with this rotation included, the Menagerie world frame is oriented the same way as the UR DH base frame. Another arm’s model may not include such a fixed rotation, so always compare at least one pose.
Solving IK with damped least squares
Inverse kinematics repeatedly maps the error between goal and current pose, (3 position + 3 rotation), back into joint space through the Jacobian. In the Modern Robotics code library, IKinSpace is a Newton-Raphson iteration that multiplies a twist error obtained from the matrix logarithm by the Jacobian pseudo-inverse (np.linalg.pinv), with a hard-coded default of 20 iterations. To tame the large joint steps that the pseudo-inverse produces near singularities, add a damping term — damped least squares (DLS):
With this reduces to the pseudo-inverse; a larger gives smaller, steadier steps. For the rotation error, the code uses the small-angle approximation (the sum of cross products of the current and goal rotation-matrix columns). When the goal orientation is far from the current one, the matrix-log approach used in the textbook is more accurate.
In MuJoCo, mj_jacSite fills the positional Jacobian jacp and rotational Jacobian jacr of a site (3×nv each, world-aligned axes). The API docs say that for the Jacobian to be consistent with qpos, mj_kinematics must be followed by mj_comPos.
import numpy as np
import mujoco
m = mujoco.MjModel.from_xml_path("universal_robots_ur5e/ur5e.xml")
d = mujoco.MjData(m)
sid = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_SITE, "attachment_site")
mujoco.mj_resetDataKeyframe(m, d, m.key("home").id)
mujoco.mj_kinematics(m, d)
target = d.site_xpos[sid] + np.array([0.10, -0.05, -0.30]) # grasp point
R_target = d.site_xmat[sid].reshape(3, 3).copy() # keep orientation
jacp = np.zeros((3, m.nv))
jacr = np.zeros((3, m.nv))
lam = 0.05
for it in range(200):
mujoco.mj_kinematics(m, d)
mujoco.mj_comPos(m, d)
R = d.site_xmat[sid].reshape(3, 3)
e = np.hstack([target - d.site_xpos[sid],
0.5 * sum(np.cross(R[:, i], R_target[:, i]) for i in range(3))])
if np.linalg.norm(e) < 1e-4:
break
mujoco.mj_jacSite(m, d, jacp, jacr, sid)
J = np.vstack([jacp, jacr])
d.qpos[:] += J.T @ np.linalg.solve(J @ J.T + lam**2 * np.eye(6), e)
d.qpos[:] = np.clip(d.qpos, m.jnt_range[:, 0], m.jnt_range[:, 1])
print(it, d.qpos.round(4))
# 4 [-1.8011 -1.4184 2.2707 -2.4231 -1.5708 -0.2303]
A goal offset from home by +10 cm in x, -5 cm in y and -30 cm in z converges after 4 iterations with about 0.026 mm of position error. Solving the same goal with the DH fk from the previous section and a geometric Jacobian (built from each joint’s z-axis and origin as , ) yields joint angles within 0.001 rad of these, the residual coming from the same link-offset rounding. Adding dq straight into qpos, as above, is only valid because every joint is a hinge and nq == nv; with ball or free joints in the model, use mj_integratePos.
A pick-and-place cycle chains these IK solves rather than running one:
- Compute the flange goal for the pre-grasp pose (10 cm along the object’s +Z) and solve IK from home.
- Seed the grasp pose (TCP at the object center) with the step 1 solution; because the seed is close, it usually converges in a few iterations.
- After closing the gripper, solve lift, pre-place and place poses the same way, each seeded from the previous solution.
- Only hand a solution to trajectory interpolation after checking it against joint limits and the Jacobian condition number.
For static poses, joint torques follow from (Modern Robotics, Chapter 5, “Velocity Kinematics and Statics”). Plug in the fingertip force caused by the payload to get per-joint torque demands, then carry them through gear ratio and motor specs in the actuator torque calculator to continue into hardware sizing.
Converting a camera pixel into robot coordinates
When perception reports an object center as pixel plus depth, a pinhole model gives a 3D point in the camera frame, which then moves into the world. Per the MuJoCo XML reference, a camera looks along the -Z axis of its frame with +X pointing right and +Y pointing up, and fovy is the vertical field of view (in degrees for perspective cameras regardless of the compiler setting; default 45). The focal length in pixels is therefore .
import numpy as np
import mujoco
XML = """
<mujoco>
<worldbody>
<camera name="top" pos="0.5 0 1.2" xyaxes="0 -1 0 1 0 0" fovy="58"/>
<body name="box" pos="0.62 0.08 0.03">
<geom type="box" size="0.03 0.03 0.03"/>
</body>
</worldbody>
</mujoco>
"""
m = mujoco.MjModel.from_xml_string(XML)
d = mujoco.MjData(m)
mujoco.mj_forward(m, d) # mj_kinematics alone leaves cam_xpos unset
W, H = 640, 480
f = 0.5 * H / np.tan(np.deg2rad(m.camera("top").fovy[0]) / 2)
cx, cy = W / 2, H / 2
R_wc = d.camera("top").xmat.reshape(3, 3)
p_wc = d.camera("top").xpos.copy()
def world_to_pixel(p_w):
p_c = R_wc.T @ (p_w - p_wc)
depth = -p_c[2] # camera looks along -Z
return np.array([cx + f * p_c[0] / depth, cy - f * p_c[1] / depth]), depth
def pixel_to_world(u, v, depth):
p_c = np.array([(u - cx) / f * depth, -(v - cy) / f * depth, -depth])
return p_wc + R_wc @ p_c
uv, z = world_to_pixel(d.body("box").xpos + [0, 0, 0.03]) # center of the box top
print(uv.round(1), round(z, 3), pixel_to_world(*uv, z).round(4))
# [289.6 194.4] 1.14 [0.62 0.08 0.06]
Two details trip people up here. First, calling only mj_kinematics leaves cam_xpos at zero, so the depth is zero and the result is nan; the API docs assign camera and light poses to mj_camlight, and mj_forward runs the full pipeline including it. Second, the pixel row index v grows downward while the MuJoCo camera’s +Y points up, hence the sign flip on y. Likewise, when importing a camera calibration made under the convention where the optical axis is +Z and image-down is +Y, insert the rotation , which flips y and z, to land on the same point in MuJoCo. A world → pixel → world round trip that returns is the fastest sanity check.
Three reasons IK fails: reach, singularities and joint limits
The same DLS code will not converge on every target. Almost every failure falls into one of three buckets, and each one has a different number to inspect.
| Cause | Symptom | What to inspect | Remedy |
|---|---|---|---|
| Out of reach | Error shrinks, then stalls until the 200-iteration cap | Distance from base to target vs arm length | Move the robot mount or the work surface |
| Singularity | Joints jump in one step; rotation error will not drop | np.linalg.cond(J) | Change the seed or raise ; keep the path away from singular poses |
| Joint limit | After np.clip, the error plateaus at a fixed value | Whether qpos sits on a jnt_range bound | Seed with another IK branch (elbow up/down, wrist flip) |
Computed from the UR5e DH model, the geometric Jacobian’s condition number is about 8.3 at the home pose but about in the all-zero stretched pose — effectively singular. With joints 2, 3 and 4 parallel and the arm straightened, motion along the arm’s own direction is impossible. A target at , 1.2 m from the base, is beyond m even with the wrist offsets added, and the solver gives up after 200 iterations. The Menagerie model limits only elbow_joint to rad and every other joint to rad, so the elbow is usually the joint that hits the clamp.
For arms with seven or more degrees of freedom, such as many humanoid arms, the same DLS pushes the extra freedom into the null space, so the solution is no longer unique. How to read arm DOF and payload figures on a datasheet is covered in how to read a humanoid robot spec sheet.
Three hand checks before you trust the numbers
- The zero pose explained by DH sums: with all joints at zero, the FK position should be explainable as table sums, . For the UR5e that is .
- Rotation-matrix properties: for every that FK returns, check
np.allclose(R.T @ R, np.eye(3))andnp.linalg.det(R) ≈ 1. If either fails, a sign in the DH matrix or the unit of α (degrees vs radians) is wrong. - Finite-difference Jacobian: perturb one joint by rad, build a numerical Jacobian from the position change, and confirm it matches the analytic one to around . At the UR5e home pose the largest difference is about .
Once FK and the Jacobian pass these three checks, layer IK, the camera transform and trajectory generation on top in that order; when something breaks later, the search space stays small. To carry poses verified in simulation into real demonstration data, continue with the LeRobot SO-101 data collection and ACT training guide.