Skip to content

What Math Does a 6-DOF Robot Arm Need for Pick-and-Place? Frames, Forward and Inverse Kinematics in Python

The minimum math for 6-DOF pick-and-place, checked against the official UR5e DH table and MuJoCo Menagerie: transforms, FK, damped least-squares IK, pixel-to-robot.

Contents

Key takeaways

  1. Pick-and-place math boils down to two steps: express the object pose in the robot base frame (camera transform), then find joint angles that reach it (inverse kinematics). Both are products and inverses of 4×4 homogeneous transforms.
  2. Forward kinematics from the official UR5e DH table matches the attachment_site of the MuJoCo Menagerie UR5e to within about 1 mm; the gap comes from the MJCF writing link offsets as 0.163 and 0.392 instead of the DH values 0.1625 and 0.3922.
  3. Damped least-squares IK converges on a target 30 cm away from the home pose in 4 iterations to under 0.03 mm of error, but the fully stretched all-zero pose is singular, with a Jacobian condition number around 10^18.
  4. In MuJoCo, mj_kinematics only updates body and site poses; camera poses (cam_xpos, cam_xmat) need mj_camlight or a full mj_forward.
  5. A MuJoCo camera looks down its frame’s -Z axis with +X right and +Y up, so converting to pixel coordinates whose row index grows downward requires flipping the sign of y.

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 Ta b T_{a\,b} and reads it as “the pose of frame b seen from frame a”. With that convention, Ta b Tb c=Ta c T_{a\,b} \, T_{b\,c} = T_{a\,c} only works when the inner subscripts match, so ordering mistakes become visible on the page.

FrameSymbolDefined byRole in pick-and-place
WorldworldCell layout (e.g. a table corner)Common reference tying robots and cameras together
BasebaseWhere the robot is mountedThe frame IK targets are expressed in
Flange (end effector)eeManufacturer’s DH tableOutput of forward kinematics
Tool (TCP)tcpGripper geometryThe point that actually touches the object; Tee tcp T_{ee\,tcp} is constant
CameracamCalibration result or MJCFReference for turning pixels into 3D points
ObjectobjPerception outputThe grasp target

The whole calculation reduces to two chains built from that table.

Tbase obj=Tbase cam Tcam obj T_{base\,obj} = T_{base\,cam} \, T_{cam\,obj} Tbase eegoal=Tbase obj Tobj grasp Tee tcp−1 T_{base\,ee}^{\text{goal}} = T_{base\,obj} \, T_{obj\,grasp} \, T_{ee\,tcp}^{-1}

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 R∈SO(3) R \in SO(3) and a translation p p into a 4×4 matrix. Rather than calling a general matrix inverse, use the structure directly: T−1=[R⊤−R⊤p01] T^{-1} = \begin{bmatrix} R^\top & -R^\top p \\ 0 & 1 \end{bmatrix} . 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 θi \theta_i is not in the table; each joint angle goes in directly.

Jointa [m]d [m]α [rad]
100.1625π/2
2-0.42500
3-0.392200
400.1333π/2
500.0997-π/2
600.09960

In standard DH, one link contributes Ti=Rz(θi) Tz(di) Tx(ai) Rx(αi) T_i = R_z(\theta_i)\,T_z(d_i)\,T_x(a_i)\,R_x(\alpha_i) , and forward kinematics is the product Tbase ee=T1T2⋯T6 T_{base\,ee} = T_1 T_2 \cdots T_6 .

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 a2+a3=−0.425−0.3922 a_2 + a_3 = -0.425 - 0.3922 , y = -0.2329 m is −(d4+d6) -(d_4 + d_6) , and z = 0.0628 m is d1−d5 d_1 - d_5 . 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.

  1. Clone the Menagerie repository and run from the directory above universal_robots_ur5e (the meshes in assets/ must be present for the model to load).
  2. Write the joint angles into qpos and call mj_kinematics to update body and site poses.
  3. Read site_xpos (nsite×3) and site_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, e∈R6 e \in \mathbb{R}^6 (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 λ \lambda — damped least squares (DLS):

Δq=J⊤(JJ⊤+λ2I)−1e \Delta q = J^\top \left( J J^\top + \lambda^2 I \right)^{-1} e

With λ=0 \lambda = 0 this reduces to the pseudo-inverse; a larger λ \lambda gives smaller, steadier steps. For the rotation error, the code uses the small-angle approximation erot=12∑iri×rid e_{rot} = \tfrac{1}{2} \sum_{i} r_i \times r_i^{d} (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 zi z_i and origin pi p_i as Jv=zi×(pe−pi) J_v = z_i \times (p_e - p_i) , Jω=zi J_\omega = z_i ) 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:

  1. Compute the flange goal for the pre-grasp pose (10 cm along the object’s +Z) and solve IK from home.
  2. 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.
  3. After closing the gripper, solve lift, pre-place and place poses the same way, each seeded from the previous solution.
  4. 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 τ=J⊤F \tau = J^\top F (Modern Robotics, Chapter 5, “Velocity Kinematics and Statics”). Plug in the fingertip force F F 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 (u,v) (u, v) plus depth, a pinhole model gives a 3D point in the camera frame, which Tworld cam T_{world\,cam} 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 f=H/2tan⁡(fovy/2) f = \dfrac{H/2}{\tan(\text{fovy}/2)} .

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 diag(1,−1,−1) \mathrm{diag}(1,-1,-1) , which flips y and z, to land on the same point in MuJoCo. A world → pixel → world round trip that returns (0.62,0.08,0.06) (0.62, 0.08, 0.06) 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.

CauseSymptomWhat to inspectRemedy
Out of reachError shrinks, then stalls until the 200-iteration capDistance from base to target vs arm lengthMove the robot mount or the work surface
SingularityJoints jump in one step; rotation error will not dropnp.linalg.cond(J)Change the seed or raise λ \lambda ; keep the path away from singular poses
Joint limitAfter np.clip, the error plateaus at a fixed valueWhether qpos sits on a jnt_range boundSeed 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 1.4×1018 1.4 \times 10^{18} 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,0,0.3) (1.2, 0, 0.3) , 1.2 m from the base, is beyond ∣a2∣+∣a3∣=0.8172 |a_2| + |a_3| = 0.8172 m even with the wrist offsets added, and the solver gives up after 200 iterations. The Menagerie model limits only elbow_joint to ±3.1415 \pm 3.1415 rad and every other joint to ±6.28319 \pm 6.28319 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

  1. The zero pose explained by DH sums: with all joints at zero, the FK position should be explainable as table sums, (a2+a3,  −(d4+d6),  d1−d5) (a_2 + a_3,\; -(d_4 + d_6),\; d_1 - d_5) . For the UR5e that is (−0.8172,−0.2329,0.0628) (-0.8172, -0.2329, 0.0628) .
  2. Rotation-matrix properties: for every R R that FK returns, check np.allclose(R.T @ R, np.eye(3)) and np.linalg.det(R) ≈ 1. If either fails, a sign in the DH matrix or the unit of α (degrees vs radians) is wrong.
  3. Finite-difference Jacobian: perturb one joint by 10−6 10^{-6} rad, build a numerical Jacobian from the position change, and confirm it matches the analytic one to around 10−6 10^{-6} . At the UR5e home pose the largest difference is about 2.5×10−7 2.5 \times 10^{-7} .

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.

Common mistakes

  • Multiplying T_a_b · T_b_c in the wrong order, or using the base-to-camera transform where camera-to-base is needed, so the object lands somewhere else entirely
  • Forgetting that MJCF angles default to degrees and writing joint ranges as radian numbers — check whether the file sets compiler angle=“radian” the way Menagerie’s UR5e does
  • Seeding inverse kinematics with all joints at zero, which starts the solver on a singular pose — seed from the home keyframe or the previous solution instead
  • Sending IK output to the controller without clamping it to the joint limits

Pre-flight checklist

  • Every frame is named T_parent_child and the inner subscripts match along each multiplication chain
  • DH-based FK has been compared, in millimetres, against the TCP position your simulator or robot controller reports
  • Before running IK, the target is confirmed to lie within reach (for the UR5e, |a2|+|a3| = 0.8172 m plus the wrist offsets)
  • The Jacobian condition number is printed at the converged solution to make sure it is not near a singularity
  • The pixel-to-world conversion round-trips a known point (world → pixel → world) back to its original coordinates

Frequently asked questions

Should I use the product of exponentials instead of DH?
Modern Robotics develops forward kinematics with screw axes and the product of exponentials, and its code library provides FKinSpace, JacobianSpace and IKinSpace. If the manufacturer publishes a DH table, starting with DH is fine; if one codebase has to handle many robots, PoE is less tied to frame-placement rules.
Can mj_jac give the Jacobian of an arbitrary point, such as a fingertip, rather than a site?
According to the MuJoCo API docs, mj_jac treats a 3D point given in world coordinates as attached to a chosen body and fills jacp and jacr (3×nv each). The Jacobian is expressed with its origin at the body’s center of mass but with axes aligned to the world frame, and variants such as mj_jacSite and mj_jacBody call mj_jac internally.
How do I get camera extrinsics on a real robot?
For a wrist-mounted camera, hand-eye calibration estimates T_ee_cam; for a fixed camera it estimates T_base_cam. Both work by imaging a calibration target from several robot poses and solving the resulting equations, and the result drops straight into the chain T_base_cam = T_base_ee · T_ee_cam used in this post.

Sources & verification

  1. Universal Robots — DH parameters for calculations of kinematics and dynamics (UR5e table)
  2. MuJoCo Documentation — API Functions (mj_kinematics, mj_comPos, mj_jac, mj_jacSite, mj_camlight)
  3. MuJoCo Documentation — XML Reference (compiler angle, joint limited, camera frame)
  4. MuJoCo Documentation — API Types (mjData site_xpos, site_xmat, cam_xmat)
  5. MuJoCo Menagerie — Universal Robots UR5e model
  6. Modern Robotics: Mechanics, Planning, and Control (Lynch & Park) — official page
  7. NxRLab/ModernRobotics — textbook code library (IKinSpace and friends)

Last verified: