Manipulator kinematics: forward, Jacobian and inverse
Compute forward kinematics with Denavit-Hartenberg parameters and products of exponentials, derive manipulator Jacobians, and use damped inverse kinematics and null-space projection.
After this lesson you can
- Calculate forward kinematics by DH and product of exponentials and check that they agree.
- Derive the spatial and body Jacobians of a serial manipulator.
- Detect singularities from Jacobian rank and interpret the manipulability ellipsoid.
- Implement differential inverse kinematics with damped least squares and joint limits.
- Use the null space to optimize a secondary goal for a redundant arm without moving its end effector.
Before you start
From joints to pose
An expert moving a gripper must convert a desired pose into joint values. Forward kinematics maps joints to pose; inverse kinematics seeks joint values for a pose and may have several solutions or none. Frame geometry and SE(3) transformations establish the conventions.
Two descriptions of the same chain
Joint space contains the variables ; task space contains the position or pose to control. The Denavit-Hartenberg convention assigns frames and four parameters per link. In the standard version a revolute joint is expressed as . The ordered product of the six matrices gives the pose. Modified DH changes the formulas: the table and convention must agree.
Forward kinematics by product of exponentials writes
Here is the pose at and each is the joint’s twist in the reference spatial frame. For a unit revolute axis through , . Both methods describe the same chain when the axes, frames and joint zero positions agree. Transformations apply from right to left, and each exponential is the SE(3) exponential from the previous lesson.
For a prismatic joint the twist has and equal to the translation direction. For a revolute joint, a point on the axis has zero velocity, so . The exponential formulation stores each axis’s geometry directly in the reference pose; DH encodes it through relations between neighbouring frames. Both require documenting the tool origin and how zero angles are defined.
Velocities and singularities
The manipulator Jacobian relates joint rates to twist. In the spatial frame, column is the original axis transported by preceding transformations:
A later joint does not change the spatial axis of an earlier joint. To obtain a column, perturb and move its exponential left by conjugation. The relation between Jacobians uses the adjoint and requires twist and error to be expressed in the same frame.
If is the product of exponentials before joint , a variation inserts immediately after . Conjugating it to the left end gives a spatial increment with twist . Repeating for all joints and adding first-order terms gives . The endpoint position Jacobian is another matrix: the linear component of a spatial twist is the field velocity at the origin, while the velocity of point is .
A kinematic singularity occurs when the Jacobian loses rank relative to its maximum rank. The image of the joint-velocity sphere is an ellipse in the planar case, or an ellipsoid in higher dimensions. Its semiaxis lengths are proportional to the singular values of . If the smallest vanishes, there is an instantaneous task direction the arm cannot produce. The determinant of summarizes volume, but does not reveal all directions by itself. The condition number compares the largest and smallest singular values and diverges when rank is lost.
In the first interactive, the three links measure , and units. Each planar Jacobian column is perpendicular to the vector from its pivot to the tip. The ellipse computes directly and uses graphic scale ; these are not hardware data. Stretch the arm until all columns are parallel: the ellipse collapses to a segment. A singular configuration does not mean the robot cannot move, but that it loses one instantaneous task direction.
For the planar arm, if is the pivot and the tip, the position column is . The image of a unit sphere of joint increments has shape matrix . The graphic scaling factor only makes the ellipse easier to see: its proportions, not that size, indicate anisotropy. Near a singularity, a small Cartesian velocity in some direction may require very large joint velocities.
Inverse kinematics and damping
Differential inverse kinematics linearizes a task as . For a pose, use a six-component error obtained from the relative pose logarithm rather than matrix subtraction. An analytical solution, when available, can enumerate branches; a numerical method depends on its initial seed, and failure does not establish that no solution exists.
The pseudoinverse gives a minimum-norm solution when the system is compatible. With the SVD , the undamped inverse amplifies each component by . Damped least-squares inverse kinematics minimizes
The normal equations give the solution for . In the singular basis, each gain is : it does not diverge as . The cost is poorer tracking in the difficult direction. Excessive also slows well-conditioned directions. Joint limits, maximum step size and stopping criteria must be added explicitly. Clipping a solution afterwards can alter the task; constrained optimization is appropriate when strict limits must be respected.
This step is Levenberg-Marquardt quadratic regularization. For a differentiable square map with an invertible Jacobian, the inverse function theorem guarantees a local inverse; for a redundant arm or lower-dimensional task, analyze rank and degrees of freedom rather than applying the square statement literally.
The maximum gain for occurs at and equals , so damping bounds error amplification in a single step. For an unreachable target a large residual may remain even when iterations stabilize. The transpose method is cheaper and locally decreases squared error with a sufficiently small step, but its speed depends on conditioning and gain. Comparing final error alone would hide the size of intermediate movements, so the figure also shows the largest joint step.
The second figure computes on a planar three-link arm. It applies the transpose with gain 0.12, the pseudoinverse or the damped inverse with gain 0.7; the latter two operate on . The pseudoinverse discards eigenvalues below . The iterations are deterministic kinematic simulations without limits or dynamics; they should not be interpreted as safe commands for a physical arm. An unreachable target leaves an unavoidable residual.
Redundancy and the null space permit a secondary task. If has a null space and is its exact pseudoinverse, satisfies . Thus adds a secondary direction without changing the task to first order. With a damped inverse is no longer an exact projector; the third figure therefore displays drift and applies pose correction. Its seven axes and lengths are a synthetic model, not a Panda. The secondary option locally increases elbow distance from a point; it does not guarantee whole-body collision avoidance.
That figure’s model uses local axes , an initial translation of 0.4 in and then lengths along the local axis. It starts at radians. At each of 45 steps it projects a joint preference and, if the control is enabled, adds the gradient of distance from the chain’s fourth point to obstacle . A six-component proportional correction counteracts pose drift. The trajectory and indicators are recalculated with these equations, not from a recorded path; linearization and damping leave a small visible drift.
There is not always a unique secondary path. A seven-joint arm controlling a six-dimensional pose has at least one null direction in a rank-six configuration; at a singularity it may have more, but can also lose primary-task capability. A hierarchical scheme applies tasks in priority order and updates the space available to each. A single-task projector does not replace planning with limits, contacts and obstacles for every link.
Lab: UR5 with DH and exponentials
We use the nominal Universal Robots UR5 table in metres and radians. Nominal parameters do not replace calibration of a specific robot. We derive axes in the zero pose from the same table, so the DH/PoE comparison checks implementation and conventions, not an independent hardware measurement. Twist order is .
import numpy as np
from scipy.spatial.transform import Rotation
AA=np.array([0,-.425,-.39225,0,0,0])
DD=np.array([.089159,0,0,.10915,.09465,.0823])
AL=np.array([np.pi/2,0,0,np.pi/2,-np.pi/2,0])
def hat(w):
x,y,z=w
return np.array([[0.,-z,y],[z,0.,-x],[-y,x,0.]])
def left_jac(w):
a=np.linalg.norm(w); W=hat(w)
if a<1e-5: c,d=.5-a*a/24,1/6-a*a/120
else: c,d=(1-np.cos(a))/a**2,(a-np.sin(a))/a**3
return np.eye(3)+c*W+d*W@W
def exp6(x):
w=x[3:]; T=np.eye(4); T[:3,:3]=Rotation.from_rotvec(w).as_matrix(); T[:3,3]=left_jac(w)@x[:3]
return T
def inv(T):
A=np.eye(4); A[:3,:3]=T[:3,:3].T; A[:3,3]=-A[:3,:3]@T[:3,3]; return A
def log6(T):
w=Rotation.from_matrix(T[:3,:3]).as_rotvec(); return np.r_[np.linalg.solve(left_jac(w),T[:3,3]),w]
def adj(T):
R,t=T[:3,:3],T[:3,3]; return np.block([[R,hat(t)@R],[np.zeros((3,3)),R]])
def dh(a,d,alpha,q):
c,s=np.cos(q),np.sin(q); ca,sa=np.cos(alpha),np.sin(alpha)
return np.array([[c,-s*ca,s*sa,a*c],[s,c*ca,-c*sa,a*s],[0,sa,ca,d],[0,0,0,1.]])
def fk_dh(q):
T=np.eye(4)
for a,d,alpha,v in zip(AA,DD,AL,q): T=T@dh(a,d,alpha,v)
return T
def home_screws():
T=np.eye(4); S=[]
for a,d,alpha in zip(AA,DD,AL):
w=T[:3,2]; p=T[:3,3]; S.append(np.r_[-np.cross(w,p),w]); T=T@dh(a,d,alpha,0)
return np.array(S).T,T
S,M=home_screws()
def fk(q):
T=np.eye(4)
for i in range(6): T=T@exp6(S[:,i]*q[i])
return T@M
def jac_space(q):
T=np.eye(4); J=np.zeros((6,6))
for i in range(6):
J[:,i]=adj(T)@S[:,i]; T=T@exp6(S[:,i]*q[i])
return J
def jac_body(q): return adj(inv(fk(q)))@jac_space(q)def ik(target,q,lam=.05,steps=100):
q=q.copy()
for k in range(steps):
e=log6(inv(fk(q))@target)
if np.linalg.norm(e)<1e-5: break
J=jac_body(q); delta=J.T@np.linalg.solve(J@J.T+lam**2*np.eye(6),e)
delta=np.clip(delta,-.15,.15); q=np.clip(q+delta,-2*np.pi,2*np.pi)
return q,k,np.linalg.norm(log6(inv(fk(q))@target))
rng=np.random.default_rng(9); q=rng.uniform(-1,1,6)
eps=1e-6; T=fk(q)
numeric=np.column_stack([(log6(inv(T)@fk(q+eps*np.eye(6)[i]))-log6(inv(T)@fk(q-eps*np.eye(6)[i])))/(2*eps) for i in range(6)])
numeric_space=np.column_stack([(log6(fk(q+eps*np.eye(6)[i])@inv(T))-log6(fk(q-eps*np.eye(6)[i])@inv(T)))/(2*eps) for i in range(6)])
print('Error DH/PoE:',np.max(np.abs(fk(q)-fk_dh(q))))
print('Error jacobiano cuerpo:',np.max(np.abs(jac_body(q)-numeric)))
print('Error jacobiano espacial:',np.max(np.abs(jac_space(q)-numeric_space)))
target=fk(np.array([.3,-.7,.8,-.5,.7,.2]))
solution,n,error=ik(target,np.array([.1,-.5,.7,-.4,.5,.1]))
print('IK iteraciones y error:',n,error)
assert np.allclose(fk(q),fk_dh(q),atol=1e-10)
assert np.allclose(jac_body(q),numeric,atol=1e-7)
assert np.allclose(jac_space(q),numeric_space,atol=1e-7)
assert error<1e-5The limit in this exercise is a teaching constraint, not a safety check or calibrated equipment limit. The error combines translation and rotation units; choose explicit weighting for a real application. The finite-difference check uses the body-relative logarithm, as does the IK.
Local lab: MuJoCo Panda
The model comes from a pinned version of MuJoCo Menagerie. The first run downloads the XML and meshes into oryon-panda-model in the working directory; it requires network access and mujoco installed in the local lab. We add a site to the hand to measure the end effector. Our Jacobian uses axes and anchors calculated by MuJoCo and is compared against mj_jacSite.
import os, urllib.request, xml.etree.ElementTree as ET
from pathlib import Path
import numpy as np
import mujoco
root=Path(os.environ.get('ORYON_PANDA_DIR',str(Path.cwd()/'oryon-panda-model')))
root.mkdir(parents=True,exist_ok=True)
base='https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/822c2d8f877dd166c5b7d3c9f7e3c3b6589473b7/franka_emika_panda/'
xml=root/'panda.xml'
if not xml.exists(): urllib.request.urlretrieve(base+'panda.xml',xml)
tree=ET.parse(xml)
for mesh in tree.findall('.//asset/mesh'):
filename=mesh.get('file')
if filename:
dest=root/'assets'/filename; dest.parent.mkdir(parents=True,exist_ok=True)
if not dest.exists(): urllib.request.urlretrieve(base+'assets/'+filename,dest)
hand=tree.find(".//body[@name='hand']")
ET.SubElement(hand,'site',{'name':'tool','pos':'0 0 0.10','size':'0.005'})
path=root/'panda_tool.xml'; tree.write(path,encoding='utf-8',xml_declaration=True)
model=mujoco.MjModel.from_xml_path(str(path)); data=mujoco.MjData(model)
mujoco.mj_resetDataKeyframe(model,data,0); mujoco.mj_forward(model,data)
site=mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_SITE,'tool')
joints=[mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_JOINT,f'joint{i}') for i in range(1,8)]
dofs=model.jnt_dofadr[joints]; qaddrs=model.jnt_qposadr[joints]
Jp=np.zeros((3,model.nv)); Jr=np.zeros((3,model.nv))
mujoco.mj_jacSite(model,data,Jp,Jr,site)
own=np.column_stack([np.cross(data.xaxis[j],data.site_xpos[site]-data.xanchor[j]) for j in joints])
print('Error máximo del jacobiano lineal:',np.max(np.abs(own-Jp[:,dofs])))
assert np.allclose(own,Jp[:,dofs],atol=1e-10)npm run lab and open the connection link.initial=data.site_xpos[site].copy(); limits=model.jnt_range[joints]; center=limits.mean(axis=1)
period=5.0; control_steps=10; dt=model.opt.timestep*control_steps
errors=[]; qref=data.qpos[qaddrs].copy()
for k in range(int(period/dt)):
time=k*dt
desired=initial+np.array([0.03*(np.cos(2*np.pi*time/period)-1),0.03*np.sin(2*np.pi*time/period),0.])
mujoco.mj_jacSite(model,data,Jp,Jr,site); J=Jp[:,dofs]
damp=0.03; pinv=J.T@np.linalg.solve(J@J.T+damp**2*np.eye(3),np.eye(3))
e=desired-data.site_xpos[site]; q=data.qpos[qaddrs].copy()
qdot=pinv@(10*e)+(np.eye(7)-pinv@J)@(-0.1*(q-center))
qdot=np.clip(qdot,-0.4,0.4)
qref=np.clip(qref+qdot*dt,limits[:,0],limits[:,1]); data.ctrl[:7]=qref
for _ in range(control_steps):
data.qfrc_applied[:]=data.qfrc_bias
mujoco.mj_step(model,data)
errors.append(np.linalg.norm(e))
print('Pasos:',len(errors),'error medio (m):',np.mean(errors),'máximo (m):',np.max(errors))
assert np.isfinite(errors).all()npm run lab and open the connection link.The task controls site position, not orientation. Dynamic bias compensation is idealized, and the damped projector permits small interference from the secondary task. The local run tests the simulation workflow; it is neither a benchmark nor authorization to apply these commands to hardware. Errors depend on the integrator, model and control parameters.
Exercises
Step 1 of 2. Which factors transport the axis before applying it?
Step 1 of 2. Which equation does the minimum satisfy?
ik_dls(fk, jac, target, q0, lam), where fk(q) is a position vector, jac(q) its Jacobian and lam is positive. Perform up to 100 DLS steps, limit each component to 0.2 and return q. The stopping tolerance is 1e-6.def ik_dls(fk, jac, target, q0, lam):
pass