A head camera sits 8 cm in front of the torso pivot. Turn the torso 30° and code that adds that offset without rotating it closes the gripper 4.14 cm to the left of the bottle. With the torso square, the same code is perfect.
Drag the torso yaw, then switch between the two ways to add the offset. The gap opens only when the torso turns. Then we build, piece by piece, the pose, the composition rule, rotation formats, the ROS conventions and a tf tree you can break.
You need matrix times vector, sine and cosine and a little Python. We build the rest from zero.
Lesson 1 of the Robotics Engineering track. Next: Lesson 2, Time and Sync. The geometry itself, from first principles: VNAV Lecture 1, 3D Geometry and Lecture 2, Lie Groups. This lesson spends its words on the bugs.
Illustrative pick cell, top view, in metres: camera 0.080 m in front of the pivot, bottle fixed at (0.52, −0.30) m in base_link. Exact maths. The circle at the top right magnifies the bottle five times.
Chapter 0
Read a grasp error as a function of one angle, and predict it before you open the code
A humanoid's gripper closes 4 cm to the left of the bottle, but only when the torso turns 30° to the right. With the torso square, it grasps a hundred times in a row.
Every part tests clean: backlash 0.4 mm, joint tracking 0.05°, reprojection 0.21 px, detector within 6 mm. Each part is right in its own frame, its own origin and three axes. The error lives in the arithmetic that joins the frames.
Read the symptom as a function: zero at 0°, 4 cm at 30°. So the torso rotation multiplies the cause. A fixed mounting error would show at 0° too.
The torso yaw turns one quantity on its way to the base: the offset t from the torso pivot to the head camera, (0.080, 0, 0.420) m. Correct code turns it by the torso rotation R first. The broken helper adds t as it is. The miss is e = t − R t.
Left: the camera offset swings around the pivot as the torso turns (blue), while the broken code keeps it where it was (purple). The yellow chord between them is the miss. Right: the miss for every angle. Drag both sliders.
Exact maths. The circle on the left is not to scale; the plot is. The dashed line is the small-angle guess, angle in radians times the offset.
How big is the miss for a torso angle ψ (psi)? A turn about the vertical cannot move anything along it, so the 42 cm of height drops out. Call the part of t square to the axis t⊥ (t-perp): here the forward 8.0 cm.
The size of e equals two times sine of half the absolute value of psi, times the length of t-perp.
Turning t by psi swings its tip along a circle of radius t-perp. The miss is the straight chord from the start of the arc to its end. Half the chord is t-perp times the sine of half psi, so double it.
ψ = −30° and t-perp = 0.080 m: |e| = 2 × sin 15° × 0.080 = 2 × 0.2588 × 0.080 = 0.0414 m, or 4.14 cm. The full vector is e = (0.0107, 0.0400, 0) m: 4.00 cm along +y, the robot's left, and 1.07 cm forward. That is the reported symptom.
The same line gives 1.39 cm at 10° and 11.31 cm at 90°. Under about a radian, angle times lever arm is close: 0.524 × 0.080 = 4.19 cm, 1.2% high. One degree at one metre is 17 mm.
Symptom: the miss is zero at the neutral pose and grows with one joint angle.
Measure: turn that joint the other way and record which side the gripper misses on. At +30° the sideways part flips to −4.00 cm; the forward 1.07 cm and the size, 4.14 cm, stay.
Fix: find the helper that adds a child offset without turning it. Write tAC = RAB tBC + tAB (Chapter 2).
Chapter 1
Pack a pose into a 4 by 4 matrix, then feed it a point and a direction
A pose has two parts. The rotation RAB holds frame B's axes, measured in A. The translation tAB is B's origin in A's metres. To move a point from B numbers to A numbers, turn it, then add the shift.
A shift is not a matrix product: every matrix sends zero to zero. Homogeneous coordinates fix that: give each point a fourth number, 1, and one 4 by 4 matrix does both steps. VNAV Lecture 1 builds it from zero; here we use it.
The teal frame is the robot base B in the grey world W. The pink dot is a shelf corner, and the pink arrow is the shelf face's normal, both measured in B. Turn and move the base, then pick the fourth number.
Exact maths, drawn from above (z is out of the screen). Base y is fixed at 1 m. Warm entries are the rotation block; teal entries are the translation.
A-p over one equals the block matrix R-A-B, t-A-B, over zeros and one, times B-p over one.
Multiply B-p by R-A-B to turn it into A's axes. The point's fourth number, 1, multiplies the column t-A-B, so the same product adds the shift. The bottom row returns a 1 for the next pose.
The base stands at (2, 1, 0) m, yawed 30°. A shelf corner sits at B-p = (0.5, 0.2, 0) m. R times B-p is (0.333, 0.423, 0); add t: A-p = (2.333, 1.423, 0) m. Check: the corner is 0.539 m from the base in both frames, because a pose never changes a distance.
A direction, such as a normal or a camera ray, has no position. It takes a 0, so the shift drops out. The shelf normal (−1, 0, 0) becomes (−0.866, −0.500, 0). Give it a 1 and it becomes (1.134, 0.500, 0), length 1.24: not a direction.
Rigid also means no mirrors. R⊤R = I keeps lengths; det R = +1 keeps the frame right-handed. A mirror passes the first test.
Symptom: the scene comes out mirrored; the robot reaches left when the target is on the right.
Measure: take det R of every loaded extrinsic. R⊤R = I holds for a mirror too, so the orthogonality check alone stays green.
Fix: flip the wrong axis in the CAD or calibration export, and assert det R > 0 when the file loads.
Chapter 2
Chain two poses with the inner letters touching, and undo one with a transpose and a turn
Calibration gives the tool on the base, TBT. The localizer gives the base in the world, TWB. The tool in the world is their product with the inner letters touching: TWT = TWB TBT. In TBT TWB the inner letters are T and W. That line is a bug, and numpy multiplies it without a word.
The teal base sits at (2, 1) m in the grey world. Its tool is 0.25 m in front of it, turned 45°. The purple marker is where each line of code puts the tool. Turn the base.
Exact maths, top view. "Round trip" sends the world origin into the base frame with the naive inverse, then back with TWB.
Where does the rule come from? Move a tool point into B, then into W. Substitute the first step into the second, and match the terms against one pose TWT:
R-W-T equals R-W-B times R-B-T, and t-W-T equals R-W-B times t-B-T, plus t-W-B.
Multiply the rotations in chain order. Turn the child's offset t-B-T into world axes with R-W-B. Then add the parent's offset t-W-B, which is already in world metres.
Base yawed 30° at t-W-B = (2, 1) m; tool offset t-B-T = (0.25, 0) m. R-W-B times t-B-T is (0.217, 0.125); add t-W-B: t-W-T = (2.217, 1.125) m. Adding without the turn gives (2.250, 1.000), 0.129 m off: Chapter 0's bug in a new place.
Now undo a pose. TBW is the world seen from the base, and TWB TBW = I. The rotation block forces R′ = R⊤. The shift block forces R t′ + t = 0, so t′ = −R⊤t.
T-B-W equals T-W-B inverse: R-W-B transpose on top left, minus R-W-B transpose times t-W-B on top right, zeros and a one below.
Transpose the rotation. Turn the old shift t-W-B into the base's axes with that transpose, then negate it. Never use minus t alone, and never transpose the whole 4 by 4.
R-W-B transpose times (2, 1, 0) is (2.232, −0.134, 0). So t-B-W = (−2.232, 0.134, 0) m: the world origin is 2.232 m behind the base. The naive −t = (−2, −1, 0) is 1.157 m wrong.
Symptom: LiDAR points projected into the camera image land tilted and offset, but they look plausible in the viewer.
Measure: print the length of the computed LiDAR-to-camera translation and compare it with a tape measure between the two mounts.
Fix: name every transform T_target_source, check that inner letters touch, and invert with R⊤ and −R⊤t.
Chapter 3
Read one turn as a matrix, three angles, an axis-angle and a quaternion, and catch a swapped component order
A rotation has three degrees of freedom, and one stack spells it four ways. The matrix: 9 numbers, no singularity, fastest for many points. Euler angles (yaw, pitch, roll): readable, but they lock at 90° of pitch. Axis-angle: one turn by θ about a unit axis n. The unit quaternion: 4 numbers of length 1, compact and easy to interpolate.
So a stack sends quaternions, turns point clouds with matrices, and shows Euler angles only to people. Every format crossing is a place for a bug. VNAV Lecture 1 derives each conversion.
The teal frame is the turned body; grey is the world. Pick an axis and sweep the angle. Then switch on the misread: a scalar-first array is read as x, y, z, w, and the purple frame shows what the reader builds.
Exact maths. Euler angles are yaw-pitch-roll with R = Rz Ry Rx; quaternions are scalar last, Hamilton, as in ROS and SciPy. We checked the conversions against SciPy on 4,000 random turns.
The quaternion comes straight from axis-angle. Call the unit axis n = (nx, ny, nz) and the angle θ (theta). Everything uses half the angle:
q equals n-x, n-y, n-z, each times sine of theta over two, and then cosine of theta over two last.
Halve the angle theta. Scale the axis n by the sine of that half. Put the cosine of the half last. Negate all four numbers and you get the same turn.
A 5° yaw: n = (0, 0, 1), half angle 2.5°. q = (0, 0, 0.0436, 0.9990). The scalar w is near 1 because the turn is small.
Two component orders live in one process. ROS's geometry_msgs/Quaternion has fields x, y, z, w. SciPy's from_quat assumes scalar last unless you pass scalar_first=True. Eigen's constructor takes w first but stores x, y, z, w. The danger is the line that flattens named fields into a bare array.
Worked misread. A w-first source sends the 5° yaw as (0.9990, 0, 0, 0.0436). A scalar-last reader gets w = 0.0436, so θ = 2 arccos(0.0436) = 175.0°, about x. The length is still exactly 1.
Symptom: an orientation is wildly wrong from the first frame after a driver change. It does not drift; it is steady and wrong.
Measure: for a mount you expect to be a few degrees, |w| must be near 1. Assert |w| > 0.9 at the line that flattens the message into an array.
Fix: read named fields, or pass the order explicitly (scalar_first in SciPy). Keep one order per codebase and write it in the type name.
Chapter 4
Tilt a camera mount toward straight up and watch the pan rate blow up; then catch a quaternion that flips sign
A pan-tilt camera tracks a drone climbing overhead. Near 87° of tilt the picture sticks, then the mount whips round. Two different bugs make that same video. One is gimbal lock, a real limit of Euler angles. The other is a quaternion sign flip, fixed with one dot product.
Gimbal lock first. Euler angles write R = Rz(ψ) Ry(θ) Rx(φ): yaw ψ, then pitch θ, then roll φ. The three angle rates turn about three different axes. The matrix that maps them to the body's turn rate has determinant cos θ (Code Lab below). At θ = 90° it loses a rank: yaw and roll become the same motion.
Left: the mount from the side, tilted toward the drone. Right: the pan rate the motor must make for a steady body turn, against the tilt. The yellow line is the motor's limit. Drag the tilt.
Illustrative mount with a 120°/s pan motor and roll held at 0. Exact formula.
Hold roll at zero and ask for a body turn rate r about the body's z axis. Call the yaw-angle rate the motor must make ψ̇ (psi-dot). The third row of that matrix gives the rule:
Psi-dot equals r over cosine theta.
Divide the needed turn rate r by the cosine of the tilt theta. As theta nears 90°, the cosine nears 0, and the yaw rate the motor needs grows without limit.
r = 5.73°/s (0.1 rad/s). Level: 5.7°/s. At 85°: 65.7°/s. At 89°: 328°/s. A 120°/s motor saturates past 87.3°, which is where the picture sticks.
Now the sign flip. A quaternion q and its negative −q are the same turn: every entry of R is a product of two components, so the sign cancels. If one sample in a stream arrives negated, interpolation takes the long way round. Two samples at 4° and 6° of yaw, the second negated, have a dot product of −0.99985:
The fix goes before every slerp or average. If the dot product q1·q2 is negative, replace q2 by −q2. The arc drops to 1.0° and the turn to 2.0°.
Symptom: the mount sticks near overhead, or whips almost a full turn once, with no build-up.
Measure: plot the commanded pan rate beside 1/cos(tilt), and the dot product of consecutive quaternions. A smooth ramp that follows 1/cos is gimbal lock; a single negative dot product is a sign flip.
Fix: drive the pointing error as a rotation vector and convert to motor angles last; canonicalise signs before every slerp or average.
Chapter 5
Rebuild the optical-to-body rotation from the axes, and keep the controller on the smooth frame
A camera says a box is at (0, 0, 2). In the camera's optical frame that means 2 m straight ahead. Read as a body frame, it means 2 m straight up. Nothing about the three numbers looks wrong. Two ROS documents set the agreements that prevent this.
| REP 103 sets | The convention |
|---|---|
| Units | SI: metres, seconds, radians |
| Body frames | x forward, y left, z up, right-handed |
| Short-range geographic frames | ENU: x east, y north, z up |
| Camera optical frames | suffix _optical: z forward, x right, y down |
| Preferred rotation format | quaternion: compact, no singularities |
Build the optical-to-body rotation RBO from the axes. A column of a rotation matrix is where a basis vector goes. Optical x (right) is body −y. Optical y (down) is body −z. Optical z (forward) is body +x.
Worked chain. The base stands at (2, 1, 0) m, yawed 30°; the camera is 7 cm forward and 66 cm up. A box 3 m down the optical axis lands at (4.659, 2.535, 0.660) m. Skip RBO and it lands at (2.061, 1.035, 3.660): 3.66 m in the air and 4.24 m wrong.
REP 105 names the frames of a mobile robot: earth, then map, then odom, then base_link. The odom frame is continuous but drifts without bound. The map frame does not drift but may jump. Each frame has one parent, so the localizer computes map to base_link but publishes the map-to-odom transform. Every jump lands in that one edge.
Top: the robot drives a straight aisle at 1 m/s, and the localizer corrects map to odom once a second, so the pose read in map steps back. Bottom: the speed a 200 Hz controller computes from the pose it reads. Pick the frame and the size of the correction.
Illustrative: 1 m/s, 200 Hz control, one correction per second, held (not interpolated). The spike height is the correction divided by 5 ms.
Worked number. A 0.35 m correction read in map by a 200 Hz controller looks like 0.35 / 0.005 = 70 m/s for one tick. If tf interpolates between 10 Hz corrections instead, the same jump becomes a 3.5 m/s plateau for 0.1 s: no longer impossible, still wrong.
The earth frame sits at the origin of ECEF, the Earth-centred frame. Its coordinates are near 6.4 million metres, where a float32 can only step in 0.5 m. One kilometre from a local origin, the step is 0.06 mm. So register in earth and compute in map.
Symptom: the robot flinches a few times a minute, more often when localization works well.
Measure: overlay the times of map-to-odom updates on the acceleration command. Every spike sits on an update.
Fix: feed controllers, velocity estimators and scan deskewing from odom. Use map only to plan and to display.
Chapter 6
Change one calibration number at a time and read its pattern across the image and across range
A manipulator that picked well now misses on the far bin. The near bin still works. Which of the camera's two calibrations broke?
Intrinsics map a ray to a pixel: focal lengths, principal point, distortion. They travel with the device. Extrinsics place the camera frame on the robot: an SE(3) pose. They act on opposite sides of the perspective divide, the division by depth, so their errors have different shapes.
Call the point's right and forward coordinates Xc and Zc. Call the focal length in pixels fx and the centre column cx. Ignoring distortion, the pixel column is:
u equals f-x times X-c over Z-c, plus c-x.
Divide the point's sideways distance X-c by its depth Z-c to get the slope x-n. Scale x-n by f-x. Shift by c-x.
With made-up numbers: f-x = 800 px and c-x = 640 px. A point 0.4 m right at 2 m depth has x-n = 0.2, so u = 800 × 0.2 + 640 = 800 px.
Each fault moves one symbol. A focal error δf moves u by δf · x-n: zero at the centre. A centre error δc moves every pixel by δc. A sideways mount shift δt moves u by f-x δt / Z-c: it fades with depth. A mount yaw θ tilts every ray:
Delta-u equals f-x times theta times one plus x-n squared.
Multiply the yaw error theta by the focal length f-x. That is the shift at the centre. Toward the edges, multiply it by one plus x-n squared as well.
With made-up numbers: θ = 0.2° = 0.00349 rad and f-x = 800 px. At the centre Δu = 2.79 px; at x-n = 0.8 it is 2.79 × 1.64 = 4.58 px. The exact rotation gives 4.59 px.
Left: the image, with arrows showing where each point moves (drawn thirty times longer). Right: the sideways miss in millimetres against range, for a centred target (solid) and an off-axis one at x-n = 0.4 (dashed). Pick a fault.
Illustrative camera: f = 800 px, 1280 by 960 image, no distortion. First-order formulas from this chapter.
So test two ranges times two image positions. Flat with range: extrinsic translation. Growing, and gone when centred: focal length or distortion. Growing, and still there when centred: mount rotation or principal point. With good distortion values, the yaw's edge bulge splits those two.
Symptom: near picks pass, far picks fail, and nothing in the software changed.
Measure: the miss at 1 m and 3 m, with the target centred and off-axis. A 0.2° yaw misses by 3.5 mm at 1 m and 10.5 mm at 3 m, centred or not.
Fix: recalibrate only the guilty block. Lesson 5, Calibration covers how.
Chapter 7
Inject one frame bug at a time, then name it from four probe moves alone
Night shift. The humanoid misses totes by about 20 cm, and every subsystem reports green. A frame bug hides from every part that does not span the broken edge. Use Chapter 0's tool: turn one thing at a time and see what the error depends on.
The chain has four edges. The localizer gives odom to base_link (base yaw β). The waist gives base_link to torso (yaw ψ, 4 cm forward). A static mount gives torso to head_camera, 8 cm forward. The camera sees the tote 0.35 m ahead and 0.10 m left. The target is TOB TBT TTC Cp.
Top: the tree; the broken edge turns red. Below: the cell from above, with the pink tote and the purple spot where the software sends the gripper. Pick a bug, move the robot, then press Run the probes.
| probe | square | torso 30° | base 30° | base twice as far |
|---|---|---|---|---|
| miss | – | – | – | – |
Illustrative humanoid, planar maths, exact. The optical bug also puts the tote 0.35 m too high; the miss counts that height.
Worked number. At the defaults (β = 15°, ψ = −35°, base 0.78 m out) the tote is at (1.077, 0.457) m. The wrong inverse misses by 2 sin(7.5°) × 0.781 m = 20.4 cm. That is the chord of the base position, turned by the base yaw.
| Bug | Square | Torso 30° | Base 30° | Base twice as far |
|---|---|---|---|---|
| Unrotated offset | 0 | 4.14 cm | 0 | no change |
| Reversed order | 0 | 40.4 cm | 2.1 cm | about doubles |
| Wrong inverse | 0 | 0 | 40.4 cm | doubles |
| Optical skipped | 57.9 cm | 57.9 cm | 57.9 cm | no change |
Symptom: you sweep a joint, the miss does not move, and you clear that joint.
Measure: check that the joint could move your metric at all. A rotation at the end of a chain turns the leaf's axes about its own origin and never moves that origin.
Fix: probe with a joint that has a lever arm to the quantity you measure, or measure orientation as well as position.
Chapter 8
Keep the bug table, the code and the next steps in one place
A number on a robot means nothing until you name its frame. A pose TAB takes B numbers to A numbers, and chains touch inner letters. Child offsets turn before they add; inverses transpose and turn. Quaternions have an order and a sign.
REP 103 fixes the axes, and REP 105 keeps jumps out of the controller's frame. When something misses, ask what the error is a function of.
| Bug | Symptom | Signature that names it |
|---|---|---|
| Unrotated child offset | zero when the parent is square | sideways part flips with the joint; size 2 sin(|ψ|/2) |t⊥| |
| Reversed composition | large, stable error | inner letters do not touch; grows with distance from the root |
| Inverse with −t | round trip does not return | T T−1 ≠ I; residual (I − R)t |
| Mirror (det = −1) | scene comes out mirrored | R⊤R = I passes, det R = −1 |
| Quaternion order | wildly wrong from boot, steady | length 1, but |w| small for a small turn |
| Quaternion sign flip | one near-full-turn whip | dot product of consecutive samples < 0 |
| Gimbal lock | pan rate saturates near overhead | rate follows 1/cos(pitch) |
| Optical frame skipped | forward reads as up | axes swapped exactly; same miss everywhere |
| Controller on map | flinch a few times a minute | spikes sit on map-to-odom updates |
| Extrinsic yaw | far picks fail | miss grows with range, survives centring |
| Focal length | off-axis far picks fail | zero at the image centre |
python import numpy as np def se3(R, t): """T_AB from R_AB (3x3) and t_AB (3,): takes B numbers, gives A numbers.""" T = np.eye(4); T[:3, :3] = R; T[:3, 3] = t return T def compose(T_ab, T_bc): """T_AC = T_AB T_BC. The inner letters touch.""" return T_ab @ T_bc def inverse(T_ab): """T_BA = [R^T, -R^T t; 0 1]. Never T.T, never -t.""" R, t = T_ab[:3, :3], T_ab[:3, 3] return se3(R.T, -R.T @ t) def apply(T_ab, p_b, w=1.0): """w = 1 for a point, w = 0 for a direction (a normal, a ray).""" return (T_ab @ np.append(p_b, w))[:3] def quat_from_axis_angle(n, theta): """Scalar LAST (x, y, z, w), Hamilton: the ROS and SciPy order.""" n = np.asarray(n, float) / np.linalg.norm(n) return np.append(n * np.sin(theta / 2), np.cos(theta / 2)) def quat_to_R(q): x, y, z, w = q return np.array([ [1 - 2*(y*y + z*z), 2*(x*y - w*z), 2*(x*z + w*y)], [2*(x*y + w*z), 1 - 2*(x*x + z*z), 2*(y*z - w*x)], [2*(x*z - w*y), 2*(y*z + w*x), 1 - 2*(x*x + y*y)]]) def canonical(q_ref, q): """Same hemisphere as q_ref before any slerp or average.""" return q if np.dot(q_ref, q) >= 0 else -q def check_rotation(R, tol=1e-6): """Orthogonal AND right-handed. A mirror passes the first test only.""" assert np.abs(R.T @ R - np.eye(3)).max() < tol, "not orthogonal" assert np.linalg.det(R) > 0, "det = -1: a mirror, not a rotation"
We checked every function above against SciPy's Rotation on 3,000 random poses.
Where it sits. Production stacks hand this to tf2 and to Lie-group libraries such as Sophus and manif. They exist because they make whole classes of these mistakes impossible, not because the multiply is hard. For increments inside an estimator, the series perturbs on the right, R exp(δ∧), as VNAV Lecture 2 sets out.
Now teach it: press Present or Teach and explain the 4.14 cm miss from the symptom alone. Then go back to the pick cell and predict the miss at 60° before you drag.