Skip to content
Tech Interview Prep
Technical interview guide

Robot Kinematics

The geometry of robot motion: translating between joint angles and the position of the robot's end effector.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Modern Robotics, ROS 2 Rolling tf2/URDF, MoveIt 2, Drake, Pinocchio, MATLAB Robotics System Toolbox, SciPy, and Eigen documentation reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Design a forward-kinematics interface for a robot service.

Answer

The 90-second version

I'd state my assumptions first: the model is a URDF, units are SI (metres, radians), frames follow REP-103, and the service is stateless compute. It does not hold robot state. Then the interface: the request carries a model identifier (a content hash of the URDF, not a version string), a named base frame, a named target frame, a joint configuration as name→value pairs, and the timestamp the configuration was sampled. The response is a pose, position plus orientation, with explicit convention metadata: quaternion order, units, and the frame the pose is expressed in.

Why it behaves that way

Forward kinematics walks the chain from base link to target link and composes one transform per joint. A revolute joint contributes a rotation about its axis by the joint angle; a prismatic joint contributes a translation along its axis; a fixed joint contributes a constant transform. The composition is T_base_target = T_base_link1 · T_link1_link2 · … · T_linkN_target. Matrix multiplication does not commute, so the order of the chain is the whole computation: permuting joint order in the request must not change the result, because the chain order comes from the model, not the request.

Mimic joints are the trap. A gripper finger's value is derived from a source joint via a multiplier and offset. You must resolve mimics before composing, or you compute a pose the real robot cannot reach. If a client sends a mimic joint explicitly, that conflicts with the derived value: reject it rather than silently pick one.

Caching

The cache key is (model_hash, base, target, joint_configuration). The timestamp is deliberately excluded: it records when state was sampled, not the geometry. Two requests with identical joint values and different timestamps produce the identical pose, so keying on the timestamp makes every request a miss. The timestamp still matters: it drives a staleness check. If the sample is older than your freshness budget, return the pose but flag it, or reject, depending on whether the caller is planning or controlling.

Worked trace

Two-link planar arm, both revolute about z, each link 1.0 m, q1 = 0, q2 = π/2.

T = Rz(0) · Trans(1,0,0) · Rz(π/2) · Trans(1,0,0)
Rz(0)      = I
Trans(1,0,0) → (1, 0, 0)
Rz(π/2) rotates the next offset: Trans(1,0,0) → (0, 1, 0)
position = (1,0,0) + (0,1,0) = (1, 1, 0)
orientation = Rz(π/2) → quaternion (x,y,z,w) = (0, 0, 0.7071, 0.7071)

Trade-offs

DecisionAlternativeWhen it flips
Return pose + convention metadataReturn a 4×4 matrixMatrix is unambiguous but 12 numbers; pose matches geometry_msgs/Pose and is what callers want
Reject out-of-limit configsClamp to limitsReject for a reporting service; clamp only inside a controller that must keep moving
Cache the poseRecompute every callFK is a handful of matrix multiplies (microseconds); cache only pays off for long chains or high request rates, and adds invalidation cost
Quaternion order (x,y,z,w)(w,x,y,z)ROS uses xyzw; some libraries use wxyz: state it in the response so callers never guess

Failure modes

  • Missing joint: never default to zero; zero is a real pose and silently wrong. Detect by validating every model joint name is present, and return the missing name.
  • Model-version mismatch: client built a config for URDF v1, server holds v2, joint names differ. Detect by echoing the model hash in the response and rejecting on mismatch.
  • Unknown frame: base or target not in the model. Reject with the frame name.
  • Stale timestamp: geometry is correct, state is old. Flag it; the caller decides.

Tests: known poses, transform composition, alternate bases, joint-order permutations, unit handling, missing joints, model-hash changes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Prevent frame-direction bugs in a kinematics API.

Answer

Core (first 90 seconds). Assume a rigid-body API where a transform maps points from a source frame to a target frame, and the bug class is direction: a composition or inverse done in the wrong order, so the arm moves mirrored or a point lands on the wrong side. The fix is to make direction a type, not a comment. Encode both frames in the transform's type, name it target_T_source, and let the compiler reject any composition whose middle frames disagree. Add runtime frame IDs only where frames are resolved at runtime, the way tf2 carries string frame names.

Why the notation catches inversions. target_T_source reads left-to-right as "target from source", so the composition rule falls out: target_T_source = target_T_mid * mid_T_source. The middle frames must be identical: exactly the condition a phantom-type operator* enforces at compile time.

C++
// C++17, Eigen 3.4
#include <Eigen/Geometry>

template <class From, class To>
struct Transform {
    Eigen::Isometry3d T;   // maps a point in From to a point in To
};

struct map; struct base_link; struct camera_link;

// Compose only when the middle frames agree: (B->C) * (A->B) = (A->C)
template <class A, class B, class C>
Transform<A, C> operator*(const Transform<B, C>& lhs, const Transform<A, B>& rhs) {
    return {lhs.T * rhs.T};
}

template <class From, class To>
Transform<To, From> inverse(const Transform<From, To>& t) {
    return {t.T.inverse()};
}

Trace it the way the compiler deduces:

  • Transform<base_link, camera_link> T_bc; and Transform<map, base_link> T_mb;
  • auto T_mc = T_bc * T_mb; binds B=base_link, C=camera_link on the left and A=map, B=base_link on the right. B agrees, so it yields Transform<map, camera_link>: map to camera. Correct.
  • auto bad = T_mb * T_bc; binds B=map on the left and B=camera_link on the right. Deduction fails and the build stops. That is the catch.

Inverse is not negation. For T = [R t; 0 1], T^-1 = [R^T, -R^T t; 0 1]. Take R = +90° about z, t = (1,0,0). Then R^T t = (0,-1,0), so the inverse translation is (0,1,0), not the (-1,0,0) you get by negating t. Check: T^-1(1,0,0) = R^T(1,0,0) + (0,1,0) = (0,0,0). ✓

Trade-offs.

approachcatchescost
phantom typeswrong composition/inverse at buildtemplate error noise; can't carry runtime frame names; types thread through every signature
runtime frame-ID tags + assertwrong composition at first calla compare per composition; fails in the field, not the build
forbid raw matrix multiplybypass of the checkslose Eigen expression templates and interop; people add .matrix() escape hatches

Failure modes.

  • Inverse by negating translation only: the arithmetic above shows the wrong point.
  • Quaternion double cover: q and -q are the same rotation, so q1 == q2 fails. Compare via the sign of q1.coeffs().dot(q2.coeffs()) or the angle between them.
  • Dynamic frames: tf2's lookupTransform(target_frame, source_frame, time) returns target_T_source, the argument order is itself a footgun, and throws ExtrapolationException when time falls outside the buffer (default 10 s cache). A caught-and-ignored exception leaves the last good transform in place.
  • Chain resolution: a typo'd frame name that resolves to a different frame silently. Log the resolved chain (frame names plus timestamps) so the wrong chain is visible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Validate and repair rotation data at a system boundary.

Answer

Assumptions I'd state first. The boundary hands me a 3×3 matrix in float32 (a vision pose), downstream is a controller that assumes SO(3), and I can't change the upstream. If the payload is a quaternion the checks change but the decision doesn't.

The 90-second answer. Validate cheaply, repair only small drift, reject the rest, and make every repair visible. Four tests in order of cost: shape, finiteness, orthogonality residual, determinant sign. The residual is ‖RᵀR − I‖_F. For float32 I set the tolerance at 1e-5; for float64, 1e-10. Those aren't arbitrary: float32 carries ~7 significant digits (machine epsilon 1.19e-7), and a rotation composed 10⁴ times in float32 accumulates orthogonality error on the order of 1e-5 to 1e-4. Tighter than the arithmetic can hold rejects valid data; looser passes a visibly sheared matrix.

Why SVD gives the nearest rotation. SO(3) is a manifold, not a subspace, so I can't subtract the error. The Frobenius-norm projection of an arbitrary 3×3 matrix M onto SO(3) is: SVD M = UΣVᵀ, then R = U·diag(1, 1, det(UVᵀ))·Vᵀ. The unconstrained orthogonal projection is UVᵀ; if det(UVᵀ) = −1 that's a reflection, so I flip the sign of the smallest singular value's column to land on the rotation branch. That is the whole repair.

Python
import numpy as np

def validate(R, tol):
    if R.shape != (3, 3): return "shape"
    if not np.all(np.isfinite(R)): return "nonfinite"
    if np.linalg.norm(R.T @ R - np.eye(3), 'fro') > tol: return "orthogonality"
    if np.linalg.det(R) < 0: return "reflection"
    return None

def project_so3(M):
    U, _, Vt = np.linalg.svd(M)
    D = np.diag([1.0, 1.0, np.sign(np.linalg.det(U @ Vt))])
    return U @ D @ Vt

Trace. Take M = R_z(30°) with a 1e-4 shear in the (0,1) entry:

M = [[0.8660254, -0.4999,   0],
     [0.5,        0.8660254, 0],
     [0,          0,         1]]

MᵀM − I has (0,1) = (1,0) = 8.66e-5 and (1,1) = −1e-4, so ‖MᵀM − I‖_F ≈ 1.6e-4: above the float32 tolerance of 1e-5, so it fails. det(M) = 0.8660254² + 0.5·0.4999 ≈ 0.99995, positive, so it is not a reflection. project_so3 returns a matrix whose residual is ~1e-16 in float64, and the correction angle is ~1e-4 rad ≈ 0.006°. I log that angle; above 0.1° I escalate instead of repairing.

Convention is the trap. A transposed matrix is still a valid rotation: orthogonality and determinant both pass. If upstream sends column-major and I read row-major, I get Rᵀ, a rotation by the inverse angle, and no invariant catches it. I check convention against a known reference: push a known axis (+Z) through and compare to the expected output, or replay a calibration pose captured at commissioning. This is the failure that survives every numeric test.

Reject vs clamp vs quarantine. Rejecting a frame stalls the pipeline and drops sensor data you may need. Silent repair hides an upstream bug (a miscalibrated camera, a bad serialization) and the controller never learns. The middle path is quarantine: substitute the last known-good rotation, log the correction angle and source, alert when repair rate or correction magnitude crosses a threshold. I repair when the residual is within ~10× the arithmetic noise floor (~1e-4 for float32) and the correction angle is under 0.1°; above that I quarantine and page. A reflection (det < 0) is never repaired: it means a handedness or convention bug, and projecting it to SO(3) would silently flip the pose.

Production detection. Emit the orthogonality residual per source and alert on p99 crossing tolerance, not on a single frame. Count repairs per second and histogram the correction angle. A rising repair rate is the early signal of drift accumulation in an upstream integrator; a step change is a convention or calibration break.

Tests. Identity; a random valid rotation round-tripped through a quaternion and back; a near-drift matrix just under and just over tolerance; a reflection; NaN/Inf; and a transposed matrix to confirm the convention check fires.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Use Euler angles safely at an external interface.

Answer

Core answer. Treat Euler angles as a wire format, not a working representation. At the interface, pin the convention in the schema: for example "intrinsic ZYX (yaw, pitch, roll), right-handed, active, degrees, yaw ∈ (−180, 180], pitch ∈ [−90, 90], roll ∈ (−180, 180]", then convert to a quaternion on receipt and never compose, interpolate, or integrate in Euler. The convention is not optional metadata: the same three numbers mean different rotations under different axis orders, and a consumer that guesses wrong is silently off by tens of degrees.

Why the two failure modes bite.

Gimbal lock. For intrinsic ZYX, R = Rz(yaw)·Ry(pitch)·Rx(roll). At pitch = ±90°, Ry(90°) maps the z-axis onto the x-axis, so the first and third rotations act about the same physical axis. The rotation then depends only on (roll − yaw), not on yaw and roll separately. Concretely, (yaw=30°, pitch=90°, roll=40°) and (yaw=10°, pitch=90°, roll=20°) both give

[[ 0.      0.1736  0.9848]
 [ 0.      0.9848 -0.1736]
 [-1.      0.      0.    ]]

so a round trip through the wire format cannot return the numbers you sent. The same singularity appears in the rate mapping: yaw rate = (ω_y sin φ + ω_z cos φ)/cos θ, which diverges as θ → 90°. A small body rotation demands unbounded yaw rate.

Wrapped-angle subtraction. If target yaw is 179° and current yaw is −179°, target − current is 358°, not −2°. A controller fed that error slews the long way around. Wrap the difference: (target - current + 180) % 360 - 180, or atan2(sin(a-b), cos(a-b)).

Conventions you will actually meet.

InterfaceConventionDefault / units
ROS tf.transformations.euler_from_quaternionaxes string; 'sxyz' = extrinsic static xyz = intrinsic ZYXdefaults to 'sxyz'
scipy Rotation.from_eulerseq string; uppercase intrinsic, lowercase extrinsicno default: seq is required
URDF <origin rpy="r p y">fixed-axis (extrinsic) XYZ = intrinsic ZYXradians, no degrees option
ROS sensor_msgs/Imuquaternion on the wire—

Code.

Python
import numpy as np
from scipy.spatial.transform import Rotation as R

# Wire format: intrinsic ZYX (yaw, pitch, roll), degrees, right-handed, active.
a = R.from_euler('ZYX', [30.0, 90.0, 40.0], degrees=True)
b = R.from_euler('ZYX', [10.0, 90.0, 20.0], degrees=True)
print(np.allclose(a.as_matrix(), b.as_matrix()))          # True
print(np.round(a.as_matrix(), 4))
# [[ 0.      0.1736  0.9848]
#  [ 0.      0.9848 -0.1736]
#  [-1.      0.      0.    ]]

target, current = 179.0, -179.0
print(target - current)                                    # 358.0
print((target - current + 180.0) % 360.0 - 180.0)          # -2.0

Trade-offs. Euler is 3 numbers, human-readable, and fine for a config file or a display. It is the wrong choice the moment you compose, interpolate, or integrate: lerping Euler angles does not take the shortest path, and the representation is singular. Quaternions are 4 numbers, singularity-free, and slerp is correct, at the cost of double cover (q and −q are the same rotation) and a normalization step. Rotation matrices are 9 numbers, singularity-free, but drift off orthonormal under repeated multiplication and need re-orthonormalization. ROS puts quaternions on the wire for exactly this reason.

Failure modes and detection. Non-uniqueness at pitch = ±90°: detect by checking |pitch| against a threshold (say 89.9°) and refusing or switching representation. Wrap error: unit-test the pair (179°, −179°) and assert the error is −2°, not 358°. Convention mismatch: round-trip a canonical triple through the interface and compare matrices, not angles. Quaternion sign flip: assert dot(q1, q2) ≥ 0 before slerp.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design quaternion storage and interpolation for robot poses.

Answer

Core answer (first 90 seconds)

Store the pose as a unit quaternion in (x, y, z, w) order, float32 on the wire and float64 in the integrator, representing the active rotation that maps a vector in the child frame into the parent frame (ROS tf2 convention, right-handed). Normalize on ingest and after every integration step; reject ‖q‖ < 1e-6 as invalid. Interpolate with slerp when a step can exceed ~10°, nlerp when it cannot. Before interpolating, negate the incoming quaternion whenever dot(q_prev, q_next) < 0.

Storage layout, and why it bites

Component order is the most common integration bug. ROS geometry_msgs/Quaternion, tf2, scipy.spatial.transform.Rotation.as_quat(), Unity and glTF 2.0 all serialize (x, y, z, w). Eigen's Quaterniond stores coeffs in that same memory order, but its constructor is Quaternion(w, x, y, z), so Quaterniond(q.x, q.y, q.z, q.w) compiles and silently yields a wrong rotation. GLM defaults to (w, x, y, z). Pick one order, name it in the header, convert at every boundary.

representationbytes (float32)interpolationbreaks when
quaternion16slerp/nlerp, constant velocitysign flip, non-unit norm
rotation matrix36needs re-orthonormalizationdrift makes it non-orthogonal
axis-angle16ambiguous at θ=0θ→0 or θ→2π
Euler12ambiguousgimbal lock at ±90° pitch

Why slerp, and what nlerp costs

slerp moves at constant angular velocity along the great circle between q0 and q1. nlerp normalizes the linear blend: it avoids the acos and two sin calls, but its angular velocity varies. The deviation peaks away from the midpoint. Computed for a step of rotation angle θ:

  • θ = 180°: nlerp deviates from slerp by up to ~4.1° (at t≈0.25)
  • θ = 90°: ~0.45°
  • θ = 10°: <0.01°

So at 1 kHz control with per-frame steps under 10°, nlerp is indistinguishable and cheaper; for a 180° wrist flip the 4° path error shows up as a velocity dip. Use slerp for large steps, nlerp for small ones, and squad when you need C1 continuity across a keyframe sequence.

Sign consistency

q and −q are the same rotation (double cover). Without sign alignment, slerp takes the long way: an intended 10° step becomes 350°, a visible jerk. Fix: if dot(q_prev, q_next) < 0, negate q_next before interpolating. Detect by logging per-frame angular delta: a value near 360°−θ instead of θ is a sign flip.

Failure modes and detection

  • Sign flip → 350° jerk. Detect: per-frame angular delta above a threshold (e.g. 90°).
  • Non-unit q → the rotation matrix is scaled, poses shear. Detect: |‖q‖−1| > 1e-6.
  • Near-zero q → normalization divides by ~0, NaN enters the pose. Detect: isnan on the pose, ‖q‖ < 1e-6.
  • slerp at Ω→0 or Ω→π → sin Ω → 0, division by zero. Handle: fall back to nlerp near 0, sign-flip near π.
  • float32 drift: ~1e-7 relative per operation; a 1 kHz loop that never renormalizes accumulates norm error of order 1e-4 within a minute (random-walk estimate). Renormalize every step.

When not to use quaternions

If you must interpolate translation and rotation together over large translations, dual quaternions avoid the screw-motion artifacts of separate lerp+slerp. If you are optimizing over rotations (IK, bundle adjustment), work in the Lie algebra via the log map and retract with exp: quaternion components are constrained, so gradient steps leave the unit sphere.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Review a base-to-camera-to-tool transform chain.

Answer

State the assumptions first: eye-in-hand camera rigidly bolted to the flange, ROS 2 with tf2, and the vision node already producing an object pose in the camera optical frame. If it's eye-to-hand the chain changes shape but the review doesn't.

The chain is a product of rigid transforms, and the review is four questions: is each edge pointing the right way, is the order right, is the time coherent, and which edge dominates the error.

For eye-in-hand:

T_base_obj = T_base_tool · T_tool_cam · T_cam_obj

T_base_tool comes from forward kinematics: URDF plus joint states through robot_state_publisher. T_tool_cam is the hand-eye calibration (cv2.calibrateHandEye or equivalent), a static edge. T_cam_obj is the vision output. ROS uses column vectors, so the product reads left to right along the chain; port it to a row-vector convention and the order reverses. That reversal is the most common silent bug.

Direction: tf2's TransformStamped has header.frame_id as parent and child_frame_id as child, and lookupTransform(target, source, time) returns the transform taking a point in source into target. So T_tool_cam is lookupTransform('tool0', 'camera_link', t), not the reverse. Inverting the wrong edge still yields a matrix that looks like a pose and still multiplies cleanly; nothing throws.

Time: this is where the moving flange bites. tf2 interpolates across the tree inside a single lookupTransform call, so one lookup at the image timestamp is coherent by construction. The bug is running vision at t_capture and querying the arm at t_now. At 0.2 m/s tool speed and a 50 ms gap that's 10 mm of position error before any calibration error. Stamp the image and query the arm at that stamp. tf2's Buffer caches 10 s by default; older gives ExtrapolationException, an unpublished frame gives LookupException.

Failure modes worth naming. Drifted hand-eye: someone bumps the bracket or re-homes the arm, T_tool_cam is now off by a few mm and a fraction of a degree. Detect it by putting a target at a known base-frame pose and comparing the chain's answer to the measured one: the residual grows and stays. Cost is a systematic grasp offset; 5 mm on a 20 mm part is a miss. Wrong convention: camera_link versus camera_optical_frame. ROS optical frames are x right, y down, z forward (REP-103); the body frame is x forward, y left, z up. Mixing them rotates the result 90° and reads as a calibration problem. Stale TF: a static edge published once at startup with a bad value, or a dynamic edge that stopped updating.

Verification: transform known points. The tool tip is (0,0,0) in tool0 and must land on the flange origin. Transform the camera's z axis and check it points where the camera looks. With a fixed target at a known base pose, close the loop through the whole chain.

Sensitivity: perturb each extrinsic by 1 mm and 0.1° and watch the object pose move. Translation errors propagate 1:1. 2 mm in T_tool_cam is 2 mm at the object. Rotation errors scale with range: 0.5° about the camera z at 0.5 m is 0.5·π/180·0.5 ≈ 4.4 mm lateral. That tells you whether to spend the day on calibration or on timestamping.

The alternative is to skip the chain and calibrate base-to-camera directly with a target on the floor. Fine for a fixed cell, but it doesn't survive the arm being re-homed and it can't tell you which edge drifted.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

What is the difference between geometric and analytical Jacobians, and how do you map end-effector velocities between them?

Answer

Core Distinction

The geometric Jacobian ($J_g$) maps joint velocities $\dot{q} \in \mathbb{R}^n$ directly to a physical spatial twist $V = [\omega^T, v^T]^T \in se(3) \cong \mathbb{R}^6$ (or $[v^T, \omega^T]^T$ depending on twist ordering conventions), expressing instantaneous physical angular velocity $\omega$ and linear velocity $v$.

$$V = \begin{bmatrix} \omega \ v \end{bmatrix} = J_g(q) \dot{q}$$

The analytical Jacobian ($J_a$) is the direct partial derivative of an operational space coordinate vector $x(q) = [p(q)^T, \phi(q)^T]^T \in \mathbb{R}^m$ with respect to joint coordinates $q$:

$$\dot{x} = \begin{bmatrix} \dot{p} \ \dot{\phi} \end{bmatrix} = \frac{\partial x(q)}{\partial q} \dot{q} = J_a(q) \dot{q}$$

where $\phi$ is an explicit minimal local parameterization of orientation (such as Euler angles, roll-pitch-yaw, or Rodrigues parameters).

The Mapping Mechanism

Angular velocity $\omega$ is not the direct time derivative of any three-parameter orientation representation (i.e., $\omega \neq \dot{\phi}$). Instead, instantaneous angular velocity relates to $\dot{\phi}$ through a configuration-dependent linear transformation matrix $T(\phi)$:

$$\omega = T(\phi) \dot{\phi}$$

For example, using ZYX Euler angles $\phi = [\alpha, \beta, \gamma]^T$ (yaw, pitch, roll):

$$\omega = \begin{bmatrix} 0 \ 0 \ 1 \end{bmatrix} \dot{\alpha} + R_z(\alpha) \begin{bmatrix} 0 \ 1 \ 0 \end{bmatrix} \dot{\beta} + R_z(\alpha) R_y(\beta) \begin{bmatrix} 1 \ 0 \ 0 \end{bmatrix} \dot{\gamma} = T(\phi) \dot{\phi}$$

Relating the full twist to operational velocity gives:

$$V = \begin{bmatrix} \omega \ v \end{bmatrix} = \begin{bmatrix} T(\phi) & 0 \ 0 & I_{3\times 3} \end{bmatrix} \begin{bmatrix} \dot{\phi} \ \dot{p} \end{bmatrix} = E(\phi) \dot{x}$$

Substituting $\dot{x} = J_a \dot{q}$ and $V = J_g \dot{q}$:

$$J_g(q) = E(\phi) J_a(q) \implies J_a(q) = E(\phi)^{-1} J_g(q)$$

where $E(\phi) = \begin{bmatrix} T(\phi) & 0 \ 0 & I \end{bmatrix}$ (adjusted according to whether twist is defined as $[\omega, v]$ or $[v, \omega]$).

Comparison Table

PropertyGeometric Jacobian ($J_g$)Analytical Jacobian ($J_a$)
CodomainLie algebra $se(3)$ (physical twist: $\omega, v$)Coordinate tangent space $\mathbb{R}^6$ ($\dot{p}, \dot{\phi}$)
SingularitiesPhysical kinematic singularities only (loss of task-space rank)Kinematic singularities plus representation singularities where $\det(T(\phi)) = 0$
Frame InvarianceCoordinate-free vector property; transforms via Adjoint matrixDependent on chosen chart/coordinates for $SO(3)$
Duality with ForcesDirect: $\tau = J_g^T F$ maps physical wrenches $[m^T, f^T]^T$ to joint torquesRequires transformation: $\tau = J_a^T h_a$, where $h_a$ are generalized coordinate forces

Failure Modes & Trade-offs

  1. Representation Singularity Leakage: Inverting $J_a$ near orientation singularities (e.g., gimbal lock at pitch $\beta = \pm \pi/2$ for Euler angles) introduces unbounded joint velocities $\dot{q} = J_a^{-1} \dot{x}$, even when the robot arm is fully inside its physical manipulability ellipsoid. $J_g$ has no representation singularities.
  2. Energy Inconsistency in Control: Setting joint torques as $\tau = J_a^T F_{\text{task}}$ assuming $F_{\text{task}}$ is a Cartesian wrench will corrupt torque commands unless $F_{\text{task}}$ has been converted through $E(\phi)^T$.
  3. Quaternion Formulations: When $x$ uses a unit quaternion $q_e = [\eta, \epsilon^T]^T \in S^3$, $J_a$ is $7 \times n$. It requires pseudo-inversion with quaternion normalization constraints ($q_e^T \dot{q}_e = 0$) or projection via $\omega = 2 E(q_e) \dot{q}_e$ to avoid rank-deficiency issues.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Define manipulability and singularity health metrics.

Answer

Core answer. Manipulability is a scalar summary of how much task-space velocity the arm can produce per unit of joint velocity. Yoshikawa's index is

w = sqrt(det(J Jᵀ))

where J is the m×n task Jacobian at the current configuration. Since det(JJᵀ) = ∏σᵢ², w is the product of the singular values: proportional to the volume of the manipulability ellipsoid, the image of the unit joint-velocity ball {q̇ : ‖q̇‖ = 1} under J. For a non-redundant 6-DOF arm J is 6×6 and w = |det J|.

Singularity health is the set of metrics that say how close J is to losing rank: the smallest singular value σ_min, the condition number κ = σ_max/σ_min, and the direction of weakest authority. The left singular vector u_min belonging to σ_min. State your assumptions: one consistent task frame, all rows in the same unit, J evaluated at the current configuration.

Mechanism. At a singularity J loses rank, one σ goes to zero, and the ellipsoid collapses to a plane. The pseudoinverse J⁺ = V Σ⁺ Uᵀ amplifies by 1/σ_min, so a commanded task velocity along u_min demands joint rate scaled by 1/σ_min. For square J, σ_min is also the distance in Frobenius norm from J to the nearest rank-deficient matrix: it is literally how far the pose is from singularity.

Scaling. J's rows carry different units: translational rows are m/rad for revolute joints, rotational rows are dimensionless. det(JJᵀ) then mixes units and w is not comparable across poses or unit systems. Multiply the rotational rows by a characteristic length L, or divide the translational rows by L, so every row shares one unit before computing w, σ_min or κ. L is a choice (arm reach, wrist-to-tool distance) and must be stated, because w and κ both move with it.

Metrics and when to use each.

metricformulareadsblind to
wsqrt(det(JJᵀ)) = ∏σᵢoverall dexterity volumescaling, joint limits
σ_minsmallest singular valueworst-case task gain, distance to singularitywhich direction
κσ_max/σ_minanisotropyredundant J (n>m), where extra DOF keep σ_min away from zero and κ stays moderate
u_minleft singular vector of σ_minweakest directionmagnitude

κ is only meaningful when σ_min is bounded away from zero and J is well scaled; on a redundant arm it stays small and hides the useful signal, so use σ_min there. w is not scale-invariant and says nothing about joint limits: a pose near a limit can still score high.

Worked arithmetic (illustrative). Scaled 2×2 Jacobian J = diag(1.0, 0.05). Singular values 1.0 and 0.05, so w = 0.05 and κ = 20. Command ẋ = [0, 0.1] m/s along the weak axis: q̇ = J⁻¹ẋ = [0, 0.1/0.05] = [0, 2] rad/s. Extend the arm until σ_min = 0.01: κ = 100, and the same 0.1 m/s command needs q̇₂ = 10 rad/s. Five times the joint rate for the same task speed. That is the number that trips a rate limit.

Failure modes and detection. σ_min → 0 with a nonzero command along u_min shows up as joint-rate saturation plus growing residual task error; watch both next to the metric, because the metric alone does not tell you the command was in the weak direction. A high w while the arm sits near a joint limit is the classic false pass: check joint-limit proximity separately. Illustrative thresholds, consistent with each other: warn at κ > 20 (σ_min < 0.05 σ_max), slow the commanded speed at κ > 100, stop at κ > 1000, with hysteresis so a pose hovering at a boundary does not chatter between states.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Design behavior near a kinematic singularity.

Answer

Assume a 6-DOF serial arm with a 6×6 Jacobian J(q), task xdot = J qdot, control at 1 kHz, and a joint velocity limit of 2 rad/s. The controller must decide what to do when the smallest singular value σ_min(J) approaches zero.

Core answer. Do not gate on det(J). Compute σ_min from an SVD every cycle. If σ_min > ε (I use ε = 0.05 after normalizing J by arm length), use the plain pseudoinverse. If σ_min < ε, switch to damped least squares: qdot = Jᵀ(JJᵀ + λ²I)⁻¹ xdot, with λ ramped as λ = λ_max sqrt(1 - (σ_min/ε)²) for σ_min < ε, else 0. λ_max = 0.1 is a reasonable starting point. Then clamp qdot to joint limits, project a secondary task (joint-limit avoidance) through the nullspace, and if σ_min falls below a hard floor (0.01) or the required task direction lies in the lost subspace, stop or command a precomputed alternate posture.

Why it works. σ_min is the gain from joint motion to the least-mobile Cartesian direction. As σ_min→0, the pseudoinverse has a 1/σ_min term, so a 0.1 m/s command can demand tens of rad/s. DLS adds λ² to the singular values of J, so the inverse is bounded by 1/λ. The cost is tracking error in that direction: the fraction of the command not achieved is λ²/(σ_min²+λ²). At σ_min = 0.02 and λ = 0.1, that is 0.01/(0.0004+0.01) ≈ 96% of the command in the singular direction is not tracked, but joint velocities stay bounded.

Worked trace. Two-link planar arm, l1 = l2 = 0.5 m, q1 = 0, q2 = 0.1 rad. J = [[-0.0499, -0.0499], [0.9975, 0.4975]]. SVD gives σ_min ≈ 0.022. Command xdot = [0.1, 0] m/s. Without damping, qdot ≈ [2.0, -4.0] rad/s. With λ = 0.1, qdot ≈ [0.09, -0.19] rad/s. Damping cuts joint speed by ~20× at the cost of not tracking the x command. That is the trade-off you are buying.

Alternatives. DLS is cheap (one SVD plus a 6×6 inverse) and smooth, but it trades tracking for bounded velocity and can still violate joint limits if λ is too small. Constrained optimization (QP) can enforce joint limits and task priority exactly, but costs more per cycle and can chatter if the active set changes. Use DLS when the singularity is transient and the task can tolerate error; use QP when joint limits or safety constraints are hard. A fixed λ is simpler but over-damps away from the singularity; the ramped λ above keeps tracking when σ_min is healthy.

Failure modes and detection.

  1. σ_min is small but the task direction is not in the lost subspace: DLS over-damps unnecessarily. Detect by projecting xdot onto the left singular vector of σ_min; if that projection is below 10% of ||xdot||, don't damp.
  2. λ too small: joint velocity saturates, integrator windup, then a lurch when leaving the singularity. Detect by monitoring qdot saturation and the integral of tracking error.
  3. Branch transition: two IK solutions meet at the singularity; a naive switch causes a 180° joint jump. Detect by comparing commanded to actual joint angles; if the jump exceeds 0.5 rad in one cycle, blend over 100 ms.
  4. Sensor noise: σ_min from a noisy Jacobian crosses the threshold every cycle, causing damping chatter. Detect by hysteresis: enter damping at σ_min < 0.05, leave at σ_min > 0.08.

Operational cost. Near a singularity the arm may need to slow to 0.1 m/s or stop for 200 ms while it reconfigures. That is acceptable for pick-and-place but not for a continuous welding pass. State that trade-off in the design review.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Specify an IK objective and acceptance test.

Answer

Assume a 6-DoF serial arm, a pose target for the tool flange, and a numerical solver (damped least squares or a QP). The objective is a cost over the pose residual plus constraints; the acceptance test is a per-component check on the returned joint vector, recomputed with independent forward kinematics: never the solver's own reported cost.

Objective. Let p_d, R_d be the target position and orientation in the target frame, and p(q), R(q) the FK result for joint vector q. Position residual e_p = p_d - p(q). Orientation residual is the geodesic on SO(3):

e_o = log(R_d^T R(q))            # rotation vector, so(3)
theta = ||e_o|| = arccos((tr(R_d^T R(q)) - 1) / 2)

Cost: J = ||e_p / L||²_Wp + ||e_o||²_Wo + regularization, where L is a characteristic length (e.g. 0.1 m for a 10 cm reach task) that makes the two terms dimensionless so Wp, Wo are comparable.

Why the geodesic, not Euler subtraction. Euler-angle differences are not a metric: near pitch ±90° the angles jump, so a 1° physical rotation can read as a 90° difference, and the value depends on the chosen Euler convention. The log map returns the shortest rotation and is frame-invariant.

Why a scalar hides violations. Two solutions for the same target, L = 0.1 m:

solutionpos errori errJ = (pos/L)² + ori²
A5 mm0.005 rad0.0025 + 0.000025 = 0.002525
B1 mm0.05 rad0.0001 + 0.0025 = 0.0026

A and B are within 3% on the scalar, but if the task tolerance is 2 mm position, A fails and B passes. A weighted sum lets a large error on one axis be traded against another; only per-component checks catch it.

Hard vs soft. Make it hard when violation is unsafe or infeasible (joint limits, self/environment collision, torque limits) enforced as constraints or rejected outright. Make it soft when it is a preference (elbow-up posture, distance from singularity) placed in the nullspace or as a regularizer. Deciding criterion: if a returned q that violates it must never be executed, it is hard.

Acceptance test. Recompute FK from the returned q and check each item:

  • Position: per-axis |Δx|, |Δy|, |Δz| ≤ 1 mm in the target frame (or norm ≤ 1 mm).
  • Orientation: geodesic theta ≤ 0.5° = 8.7e-3 rad.
  • Joint limits: margin ≥ 2° from every limit.
  • Collision: minimum clearance ≥ 5 mm.
  • Task mask: only constrained axes are checked; for a drill, rotation about the tool approach axis is free and must be masked out, or reachable targets get rejected.

Failure modes. Soft joint limits with a large weight still return a limit-violating q when the pose is unreachable: acceptance must reject it. Local minima satisfy the cost but miss the target; detect by restarting from several seeds and comparing best per-component residuals. A solver-reported cost below threshold is not evidence of a valid pose.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design an IK result contract and failure handling.

Answer

Core answer (first 90 seconds)

An IK result is a value object with a status enum, not a boolean, not a bare joint vector. The caller branches on status; it never branches on "is the solution field populated".

Minimum contract:

  • status: SUCCESS | APPROXIMATE | TIMEOUT | NO_SOLUTION | INVALID_INPUT | NUMERICAL_FAULT
  • q: joint vector, defined only for SUCCESS and APPROXIMATE
  • residual: (pos_err_m, rot_err_rad), computed by running FK on q against the target as it is now
  • margins: per-joint distance to limits, plus collision margin if the solver checks it
  • iterations, elapsed_s, seed, solver_name, model_hash

The rule that carries the design: SUCCESS means FK(q) meets tolerance against the current target. A cached solution from an earlier call is never promoted to SUCCESS. MoveIt already ships this shape: GetPositionIK returns a RobotState plus MoveItErrorCodes, which separates TIMED_OUT from NO_IK_SOLUTION so the caller can retry one and not the other.

Why residuals, and how they are computed

Position error is ||p_ach - p_tgt||_2. Orientation error is the rotation angle of R_tgt @ R_ach.T: theta = arccos((trace(R) - 1) / 2). Both are cheap (one FK, no solver call) which is why the contract can afford to recompute them on every result rather than trusting the solver's internal convergence flag. A solver can report converged on a step it clipped, or on a residual measured against a target that has since moved.

Python
import numpy as np
POS_TOL, ROT_TOL = 1e-3, 1e-3          # 1 mm, 1 mrad

def residual(T_ach, T_tgt):
    dp = np.linalg.norm(T_ach[:3, 3] - T_tgt[:3, 3])
    R = T_tgt[:3, :3] @ T_ach[:3, :3].T
    dth = np.arccos(np.clip((np.trace(R) - 1.0) / 2.0, -1.0, 1.0))
    return dp, dth

def classify(dp, dth, iters, max_iters, elapsed, budget):
    if dp <= POS_TOL and dth <= ROT_TOL:
        return "SUCCESS"
    if elapsed >= budget or iters >= max_iters:
        return "TIMEOUT"
    return "APPROXIMATE"

Trace: residual(T, T) gives R = I, trace = 3, (3-1)/2 = 1, arccos(1) = 0 → (0.0, 0.0). classify(0.0, 0.0, 12, 100, 0.002, 0.005) → first branch → SUCCESS. classify(0.004, 0.0002, 100, 100, 0.005, 0.005) → position over tolerance, elapsed at budget → TIMEOUT.

Trade-offs: three failure policies, not one

  1. Retry with a new seed. Works when the failure is a local minimum. TRAC-IK is built on this: it runs KDL's Newton-Raphson and an SQP solver in parallel and takes the first to converge, exposing a timeout parameter (commonly 5 ms in the ROS plugin) and a solve_type of Speed/Distance/Manip1/Manip2. Retry only pays if the seed distribution actually changes: re-seeding with the same q_init is a no-op. KDL's ChainIkSolverPos_NR_JL defaults to maxiter=100, eps=1e-6, so a bare retry loop hits the same wall.
  2. Accept APPROXIMATE. Right for a compliant task (peg insertion under force control) or a visual-servo loop that corrects next frame. Wrong for a hard constraint like a weld seam.
  3. Return partial (position met, orientation off). Only useful if the caller can decompose the task; most planners cannot, so this is usually a trap.

Rejecting everything is also a policy, and it is the wrong default for a 100 Hz servo loop: a TIMEOUT at 5 ms that aborts the cycle is worse than an APPROXIMATE the next cycle corrects.

Failure modes

failurecausedetectionresponse
stale solutiontarget frame moved (conveyor, new perception frame), cached q returnedrecompute FK on q, compare to current targetreject, re-solve
silent singularitysigma_min(J) -> 0, step clipped, residual looks smallsigma_min or the DLS damping termdamped step, flag APPROXIMATE
limit violationsolver clamps q after the factmargins negativereject
model mismatchcalibration changedmodel_hash differsreject, reload

Arithmetic that sets the tolerances

1 mrad of orientation error at a 0.5 m tool offset is 0.5 mm of tip error, so 1 mm and 1 mrad are roughly matched at that lever arm; at a 1.5 m reach the orientation term dominates and should be tightened. For damped least squares the step gain is sigma / (sigma^2 + lambda^2), peaking at sigma = lambda with value 1 / (2*lambda): lambda = 0.01 caps the gain at 50, lambda = 0.1 at 5. That is the knob between crawling near a singularity and jumping across it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Select among multiple IK solutions safely.

Answer

Assumptions. 6R arm with a spherical wrist (up to 8 analytic IK solutions) or 7R redundant arm (a 1-D self-motion manifold, usually sampled by swivel angle). 1 kHz control loop, joint limits ±170°. Different arm, same structure, different numbers.

Core answer. Never command the first solution the solver returns. Enumerate all of them, apply hard filters that cannot be traded off, then rank the survivors with continuity as the primary key. Hard filters: joint limits, self/environment collision, singularity margin (smallest singular value of the Jacobian), and hardware constraints such as cable-limited wrist travel. Ranking: joint-space distance from the measured configuration first, then manipulability, then posture and secondary objectives. Carry the branch identity across cycles and add a hysteresis margin so solver noise near a branch merge does not flip you. If the only feasible candidate is a large joint-space jump away, do not take it: return failure and replan the Cartesian path. Check the interpolated path, not just the endpoints.

Why continuity leads. IK branches are discrete: up to 8 for a 6R spherical-wrist arm, a continuum for a 7R arm. Two branches meet only where the Jacobian loses rank: for a 2R planar arm, at full extension (θ₂ = 0) and full fold (θ₂ = ±180°). At the merge they are the same configuration, so a sub-millimetre Cartesian move can land you on either. Ranking by joint-space distance from where you are keeps you on the branch you are on, because the alternative is metres away in joint space. Continuity does not pick the best solution; it picks the one that does not require the arm to teleport.

Manipulability, and when it cannot decide. Yoshikawa's measure is w = √(det(J Jᵀ)), which for square J is |det J|. The singularity margin is σ_min(J), the smallest singular value: distance to losing a degree of freedom. For a 2R planar arm with links L₁, L₂, det J = L₁L₂ sin θ₂, so |det J| depends only on |θ₂| and is identical for elbow-up and elbow-down. Manipulability can never break that tie; continuity and joint limits do. Rank it as a filter and tiebreaker, never as the primary key.

Worked trace. 2R planar arm, L₁ = L₂ = 0.5 m, limits ±170°, σ_min threshold 0.05, switch margin 0.35 rad, jump limit 0.5 rad.

Python
import numpy as np

def wrap_to_pi(a):
    return (a + np.pi) % (2*np.pi) - np.pi

def select(q_meas, candidates, limits, J_of, collides, active=None,
           sigma_min=0.05, switch_margin=0.35, jump_max=0.5):
    """candidates: list of (branch_id, q). Returns (q, status)."""
    feasible = []
    for bid, q in candidates:
        if np.any(q < limits[:, 0]) or np.any(q > limits[:, 1]):
            continue                                  # joint limits
        if collides(q):
            continue                                  # self / environment
        s = np.linalg.svd(J_of(q), compute_uv=False)
        if s[-1] < sigma_min:
            continue                                  # singularity margin
        d = np.linalg.norm(wrap_to_pi(q - q_meas))
        feasible.append((bid, q, d, s[-1]))
    if not feasible:
        return None, "no feasible candidate"
    feasible.sort(key=lambda c: c[2])                 # continuity first
    bid, q, d, smin = feasible[0]
    if active is not None:
        cur = [c for c in feasible if c[0] == active]
        if cur and d > cur[0][2] - switch_margin:     # hysteresis
            return cur[0][1], "kept branch %s" % active
    if d > jump_max:
        return None, "only candidate %.2f rad away; replan" % d
    return q, "ok"

Starting at q_meas = (−23.4°, 108.7°) on branch A:

target (m)branch A q (deg)d_A (rad)σ_min Abranch B q (deg)d_B (rad)σ_min Bresult
(0.50, 0.30)(−23.4, 108.7)0.000.35(85.3, −108.7)3.130.35A
(0.55, 0.33)(−19.1, 100.2)0.160.33(81.1, −100.2)3.210.33A
(0.995, 0.00)(−5.7, 11.5)—0.045(5.7, −11.5)—0.045none

Row 3 is the interesting one: the target is reachable in Cartesian space, both branches clear the joint limits, and both are rejected on σ_min. The selector returns failure rather than the least-bad pose.

Failure modes.

Branch flip mid-motion. The branch you are on becomes infeasible, a joint limit or σ_min crossing the threshold, and the only survivor is 3.2 rad away. Detect it by comparing d_best against a jump threshold every cycle and logging the branch id. Cost: 3.2 rad in one 1 ms cycle is 3200 rad/s, past any joint's limit, so the controller faults or the trajectory smoother turns it into a whip. Response: reject, stop, replan the Cartesian path so the arm crosses the merge region deliberately.

Singularity found mid-transition. Both endpoints clear σ_min = 0.05 but the interpolated path dips below. Detect by sampling the joint-space path, every 5° of joint travel is plenty, and evaluating σ_min at each sample. Cost: q̇ = J⁻¹ẋ, so ‖q̇‖ ≤ ‖ẋ‖/σ_min; at σ_min = 0.01 and ẋ = 0.1 m/s that is 10 rad/s, which the joint cannot track, so the tool lags the command and the path is wrong even when nothing faults.

No feasible candidate. Return the reason, not the nearest solution. The caller needs to know whether limits, collision or σ_min killed it, because the fix differs: limits → replan the Cartesian path; collision → move the obstacle or the approach; σ_min → route around the singularity. Silently returning the least-bad candidate is how you get a collision.

What would change the decision. On a 7R arm sampling the self-motion manifold, continuity ranking is over the swivel angle rather than discrete branches, and the margin becomes a rate limit on swivel change. If the arm is parked and the task is quasi-static, manipulability can lead, because there is no motion to be continuous with. And with a real-time Cartesian servo using damped least squares, the damping handles the singularity, but you still need the joint-limit and collision filters.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Build a robust multi-start numerical IK strategy.

Answer

Assumptions first: a 7-DOF serial arm, a 6-DOF target pose with tolerances of 1 mm and 0.5°, damped least squares (Levenberg–Marquardt) as the local solver, joint limits and a collision checker available. If the arm were 6-DOF and non-redundant I'd try an analytic solver (IKFast) first and only fall back to multi-start when limits or collisions invalidate the closed-form solutions.

Multi-start is a search over the basins of attraction of a local solver. A Newton-type step converges to the solution nearest the seed, so the seed decides which branch you land on: elbow-up vs elbow-down, shoulder-flip, and for a redundant arm which point on the self-motion manifold. That is the whole mechanism: you are not making the solver smarter, you are sampling the branches and picking a feasible one.

Seeds. Seed 0 is the current or predicted configuration, for continuity: smallest joint motion, which is what trajectory following wants. Then a fixed low-discrepancy set (Halton) over the joint ranges, plus targeted seeds: the mirrored elbow/shoulder branch, and samples across the redundant joint's range. Deterministic, because replay matters: the same inputs must give the same output so a failed plan is reproducible.

Residual scaling. The error vector mixes metres and radians. I weight orientation by a characteristic length L (I use 0.1 m/rad) so 0.1 rad costs the same as 1 cm, or set separate tolerances. Without it the damping term λ²I is applied to a Jacobian whose position and orientation blocks differ by orders of magnitude, and the solver trades one against the other arbitrarily.

Worked run: 7-DOF arm, target pose, DLS, per-seed budget 5 ms, tolerance 1 mm / 0.5° (figures illustrative):

seedsourceiterspos errori errterminationfeasible
0current config120.8 mm0.3°convergedyes
1Halton400.9 mm0.4°convergedno (collision)
2elbow-flip90.7 mm0.2°convergedyes
3Halton4022 mm6°max itersno
4redundant-joint sweep151.1 mm0.6°convergedno (limit)

Ranking: feasible solutions first, then joint-space distance to seed 0 (continuity), then residual. Seed 0 wins if feasible; otherwise seed 2.

Budget arithmetic: worst case is N seeds × per-seed budget. Five seeds at 5 ms is 25 ms; eight is 40 ms. A 100 Hz control loop has 10 ms, so you cannot run eight seeds inline: you run them off the critical path or cut to two or three.

Failure modes and detection.

  • False convergence: the flag says converged but the residual is above tolerance (seed 3 above: 22 mm). Detect by checking the final residual, never the flag.
  • Limit trapping: a joint pinned at its bound while the residual is dominated by motion along that direction. Detect by checking joints within ε of a limit.
  • Wraparound: ±π representation turns a +350° target into −10°. Detect by joint-space distance to the seed exceeding π; re-seed with the wrapped equivalent.
  • Singularity: smallest singular value of J below threshold; symptom is large Δq for a small residual change. DLS damps it but biases the solution toward the seed.
  • Timeout under load: per-seed wall-clock varies; log it, because the symptom is nondeterministic output.

Trade-offs. DLS vs pure Newton: DLS survives singularities but converges slower and is biased toward the seed. Deterministic vs random seeds: replay and coverage guarantees vs broader sampling. More seeds vs latency: linear cost. And a portfolio solver like TRAC-IK (KDL and an SQP solver in parallel threads, first to converge wins) buys robustness a different way, without the seed sweep.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Use redundancy for joint-limit avoidance.

Answer

Assumptions first. Redundant arm: n joints, m task DOF, n > m. Velocity-level control at 1 kHz, joint limits known and static. I'm assuming the primary task is a Cartesian pose or velocity command and that we're free to trade secondary motion however we like.

The answer. Split the joint velocity into a task part and a self-motion part:

q̇ = J⁺ ẋ + (I − J⁺J) z

The first term does the task. The second lives in the null space of J, so it moves the arm without moving the end effector. Why it preserves the task: J(I − J⁺J) = J − J J⁺ J = J − J = 0, using the Moore–Penrose identity J J⁺ J = J. So whatever z is, J q̇ = ẋ exactly.

For joint-limit avoidance, pick z = −k ∇H(q), where H is the Liégeois potential:

H(q) = Σ (q_max − q_min)² / (4 (q_max − q)(q − q_min))

It goes to +∞ at either limit, so its gradient always points back into the interior. k is a gain: start around 0.1–1 in units of 1/s and tune.

Worked trace. Take a 3-joint arm with a 2-DOF task, J = [[1,0,1],[0,1,0]], ẋ = [1,0]ᵀ.

J⁺ = Jᵀ(JJᵀ)⁻¹ = [[0.5,0],[0,1],[0.5,0]], so q̇_task = [0.5, 0, 0.5]ᵀ. Check: J q̇ = [1, 0]. ✓

N = I − J⁺J = [[0.5,0,−0.5],[0,0,0],[−0.5,0,0.5]]. Joint 2 is locked out of the null space entirely: it's the only joint that moves the y-axis, so it can't self-move.

Now say joint 3 is near its upper limit, so ∇H = [0,0,1]ᵀ. Then N z = N(−k[0,0,1]ᵀ) = k[0.5, 0, −0.5]ᵀ. With k = 0.1: q̇ = [0.55, 0, 0.45]ᵀ. Joint 3 backs off the limit, joint 1 speeds up to hold the task. J q̇ = [1,0] still. ✓

Weighting. Instead of adding a gradient, you can bake the limit into the pseudoinverse with a diagonal weight W: J⁺_W = W⁻¹Jᵀ(J W⁻¹ Jᵀ)⁻¹, and N_W = I − J⁺_W J. Raise w_i as joint i approaches its limit and that joint resists motion. Same example, w₃ = 10:

q̇₁q̇₂q̇₃
unweighted0.50000.500
w₃ = 100.90900.091

Both give J q̇ = [1,0]. The weighted version moves the near-limit joint ten times less. The gradient method is easier to tune; the weighting method is smoother because it never adds a separate velocity term.

Failure modes.

  • Singularity. When J loses rank, J⁺ blows up. Use damped least squares, J⁺ = Jᵀ(JJᵀ + λ²I)⁻¹, with λ around 1–10% of σ_max. Damping means J N ≠ 0 exactly, so the primary task picks up a small error: that's the price.
  • Rank change. dim(null) = n − rank(J). At a singularity the null space grows, so you get more freedom, not less; but the projector built from a damped inverse is no longer exact.
  • Saturation. If the primary task alone needs more joint velocity than the limits allow, no null-space trick saves you. Clamp q̇ and re-solve, or move to a hierarchical QP that minimizes task error subject to hard joint-velocity bounds, then the secondary in what null space remains.
  • Integration drift. Null-space control is instantaneous. Euler integration at 1 kHz accumulates error; close the loop on task-space error rather than trusting feedforward.
  • Gain too high. Large k near a limit causes chatter. Cap the secondary velocity and low-pass the potential.

When not to use it. If the arm isn't redundant (n = m), there's no null space and you must either sacrifice the task or use a QP with explicit limits. If you need a hard guarantee that limits are never crossed, a constrained optimizer is the right tool: the potential only discourages, it doesn't forbid.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Handle joint position, velocity, and acceleration limits across kinematics.

Answer

Assumptions: a serial arm with a URDF/SDF model, a real-time control loop at 500 Hz–1 kHz, and a planner that hands joint trajectories to the controller. Limits live in three stages, and each stage enforces a different subset.

Core answer. Pose IK enforces position limits only, as hard bounds on the joint vector. Differential IK enforces velocity limits as hard bounds on q̇, plus position limits converted to velocity bounds over the control period. Trajectory generation enforces velocity, acceleration, and optionally jerk limits on the time-parameterized path. The rule that keeps this honest: never let a downstream stage be the first to see a limit. Clamp at the earliest stage that can see it, and report the margin you gave up.

Where the numbers come from. URDF <limit> gives lower, upper, velocity, effort per joint: no acceleration. MoveIt's joint_limits.yaml adds has_acceleration_limits/max_acceleration and has_jerk_limits/max_jerk, the fields moveit_msgs/JointLimits carries. If the datasheet has no acceleration figure, derive it from torque: q̈_max = M(q)⁻¹(τ_max − C(q,q̇)q̇ − g(q)), evaluated at the worst-case configuration, then derate. Concretely, the UR5 datasheet gives 180°/s ≈ 3.14 rad/s per joint; acceleration is unpublished and commonly starts at 5–10 rad/s² before derating against measured tracking error.

The QP. Differential IK at each tick:

minimize   ||J(q) q̇ − v_des||²_W + λ ||q̇||²
subject to q̇_min ≤ q̇ ≤ q̇_max                    (velocity)
           q_min ≤ q + q̇ Δt ≤ q_max              (position, one step ahead)
           q̈_min ≤ (q̇ − q̇_prev)/Δt ≤ q̈_max     (acceleration)

with q̇_max = min(velocity_limit, (q_max − q)/Δt) per joint. That clamp is what makes the position limit bite before the velocity limit: as a joint approaches its bound, admissible q̇ shrinks to zero over one control period, so the solver must decelerate instead of saturating. If the QP is infeasible, target outside reach given the bounds, drop the task term to a soft cost with slack and keep the joint bounds hard. A robot that stops is recoverable; one that violates a hard stop is not.

Wrap-around. Continuous joints have no lower/upper in URDF; their state is an angle on a circle. Two places it bites. IK returns θ = 6.0 rad for a joint currently at 0.1 rad: same pose, but the trajectory sweeps 5.9 rad; normalize the error to (−π, π] and pick the branch nearest the current state. Interpolation between 3.0 and −3.0 rad sweeps 6 rad the wrong way; use shortest-arc interpolation or normalize both endpoints. MoveIt handles this in JointModel::enforcePositionBounds/normalizeAngle; write your own IK and you own it.

Failure modes.

failurehow it shows updetection
Position limit hit mid-trajectorycontroller faults, joint stops, trajectory_execution abortscompare commanded vs measured joint position each tick; log margin
Velocity saturationend-effector lags the commanded path, deviation growstrack ‖p_cmd − p_actual‖; replan past tolerance
Acceleration limit too highcurrent spikes, tracking error, mechanical wearmonitor motor current vs τ_max; derate max_acceleration
Model/controller mismatchplanner thinks it is within limits, controller rejectsdiff URDF limits against controller config at startup; fail loudly
Wrap-aroundjoint takes the long way, cable wrap, singularityflag

Trade-offs. Soft avoidance costs, a repulsive term growing near the bound, keep the QP feasible and decelerate smoothly, but they do not guarantee the bound holds; a fast enough command still crosses it. Use them for the approach, hard constraints for the boundary. When the task genuinely needs the full workspace, the answer is to re-plan the base or the grasp, not to widen a hard limit: that is a hardware decision, not a software one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design a teleoperation differential-IK loop.

Answer

Assume a 7-DOF arm with a joint-velocity interface, a 1 kHz servo loop, and a master that publishes pose/twist at 125 Hz. The loop runs every 1 ms: read the newest master sample, reject it if its timestamp is older than 100 ms, transform the twist into the arm base frame using the current end-effector pose, deadband below 0.5 mm/s and 0.005 rad/s, clamp Cartesian speed to 0.25 m/s, compute J(q), solve for qdot, integrate with the measured dt clamped to [0.5 ms, 5 ms], and send qdot plus a position target.

The reason for damping is numerical, not stylistic. Near a singularity the smallest singular value of J goes to zero, so the pseudoinverse gain 1/sigma goes to infinity. A 0.1 m/s command with sigma_min = 0.01 would demand 10 rad/s at the wrist. Damped least squares adds lambda^2 to the eigenvalues of J J^T, bounding the joint-rate gain by 1/(2 lambda). With lambda = 0.025, the same command is bounded by 2 rad/s. The cost is task-space error near the singularity: the arm slows down instead of lurching. Use DLS when the arm is well inside its limits and the main risk is a singular Jacobian; it is one SVD and a 6x6 solve, cheap enough at 1 kHz. Use a QP when joint limits, acceleration limits, or collision cones must be hard constraints. A common compromise is DLS for nominal teleop plus a 100 Hz QP safety filter that clamps qdot.

Watchdog timing follows the master period. Three missed 125 Hz periods is 24 ms: hold the last qdot. At 200 ms, ramp qdot to zero over 100 ms and engage brakes. Drift correction runs every 10 ms: compare the measured end-effector pose to the integrated desired pose; if position error exceeds 2 mm or orientation error exceeds 0.02 rad, add a correction twist with 10 Hz bandwidth. Without that, numerical integration and model mismatch accumulate, and the operator's hand and the robot diverge.

dt = clamp(now - last, 0.0005, 0.005)
cmd = latest_master()
if now - cmd.t > 0.100: stop()
v = R_base_ee(cmd.twist)
v = deadband(v, 0.0005, 0.005)
v = clamp_norm(v, 0.25)
J = jacobian(q)
U,S,Vt = svd(J)
lam = 0.05 * max(0, 1 - S[-1]/0.02)
qdot = J.T @ solve(J@J.T + lam**2 * I, v)
qdot += (I - pinv(J)@J) @ (2.0 * (q_posture - q))
qdot = clamp(qdot, qdot_min, qdot_max)
q += qdot * dt

Failure modes, with detection and cost:

failuredetectioncost
packet losssequence gap or age > 24 mshold last command for 24 ms, then ramp stop
stale commandtimestamp age > 100 msstop; operator must re-engage
jitterinter-arrival variance > 10 ms20-40 ms jitter buffer; more feels sluggish
singularitysigma_min < 0.02DLS reduces task speed; tracking error grows
limit approachq + qdot * 0.1 s within 5% of limitclamp or nullspace push
frame switchcommanded vs measured pose mismatch > 1 mmjump; require re-sync
operator releasedeadman switch statestop within 100 ms

Worked trace: command v = 0.1 m/s along x, sigma_min = 0.01. Undamped, qdot can reach 0.1/0.01 = 10 rad/s. With lambda = 0.05 * (1 - 0.01/0.02) = 0.025, the maximum gain is 1/(2*0.025) = 20, so qdot is bounded by 0.1 * 20 = 2 rad/s. The task velocity is reduced near the singularity, but the joint rate stays inside a 2 rad/s limit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Connect IK to motion planning without losing safety constraints.

Answer

Clarify first. Is the arm a 6-DOF serial manipulator with a spherical wrist, is the cell fenced or collaborative, and what is the cycle-time budget? Assume a 6R arm, position-controlled, MoveIt 2 on ROS 2 with ros2_control, in a cell governed by ISO 10218-1/-2 (plus ISO/TS 15066 if collaborative).

The bridge between IK and planning is a goal set, not a single configuration. IK turns the task pose into candidate joint configurations; the planner searches from the measured state to any candidate that survives limit, self-collision and environment checks. Safety constraints live in three independent places: the collision scene with margins, the joint velocity/acceleration/jerk limits, and the safety-rated layer (SSM, STO) that does not depend on the planner at all.

Why a limit-valid IK solution can still be unusable. IK solves for the tool pose only. It says nothing about the elbow, forearm, or a payload. A 6R arm with a spherical wrist has up to eight IK branches (Pieper): elbow-up/down, shoulder front/back, wrist flip. Several are in collision or near a singularity even though the tool pose is exact. Numerical solvers (KDL, the MoveIt default) clamp to joint limits and can return a solution sitting on a limit with a large residual; analytic solvers (IKFast) return all branches but need a closed-form-solvable structure. TRAC-IK runs KDL and an SQP solver concurrently and returns the first to converge.

Worked trace: 2-link planar arm, L1 = 0.5 m, L2 = 0.4 m, target (0.6, 0.2).

Python
import math
L1, L2 = 0.5, 0.4
x, y = 0.6, 0.2
c2 = (x*x + y*y - L1*L1 - L2*L2) / (2*L1*L2)   # -0.025
t2 = math.acos(c2)                              # 1.5958
for s in (+1, -1):
    th2 = s * t2
    th1 = math.atan2(y, x) - math.atan2(L2*math.sin(th2), L1 + L2*math.cos(th2))
    print(round(th1, 4), round(th2, 4))
# -0.3628 1.5958
#  1.0063 -1.5958

Both branches satisfy joint limits. Now check the elbow against an obstacle at (0.45, -0.15), radius 0.08 m:

branchθ1, θ2 (rad)elbow (m)distance to obstacleverdict
A-0.3628, +1.5958(0.467, -0.177)0.032 mcollision
B+1.0063, -1.5958(0.267, +0.423)0.601 mclear

Only branch B is a valid goal. The tool pose was exact in both.

Trade-offs.

approachstrengthwhen it fails
IK-then-plan (goal set)fast, near-deterministic, good cycle timeno collision-free IK branch exists: move the base or re-grasp
Sampling planner with goal set (OMPL RRTConnect)handles clutternon-deterministic, no cycle-time guarantee
Analytic IK (IKFast)microseconds, all branchesneeds a closed-form-solvable structure; breaks if the arm changes
Cartesian planner (Pilz LIN)straight-line, predictableonly if the line is collision- and singularity-free

Failure modes and detection.

  • IK non-convergence: check the residual, not the return code. Reject if position residual > 1e-4 m or orientation > 1e-3 rad after the iteration budget.
  • Goal in collision: FCL contact distance < 0 at the goal state, checked before planning.
  • Mid-execution invalidation: compare measured joint state to the planned state each control cycle (ros2_control typically 100 Hz–1 kHz); a following error above threshold, or a scene/calibration change, triggers replan or stop.
  • SSM breach: protective separation distance Sp = Sh + Sr + Ss + C + Zd + Zr (ISO/TS 15066); the safety scanner trips a protective stop.
  • Cost of a stop: a category 1 stop decelerates along the path; category 0 cuts power and may need re-homing. In a collaborative cell a protective stop costs a full cycle and a manual reset.

When not to use IK-then-plan. Free-form motion in clutter: don't force a goal pose. Use sampling-based planning with a goal set, and reserve Cartesian planners for straight-line moves that are provably clear.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you parameterize a geometric path into a time-dependent trajectory subject to joint velocity, acceleration, and jerk limits?

Answer

Core answer. The path $q(s)$, $s\in[0,1]$, is fixed. You need a monotone time scaling $s(t)$ with $s(0)=0$, $s(1)=1$, $\dot s(0)=\dot s(1)=0$. Every joint limit becomes a scalar bound on $\dot s$, $\ddot s$, $s^{(3)}$ through the chain rule, so the problem lives in the $(s,\dot s)$ phase plane: plus $\ddot s$ once jerk is bounded. Velocity limits give a ceiling curve; acceleration limits give an interval of admissible $\ddot s$ at each $(s,\dot s)$; jerk limits give an interval of admissible $s^{(3)}$ at each $(s,\dot s,\ddot s)$. Then either integrate forward/backward in the phase plane, or solve the convex problem in $b(s)=\dot s^2$.

$$\dot q = q'\dot s,\qquad \ddot q = q''\dot s^2 + q'\ddot s,\qquad q^{(3)} = q'''\dot s^3 + 3q''\dot s\ddot s + q' s^{(3)}.$$

Mapping the limits. For joint $i$ with limits $v_i, a_i, j_i$:

  • Velocity: $\dot s \le \min_i v_i/|q'i(s)| \equiv \dot s{\max}(s)$. The maximum velocity curve (MVC).
  • Acceleration: $-a_i \le q''_i\dot s^2 + q'_i\ddot s \le a_i$. Linear in $\ddot s$, so each joint gives an interval; intersect over $i$. The intersection can be empty when $\dot s$ is too large: that is the acceleration-limited boundary of the reachable set. If $q'_i(s)=0$ at some $s$, that joint's constraint no longer involves $\ddot s$; it becomes a bound on $\dot s$ alone.
  • Jerk: $-j_i \le q'''_i\dot s^3 + 3q''_i\dot s\ddot s + q'_i s^{(3)} \le j_i$, linear in $s^{(3)}$ given $(s,\dot s,\ddot s)$.

Methods.

MethodStateLimitsCostNotes
Phase-plane integration (Bobrow)$\dot s$ on a gridv, a$O(N)$needs switching/tangent-point search; discontinuous profiles at tangents
TOPP-RA (convex)$b_k=\dot s_k^2$v, aLP/QP, $O(N)$globally optimal, no tangent hunting
S-curve / spline time scaling$s(t)$ splinev, a, jNLP/QPjerk bounded directly, suboptimal travel time
Third-order integration / NLP$(s,\dot s,\ddot s)$v, a, jhigherjerk does not fit TOPP-RA's convex formulation

Worked trace. Two joints, $q_1(s)=2s$, $q_2(s)=0.5s^2$, so $q_1'=2,q_1''=0$ and $q_2'=s,q_2''=1$. Limits $v=[1.0,0.2]$ rad/s, $a=[0.5,1.0]$ rad/s$^2$.

MVC: $\dot s_{\max}(s)=\min(0.5,,0.2/s)$. Joint 1 binds for $s\le0.4$, joint 2 beyond.

At $s=0.5$, $\dot s=0.3$:

  • joint 1: $|2\ddot s|\le0.5 \Rightarrow \ddot s\in[-0.25,0.25]$
  • joint 2: $|0.09+0.5\ddot s|\le1.0 \Rightarrow \ddot s\in[-2.18,1.82]$
  • intersection $[-0.25,0.25]$; joint 1 binds.

Grid $\Delta s=0.25$, $\dot s(0)=\dot s(1)=0$. Forward: $\dot s_{k+1}=\min!\big(\sqrt{\dot s_k^2+2\ddot s_{\max}\Delta s},\ \dot s_{\max}(s_{k+1})\big)$; backward the same with $\ddot s_{\min}$ from the end.

$s$00.250.50.751.0
$\dot s_{\max}$0.50.50.40.2670.2
forward00.3540.40.2670.2
final00.3540.40.2670.2

The backward pass never binds here. Segment times from $\Delta t=\Delta\dot s/\ddot s$: 1.41, 0.66, 0.75, 1.08 s. Total $\approx 3.9$ s. The first segment runs at $\ddot s=0.25$, i.e. joint 1's acceleration limit; the rest rides the MVC.

Failure modes.

  • C$^1$ corners: $q''\to\infty$, the admissible $\dot s$ collapses to zero and acceleration is infeasible. The path must be C$^2$ for acceleration bounds and C$^3$ for jerk bounds: blend corners with a fillet or B-spline before parameterizing.
  • Tangent points: where the MVC falls faster than $\ddot s_{\min}$ allows, the profile must leave the MVC before reaching it. A coarse $\Delta s$ skips this and the controller sees a violation; re-evaluate $\ddot q$ at the control rate (1 kHz) to catch it.
  • Jerk by post-filtering: smoothing the acceleration profile after parameterization does not guarantee the jerk bound; enforce it in the parameterization.
  • Endpoints: $dt=ds/\dot s$ diverges as $\dot s\to0$; use $\Delta t=\Delta\dot s/\ddot s$ on constant-acceleration segments.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Review whether a kinematically valid robot motion is executable.

Answer

Assumptions first: the rigid-body model (mass matrix, Coriolis, gravity) is accurate enough for the payload in hand, actuator torque limits are known as separate continuous and peak values, and the controller's tracking bandwidth is a known number. Kinematic validity (IK solved, joint limits respected, no collision) only says the path lies in the reachable, collision-free configuration space. It says nothing about whether the actuators can drive it. Executability is decided by time-parameterizing the path under dynamic constraints and checking the resulting torque, velocity and thermal profile against limits with margin.

Why torque limits bind. For a path q(s), s ∈ [0,1], the manipulator dynamics are τ = M(q)q̈ + C(q,q̇)q̇ + g(q). Substituting q̇ = q′(s)ṡ and q̈ = q′(s)s̈ + q″(s)ṡ² gives, per joint i:

τ_i = b_i(s)·s̈ + a_i(s)·ṡ² + g_i(s)

Torque is affine in s̈. So τ_i^min ≤ τ_i ≤ τ_i^max becomes a pair of linear bounds on s̈ for each joint at a given ṡ. The feasible region in (s, ṡ) is capped by a velocity limit curve ṡ_max(s) where the max-acceleration and max-deceleration constraints meet. If a_i(s)·ṡ² + g_i(s) alone exceeds τ_i^max, no choice of s̈ helps: the path is dynamically infeasible at that speed and you must slow down or re-plan.

Worked arithmetic (hypothetical). One joint swinging a 5 kg payload at 0.5 m radius, commanded α = 20 rad/s². Reflected inertia = 5 × 0.5² = 1.25 kg·m², so τ = 1.25 × 20 = 25 N·m. If the joint's continuous rating is 30 N·m, only 5 N·m is left for gravity and friction: thin. Peak rating might be 60 N·m, but only for about a second, so a repeated fast cycle will overheat even though each individual move passes.

Checking it in code. The affine form makes the bound computation cheap:

Python
import numpy as np

# tau_i = b_i*sddot + a_i*sdot**2 + g_i ; solve for sddot bounds per joint
def sddot_bounds(a, b, g, sdot, tau_min, tau_max):
    lo, hi = -np.inf, np.inf
    for ai, bi, gi, tmin, tmax in zip(a, b, g, tau_min, tau_max):
        if bi == 0:
            continue
        l = (tmin - ai * sdot**2 - gi) / bi
        h = (tmax - ai * sdot**2 - gi) / bi
        lo, hi = max(lo, min(l, h)), min(hi, max(l, h))
    return lo, hi  # lo > hi means infeasible at this sdot

Alternatives and when to use them. A kinematic-only check is fast and needs no dynamics model, but misses torque and thermal infeasibility: fine for a first pass, not for sign-off. Time-optimal parameterization (Bobrow-style, or TOPP-RA) gives the maximum-speed profile exactly under the model; it is the default when M, C, g are trustworthy, and conservative when they are not. Full trajectory optimization handles contact and flex but is non-convex and slow. A conservative constant-speed profile is simple and safe but leaves cycle time on the table.

Failure modes and detection. Torque saturation mid-path shows up as following error and path deviation: detect by comparing commanded current against actual and watching the servo error. Thermal overload from repeated peak moves shows up as motor temperature rise: detect with the I²t model or the motor thermistor. Commanded jerk above controller bandwidth shows up as oscillation: detect in the following-error spectrum. Stopping distance at max speed exceeding the safety zone is caught by a measured e-stop test, not by the model.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Model kinematics for a differential-drive mobile base.

Answer

Assume a two-wheel differential base with passive casters, wheels on a common axis, no lateral slip. Base frame x forward, y left, z up (ROS REP-103). Pose (x,y,θ), θ positive CCW. Wheel radius r [m], track b [m] between contact points. Encoder counts C per wheel revolution after any gearbox, positive when the wheel drives the robot forward.

The model is two equations. Forward: v = r(ω_r + ω_l)/2, ω = r(ω_r − ω_l)/b. Inverse: ω_r = (v + ω b/2)/r, ω_l = (v − ω b/2)/r. The nonholonomic constraint is v_y = 0 in the base frame; the instantaneous center of rotation lies on the wheel axis. That is the whole ideal model.

Why it works: each wheel contributes half the forward speed. Yaw rate is the difference of wheel linear speeds divided by track. Equal wheel speeds give a straight line. Opposite speeds give in-place rotation. One wheel stopped gives an arc around the stationary wheel.

At command interval Δt, integrate a constant twist exactly: if |ω| > ε, x += (v/ω)(sin(θ+ωΔt) − sinθ), y += −(v/ω)(cos(θ+ωΔt) − cosθ), θ += ωΔt. For small ω, the midpoint form x += vΔt cos(θ+ωΔt/2), y += vΔt sin(θ+ωΔt/2), θ += ωΔt is fine. Euler x += vΔt cosθ cuts corners on arcs.

Bounds: wheel speed limit ω_max gives |v ± ω b/2| ≤ r ω_max. Acceleration limits a_max, α_max. If a command violates them, scale (v,ω) by the largest factor that fits, preserving curvature. Clamping each wheel independently changes the path.

Alternatives: Ackermann cannot turn in place but is better at high speed; mecanum/omni can strafe but rollers slip, reduce payload, and worsen odometry. Differential drive is simple, high traction, zero-radius turn, but cannot crab. Pick differential for an indoor AGV that needs tight turns and no sideways motion; mecanum if you must strafe in narrow aisles; Ackermann for outdoor high-speed.

Failure modes, with detection and cost:

  • Slip: encoders overestimate motion. Detect by comparing IMU or visual odometry. 5% slip over 10 m is 0.5 m of pose error.
  • Wheel mismatch: a 1% radius error on one wheel at v = 0.5 m/s, b = 0.3 m gives ω ≈ 0.0167 rad/s, about 1.7 rad after 100 s. Detect with a straight-line test; calibrate r_l/r_r and b.
  • Quantization: C = 1024 counts/rev, r = 0.05 m gives 0.307 mm/count. At 50 Hz that is 15.3 mm/s of velocity noise. Low-pass filtering adds latency.
  • Latency: 100 ms at 1 m/s is 0.1 m of error. Timestamp and compensate.
  • Saturation: check commanded against actual wheel speed; if saturated, the path bends.
  • Low traction: wheels spin, odometry says the robot moved. Detect with IMU or visual odometry.

Worked example. Python 3.11:

Python
import math

def wheel_speeds(v, w, r, b):
    return (v + w * b / 2.0) / r, (v - w * b / 2.0) / r

def integrate(x, y, th, v, w, dt):
    if abs(w) < 1e-9:
        x += v * dt * math.cos(th)
        y += v * dt * math.sin(th)
    else:
        x += (v / w) * (math.sin(th + w * dt) - math.sin(th))
        y += -(v / w) * (math.cos(th + w * dt) - math.cos(th))
    th += w * dt
    return x, y, th

r, b = 0.05, 0.30
v, w = 0.5, 0.2
wr, wl = wheel_speeds(v, w, r, b)
print(round(wr, 3), round(wl, 3))
x, y, th = integrate(0.0, 0.0, 0.0, v, w, 0.1)
print(round(x, 4), round(y, 4), round(th, 4))

Trace: wr = (0.5 + 0.2·0.15)/0.05 = 10.6 rad/s. wl = (0.5 − 0.03)/0.05 = 9.4 rad/s. Output: 10.6 9.4. Integration: x = (0.5/0.2)(sin 0.02 − sin 0) = 0.0499967, y = −(0.5/0.2)(cos 0.02 − cos 0) = 0.00049998, θ = 0.02. Output: 0.05 0.0005 0.02. If ω_max = 10 rad/s, the right wheel at 10.6 exceeds it. Scale by 10/10.6 = 0.943: v = 0.4715 m/s, ω = 0.1887 rad/s. Clamping the right wheel alone would give v = 0.485 m/s, ω = 0.1 rad/s, a different arc.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Manage base and tool calibration in a multi-tool cell.

Answer

Assumptions: fixed-base arm (or a rail with a homed axis), a locking tool changer, tools identified by serial, ROS 2 with TF2 and MoveIt 2. If the base rides a mobile platform, add a base-localization source and treat world→base as a fast-changing frame, not a calibrated constant.

The answer: world→tool-tip is a product of pieces with different owners and different drift rates. Calibrate and version them separately, never as one blob, and bind each to the physical thing it describes.

frame pairownerchanges whenmethodtypical residual
world → basecell integratorcell bumped, robot re-bolted3–6 point touch-off on floor fiducials, or laser tracker0.1–0.5 mm
base → flangerobot vendornever (kinematic model)URDF from vendor—
flange → tool0tool changerevery tool change4-point touch-off or datum sphere0.05–0.2 mm
tool0 → TCPtool buildercrash, tip wear4-point plus orientation sweep~0.05 mm
flange → cameravision integratorcamera remounthand-eye (AX = XB)0.3–1.0 px reprojection

Publish each as a static transform keyed by serial (tool_<serial>_mount → tool_<serial>_tcp) and parent the active tool's TF to the flange only while that serial is verified present.

Why spatial diversity matters. One touch-off gives one equation for three unknowns. Worse, base offset and tool offset are not separable from translation alone: with the flange at orientation R the tip is p_flange + b + R·t, so at R = I you only ever observe the sum b + t. You need orientations differing by tens of degrees so b and t enter with different Jacobians. A dozen poses spanning ±40° in two axes is a reasonable starting point; keep a holdout set you never fit.

How residuals localize the fault. Fit, then read the shape of the residual, not just its RMS:

  • grows linearly with distance from base → base rotation error. 0.15 mm at 0.8 m is 0.15/800 = 0.19 mrad ≈ 0.011°.
  • grows with tool orientation change → tool rotation error.
  • constant offset in one direction → base translation error.
  • spikes on a single pose → that pose's FK or the touch fixture is bad; drop it.

Trade-offs. Touch-off is cheap (a fixture, a few minutes) and good to ~0.1 mm; a laser tracker reaches ~0.05 mm but costs five figures and needs line of sight; vision hand-eye needs the target in view and gives pixel residuals you must convert to mm at working distance. On trust vs re-verify: if the changer's repeatability (ATI quotes ±0.02 mm for the QC-21) plus the arm's (UR5e ±0.03 mm) sits well under task tolerance, store the calibration and only verify on change. For a 0.2 mm peg-in-hole, verify every change and re-fit when the check exceeds half the tolerance.

Failure modes and detection.

  • Wrong tool: read the changer's serial/RFID and compare to the TF you are about to publish; refuse to plan on mismatch. A 4-point check landing >0.2 mm from stored catches a mis-seated tool.
  • Base moved: re-touch one floor fiducial before each shift; if it moved >0.5 mm, re-run base calibration.
  • Stale cache: MoveIt's planning scene and any IK seed cache hold the old transform. On a calibration write, bump a version counter, republish the static TF, and rebuild the scene: republishing TF alone leaves stale collision geometry and IK seeds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design time-aware transform lookup for perception-to-motion.

Answer

Assumptions first. Frames form a tree (odom → base_link → camera_optical), every node stamps on one clock domain, and the planner needs the camera→odom relation at the instant the image was exposed, not at the instant the planner runs. If those don't hold (multiple clock domains, or a consumer that only needs "roughly now") the design changes.

Core answer. Timestamp at acquisition on the sensor's own clock, keep a bounded ring buffer of stamped transforms, and look up the entire chain at the measurement time in one call. Interpolate between the two samples that bracket that time; refuse to extrapolate past either end. The buffer is the whole design: it turns "what was the pose then" into a bounded, checkable query.

Why interpolation is safe and extrapolation is not. tf2 stores each edge as (translation, quaternion, stamp) and, for a query between two stamps, linearly interpolates translation and slerps rotation. The error is the curvature over the gap: exact for constant velocity, and roughly a·Δt²/8 under acceleration a. At 100 Hz TF (Δt = 10 ms) and a = 1 m/s² that is 12 µm: below any perception noise. Extrapolation has no such bound: error grows with the square of the distance past the edge, and the buffer holds no evidence the motion continued.

Artefacts.

Code (ROS 2 / tf2, Python):

Python
buf = Buffer(cache_time=Duration(seconds=10.0))   # tf2 default is 10 s
t_meas = Time.from_msg(cloud.header.stamp)        # acquisition time, same clock as TF

try:
    T = buf.lookup_transform('odom', 'camera_optical', t_meas,
                             timeout=Duration(seconds=0.05))
except ExtrapolationException:
    drop_frame()          # t_meas outside [oldest, newest] in buffer
except ConnectivityException:
    raise                 # tree broken between odom and camera

Error budget at 1 m/s and 2 rad/s:

sourcemagnitudepositionangle
PTP residual<1 µs<1 µm<0.001°
NTP residual1–10 ms1–10 mm0.1–1.1°
camera exposure+readout30–100 ms3–10 cm3.4–11.5°
TF gap at 100 Hz10 ms1 cm1.1°

The camera's own exposure dominates; clock sync only matters once it exceeds the TF gap.

Trade-offs. Three options: nearest sample (zero latency, error up to half the gap. 5 ms → 5 mm / 0.57°), interpolation (zero latency, bounded by curvature. The default), or wait for the next sample (best accuracy, adds up to one sample period of latency). Pick interpolation unless the consumer is offline; pick nearest only when the gap is far below the motion's time constant.

Failure modes and detection.

  • Clock step (NTP stepping instead of slewing): timestamps jump backwards and the buffer inserts out of order. Detect by monitoring |t_msg − t_arrival| and the clock offset; fix with chrony/PTP slew.
  • Out-of-order joint states: a joint stamped after the TF it should precede. Detect by comparing stamp deltas across the chain; reject the frame.
  • Missing edge: ConnectivityException. Detect with a periodic tree-connectivity check.
  • Extrapolation: the planner asks for a time past the newest TF (e.g. a lookahead horizon). Detect by counting ExtrapolationException; fix by shortening the horizon or lengthening the buffer.

Log the chosen time, the chain, and the interpolation gap per frame: that is what makes a bad pose debuggable after the fact.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Plan and accept a robot kinematic calibration.

Answer

First I'd pin down what we're actually fixing. Kinematic calibration buys absolute accuracy, not repeatability. A typical 6-axis industrial arm repeats to 0.05–0.1 mm but its absolute accuracy out of the box is 1–3 mm, and that gap is what calibration closes. If repeatability is already blown, calibration is the wrong tool: that's backlash, a worn gearbox or a bent link, and I'd stop and fix the mechanics first. Remastering the encoders is the other cheap alternative when the error is a pure joint-offset shift; replacing a joint is the answer when the error is load- or direction-dependent, because no kinematic model captures that.

Assumptions I'd state up front: rigid links, joint offsets and link geometry constant over the measurement window, tool and base frames known, thermal drift small. If the cell runs hot or the payload swings, I'd say so, because those break the model.

Parameters: start with a full DH-style set (four per joint, 24 for a 6R) plus base and tool frames. Not all are observable. Joint-1 offset and base rotation about Z are the same rotation; a link length and a tool offset along the same axis trade off. So I'd run the identification and look at the singular values of the Jacobian: parameters whose singular values sit near the noise floor get dropped or lumped, not estimated. That's what identifiability means here: the pose set has to excite the parameters. I'd pick 30–50 poses spanning each joint's range and the workspace, avoiding singularities and joint limits, and hold back 10–15 poses I never fit on.

Measurement: a laser tracker, Leica AT960 or API Radian, with an SMR or probe tip gives 6D pose to roughly 15 µm + 6 µm/m, which is plenty. A Renishaw QC20-W ballbar is cheaper and faster but only measures circular paths, so it catches backlash and geometry error, not full pose. A touch probe on a master ball is the cheap option if the cell already has one.

Estimation: least squares on the residuals, Huber or trimmed loss so one bad pose doesn't drag the fit, and bounds on parameters so the solver can't run to a physically impossible link length.

Acceptance is before/after on the holdout, by region. Illustrative numbers:

regionRMS pos before → aftermax pos before → afterholdout RMS
centre of workspace1.2 → 0.15 mm2.8 → 0.35 mm0.18 mm
near reach limit1.9 → 0.30 mm3.6 → 0.55 mm0.34 mm

Orientation error should drop similarly, say 0.3° → 0.05°. The holdout has to improve too, if only the fit poses improve, I've overfit. Repeatability I'd measure separately, ISO 9283 style, 30 cycles to the same pose, and it must not get worse.

Failure modes: overfitting to the measurement poses; thermal drift so the calibration is valid at one temperature only; a base-frame error that rotates the whole error field; a collision that bent a link after calibration. Detection is the holdout set plus a periodic single-pose re-check against a known artefact.

Then version the parameter file, get sign-off, keep the previous set for rollback, and retest after a tool change, base move, encoder remaster, collision or mechanical repair.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Build property tests for forward kinematics and Jacobians.

Answer

Core answer (say this first)

Assume a URDF with n actuated joints, FK returning T_world_ee ∈ SE(3), and a Jacobian expressed in the end-effector body frame. The test that catches nearly every Jacobian bug is a finite-difference oracle: perturb one joint by h, recompute FK, take the SE(3) logarithm of the relative transform, divide by h, and compare that column against the analytic Jacobian. Composition, inverse and rotation-orthonormality checks are cheap and worth keeping, but they never touch the derivative, which is where the bugs are.

The oracle

Python
import numpy as np
from scipy.spatial.transform import Rotation

def skew(w):
    return np.array([[0, -w[2], w[1]],
                     [w[2], 0, -w[0]],
                     [-w[1], w[0], 0]])

def se3_log(T):
    """T in SE(3) -> twist [omega; v], omega in radians."""
    Rm, p = T[:3, :3], T[:3, 3]
    w = Rotation.from_matrix(Rm).as_rotvec()
    th = np.linalg.norm(w)
    W = skew(w)
    if th < 1e-8:
        Vinv = np.eye(3) - 0.5 * W + (1.0 / 12.0) * W @ W
    else:
        c = (th / 2.0) / np.tan(th / 2.0)
        Vinv = np.eye(3) - 0.5 * W + ((1.0 - c) / th**2) * W @ W
    return np.concatenate([w, Vinv @ p])

def jac_fd(fk, q, h=1e-6):
    T0 = fk(q)
    J = np.zeros((6, len(q)))
    for i in range(len(q)):
        dq = np.zeros_like(q); dq[i] = h
        J[:, i] = se3_log(np.linalg.inv(T0) @ fk(q + dq)) / h
    return J

Why the log, not Euler differencing

Near pitch = ±90°, Euler-rate differencing divides by cos(pitch) → 0: a 1e-6 rad perturbation produces a 1e-3 error in the recovered rate, so the test either fails spuriously or gets loosened until it catches nothing. The SE(3) log returns a 6-vector in radians and metres, is frame-invariant, and stays bounded through the singularity. Central differences give O(h²) truncation plus O(ε/h) roundoff with ε = 2.2e-16, minimised at h ≈ (3ε)^(1/3) ≈ 8e-6. Sweep h ∈ {1e-5, 1e-6, 1e-7} and require the error to fall then rise; a monotone trend means the analytic Jacobian is wrong, not the step size.

Tolerances

quantityvaluenote
step h1e-6 (central)optimal ≈ 8e-6 for double
assertmax|J_a − J_fd| < 1e-6 · max(1, |J_a|)scale by twist magnitude
σ_min(J) gate1e-3skip comparison below this

Trade-offs: analytic vs AD vs FD

Analytic: microseconds per call, hand-derived, silently wrong the moment the kinematic chain changes. AD: correct by construction, roughly 2–10× the FK cost plus tape memory, no re-derivation. Use it when you ship many URDF variants or the model changes weekly. FD: O(n) FK calls per Jacobian, noisy, only ever a test oracle. Deciding criterion: frozen model and a 1 kHz control loop → hand-derive and test with FD; many variants or a moving model → AD and test with FD.

Failure modes

  • Near-singular. σ_min(J) drops below ~1e-3; the symptom is a control loop that oscillates at the joint limit, or an FD/analytic mismatch that grows as 1/sin(θ) if you used Euler differencing. Detect by gating on σ_min before comparing.
  • Mimic joints. The true column for the master joint is J_master + k·J_mimic. If the analytic Jacobian omits the coupling, the FD oracle disagrees by exactly k·J_mimic: a residual that is a fixed multiple of another column, which is the signature. Detect with assert np.allclose(J[:, master], J_fd[:, master]).
  • Floating base. The base twist lives in a different frame; perturb the base in the same frame the Jacobian is expressed in, or the comparison fails by a fixed rotation.

Cost of missing these: a wrong Jacobian on a 6-DOF arm at 1 kHz shows as millimetres-per-second drift or a limit cycle; the CI test that catches it runs in seconds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Review and validate a robot kinematics stack end to end.

Answer

The 90-second answer. Pin the stack before testing anything: ROS 2 Humble, MoveIt 2, tf2, KDL or Pinocchio for kinematics, OMPL for planning, Ruckig or TOTG for time parameterization, joint_trajectory_controller from ros2_control, and record the versions. Then validate in layers, cheapest and most isolating first, against one invariant: the same Cartesian pose must be reached by every path through the stack, and the residual between commanded and measured must stay inside a bound you picked before you started. FK/IK and Jacobian checks run offline and catch model errors. Planning and time parameterization run in simulation and catch reachability and limit violations. Only measured motion on the real arm at reduced speed catches calibration, backlash and controller tuning. Math errors show up in simulation; hardware errors don't.

What each layer catches. Transforms: look up the chain at the trajectory timestamp, not at latest. A stale transform or wrong parent frame corrupts everything downstream and looks like a kinematics bug. Log frame IDs and timestamps next to the residual: a residual that grows with time or jumps after a scene change is a transform problem.

FK/IK round trip: sample joint states inside limits, run FK, run IK back, compare. Catches URDF and DH errors. It does not catch a branch flip, because both branches reach the same pose, so also compare consecutive IK solutions in joint space.

Jacobian: finite-difference against analytic. Relative error should sit at the finite-difference noise floor, 1e-6 or better with a well-chosen step; above 1e-3 the analytic Jacobian and the URDF disagree. Then look at conditioning, because that predicts controller trouble.

Planning: unreachable targets must fail with a reason, not hang; NaN and out-of-workspace targets must be rejected at the boundary. Collision and self-collision checks reject the plan before it runs: a plan that passes but contacts in simulation means the collision geometry (SRDF, padding) is wrong, not the planner.

Time parameterization: check the trajectory against velocity, acceleration and jerk limits before it reaches the controller.

Controller and safety: command the trajectory, log actual joint positions, compute following error. Then measure the stop: e-stop asserted to zero velocity. That number, not the watchdog period, is what the risk assessment needs.

Worked trace. A 2-link planar arm, L1 = 0.5 m, L2 = 0.4 m, joint velocity limit 1.0 rad/s: small enough to check by hand; the same checks run on the 6-DOF URDF.

Planner target: (x, y) = (0.4330, 0.6500) m.

IK: cos q2 = (x² + y² − L1² − L2²)/(2 L1 L2) = (0.6100 − 0.4100)/0.4 = 0.5000, so q2 = ±60°.

  • Elbow-up: q1 = atan2(0.65, 0.4330) − atan2(0.4 sin 60°, 0.5 + 0.4 cos 60°) = 56.33° − 26.33° = 30.00°.
  • Elbow-down: q1 = 56.33° + 26.33° = 82.66°, q2 = −60°.

FK back from (30.00°, 60.00°): x = 0.5 cos 30° + 0.4 cos 90° = 0.4330, y = 0.5 sin 30° + 0.4 sin 90° = 0.6500. Residual 0. The elbow-down solution lands on the same pose but sits 131° away in joint space (Δq1 = 52.7°, Δq2 = 120°). A Cartesian residual check passes both; only the joint-space comparison sees the flip.

Jacobian at (30°, 60°): det J = L1 L2 sin q2 = 0.2 × 0.8660 = 0.1732; singular values 0.854 and 0.203, κ = 4.2.

Same target, elbow at 5°: det J = 0.2 × 0.0872 = 0.0174, σ = (0.984, 0.0177), κ = 55.5. Command 0.1 m/s along +y and solve J q̇ = ẋ:

  • at q2 = 60°: q̇ = (0.23, −0.38) rad/s
  • at q2 = 5°: q̇ = (1.32, −2.75) rad/s

Same Cartesian command, 7× the joint velocity, and 2.75 rad/s is over the 1.0 rad/s limit. The time parameterizer must slow the path or the controller saturates and following error grows. The condition number told you that before you ran anything.

Re-run only what the change touches.

ChangeRe-run
New calibrationtransforms, FK/IK round trip
New URDF or DHFK/IK, Jacobian vs finite difference
New planner or time parameterizerreachability, collision, limit checks
New controller gainsmeasured tracking at reduced speed
New package versionall of the above, in that order

Full end-to-end every time is expensive and mostly redundant; the layers are independent enough to target.

Curated: · Written: · Reviewed:

Difficulty: Hard