Skip to content
Tech Interview Prep
Technical interview guide

Perception & SLAM

How a robot builds a map of an unknown environment while simultaneously figuring out its own location within it.

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

Scope: ORB-SLAM3, Cartographer, GTSAM, Ceres, OpenCV 4.x, ROS 2 Rolling, Kalibr, PCL, Nav2, TUM RGB-D, KITTI, and evo references 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

Choose mapping, localization, odometry, or SLAM for a robot product.

Answer

Assumptions first: a warehouse AMR, differential drive, 1.5 m/s, 2.5 m aisles, one 2D LiDAR at 1.8 m, wheel encoders, a MEMS IMU, and a site map built during commissioning. Pallets move daily; the building shell does not.

My answer: localization against a governed map at runtime, AMCL in Nav2, with SLAM used only during commissioning to build that map, and odometry as the motion model inside the filter, never as a standalone answer. Mapping alone is not a product mode; you would have a map and no pose to act on.

Why not odometry alone: a differential drive with decent encoders drifts roughly 1–2% of distance travelled, and a MEMS gyro adds a few degrees per minute of bias. Over a 100 m run that is 1.5 m of error. The half-aisle is 1.25 m, so the robot reaches the racking before the next correction. Odometry is the thing you integrate between LiDAR updates, not the thing you trust.

OptionGives youCostPick when
Odometrypose increments at 100 Hz, no mapdrifts 1–2% of distanceonly inside a few metres, or as a filter input
Localization (AMCL)pose in a known map, ~5 cm in a mapped aisleneeds map + LiDAR, ~10 Hzmap exists, environment mostly static
Mapping with trusted posesa map, from poses you already believeneeds an accurate pose sourcecommissioning, or a dedicated survey robot
SLAM (slam_toolbox, Cartographer)pose and map jointly, loop closurehighest compute, hardest to debugno map, unknown or changing environment

Nav2 AMCL defaults are worth knowing because they set your correction rate: update_min_d 0.25 m, update_min_a 0.2 rad, 500–2000 particles, likelihood_field sensor model. At 1.5 m/s you get a pose correction roughly every 0.17 s of travel.

Failure modes, with detection and cost:

  1. Ambiguous localization in symmetric aisles. The particle cloud collapses onto the wrong aisle. Detect it from the cluster spread and best-particle weight: if the spread exceeds ~0.5 m or the scan likelihood falls below the running median, flag it. Recover by stopping and relocalizing globally (AMCL with unknown initial pose, or driving to an AprilTag fiducial) which costs 5–20 s of driving and blocks the aisle.
  2. Stale map. Pallets moved. Detect it as a scan-match residual that grows in one zone while the global pose stays consistent. Recover by re-surveying that zone and bumping the map version. Without a fleet-wide map service that is a day of re-survey.
  3. LiDAR dropout with odometry fallback. Watchdog the scan topic rate. At 1.5 m/s and 0.5 m/s² deceleration the stopping distance is 2.25 m: longer than the 1.25 m half-aisle, so on degraded sensing you must drop to 0.5 m/s, where stopping distance is 0.25 m.

When I would choose differently: no map and an unknown environment (exploration, inspection) makes SLAM the runtime mode, not a commissioning tool. A robot that never leaves a 10 m cell, a conveyor transfer station, is fine on odometry plus one fixed fiducial, and that is cheaper than maintaining a map at all.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Implement REP-105 frame semantics for navigation.

Answer

Assumptions: ROS 2 (Humble/Jazzy), Nav2 stack, differential-drive base with wheel encoders and an IMU, 2D lidar. Frame names and rules are identical on ROS 1; only node names change.

Core answer

REP-105 splits the tree into two edges with different contracts. odom -> base_link is continuous: it never jumps, and it drifts. map -> odom is the correction: it is discontinuous, and it absorbs all the drift. The robot's pose in map is the composition of the two. Local controllers (Nav2 controller_server) consume odom -> base_link so velocity commands stay smooth; global planners consume map so goals sit in a stable frame. Nothing publishes map -> base_link directly.

Mechanism

Wheel odometry integrates encoder ticks. Scale error, wheel slip and unequal radii accumulate, typically 1–5% of distance travelled. After 100 m at 1%, the odom pose is ~1 m off: smooth, but wrong. AMCL or slam_toolbox estimates pose in map and publishes:

map -> odom = (map -> base_link measured) * inverse(odom -> base_link)

When the localizer corrects, that product changes, so map -> odom jumps. That is the design, not a bug. Smoothing it would mean lying about the correction, and the controller would chase a pose that disagrees with the map.

edgepublishertypical ratecontract
odom -> base_linkwheel odom or robot_localization EKF30–50 Hzcontinuous, drifts
map -> odomAMCL or slam_toolbox5–10 Hzdiscontinuous, corrects
base_link -> laserrobot_state_publisherstaticfixed

Worked trace

odom -> base_link reads (10.0, 0.0). AMCL's first fix puts the base at (10.5, 0.0) in map, so it publishes map -> odom = (0.5, 0.0). The robot drives 0.2 m; odom now reads (10.2, 0.0), map -> odom still (0.5, 0.0), so map -> base_link = (10.7, 0.0). AMCL re-localizes and finds the base at (10.2, 0.0). It rewrites map -> odom to (0.0, 0.0): a 0.5 m jump in one edge, while odom -> base_link never moved. The controller saw no discontinuity; the planner saw the correction.

Failure modes

  • Two owners of map -> odom. AMCL and slam_toolbox both running. Symptom: pose oscillates between two values, controller jerks. Detect: ros2 run tf2_tools view_frames shows two parents for odom, or ros2 topic echo /tf shows two authorities. Fix: one owner.
  • Lookup age. tf2_ros::Buffer default cache_time is 10 s. A lookup for a stamp older than that throws LookupException. Nav2 nodes use transform_tolerance (commonly 0.1 s) to permit extrapolation into the future; if the localizer stalls longer, costmap updates fail with "Lookup would require extrapolation into the future". Detect: log spam from controller_server/costmap.
  • Timestamp race. Stamping odom -> base_link with sensor time but publishing late makes a current-time lookup extrapolate. Symptom: intermittent extrapolation errors under CPU load.

Trade-offs

AMCL as map -> odom owner wins when the map is known and static: global accuracy, but it jumps on relocalization and needs a good initial pose. slam_toolbox wins when exploring: no prior map, but map -> odom drifts and loop closures cause large jumps. In robot_localization, set world_frame to odom for the local EKF and map for a global EKF fusing GPS. Test the full tree with view_frames and a scripted relocalization.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Diagnose rank deficiency caused by gauge freedom.

Answer

When I see a solver reporting a singular Hessian or huge covariance in a pose graph, my first thought is gauge freedom. Let me clarify what I mean by that, then walk through a concrete diagnosis.

Assume we're doing full SLAM with relative measurements (odometry, loop closures) and no absolute sensors like GPS. The state is a set of poses. The measurements are invariant to a global rigid transformation. So the Jacobian has a null space. The Hessian is J^T J, so it's singular. The covariance is the inverse of the Hessian, so it's not defined; if you use a pseudo-inverse, the covariance along the gauge directions is zero, which is misleading.

The rank deficiency is exactly the dimension of the gauge group. For SE(3), it's 6: 3 translation, 3 rotation. For Sim(3), it's 7: adds scale. The Hessian's smallest eigenvalues will be near zero. I typically compute the eigenvalues and look for a gap. If the smallest eigenvalues are below 1e-6 times the largest, that's gauge.

Let's take a simple 2D pose graph with 3 nodes and 2 relative pose constraints. Each node has (x, y, theta). The Hessian is 9x9. The null space is 3: global x, y, theta. So eigenvalues: three near zero, six positive. If measurement noise is 0.1, the positive eigenvalues might be around 100, and the zero ones around 1e-12. So threshold 1e-6 * max eigenvalue works.

To confirm, I can check that the null space vectors correspond to global transformations. Apply a small global translation to all poses; the measurements don't change. So the Hessian is singular.

Now, how to handle it? Three remedies. First, fix a gauge: anchor the first pose to identity. This removes the null space. It's simple and deterministic, but it makes the covariance of the fixed pose zero, which is wrong if you want absolute uncertainty. Second, add a prior on the gauge: e.g., a weak prior on the first pose. This regularizes the Hessian. But you must choose the prior covariance; too tight biases, too loose doesn't regularize enough. Third, use a solver that handles the null space: e.g., Levenberg-Marquardt with a pseudo-inverse, or a gauge-aware solver like GTSAM's Marginals with GaussianFactorGraph? Actually, in GTSAM you can add a PriorFactor on the first pose. In Ceres, you can set a parameter block constant. So the choice depends on whether you need absolute uncertainty or just relative.

Failure modes: If you ignore gauge, the solver may not converge, or it may converge to a different solution each run (non-deterministic), or it may report huge covariances that are meaningless. Detection: check the condition number of the Hessian, or the smallest eigenvalues. Also, you can test by fixing a different node and seeing if the relative poses change (they shouldn't). If they do, you have a bug.

Operational cost: In a monocular SLAM system, if you don't fix the scale gauge, the map will drift in scale, and the covariance will be huge. You might spend hours tuning the solver, or deploy a system that gives inconsistent maps.

Here's a quick reference for gauge types:

| Gauge type | DOF | Example sensors | Null space dimension | | SE(3) | 6 | stereo camera, IMU | 6 | | Sim(3) | 7 | monocular camera | 7 |

In GTSAM 4.2 (Python), you can fix the gauge by adding a prior on the first pose:

Python
import gtsam
graph = gtsam.NonlinearFactorGraph()
prior_noise = gtsam.noiseModel.Diagonal.Sigmas([0.01, 0.01, 0.01])
graph.add(gtsam.PriorFactorPose2(0, gtsam.Pose2(0, 0, 0), prior_noise))
# ... add odometry factors ...
initial = gtsam.Values()
initial.insert(0, gtsam.Pose2(0, 0, 0))
# ... insert other poses ...
optimizer = gtsam.LevenbergMarquardtOptimizer(graph, initial)
result = optimizer.optimize()

The key is to distinguish gauge from scene degeneracy or missing calibration. Gauge is a global invariance; scene degeneracy is when the geometry itself is ambiguous (e.g., a corridor with no features); missing calibration is a sensor issue. They all cause rank deficiency, but the fix is different.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Design a factor-graph SLAM back end.

Answer

Assume a 6-DoF visual-inertial system: stereo at 15 Hz, IMU at 200 Hz, loop closures from a place-recognition front end, running on-robot. I'd build a fixed-lag smoother with the option to promote to full batch smoothing when a loop closes.

State and gauge. Variables are poses T_i ∈ SE(3), velocities, IMU biases (b_a, b_g), and landmarks. Poses are optimized on the manifold: the update is δ ∈ R⁶ applied through the SE(3) exponential, never a 4×4 matrix sum. The graph has six gauge degrees of freedom, nothing in the measurements fixes the world frame, so I anchor it with a prior factor on the first pose at σ = 1e-3 m and 1e-4 rad rather than deleting rows. That keeps the Hessian full rank and the marginal covariances meaningful.

Factors.

factorresidual diminformation
prior on T_06fixed, σ = 1e-3 m / 1e-4 rad
odometry T_i → T_{i+1}6front-end covariance, inflated ×2
IMU preintegration15preintegrated covariance (Forster et al., 2017)
landmark reprojection2 per observation~1 px, whitened
loop closure6place-recognition covariance, robust
GNSS / external3RTK σ ≈ 0.02 m, else 3 m

Sparsity and solver. Levenberg-Marquardt, not Gauss-Newton: the damping covers rank-deficient directions early, when the gauge prior is weak or a corridor gives no lateral constraint. Order variables with COLAMD, factor with sparse Cholesky. Landmarks go by Schur complement: H_ll is block-diagonal, 3×3 per landmark, so S = H_pp − H_pl H_ll⁻¹ H_lp is cheap and stays sparse, because a landmark only couples the poses that observed it. Pose marginalization is the opposite: eliminating an old pose couples every pose that shared a landmark with it, and that fill-in becomes the dense prior factor in a fixed-lag window.

Trade-offs. Full batch smoothing gives the best map; cost grows with session length. Fixed-lag bounds cost but freezes the linearization point at elimination time, so the prior is not re-linearizable. For robust loss, Huber with δ = 1.345σ is 95% efficient under Gaussian noise and fine for odometry; loop closures need switchable constraints or PCM, because one wrong match can carry a residual 100× the inlier scale.

Failure modes. A wrong loop closure shows up as a normalized chi-square per DoF above threshold; if it survives, the trajectory snaps meters in one iteration. Degenerate geometry shows as a near-zero eigenvalue of S: I gate on condition number > 1e8 and treat that direction as unobservable. Stale IMU bias linearization shows as bias correction > 0.01 rad/s per iteration; relinearize. Unbounded fill-in shows as the prior factor's nonzero count growing past the window.

Worked check. Loop closure between T_40 and T_112, measured translation (2.1, 0, 0) m, σ = 0.05 m per axis, current estimate 0.9 m apart in x. Residual 1.2 m, whitened 1.2/0.05 = 24, Mahalanobis² = 576 on that axis alone. χ²(0.99, 6) = 16.81. Reject. A true loop at the same σ lands near 1–3.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Integrate IMU measurements into a SLAM estimator.

Answer

Core answer

Assume a 6-axis MEMS IMU at 200 Hz, a camera or LiDAR at 10 Hz, and a rigid extrinsics transform between them. The job is to turn the IMU's high-rate specific force and angular rate into a motion constraint the slower estimator can use, while estimating the IMU's bias and the gravity direction as states.

The direct answer: preintegrate the IMU between keyframes into a single relative-motion factor with a covariance, add it to the graph or filter alongside the vision factors, and let the estimator solve for velocity, biases and gravity. Don't integrate raw IMU into the pose at 200 Hz: you'd add 200 states per second and the biases would be unobservable.

Mechanism

The IMU measures angular velocity ω and specific force f = a − g, expressed in the body frame. To get pose you integrate twice: attitude from ω, velocity and position from f rotated into the world frame plus gravity. Two things make this hard. First, bias: a constant gyro bias b_g produces attitude error that grows linearly, and attitude error rotates gravity, which produces a position error that grows as t³. Second, the integration is only as good as the timestamps: a 1 ms offset at 100 deg/s is 0.1 deg of attitude error per sample.

Preintegration (Forster et al., "On-Manifold Preintegration for Real-Time Visual-Inertial Odometry", IEEE T-RO 2017) fixes the recomputation problem: it accumulates ΔR, Δv, Δp relative to the keyframe in the body frame, so when the optimizer changes the bias estimate you correct the preintegrated measurement with a first-order Jacobian instead of re-integrating. At 200 Hz over a 100 ms keyframe interval that's 20 samples collapsed into one factor.

Alternatives

choicewhen it winscost
Loosely coupledIMU is a separate pose source; quick to buildvision and IMU errors are correlated but treated as independent; worse under fast motion
Tightly coupledraw IMU residuals inside the estimator; standard for VIOmore state, needs bias observability handling
EKF (MSCKF)fixed budget, real-time on embeddedlinearization error, must marginalize old poses
Factor graph (GTSAM, Ceres)offline or desktop, re-linearizationheavier, needs a good initial guess

Deciding criterion: if you can afford re-linearization and want accuracy under aggressive motion, factor graph with preintegration. If you're on a phone at 30 Hz with a hard CPU budget, MSCKF.

Observability and failure modes

Gravity direction, scale and accel bias are only separable under excitation: a stationary or constant-velocity sequence leaves them unobservable, and the estimator will trade one against the other. Rotate the device about two axes during init.

  • Gyro saturation: consumer IMUs clip around ±2000 deg/s. Detect by watching for runs of identical max-magnitude samples; symptom is attitude divergence during fast rotation.
  • Vibration aliasing: high-frequency vibration rectifies into a bias-like offset. Detect by comparing the IMU's integrated displacement against vision over a stationary window.
  • Time offset: 1 ms at 1 m/s is 1 mm, but at 100 deg/s it's 0.1 deg. Detect by sweeping the offset and minimizing reprojection error.
  • Dropout: detect by a timestamp gap > 2× nominal period; fall back to constant-velocity propagation and inflate covariance.

Arithmetic

A gyro bias of 0.1 deg/s held for 10 s gives 1 deg of attitude error. That 1 deg tilts gravity, giving an accel error of 9.81 × sin(1°) ≈ 0.17 m/s², which over the same 10 s is ½ × 0.17 × 100 ≈ 8.5 m of position drift. This is why bias must be a state, not a constant.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design timestamp handling for a camera-IMU-LiDAR stack.

Answer

The 90-second answer. Assume a vehicle with a 10 Hz LiDAR, 20 Hz camera and 200 Hz IMU on one compute box, and a requirement that fused state be geometrically consistent to a few centimetres at 10 m/s. My design: every sensor timestamps at the source, all sources share one PTP-disciplined clock domain, and every consumer transforms into a common frame using the timestamp that travelled with the sample. Never the arrival time.

Why that matters: at 10 m/s a 100 ms LiDAR revolution puts the first and last returns 1 m apart. Fusing that as one instant is a metre-scale lie. So the LiDAR carries per-point or per-firing timestamps, and the camera carries exposure-start, not readout-end.

Clock domains. Three exist: sensor-internal (camera trigger, LiDAR firing sequence, IMU sample clock), host monotonic, and wall time. Only the first two matter for fusion; wall time is for logs. Discipline the host with PTP (IEEE 1588) and hardware timestamping at the NIC PHY: sub-microsecond on a switched LAN with transparent clocks, tens of microseconds to low milliseconds with software timestamping under load. A free-running crystal at 50 ppm drifts 180 ms per hour, which is why you cannot skip this.

Where to stamp. Hardware timestamping beats software because it removes interrupt and queueing jitter. PPS gives a precise edge but no epoch; PTP gives both but needs boundary or transparent clocks in every switch or accuracy collapses. GNSS+PPS as grandmaster is the usual outdoor choice, with a holdover oscillator when GNSS drops.

Per-sensor specifics. LiDAR: prefer per-point timestamps (Ouster, Hesai expose them); if only a scan-start stamp exists, deskew with IMU-integrated motion across the scan. Camera: hardware trigger plus exposure-start stamp; rolling shutter adds intra-frame skew. IMU: stamp each sample and integrate between them.

choicewins whencost
HW timestampjitter budget < 100 µsNIC/PHY support
SW timestampprototype, no PTP NIC100 µs–ms jitter under load
PTPmulti-sensor, sub-µs neededswitch config, GM failover
PPS onlyone simple edgeno epoch, needs NMEA
Per-point LiDAR tsmotion above ~1 m/sbandwidth, driver support
Scan-start + deskewlegacy sensorsneeds good IMU, model error

Buffering. Hold a bounded reorder window sized to twice the worst-case transport latency, then drop. Compensate motion only with a valid model and reject extrapolation past roughly 50 ms.

failuresymptomdetect
clock step backwardsnegative dt, filter divergencemonotonicity check, dt < 0 or > 5× nominal
PTP grandmaster failoveroffset jumpoffset above threshold for N samples
missing per-point tsresidual grows with yaw ratecompare deskewed vs raw registration
dropped or reordered framesgaps in streamsequence numbers
trigger jitterexposure start variescompare HW timestamp to trigger edge

Arithmetic. 10 m/s × 100 ms = 1 m scan smear. 10 m/s × 10 ms exposure = 10 cm smear. 200 Hz IMU = 5 ms between samples, so a 1 ms timestamp error is 20% of a sample period.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Manage spatial calibration for a multi-sensor robot.

Answer

Core answer

Clarify first: which sensors, what frame tree, required accuracy, static or online, compute budget. Assume rigid mounts, time sync within 1 ms, and a calibration target available. The answer: calibrate intrinsics first, then extrinsics, then temporal offset, validate on held-out data, and bind the result to mount identity.

Intrinsics first because extrinsics depend on them. Use Zhang's method with a ChArUco board and OpenCV calibrateCamera; 15–20 views, target reprojection error below 0.3 px. For rolling shutter, use Kalibr's continuous-time B-spline.

Extrinsics: camera–IMU via hand-eye AX=XB (Tsai–Lenz), lidar–lidar via point-to-plane ICP, camera–lidar via AprilTag plus plane. Solve with Ceres Solver, Huber loss. Initial guess from URDF.

Temporal: estimate time offset by cross-correlating IMU angular velocity with visual odometry; Kalibr does this jointly.

Uncertainty: covariance from the Hessian (Ceres) or GTSAM iSAM2. Report 1-sigma.

Trade-offs

Target-based vs targetless: target gives 0.5 cm / 0.1° but needs a controlled scene; targetless (ICP, mutual information) works in situ but 2–5 cm and needs a good initial guess. Offline batch (Kalibr, Ceres) is more accurate but takes minutes; online (FAST-LIO2, iSAM2) corrects drift but lower accuracy. Intrinsics before vs jointly: before is simpler; joint (Kalibr) is better if the time offset is unknown.

Failure modes

Remount detection: monitor residual on known targets or compare tf to prior; if rotation > 0.5° or translation > 2 cm, flag. Chi-square test on residuals. Map invalidation: if extrinsics change, dependent maps (occupancy, semantic) must be rebuilt; e.g., 10 min for 100 m × 100 m at 5 cm resolution. Rollback: keep last N calibration versions in SQLite with sensor serial, mount ID, timestamp, hash.

Artefacts

StageMethodToolTypical residualDetection
IntrinsicsZhang, ChArUcoOpenCV< 0.3 pxreprojection
ExtrinsicsAX=XB, ICPCeres0.5–2 cmtarget residual
Temporalcross-corrKalibr< 1 msresidual vs offset
Validationheld-out—< 2 cmchi-square

Arithmetic: if each extrinsic has σ = 0.5 cm, chaining 3 transforms gives σ = √3 × 0.5 ≈ 0.87 cm. (Illustrative.)

Diagram:

base_link
├── lidar (x: 0.1, y: 0, z: 1.2)
├── camera_left (x: 0.2, y: 0.1, z: 1.1)
└── imu (x: 0, y: 0, z: 0.5)

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Validate uncertainty reported by a localization system.

Answer

Core answer. A covariance is a claim about the error distribution; validating it means testing whether the reported P matches the actual spread of the error. Pin the claim down first: frame, units, orientation as a 3-vector perturbation about the estimate (not Euler angles), and the ordering of the covariance block. Then test.

The standard test is NEES. With ground-truth error e = x_true − x̂, compute eᵀP⁻¹e. If the estimator is consistent, NEES ~ χ²(n), n = error dimension. One sample is noisy, so average over N runs: N·ANEES ~ χ²(Nn).

nsingle-sample 95% NEESN = 100, N·ANEES 95%
3 (position)[0.352, 7.815][254, 350]
6 (pose)[1.635, 12.592][534, 670]

Above the upper bound is overconfidence; below the lower is underconfidence.

Worked example. Reported P = diag(0.01, 0.01, 0.04) m² (σ = 0.1, 0.1, 0.2 m). Two ground-truth errors:

Python
import numpy as np
P    = np.diag([0.01, 0.01, 0.04])       # m^2
Pinv = np.linalg.inv(P)                  # diag(100, 100, 25)
e    = np.array([[0.15, -0.05,  0.30],
                [0.35,  0.20, -0.10]])   # m
nees = np.einsum('ij,jk,ik->i', e, Pinv, e)
print(nees)        # [ 4.75 16.5 ]
print(nees.mean()) # 10.625

Trace: Pinv = diag(100, 100, 25). Sample 1: 0.15²·100 + 0.05²·100 + 0.30²·25 = 2.25 + 0.25 + 2.25 = 4.75. Inside [0.352, 7.815], consistent. Sample 2: 0.35²·100 + 0.20²·100 + 0.10²·25 = 12.25 + 4.00 + 0.25 = 16.5. Above 7.815, that sample is overconfident. Pooled: N·ANEES = 2 × 10.625 = 21.25 against χ²(6) 95% = [1.237, 14.449] → reject. Two samples already catch it; the single-sample test alone would not.

Without ground truth: NIS. νᵀS⁻¹ν with S = HPHᵀ + R, distributed χ²(m) for m measurement dimensions. NIS runs online, but it only tests the filter against its own model: a filter with wrong R and wrong P can pass it. NIS catches divergence; NEES catches a lying covariance.

Failure modes, with symptoms.

  • Overconfidence. Reported σ = 0.1 m per axis but actual per-axis RMSE = 0.3 m: each axis contributes 0.3²/0.1² = 9, so NEES ≈ 27, far above 7.815. The planner trusts a pose 3× worse than advertised and drives into obstacles.
  • Underconfidence. NEES below the lower bound means P is inflated; the planner is over-cautious and the robot moves slower than it needs to.
  • Unmodeled correlations. Testing each axis separately lets marginals pass while the joint fails. Test the full state vector and check off-diagonals against the Monte Carlo sample covariance.
  • Linearization error. EKF covariance from Jacobians underestimates when nonlinearity is strong; NEES grows with distance from the linearization point. Compare against a UKF or particle-filter covariance.
  • Delayed measurements. Out-of-order updates applied with stale covariance produce NIS spikes on late-arriving measurements.
  • Robust losses. Huber or Cauchy down-weighting shrinks the effective R, so NIS is biased low and the reported covariance looks better than it is. Recompute NIS with the actual applied weight.

Alternatives and when they are wrong. Coverage testing: the fraction of ground-truth samples inside the 95% ellipse should be ~95%. With 1000 samples the binomial 95% interval is 93.6%–96.4%, so a run at 90% is a real failure, not noise. Cheap, no Gaussian assumption, but a scalar per regime that hides direction. Monte Carlo sample covariance versus reported P is ground truth for everything above, but needs many runs and is offline. NEES requires ground truth, so it is a benchmark tool, not a runtime monitor. All the χ² tests assume Gaussian errors: heavy-tailed real errors will reject a perfectly usable filter, so check the error histogram before trusting a rejection.

Decision. Calibrate the threshold to consequence: 2× overconfidence on a 0.05 m indoor pose is tolerable; the same factor on a 1 m highway pose is not. Report the covariance with its frame and direction, never as a scalar.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Deskew a LiDAR scan safely.

Answer

Core answer.

A spinning LiDAR does not capture a scan instantaneously. A Velodyne VLP-16 at 10 Hz takes 100 ms per revolution, firing its 16 lasers in sequence across roughly 1800 azimuth steps, so the first and last point in one "scan" are up to 100 ms apart. At 1 m/s that is 10 cm of translation smear; at 5 m/s it is 50 cm. Yaw at 90°/s over 100 ms is 9°, which at 20 m range displaces a point by about 3 m along the arc. Deskewing means giving every point the pose it actually had when it was fired, then expressing all of them at one declared reference instant.

Assumptions I would state up front: I have per-point or per-packet acquisition time (Ouster puts per-point timestamps in the packet; Velodyne drivers expose per-firing time and the header stamp is scan end by default), a calibrated firing order, and a continuous pose source. IMU at 100–200 Hz fused with wheel odometry. If any of those is missing, the honest output is degraded data, not a silently extrapolated cloud.

Mechanism. For each point with time t_i, find the two bracketing poses T(t0) and T(t1), interpolate between them (slerp for rotation, lerp for translation) to get T(t_i), and map the point into the reference frame: p_ref = T_ref⁻¹ · T(t_i) · p. The alternative, one rigid transform per scan, is only valid when motion within the scan is small against the accuracy you need. At 1 m/s and 10 cm tolerance a single transform is fine; at 5 m/s it is not.

Estimator error propagates directly and scales with range. A 0.5° angular error at 20 m is about 17 cm of lateral displacement, so far points smear worst. That is why deskewing with a bad pose can be worse than not deskewing: you have replaced a uniform offset with a range-dependent distortion.

Trade-offs. Per-point interpolation costs a pose lookup and an SE(3) interpolation per point: cheap, but it needs pose coverage across the whole scan. A per-scan rigid transform is nearly free and robust to pose gaps, and is the right call for slow platforms or short scans. A continuous-time trajectory (B-spline) or motion-compensated ICP is the heavy option when you need sub-centimetre accuracy at high speed.

Failure modes and how I would catch them.

  • Clock offset between LiDAR and IMU: symptom is a skew that grows with speed and does not vanish when stationary; detect by deskewing a static scene and checking residual against a reference; cost is a bias no amount of tuning removes.
  • Pose gap or IMU dropout: points past the last pose get extrapolated; symptom is a fan of points at scan edges; detect by counting points whose bracketing gap exceeds 20 ms and refusing to emit them.
  • Wrong extrinsics: a constant offset between LiDAR and IMU frames; detect on a known target; cost is a fixed bias.
  • Rapid rotation: a wall that should be planar comes out curved; detect by plane-fit residual.

Circularity. Never estimate the pose from the cloud you are deskewing: that hides estimator error inside the correction. Use independent odometry.

Python
# Python 3.11, numpy 1.26
def deskew(points, times, poses, t_ref, max_gap=0.02):
    ts = np.array([t for t, _ in poses])
    T_ref = interp_se3(poses, t_ref)
    out = np.empty_like(points)
    for i, (p, t) in enumerate(zip(points, times)):
        j = np.searchsorted(ts, t)
        if j == 0 or j == len(ts) or ts[j] - ts[j-1] > max_gap:
            return None                      # degraded: extrapolation or gap
        a = (t - ts[j-1]) / (ts[j] - ts[j-1])
        T = interp_se3_pair(poses[j-1][1], poses[j][1], a)
        out[i] = np.linalg.inv(T_ref) @ T @ p
    return out
scenarioscan spandisplacement
VLP-16 10 Hz, 1 m/s100 ms10 cm
VLP-16 10 Hz, 5 m/s100 ms50 cm
90°/s yaw, 20 m range100 ms~3.1 m arc
0.5° pose error, 20 m—~17 cm

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Build a robust LiDAR scan-registration stage.

Answer

Assumptions first. Spinning 3D LiDAR at 10 Hz (~100 ms per revolution), IMU or wheel odometry at ≥100 Hz, and a prior pose from the previous frame or a global fix. Without those the design changes, and I'd say so before answering.

Core answer. Deskew → voxel-downsample → initial guess → point-to-plane correspondence → robust Gauss-Newton → Hessian degeneracy check → emit transform, covariance and residual statistics, or an explicit failure. Never a pose on every call.

Why deskew precedes correspondence. A 10 Hz sweep takes 100 ms. At 15 m/s the sensor moves 1.5 m during one revolution, so the first and last points of a scan are not simultaneous. ICP linearizes about the current estimate and its basin is roughly the feature scale: tens of centimetres. 1.5 m of unmodelled motion puts the true correspondence outside that basin and the solve locks onto the wrong surface. Interpolate the odometry trajectory at each point's timestamp and transform every point into the sweep-start frame. At 200 Hz IMU, samples are 5 ms apart: 7.5 cm of motion: small enough to interpolate linearly.

Correspondence and the residual frame. For each source point p, take the nearest target point q and the normal n at q. Residual r = nᵀ(Tp − q). "Correctly framed" means the normal is taken at the target point and the residual is measured in the target frame; the Jacobian for a left perturbation ξ = [ω, v] on SE(3) is the 1×6 row [p × n, n]. Taking the normal at the source, or measuring in the source frame, flips the update direction and the solve oscillates instead of converging.

Degeneracy from the Hessian. Assemble H = Σ w JᵀJ (6×6) and eigen-decompose. In a corridor every normal is perpendicular to the corridor axis, so the translation-along-axis column of H is zero and λ_min ≈ 0; the condition number λ_max/λ_min blows up. Threshold: treat a direction as unobservable when λ_min/λ_max < ~1e-3 (Zhang et al., 2016, compare the smallest eigenvalue against a fixed bound). Don't fail the whole solve: project the update onto the well-conditioned subspace and fill the degenerate direction from the odometry prior.

Robust loss. Huber with δ ≈ 0.2–0.5 m, i.e. 2–3× the expected inlier residual, downweights dynamic objects and spurious returns; Geman-McClure is more aggressive but can stall when inliers are few.

methodresidualgood whenfails when
point-to-point ICP‖Tp − q‖unstructured geometry, no normalsplanar scenes, needs tight init
point-to-plane ICPnᵀ(Tp − q)structured indoor/urban, converges in fewer iterationscorridors, tunnels (null along axis)
GICPplane-to-plane Mahalanobismixed geometry, noisy normalscost, needs per-point covariances
NDTvoxel Gaussian likelihoodlarge scenes, no correspondence searchresolution-sensitive, sparse overlap
feature-based (LOAM-style)edge/plane feature residualssparse overlap, motionfeature-poor scenes
Python
import numpy as np

def point_to_plane_step(src, dst, nrm, T, delta=0.3):
    R, t = T[:3, :3], T[:3, 3]
    p = src @ R.T + t                        # source in target frame
    r = np.einsum('ij,ij->i', nrm, p - dst)  # signed point-plane residual
    a = np.abs(r)
    w = np.where(a <= delta, 1.0, delta / a) # Huber
    J = np.hstack([np.cross(p, nrm), nrm])   # (N,6), left perturbation
    H = J.T @ (w[:, None] * J)
    g = J.T @ (w * r)
    lam, _ = np.linalg.eigh(H)
    cond = lam[-1] / max(lam[0], 1e-12)
    if cond > 1e3:
        return None, cond                    # degenerate: caller uses prior
    dxi = np.linalg.solve(H + 1e-6 * np.eye(6), -g)
    return dxi, cond

Trace the corridor case: walls run along x, floor and ceiling are horizontal, so every normal lies in the y-z plane and n_x = 0 for all points. The x-translation column of J is n_x, so that column is zero, and H's x-translation row and column are zero. λ_min = 0, cond = ∞, and the function returns None: the caller fills x-translation from odometry instead of trusting the solve.

Failure modes. No overlap, or an initial guess outside the basin → return failure, not a pose. Rain and fog produce returns from droplets with range noise well beyond the inlier band. High angular rate outruns the deskew interpolation. Open fields and long tunnels are degenerate. A truck filling the field of view can dominate the residual even with a robust loss.

When this design is wrong. With a dense prior map and a good global fix, skip correspondence search: NDT or a direct method is cheaper. With no IMU and a feature-poor scene, no registration method recovers the pose; that is a sensor problem, not an algorithm one.

Output. T, a 6×6 covariance ≈ σ²H⁻¹ with σ² from the robust-weighted residual variance, inlier ratio, median residual, condition number, and an explicit failure flag.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design robust landmark or scan data association.

Answer

Assumptions. 2D lidar scan-to-map (or visual landmarks), predicted pose with covariance from wheel odometry fused in an EKF, and a map of landmarks each carrying a mean and 2×2 covariance. Sensor: 360 beams at 1°, 30 m range.

Core answer. Data association is a hypothesis test, not a nearest-neighbour lookup. For each measurement I compute the innovation against every candidate landmark that survives a cheap geometric prefilter, predicted position inside the sensor FOV and range, then gate on the Mahalanobis distance d² = vᵀS⁻¹v with S = HPHᵀ + R. For a 2-DOF measurement the χ² 95% gate is 5.991 and 99% is 9.210; I use 95% for dense scan points and 99% for sparse visual landmarks, where a missed match costs more than a false one. Survivors go to a robust estimator: RANSAC for the scan-to-map transform, or IRLS with a Huber kernel when I already have a good prior. I accept the transform only if the inlier ratio clears ~0.5, the inliers span the sensor footprint rather than clustering in one corner, and the normal matrix is well-conditioned. Ambiguous measurements are held as a second hypothesis for one or two frames instead of being forced.

Why the gate works, and when it doesn't. S folds the landmark covariance, the Jacobian of the measurement model, and the sensor noise R into one scale, so d² is dimensionless and comparable across range and bearing. It fails under drift: if the predicted pose is off by more than the gate radius, every true measurement falls outside and gets rejected, so the matcher spawns duplicate landmarks and the map grows. Watch the ratio of new-landmark spawns per frame: a jump from ~0.1 to >1.0 means the prior has drifted past the gate.

Worked gate trace. Landmark predicted at (10.0, 5.0), robot at (8.0, 4.0): predicted relative position (2.0, 1.0). Measurement (2.1, 0.95), so v = (0.1, −0.05). With S = diag(0.04, 0.01) (σ = 0.2 m, 0.1 m), d² = 0.1²/0.04 + 0.05²/0.01 = 0.25 + 0.25 = 0.5 < 5.991 → accept. A second measurement (2.5, 1.4) gives v = (0.5, 0.4), d² = 6.25 + 16 = 22.25 > 5.991 → reject.

RANSAC budget. With a 3-point minimal sample and 50% outliers, N = log(0.01)/log(1 − 0.5³) ≈ 35 iterations for 99% confidence. At 70% outliers (w = 0.3) it is log(0.01)/log(1 − 0.027) ≈ 169. If your outlier rate is that high, RANSAC is the wrong tool: fix the prior or switch to descriptors.

Trade-offs.

methodcostrobust tofails when
NN + χ² gateO(n log m) with a KD-treesmall prior errordrift exceeds gate radius
JCBBexponential worst case, prunedcorrelated errorsmany landmarks
descriptor + RANSAC~35–170 iterationslarge initial errorrepetitive structure
multi-hypothesisk× memorygenuine ambiguitywrong branch persists

Failure modes. Perceptual aliasing (identical pillars, a corridor): RANSAC finds a wrong consensus with a high inlier count. Detect it by low spatial spread of inliers or two hypotheses within 10% score. Degeneracy: in a corridor the along-axis eigenvalue of the ICP normal matrix is ~100× smaller than the lateral one; a condition number > 100 means the transform is unobservable along that axis, so constrain it rather than trusting the solve. Dynamics: a moving car matched to a static landmark leaves a persistent innovation after the update. Reject and re-spawn. Adversarial false similarity (repeated texture) defeats descriptor matching outright; fall back to geometry and temporal consistency.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Use robust estimation without hiding bad measurements.

Answer

The 90-second answer. Robust estimation means replacing the squared-error cost with an M-estimator whose influence function is bounded, so one bad measurement cannot drag the solution arbitrarily far. The trap is the second half of the question: the same weight that bounds an outlier's influence also erases it from your diagnostics. After downweighting, a 5 m loop-closure error and an inlier sitting at the loss knee produce the same robustified residual. So robustify the cost, but log the raw residual and the weight as separate first-class outputs, and remove or quarantine a source that stays downweighted across runs instead of letting it bias the solution forever at low weight.

Mechanism. You minimize Σ ρ(r_i²/σ_i²) instead of Σ r_i²/σ_i², where r_i is the residual and σ_i the measurement noise. It is solved by iteratively reweighted least squares: each factor gets weight w_i = ψ(r_i)/r_i with ψ = ρ'. The scale parameter c lives in residual units: a multiple of σ, not an absolute distance. Huber's δ = 1.345σ and Tukey's c = 4.685σ are the standard choices that keep 95% asymptotic efficiency on clean Gaussian data.

r/σHuber δ=1.345Cauchy c=1Tukey c=4.685DCS Φ=1
11.0000.5000.9111.000
40.3360.0590.0730.118
100.1350.01000.020
250.0540.00200.003

Huber is convex and never fully rejects: bounded influence, not zero. Cauchy and Tukey redescend to zero; Tukey is exactly zero past c. DCS (Agarwal et al., ICRA 2013) scales the information matrix by s = min(1, 2Φ/(Φ + χ²)) and is the closed-form cousin of switchable constraints. Ceres ships Huber, Cauchy and Tukey losses; GTSAM ships those plus Geman-McClure and DCS.

Worked trace. One scalar, five range measurements with σ = 0.1 m: 0.00, 0.02, −0.01, 0.01, 5.00. Least squares gives the mean, 1.004 m: a 10σ error from the true 0. Huber with δ = 1.345σ = 0.1345 m, IRLS from that start: first step weights are δ/|r|, giving x = 0.299; then 0.082; then 0.039; it converges to 0.0386 m. The outlier still pulls the estimate by 0.39σ: Huber bounds it, it does not remove it. At convergence the outlier's robustified residual is w·r = 0.0271 × 4.961 = 0.1345 m, exactly δ: on a robustified-residual plot it is indistinguishable from an inlier at the knee. Tukey from the same start is worse: every residual exceeds c = 0.4685 m, so all five weights go to zero and the problem is degenerate. That is why you anneal the scale (graduated non-convexity, Yang et al., RA-L 2020) rather than starting at the final c.

Trade-offs. Huber when you want convexity, a unique minimum, and can tolerate residual bias. Cauchy or Tukey when outliers are gross and you can afford a non-convex solve with a good initial guess. Hard chi-square gating (reject if Mahalanobis² > χ²₃,₀.₉₉ = 11.34) is cheaper and fully removes the measurement, but one threshold either rejects good data or keeps bad; soft losses degrade gracefully. DCS when you want switchable-constraint behaviour without adding variables.

Failure modes. Scale too small: inliers get downweighted, efficiency drops and the estimate drifts. Detect by the fraction of factors with w < 1, which should be about 5% under Gaussian noise at δ = 1.345σ. Scale too large: outliers keep influence. Check the raw residual distribution after convergence. Coherent false loop: a repeated corridor produces several mutually consistent wrong loop closures with small residuals, so no robust loss sees them; detect with pairwise consistency maximization (Mangelson et al., ICRA 2018) before adding them, or switchable constraints that can disable a group. Calibration bias: a wheel-odometry scale error is consistent, not outlying, so robust losses ignore it. Estimate it as a state variable. Persistent bad source: quarantine the factor, do not leave it at low weight.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Detect and handle geometric degeneracy in LiDAR odometry.

Answer

Geometric degeneracy is when the scene doesn't constrain all six pose degrees of freedom, so the optimizer's update along one or more directions is driven by noise rather than geometry. The canonical case is a straight tunnel: translation along the tunnel axis is unobservable from scan matching, while lateral translation and yaw are well constrained. The job is to detect which directions are weak and stop trusting the update there.

Mechanism. Scan matching solves a Gauss-Newton system H Δx = -b, where H = JᵀJ is the 6×6 information matrix and b = Jᵀr. Eigendecompose it: H = V Λ Vᵀ. The variance of the estimate along eigenvector v_i is proportional to 1/λ_i, so a near-zero eigenvalue means the data barely constrains that direction and the matching component of Δx is dominated by residual noise. That is the entire reason eigenvalues work as a degeneracy signal: they are the inverse of the information the scan provides.

Detection. Compute the eigenvalues each iteration and flag degeneracy when λ_min/λ_max falls below a threshold. Zhang, Kaess and Singh (ICRA 2016) formalized this and proposed solution remapping; a ratio cutoff around 1e-3 is a common starting point, tuned per sensor. Two things bite. First, scale: if translation is in metres and rotation in radians, the eigenvalues mix units and the ratio is meaningless. Normalize the Jacobian blocks before comparing. Second, degeneracy is per-direction and transient, so keep the eigenvectors, not just the scalar.

Handling. Solution remapping projects the update onto the well-conditioned subspace, Δx_well = V_well V_wellᵀ Δx, and applies only that. It is cheap and needs no extra sensor, but it leaves the weak direction unestimated, so drift accumulates there and something else must cover it. The alternatives: add a prior or inflate the covariance along weak directions (what tightly-coupled LiDAR-inertial filters such as FAST-LIO2 do), or fuse an IMU, wheel odometry or GNSS. An IMU constrains the direction short-term but biases over long horizons and needs calibration and time sync. The last resort is a bounded degraded mode: cap velocity, dead-reckon with a time limit, or stop.

SceneWeak directionsHandling
Straight tunnelalong-axis translationremap + IMU along-axis
Open field / single planeall translation, roll, pitchGNSS or motion prior
Corridor with repeated columnsalong-axis translation (aliasing)remap, cross-check overlap
Flat ground onlyz translation, roll, pitchprior / IMU

Failure modes. Threshold too high: you suppress valid updates in a normal corridor and drift when geometry was fine. Too low: the solver injects a large spurious correction along the weak direction, the pose jumps, and the map corrupts. Watch the confound: a drop in scan-to-map overlap (entering a tunnel) shrinks the whole Hessian, which looks like degeneracy but is a correspondence problem, not a geometry problem. Detect in operation by logging λ_min/λ_max, correspondence count, residuals, and the magnitude of the update along weak eigenvectors, per scan.

Python
import numpy as np

def remap_update(H, b, ratio_thresh=1e-3):
    # H: 6x6 information matrix (J^T J); b: 6-vector (J^T r)
    w, V = np.linalg.eigh(H)          # ascending eigenvalues
    lam_max = w[-1]
    degenerate = w[0] / lam_max < ratio_thresh
    dx = np.linalg.solve(H + 1e-9 * np.eye(6), -b)
    if degenerate:
        mask = w / lam_max >= ratio_thresh
        dx = V[:, mask] @ (V[:, mask].T @ dx)   # keep well-conditioned subspace
    return dx, w, degenerate

Trace: eigh returns ascending eigenvalues, so w[0] is the weakest direction. mask selects eigenvectors whose eigenvalue ratio clears the threshold; V[:, mask] @ (V[:, mask].T @ dx) is the orthogonal projection that removes the degenerate component of the update.

Arithmetic: in a corridor, suppose λ_along = 1e-4, λ_lateral = 5, λ_yaw = 8. The ratio is 1.25e-5, flagged. The 1σ uncertainty along the corridor is 1/√1e-4 = 100, versus 1/√5 ≈ 0.45 laterally: over 200× worse, so the along-corridor update is noise. (Illustrative figures.)

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design visual tracking quality and degradation handling.

Answer

Clarify and assume. I'll assume a stereo-inertial VIO stack (ORB-SLAM3-style) on a ground robot: 20 Hz cameras at 640×480, 200 Hz IMU. The question is how to know the tracker is still trustworthy, and what to do when it isn't.

Core answer. Track a small set of health signals, gate on them, and degrade in a fixed order. The signals that earn their place: tracked feature count and grid coverage, RANSAC inlier ratio, parallax, reprojection residual, exposure/clipping, blur, and IMU-visual consistency. When they cross thresholds, first try to recover within limits (exposure, feature strategy), then coast on IMU, then slow or stop, and resume only after verified relocalization.

Why these signals, and why covariance alone lies. A filter's covariance reflects the noise model you fed it, not the truth. If features are correlated (the same repeated texture patch matched twice) or biased, the filter stays confident while the estimate drifts, so you need geometric checks, not just the covariance. Inlier ratio drops before divergence when outliers grow, but it can also stay high while being wrong: repeated texture yields a consistent-but-degenerate model with many inliers. That is why parallax and degeneracy checks sit alongside it.

Parallax bounds depth observability. Depth uncertainty is roughly σ_z ≈ z²·σ_d / (f·B). With f = 400 px, baseline B = 0.1 m, z = 5 m, σ_d = 0.5 px: σ_z ≈ 25·0.5/(400·0.1) = 0.31 m (~6%). Drop effective baseline to 0.02 m (near-pure rotation) and σ_z ≈ 1.56 m (~31%). Low parallax means the depth, and monocular scale, is unobservable, no matter how many features you have.

SignalTypical gateDetects
Feature count< 100 in 640×480darkness, low texture
Grid coverage (8×8)any cell empty > 1 sconcentration
RANSAC inlier ratio< 0.5 for 5 framesoutlier regime
Median parallax< 1°depth unobservable
Reprojection RMS> 1.5 pxmodel violation
Clipped pixels> 5%glare/saturation
Laplacian variancelow vs. baselinemotion blur
IMU-visual residualchi-square rejectinconsistency

Failure modes, with detection and response.

  • Darkness/low light: feature count falls below ~100 and image mean intensity < 20/255. Response: raise gain first, then exposure time; if count stays low, coast on IMU.
  • Motion blur: angular rate × exposure time exceeds a pixel threshold; Laplacian variance collapses. Response: shorten exposure (accept more noise) or reduce commanded velocity.
  • Glare: clipped-pixel fraction > 5%. Response: exposure down; if persistent, treat region as invalid.
  • Repeated texture: high inlier ratio but median parallax < 1° or multiple competing RANSAC models. Response: reject the frame's geometry rather than trust the inliers.
  • Rapid rotation / occlusion: IMU gyro shows rotation with no visual parallax; features vanish in a region. Response: IMU-only propagation, which drifts. Bound it to ~0.5–1 s.
  • Dirty lens: persistent low gradient across the whole frame. Response: flag hardware, stop relying on vision.

Trade-offs. Tightly-coupled VIO rides out short visual outages better than loosely-coupled but is harder to tune. Direct methods survive low texture but break the brightness-constancy assumption, so exposure changes hurt them: prefer gain over exposure time, or model affine brightness. Relocalization must be geometrically verified against the map; appearance-only place recognition (DBoW2) false-positives on repeated scenes. Do not trust covariance as a health signal, and do not relocalize on appearance alone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Recover and validate scale in a monocular system.

Answer

Assume one calibrated pinhole camera and no other metric sensor. Then metric scale is not recoverable from images alone: it is a gauge freedom, not a noisy quantity. Every monocular SLAM/odometry system recovers structure and motion only up to an unknown positive factor s. To get metres you must inject a metric source, estimate s as a state, and validate it against an independent check.

Why it is unobservable. Projection is x ~ K(RX + t). Replace X → sX and t → st:

K(R·sX + st) = s·K(RX + t) ~ K(RX + t)

Same pixel. The whole scene and trajectory can be scaled by any s > 0 and produce identical images, so the solution lives in Sim(3), not SE(3).

Python
import numpy as np
f, cx, cy = 500.0, 320.0, 240.0
K = np.array([[f, 0, cx], [0, f, cy], [0, 0, 1]])

def project(X, R, t):
    Xc = R @ X + t
    p = K @ Xc
    return p[:2] / p[2]

R, X, t = np.eye(3), np.array([1.0, 0.0, 5.0]), np.zeros(3)
print(project(X, R, t))        # [420. 240.]
print(project(2 * X, R, 2 * t))  # [420. 240.]  identical

Both print [420. 240.]. Scale 1 and scale 2 are indistinguishable.

Making it observable. An IMU measures specific force f = Rᵀ(a − g) with |g| = 9.81 m/s² known. Under constant velocity a ≈ 0 and the accelerometer sees only gravity, so scale stays free. Under sufficient translational and rotational excitation the non-gravity term couples the metric size of the trajectory to the known |g|, and scale becomes observable: the standard VIO observability result (Martinelli, IEEE T-RO 2012). In practice VINS-Mono, OKVIS, MSCKF and ORB-SLAM3's inertial mode estimate scale implicitly: the state carries velocity, position and gravity direction, IMU preintegration ties consecutive keyframes in metric units, and fixing |g| at 9.81 anchors the gauge. In sliding-window bundle adjustment the same factor graph does it: reprojection errors fix relative geometry, preintegration fixes metric size.

Alternatives and when each is wrong.

sourcemetric anchorgood whenbad when
Stereo baseline bz = f·b/dtwo synced cameras, b ≥ ~5 cmsmall b: σ_z ≈ z²/(f·b)·σ_d
RGB-D / ToFdirect depthindoor, a few metressunlight, reflective or black surfaces
IMU (VIO)|g| = 9.81enough accel excitationpure rotation, constant velocity
Wheel odometrywheel radius × countsflat ground, no slipslip, uneven terrain
Known object/heightone known lengthmarker or person in viewobject absent or occluded
External (GPS/mocap)absolute positionavailableindoor, denied environments

Stereo arithmetic: f = 500 px, b = 0.1 m, z = 5 m gives d = f·b/z = 10 px, and σ_z ≈ z²/(f·b)·σ_d = 25/50 · 0.5 = 0.25 m for σ_d = 0.5 px. Depth error grows as z², so a 10 cm baseline is useless past roughly 10 m.

Failure modes and detection.

  • Pure rotation / constant velocity: accelerometer variance near zero while the gyro is active. Symptom: scale stays at its initial guess or drifts. Detect by monitoring the accelerometer's non-gravity residual over the window; if it stays below noise, do not trust scale.
  • Accelerometer bias: a constant bias looks like a gravity tilt and biases scale. Detect by watching the bias state against the gravity-direction residual: a growing bias with flat excitation means scale is being absorbed into bias.
  • Timestamp offset: a few ms between camera and IMU injects a velocity-dependent error that grows with angular rate. Detect by correlating reprojection residuals with angular velocity; a fixed offset shows as a residual proportional to ω.
  • Source dropout: lose the IMU and scale is unobservable again. Detect by checking the metric source's rate and staleness; fall back to scale-free relative motion and flag it.

Validation. Do not trust a single number. Drive a measured baseline (say a surveyed 10 m straight line) and compare estimated distance; check that scale converges and holds within a few percent across windows; verify cross-sensor residuals (reprojection, preintegration) are white rather than drifting. If scale only holds while excitation is present, it is not being estimated: it is being re-guessed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design a safe loop-closure pipeline.

Answer

Assumptions. 3D LiDAR (64-beam, 10 Hz) on a ground robot, LIO front end (LIO-SAM or FAST-LIO2), pose graph in GTSAM, campus-scale trajectory around 1 km with revisits. Swap the retrieval stage for NetVLAD/DBoW2 if the sensor is a camera; stages 2-6 are unchanged.

The core answer. A loop closure is a bet that two places are the same. The pipeline's job is to make that bet cheap to place and cheap to lose.

  1. Retrieve. Scan Context (Kim & Kim, IROS 2018): a 20x60 polar descriptor plus a ring key for KD-tree search. Rotation invariance comes from the column shift; the ring key makes lookup O(log N) instead of running ICP against every keyframe. Keep the top 10 candidates, not the top 1: the best descriptor match is often not the best geometric match.

  2. Gate temporally. Reject candidates within 30 s or 10 m of the current pose. Consecutive frames always match; they add no information and inflate inlier counts.

  3. Verify geometrically. RANSAC over feature correspondences, then ICP/GICP refinement. Require inlier ratio >= 0.6 and a fitness score below the sensor's noise floor. This is the independent check: appearance descriptors are viewpoint- and season-sensitive, geometry is not.

  4. Check consistency. PCM (Mangelson et al., ICRA 2018): build a graph over the candidate loops and keep the maximum clique whose pairwise relative transforms agree within a threshold. A single false loop can be self-consistent; a set of false loops usually is not.

  5. Constrain robustly. Cauchy or Huber kernel, DCS, or switchable constraints. Trade-off: a robust kernel is one line and adds no variables, but it downweights rather than rejects, so a consistent-but-wrong loop survives. Switchable constraints add a per-edge weight variable optimized jointly and can reject a bad loop, but the optimizer can also drive a good loop's weight to zero. PCM is a hard gate before optimization; run it first.

  6. Stage and roll back. Optimize with Levenberg-Marquardt, monitor chi-square, and cap the correction: reject any closure that moves a pose more than 5 m or 10 degrees in one step. Keep the pre-closure graph so a bad closure is one revert away.

StageTypical thresholdProtects against
Scan Context retrievaltop 10 candidatesO(N) ICP cost
Temporal gate30 s / 10 mtrivial self-matches
RANSAC + ICPinlier ratio >= 0.6perceptual aliasing
PCM cliquepairwise transform agreementcoordinated false matches
Robust kernel / switchablechi-square gateone bad loop
Correction cap5 m / 10 deg per closuremap-wide deformation

Failure modes.

  • Repeated corridor. Two identical hallways 200 m apart. Descriptor score is high, ICP inlier ratio collapses below 0.6. Without the gate the closure injects a 200 m error and poses between the corridors get dragged: a fold in the map, not local drift. Detect via inlier ratio and correction magnitude.
  • Symmetry. A 180-degree-symmetric room makes the column-shift search return the wrong yaw. Detect when the yaw estimate disagrees with odometry by more than 30 degrees.
  • Dynamics. A truck parked in the same bay on two passes. Detect when the consistency check across revisits fails.
  • Seasonal change. Descriptor score drops, recall falls, no false positives. This is the safe failure: the pipeline degrades to odometry.
  • Coordinated false features. Repeated pillars produce many mutually consistent false matches, so the clique passes. Detect by checking the clique's spatial extent against the trajectory.

Why the cap matters more than the score. Illustrative: a 1 km trajectory at 0.1% drift accumulates about 1 m. A single false loop carrying 5 m of error over a 200 m subgraph is distributed across every node between the two matched poses, so the midpoint moves roughly half the injected error, about 2.5 m: 2.5x the drift budget, and spread over the whole span. Tune thresholds for precision first: a missed loop costs drift you can absorb, a false loop costs the map.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design lost-tracking and relocalization state transitions.

Answer

Assumptions first. A stereo or RGB-D VIO system with an IMU, running against a prebuilt map, on a wheeled robot moving at up to ~1.5 m/s. Frame rate 25 Hz. All thresholds below are starting points to tune per sensor, not defaults: I'd log every signal and re-fit them from a recorded run.

The core answer. I keep five explicit states and make every transition a named, logged event, because the failure I'm defending against is a tracker that silently keeps publishing a stale pose. The states are TRACKING, DEGRADED, LOST, RELOCALIZING, RECOVERED.

StateEntry conditionBehaviour
TRACKING≥30 matched inliers, inlier ratio ≥0.5, mean reprojection error <2 px, IMU-vs-visual velocity residual <0.3 m/sFull speed, publish pose
DEGRADED10–30 inliers, or ratio 0.2–0.5, or pose covariance inflated ~3×Cap speed at 0.3 m/s, keep local obstacle avoidance, widen pose covariance
LOST<10 inliers for 5 consecutive frames (~0.2 s), or covariance diverges, or map agreement failsStop or hold last pose with growing uncertainty; do not claim current
RELOCALIZINGEntered from LOSTGenerate hypotheses, verify, do not publish a pose until verified
RECOVEREDVerified hypothesis held for 25 frames (~1 s)Resume TRACKING

Why each transition fires. Inlier count and ratio are the primary signal because they collapse first when texture or lighting fails. Reprojection error catches the case where matches exist but are geometrically wrong. The IMU residual catches kidnapping: if the visual pose jumps 1.5 m in one frame while the IMU says the robot barely moved, the innovation exceeds a chi-square gate and I force LOST rather than trust the jump. Covariance is the slow signal: it inflates before inliers fully collapse, so it drives the TRACKING→DEGRADED step early.

Relocalization. I generate multiple hypotheses with place recognition (a DBoW2/DBoW3 vocabulary over ORB descriptors, as ORB-SLAM3 does), then geometrically verify each with RANSAC PnP, requiring ≥15 inliers. A single hypothesis is cheaper but locks onto false places in repetitive corridors, so I keep the top few and require temporal consistency across 3 keyframes before accepting one.

Trade-offs. Stop-vs-crawl is decided by hazard: in a corridor with people, stop; in open space, crawl at 0.3 m/s to keep obstacle protection while relocalizing. Multiple hypotheses cost ~5–10 ms of PnP each but avoid a false-place lock. Hysteresis length trades mission resumption speed against flapping: 1 s is a reasonable start.

Failure modes and detection. Kidnapping: pose jump inconsistent with IMU, innovation over gate → force LOST. Perceptual aliasing: geometric verification passes but temporal consistency fails → reject hypothesis. Occlusion: inliers drop then recover within ~0.5 s → DEGRADED, don't relocalize yet. Sensor return: inliers climb back → require hysteresis before RECOVERED. Rapid flapping: count transitions per minute; if it exceeds ~6, lengthen hysteresis.

Trace of a kidnapping. Frame 100: 45 inliers, TRACKING. Frame 101: robot lifted; visual pose jumps 1.2 m, IMU residual 1.1 m/s → innovation over gate → LOST. Frames 102–140: RELOCALIZING, hypotheses generated, none verified. Frame 141: hypothesis with 22 inliers passes PnP. Frames 141–165: held consistent → RECOVERED at frame 166. Total blackout ~1.6 s.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Validate relocalization after the kidnapped-robot condition.

Answer

Relocalization after a kidnap is a hypothesis test, not a pose assignment. I assume a map, an odom frame, and a global localizer such as AMCL or a global scan-matching search. The robot may have been moved without odometry, so the prior is useless. My core answer: accept a relocalization only when a fresh observation, taken after the kidnap, matches the map with enough geometric inliers under a non-degenerate configuration, the pose is consistent across several independent updates, and the map-to-odom correction can be applied while the controller is stopped or bounded. Otherwise keep searching and keep the robot safe.

Why multi-view geometry disambiguates: a single 2D scan in a symmetric corridor can match many poses. Two scans from different positions constrain the relative transform between them. In practice I run RANSAC over feature correspondences or scan points, then refine with PnP for vision or ICP for lidar. The inlier count and residual tell me if the match is real. A planar or featureless wall is degenerate: the solution is underconstrained along the wall. I check the covariance eigenvalues; if the smallest eigenvalue is near zero, I reject or add another view.

Timing matters because the pose must be expressed at the same timestamp as the odom state. If the scan is 100 ms old and the robot is moving at 1 m/s, the pose is 10 cm stale. I fuse at the scan timestamp, then propagate to now. Map compatibility: dynamic objects like people or forklifts produce outliers. RANSAC handles some, but I also check the inlier ratio against the static map. If it drops below a threshold, I suspect the map changed or the scene is dynamic.

Several updates are required because one match can be a false positive. I require N consistent updates, say 3 to 5, with the pose covariance shrinking and the innovation within a chi-square gate. The updates must be independent: if they all come from the same scan, they are not independent.

Trade-offs: global search is expensive and ambiguous; tracking is cheap but fails after kidnap. I use global search to seed, then tracking to confirm. If I trust a single match, I risk false recovery and driving into a wall. If I require too many, I stay lost and block the aisle. The deciding criteria are inlier count, residual, covariance, and consistency across updates. When the second-best hypothesis has a similar score, I reject and keep searching.

Failure modes and detection:

  • Symmetric places: multiple hypotheses with similar scores. Detect by checking the ratio of best to second-best inlier count; if > 0.9, ambiguous.
  • Changed maps: inliers drop, residual rises. Detect by monitoring inlier ratio over time; if it falls below 0.5, re-search.
  • Moving occluders: outliers. Detect by RANSAC inlier ratio and by checking if outliers cluster in time.
  • False recovery: pose jumps but odom does not. Detect by comparing predicted motion from odom to observed pose change; if the jump exceeds a bound, reject.

Worked trace (hypothetical): Global search returns two hypotheses. A: 45 inliers, 0.03 m residual. B: 42 inliers, 0.04 m residual. Ratio 42/45 = 0.93, so ambiguous. I command a small rotation. A still matches with 50 inliers; B drops to 10. I accept A. I then require three more updates with covariance below 0.1 m^2. Only then do I allow normal speed.

Table of checks:

I coordinate the map-to-odom correction while the controller is stopped or bounded. If the correction is large, I stop, apply it, then ramp speed. I report pose and uncertainty at a fresh timestamp. I never assume continuity; I compare against feasible motion from odom, but I do not require it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Pick the map representation for a 3D LiDAR warehouse AMR that must localize, plan around pallets, and fit in 8 GB RAM: landmarks, occupancy grid, or TSDF?

Answer

First 60 seconds: I'd ask what the map has to answer. Localization only, or planning too? 2D or 3D? Which sensor: camera, 2D LiDAR, 3D LiDAR, RGB-D? Memory and compute budget? Then I'd answer for the common case: a 3D LiDAR warehouse AMR that must localize and plan around pallets on 8 GB RAM. I'd use an occupancy grid as the planning map and a feature or scan-context map for localization, or, if forced to one, a 2D occupancy grid with a localization layer, because it answers both queries at bounded memory. TSDF is the wrong default here.

The representation decides what the estimator minimizes and what the planner can query.

representationlocalization residualplanningmemory
feature/landmarkreprojection or 3D landmark error (ORB-SLAM3)none: no free spaceO(#landmarks), 10^4–10^5 points
occupancy gridscan matching against log-odds cells (Cartographer)direct: A*/D* on cellsO(area / res²)
TSDF / surfel / voxelpoint-to-SDF or point-to-plane ICPvia ESDF, but heavyO(volume / res³)

Memory arithmetic at 5 cm resolution:

  • 2D grid, 100 m × 100 m: 2000 × 2000 = 4×10^6 cells; 1 byte log-odds = 4 MB.
  • 3D grid, 100 × 100 × 10 m: 2000 × 2000 × 200 = 8×10^8 cells; 1 byte = 800 MB.
  • TSDF, same volume, int16 = 1.6 GB. Viable only with sparse hashed blocks, and still heavy.

That is why the choice constrains the estimator. A landmark map gives a factor graph with landmark factors: bundle adjustment, loop closure by place recognition (ORB-SLAM3). An occupancy grid gives a correlative scan matcher; there are no landmarks to optimize, so loop closure is a pose-graph constraint between submaps (Cartographer). A TSDF gives ICP against the field; the gradient is valid only inside the truncation band, so distant surfaces produce no residual. Whichever you pick lives in the map frame, with map→odom published by the localization node (REP 105, tf2).

Failure modes and detection:

  • Feature map in a textureless corridor: too few landmarks, tracking loss. Detect via inlier count and covariance growth.
  • Occupancy grid with dynamic obstacles: phantom cells. Detect via ray clearing and time decay; plan on a decaying costmap layer.
  • TSDF with truncation too small: ICP fails to converge on distant geometry. Detect via residual and iteration count.

When not to use: a landmark map cannot do collision checking. No free space. A 3D occupancy grid outdoors blows memory with volume; use submaps or a 2D projection. A TSDF as the localization map on a memory-constrained robot is the wrong tool; keep it for manipulation or mesh export. Evaluate the chosen map with a benchmark that matches the sensor (KITTI odometry for LiDAR, TUM RGB-D for RGB-D) and report ATE/RPE with evo.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you detect and exclude moving objects in a SLAM system so they don't corrupt the map or pose estimate?

Answer

The answer, up front

State the assumption first: the back end (bundle adjustment, pose graph) assumes a static world. A moving object breaks that twice: it puts a landmark in the map that isn't there, and it adds a constraint to the pose that isn't true. So I'd do three things in order: cut the outlier fraction with a semantic prior, verify geometrically per frame, and make the back end robust to whatever survives. Detection alone isn't the answer: exclusion has to happen before the landmark enters the map, and the pose has to survive the ones you miss.

Mechanism

Camera. For a match between two frames, the Sampson distance to the epipolar line is small for static points; gate at ~1–2 px scaled by pixel noise. Scene flow does the same with a rigid-flow residual. Both need baseline: under pure rotation or a small baseline the epipolar line is ill-conditioned and the test tells you nothing.

LiDAR. Range-image residual between the current scan and the map, or scan-to-scan consistency after ego-motion compensation. The strong version is visibility-based removal (ERASOR, Removert): a point that was later observed as free space was never static.

Semantics. Mask R-CNN or SegFormer masks person, car, bicycle. Class-agnostic geometry catches unknown movers; semantics catch the parked car that geometry thinks is static.

Back end. Huber and Cauchy downweight but never reject, so a large consistent outlier set still pulls the pose. Switchable constraints or dynamic covariance scaling actually remove the edge.

MethodCatchesRemoves?CostFails when
Semantic maskKnown classesYestens of ms/frame (GPU)Unknown movers; over-masks static cars
Epipolar / scene flowAny inconsistent motionYes (outlier)10–20 msSmall baseline, pure rotation, slow motion
Robust kernel (Huber)OutliersDownweights only<1 msOutlier fraction high; biases pose
Switchable constraints / DCSOutlier edgesYes (drops edge)~msNeeds a decent initial estimate
Visibility-based (ERASOR/Removert)LiDAR dynamic pointsYesper scanNeeds an accurate pose to compare against

Worked trace: why the prior has to come first

RANSAC on the essential matrix, minimal sample 5, 2000 matches.

  • 30% dynamic (600 outliers): P(clean sample) = 0.7⁵ = 0.168. Over 100 iterations, 1 − 0.832¹⁰⁰ ≈ 1. RANSAC locks onto the static model; the 600 outliers fail the Sampson gate and are dropped.
  • 60% dynamic (1200 outliers): 0.4⁵ = 0.0102. Over 100 iterations, 1 − 0.9898¹⁰⁰ = 0.64. You need 448 iterations for 99%, and the set RANSAC converges on may be the moving object if it dominates the frame.

So the semantic mask isn't a nicety. It keeps the outlier fraction below RANSAC's practical breakdown, which is the argument for combining the two rather than picking one.

Real numbers

DynaSLAM (Bescos et al., RA-L 2018) reports ATE RMSE on TUM fr3/walking_xyz of 0.459 m for ORB-SLAM2 versus 0.015 m with semantic masking plus geometric rejection: a 30× reduction, and the baseline is unusable for anything metric.

Failure modes and how I'd detect them

  • Temporarily stationary object (parked car, person standing): geometry says static, it gets mapped, and the map is wrong once it moves. Detect with hysteresis on the object's motion state, not a per-frame test.
  • Articulated motion (waving arm): the torso passes, the arm fails. Partial masking leaves a corrupted landmark.
  • Dynamic object dominating the view: tracking loss. Watch the inlier ratio; a drop below ~0.5 is the signal.
  • Over-masking: a parked car is static structure, and masking it throws away good features. Gate the semantic mask on the object actually moving.

In production I'd log inlier ratio, track length, and the fraction of features rejected per frame, and check ATE against a reference trajectory on a dynamic sequence (TUM RGB-D, KITTI). For exclusion specifically: never insert a flagged landmark, and on re-observation remove the ones already in the map.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do you fuse GNSS fixes into a SLAM estimator so a single multipath outlier cannot corrupt the trajectory?

Answer

First clarify: fix type (standalone, SBAS, RTK float, RTK fix), frame (ENU vs ECEF, REP 105 map/odom), and coupling (loose vs tight). Then: model GNSS as a unary factor on the pose in the map frame, with covariance from the receiver but inflated when multipath indicators fire. Gate every fix with a chi-squared test on the innovation; never let a single fix enter un-gated. In a graph, use a robust kernel (Cauchy/Huber) so a bad fix is downweighted, not accepted. In an EKF, reject or inflate R.

Mechanism: measurement z = h(x) + v, h is position in map frame. Innovation r = z - h(x_pred), S = H P H^T + R. Mahalanobis d^2 = r^T S^{-1} r. For 3 DoF, chi-squared 99% threshold is 11.34. If d^2 > 11.34, reject. This only works if R is honest. RTK fix reports sigma ~0.02 m, but in urban canyon multipath can cause 10-50 m error; a 1 m error with sigma 0.02 gives d^2 = 2500, rejected. If you inflate R to 1 m^2, d^2 = 1, accepted, so you must inflate R when C/N0 drops, elevation is low, or pseudorange residuals are large.

Outlier rejection: use C/N0, elevation mask, dual-antenna heading, consistency with IMU/odometry over a 1-2 s window. RANSAC over recent fixes to find a consistent subset. Switchable constraints or dynamic covariance scaling.

Blending: odometry gives high-rate relative motion; loop closures correct drift; GNSS gives absolute but noisy. Add GNSS factors at 1-10 Hz with robust kernel. Use fixed-lag smoothing (iSAM2) so a later loop closure can re-evaluate a GNSS factor. If a bad fix is accepted, robust kernel bounds its influence; without it, a single 50 m outlier can pull the whole trajectory.

Failure modes: false RTK fix (reported 1-2 cm, actual 10 m), GNSS dropout, multipath in urban canyon. Detect via innovation gating, consistency checks, and monitoring d^2 distribution. On dropout, fall back to odometry, inflate covariance, and when fix returns, gate against predicted pose.

Fix typeTypical horizontal accuracyReported covarianceAction
Standalone2-5 m CEP10-25 m^2Downweight heavily, use only for coarse init
SBAS1-2 m1-4 m^2Use with robust kernel
RTK float0.1-1 m0.01-1 m^2Gate, inflate if multipath indicators
RTK fix1-2 cm + 1 ppm1e-4 m^2Trust but still gate; false fix possible

python r = z_gnss - h(x_pred) # innovation, 3x1 S = H @ P_pred @ H.T + R # innovation covariance d2 = r.T @ np.linalg.inv(S) @ r if d2 > 11.34: # chi2, 3 DoF, 99% reject or inflate R by 100x else: K = P_pred @ H.T @ np.linalg.inv(S) x = x_pred + K @ r P = (I - K @ H) @ P_pred

Arithmetic: with RTK sigma 0.02 m, S ~ 4e-4 m^2. A 1 m error gives d2 = 1/4e-4 = 2500, rejected. Inflate R to 1 m^2 and d2 = 1, accepted: covariance honesty is the gate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do you keep a factor graph bounded in a resource-constrained SLAM estimator, when does a frame become a keyframe, and when do you marginalize versus keep full smoothing?

Answer

Clarify first. What's the update rate, the CPU, and the RAM ceiling? On an Orin-class ARM a 10 Hz estimator has ~100 ms per update, and the optimizer should take a fraction of that. "Bounded" means the state you re-linearize each iteration has fixed size, not that the map is small. Two independent knobs: when a frame becomes a keyframe (how fast the graph grows), and marginalize-vs-full-smoothing (how you pay for it).

Keyframe selection. A frame becomes a keyframe when it adds information the graph doesn't already have. Three triggers, usually OR'd:

  • Motion: translation > ~0.1 m or rotation > ~5° from the last keyframe (typical VIO values; tune to your sensor).
  • Tracking quality: tracked inliers fall below ~70% of the reference keyframe's.
  • Time: at least N frames since the last keyframe, capping the insertion rate.

Information-gain (expected covariance reduction) is more principled but needs a covariance update per candidate frame. ORB-SLAM3's LocalMapping::NeedNewKeyFrame combines a weak-tracking test with a minimum frame gap and an idle-local-mapper test.

Marginalize vs full smoothing. When the window exceeds W keyframes, eliminate the oldest with the Schur complement:

Python
import numpy as np

def marginalize(H, b, m_idx, r_idx):
    """Eliminate states m_idx; return the prior (H_p, b_p) on r_idx."""
    H_mm = H[np.ix_(m_idx, m_idx)]
    H_mr = H[np.ix_(m_idx, r_idx)]
    H_rm = H[np.ix_(r_idx, m_idx)]
    H_rr = H[np.ix_(r_idx, r_idx)]
    H_mm_inv = np.linalg.inv(H_mm)
    H_p = H_rr - H_rm @ H_mm_inv @ H_mr   # dense in general: fill-in
    b_p = b[r_idx] - H_rm @ H_mm_inv @ b[m_idx]
    return H_p, b_p

Two-pose trace, 1-D for readability: relative measurement information A=1, absolute prior on x0 of Λ=2. H = [[3, -1], [-1, 1]]. Marginalizing x0: H_p = 1 - (-1)(1/3)(-1) = 2/3. The prior on x1 is 2/3: strictly less than the 2 on x0, because information leaks through the relative constraint. That loss is the whole point.

Arithmetic. Poses-only, W=10, 6 DoF: 60×60 Hessian. Full smoothing over 1000 poses is 6000 pose variables; dense that's 36M entries = 288 MB, but you never form it dense: a pose graph's information matrix is block-tridiagonal, so sparse Cholesky is O(n) and storage O(n). Full pose-graph smoothing of 1000 poses is milliseconds with a sparse solver. What actually blows the 100 ms budget is landmarks: say 100k points × 3 = 300k extra parameters, and every iteration re-linearizes every observation.

RegimeRe-linearized per iterationCost driverUse when
Full BAall KFs + landmarks#observations × iterationsoffline, small maps
Sliding window + marginalizationfixed W KFs + window landmarksW + dense prior fill-inonline VIO, bounded RAM
Pose graph over KFsKF poses only#KFs (O(n) for a chain)loop closure, large maps

Trade-off. Marginalization freezes the linearization point of the eliminated state, so the prior injects information that isn't there → overconfidence. First-Estimates Jacobian (FEJ) keeps the marginalized Jacobians at their first estimate. Full smoothing re-linearizes everything each iteration: more accurate, more expensive.

Failure modes and detection.

  • Overconfidence: NEES = eᵀ P⁻¹ e. For a state of dimension n, E[NEES] = n. If NEES sits consistently above n, outside the chi-square bounds for n DoF, the covariance is too small and you've over-marginalized.
  • Loop closure after marginalization: the eliminated states are gone, so a loop that would have corrected them can't. Two-tier fix: keep every keyframe in a map, optimize a local covisible window, and on loop closure run pose-graph optimization over the full keyframe graph. ORB-SLAM3 does exactly this (Atlas + local BA + full BA/pose graph).
  • Drift: consistently large loop-closure corrections mean the window is too small.

When not to marginalize. Short trajectory (<100 poses) or offline: full smoothing is simpler and more accurate. Pose-graph-only (no landmarks): full smoothing is already cheap. Big compute budget: widen the window.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design scheduling and overload behavior for SLAM.

Answer

Assumptions first. Mobile robot, 3D LiDAR at 10 Hz (100 ms period), IMU at 200 Hz, Jetson Orin, ROS 2 Humble, LIO-SAM/ORB-SLAM3-style stack. Soft real-time: a missed front-end deadline loses tracking, not life-safety. The design splits SLAM into a front-end that must hit the sensor period and a back-end that may lag.

Core answer. Give the front-end a dedicated thread with bounded queue depth and priority; run global optimization incrementally in a preemptible worker. On overload, shed back-end work first, then non-key frames, never IMU. Publish a degraded-quality flag so the planner knows the map is stale.

Budgets.

stageratebudgetoverrun action
acquisition10 Hz LiDAR / 200 Hz IMU5 msdrop oldest non-IMU
tracking10 Hz60 ms (60% of period)skip frame, coast on IMU
fusion200 Hz1 msdrop
windowed BA10 Hz20 mscut Ceres iterations 10→4
loop closureasync200 msdefer
map publish1 Hz10 mspublish last
downstream10 Hz20 msdrop

Mechanism. Keyframing bounds back-end cost because full bundle adjustment grows roughly O(N³) in node count, while iSAM2 re-eliminates only variables touched by the new factor, keeping per-update cost near O(1) amortized. A keyframe every 0.5 m or 5° of rotation caps nodes: at 1 m/s that is 2 keyframes/s, so a 10-minute run adds ~1200 nodes instead of 6000 frames. The watchdog runs in the back-end callback group and compares now - last_result_ts against 3× the expected solve time (600 ms here); on breach it cancels the optimizer via a Ceres iteration callback returning false, falls back to the last pose, and sets map_status = STALE. Priority isolation is concrete: a MutuallyExclusiveCallbackGroup for tracking on its own executor, or SCHED_FIFO priority 80 on the tracking thread versus 20 on the back-end, so a long solve cannot steal the core mid-frame.

Python
# ROS 2 Humble, rclpy
class SlamNode(Node):
    def __init__(self):
        super().__init__('slam')
        self.track_cb = MutuallyExclusiveCallbackGroup()
        self.be_cb = MutuallyExclusiveCallbackGroup()
        self.create_subscription(Image, '/cam', self.track, 1,
                                 callback_group=self.track_cb)
        self.last_be = self.get_clock().now()
        self.create_timer(0.1, self.watchdog, callback_group=self.be_cb)

    def watchdog(self):
        age = (self.get_clock().now() - self.last_be).nanoseconds / 1e9
        if age > 0.6:
            self.cancel_optimization()  # Ceres iteration callback returns false
            self.map_status = 'STALE'

Drop versus degrade. Drop non-key frames when angular rate is below 30°/s and queue depth exceeds 2: IMU and odometry bridge the gap and error grows slowly. Degrade instead (widen keyframe spacing to 1.5 m, cut Ceres iterations to 4) when angular rate exceeds 60°/s or tracked features fall below 100, because inter-frame motion then exceeds the tracker's search window and dropping loses tracking outright. IMU is never dropped; it is the only high-rate motion prior.

Failure modes.

failuremanifestationdetectioncost
optimizer stallpose freezes, drift growsheartbeat age > 600 msrelocalization needed
queue growthestimates lag sensor by secondsqueue depth, p99 latencystale commands to planner
GPU contentionfront-end misses 100 ms deadlinedropped-frame countertracking lost
thermal throttleCPU 2.0→1.2 GHz, deadlines missclock/frequency monitorsustained degradation
I/O stallmap save blocks executorwrite latencymissed frames

Recovery must not replay stale commands: after a stall, reinitialize from the last good pose and let the planner re-plan from current state.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design observability for perception and SLAM.

Answer

What a strong candidate says first

Observability for perception and SLAM exists to answer one question under pressure: which measurement, transform, or version made the robot do that? If you can't answer it from logs within one shift, the instrumentation failed, no matter how many signals you emit. So I'd build three tiers, not one flat list.

Tier 1: always-on scalars (1–10 Hz, ~1–5 KB/s per robot). These go to Prometheus via OpenTelemetry and are what pages you. Per sensor: message rate, age of newest sample, drop count, and the offset between header.stamp and local arrival time. Per transform: tf2 lookup failures per second and the depth of the chain from map to the sensor frame. Per stage: input queue depth, processing latency p50/p99, output rate.

Tier 2: per-keyframe structured records (MCAP via rosbag2). One record per keyframe, not per frame. A 30 Hz camera rig running at ~2 Hz keyframes is a 15x reduction for free. Each record carries the frame graph (which node published which transform, with authority), calibration/map/code/config/model versions as a single hash, tracking evidence (matched feature count, inlier ratio), state and covariance, factor residuals with robust kernel weights, and solver rank/iterations/latency.

Tier 3: a 60-second raw ring buffer. Full-rate images and point clouds stay in RAM and flush to disk only when a trigger fires (localization jump, solver divergence, operator e-stop). This is the flight-recorder pattern, and it's the only way the storage math works.

The arithmetic that forces this design. Six 1080p cameras at 30 Hz, ~200 KB per JPEG frame: 6 × 30 × 200 KB ≈ 36 MB/s ≈ 3.1 TB/day. A 64-beam LiDAR at 10 Hz, ~1.2 MB per scan, adds ~1 TB/day. Nobody retains that. Tier 1 at 5 KB/s is ~430 MB/day: cheap enough to keep 90 days. Tier 3 at 60 s of the same streams is ~2.9 GB per trigger, which you can afford to keep forever.

Trade-offs. The alternative to the ring buffer is logging everything at reduced fidelity: decimated images, downsampled clouds. Cheaper on disk, useless for the failure you actually care about: a 200 ms window where the transform went wrong. The alternative to per-keyframe records is per-frame records; finer resolution, 15x the volume, for a signal that changes at keyframe rate anyway. Pick the ring buffer when you need forensic replay; pick decimation when you need fleet-wide statistics and disk is the binding constraint.

Failure modes and how each is detected.

  • Time sync drift. Compare header.stamp to arrival time. If p99 offset exceeds ~5 ms, tf2 lookups start throwing extrapolation errors and every downstream residual is garbage. Alert on the offset, not the exception.
  • TF tree break. Count tf2::ExtrapolationException and tf2::LookupException per second. A sustained nonzero rate means a node died or a static transform was never published.
  • Sensor dropout. Age of newest sample > 2× nominal period. A 10 Hz LiDAR silent for 200 ms is a dropout, not jitter.
  • Calibration drift. Track p95 reprojection error per camera over days. A slow ramp is a loose mount; a step is a knock.
  • Solver divergence. Chi-square per DOF above the 99th percentile of the expected distribution, or Ceres repeatedly hitting max_num_iterations. Both mean the graph is inconsistent, usually from a bad association.
  • False loop closure. Log the inlier ratio and switchable-constraint weight for every accepted loop. A loop accepted at a low inlier ratio is the classic cause of a map that teleports.

The decision each tier drives. Tier 1 pages the on-call. Tier 2 tells them which stage. Tier 3 lets them replay it. If a signal doesn't move one of those three, cut it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Define a fair SLAM evaluation protocol.

Answer

The 90-second answer. A fair SLAM protocol holds constant everything that isn't the estimator under test, fixes the alignment and metric before you look at results, and reports the spread rather than a single mean. Concretely: freeze the sequences and their raw sensor streams, the calibration files, the preprocessing (rectification, time-sync policy), the code commit and config, the hardware, and the random seeds. Then declare how estimated and reference trajectories are aligned, because that choice moves the number more than most algorithm changes do. Then report ATE and relative drift as distributions over segments, plus failures and runtime.

Alignment is the first decision, and it's a trade-off.

alignmentDoF absorbeduse whenwrong when
SE(3)6 rigidmetric scale observable: stereo, RGB-D, IMU-aidedmonocular: it silently penalizes a scale error the system cannot fix
Sim(3)6 + scalemonocular, where scale is unobservablemetric sensors: it absorbs a real scale error you should be scoring
yaw + translationroll/pitchground vehicle, gravity-observable attitudehandheld or aerial: it hides genuine attitude drift

The deciding criterion: align only the degrees of freedom the sensor suite cannot observe. Anything observable gets scored, not absorbed by the alignment.

Metrics. ATE is the RMSE of position after alignment: one number, and sensitive to a single bad loop closure. RPE measures drift between poses at a fixed delta, which is what actually accumulates. KITTI reports translational and rotational error averaged over segment lengths of 100–800 m; top entries sit around 0.5–0.7% translational error. EuRoC VIO systems land near 0.05–0.15 m ATE. Those are typical published values, not thresholds: the point is to report the same metric the reference benchmark does, so numbers stay comparable.

Failure modes, and how you catch them.

  • Scale drift (monocular): ATE grows with trajectory length; detect by plotting error against distance.
  • False loop closure: one wrong constraint snaps the map; detect by checking ATE jumps between runs and inspecting the pose graph.
  • Degenerate geometry (corridor, tunnel): the estimator is under-constrained; detect by reporting per-segment error and flagging segments where the Hessian is near-singular.
  • Time-sync error: a few ms of IMU–camera offset biases velocity and drifts; detect by sweeping the offset and watching ATE.

Artefact: ATE arithmetic. If per-pose errors after alignment are 0.02, 0.03, 0.01, 0.04 m, then ATE = sqrt((0.0004 + 0.0009 + 0.0001 + 0.0016) / 4) = sqrt(0.00075) ≈ 0.027 m. Reporting the mean (0.025 m) instead hides that the worst pose is twice the best.

What to publish. Per-sequence ATE and RPE, the aligned trajectories, failure counts, and runtime/resources. Segment by environment and motion. Use independent ground truth: a motion-capture rig or survey-grade GNSS/INS, not the estimator's own map.

Curated: · Written: · Reviewed:

Difficulty: Medium