Calibration algorithms

This documentation was generated with the assistance of AI. Please report any inaccuracies.

The per-sensor pages (Accelerometer Calibration, Gyroscope Calibration, Magnetometer Calibration) list which calibrator class to use. This page explains how the calibrators work: the system of equations they build, how it is solved, how outliers are rejected and how the turntable-free method of Tedaldi et al. ([imu-tk]) is put together from the interval detectors, the measurement generators and the "Easy" calibrators.

All the derivations below start from the shared error model of IMU Calibration. For the accelerometer it reads

and the magnetometer uses the same form with in place of . Throughout this page is the bias (hard iron for the magnetometer) and is the matrix of scale-factor and cross-coupling errors, so is the full "gain" matrix of the sensor.

Linear least squares (known true signal)

The error model is linear in its parameters

When the true signal of every measurement is known (the KnownFrame and KnownBiasAndFrame families, for every sensor), the unknowns and enter the model linearly. Writing the entries of as (row , column ; the diagonal entries are the scale factors ) and moving the known term to the left gives, per measurement ,

Stack the three entries of and the nine of (column by column) into one parameter vector

Using the identity , every measurement contributes one 3-row block to the system:

With measurements the blocks are stacked into the design matrix ( ) and the observation vector ( ):

The library orders the unknowns with the diagonal first, as . That is only a column permutation of the vector above. In that ordering, and writing for the components of , the block of measurement is

The first row reads , which is just the first component of the matrix equation above.

Normal equations and the least-squares solution

The system is over-determined as soon as there are more rows than unknowns, so the noise prevents an exact solution. The calibrator looks for the that minimizes the sum of squared residuals:

KnownFrameAccelerometerLinearLeastSquaresCalibrator (and the equivalent gyroscope and magnetometer classes) builds and exactly as above and hands them to the least-squares solve of the algebra library, which returns the same minimizer as the normal equations without the need to form explicitly (squaring the matrix would square its condition number). The estimated and are then copied out of . Because the problem is linear no initial guess is needed and the solution is obtained in a single step.

For the KnownBias…​ variants the bias is moved to the left-hand side too ( ) and the first three columns of disappear, leaving only the entries of .

The common z-axis reduction

A general has nine entries. The "common z-axis" assumption (commonAxisUsed = true) declares that the z axis of the sensor frame coincides with the z axis of the orthogonal body frame and that the x-y plane contains the sensor’s y axis. This forces to be upper triangular:

so and only six entries remain. The parameter vector drops from twelve to nine unknowns (three biases plus six entries of ), the last three columns of every are removed, and the block becomes

with unknowns . This is the same triangular structure Tedaldi et al. impose on their accelerometer misalignment matrix (see The Tedaldi et al. method). In the Known…​Frame…​LinearLeastSquares classes the flag defaults to false, i.e. the general twelve-unknown case.

How many measurements are needed

Each measurement contributes three scalar equations, so the linear solvers need at least measurements for unknowns. The classes enforce the following minimums (MINIMUM_MEASUREMENTS):

Family (linear solver) Unknowns (general) Unknowns (common z-axis) Minimum measurements

Accelerometer / magnetometer KnownFrame: bias and M

12

9

4

Accelerometer / magnetometer with a known bias: only M

9

6

3

Gyroscope KnownFrame (b, M and G, 21 unknowns)

21

18

7

Gyroscope KnownBiasAndFrame (M and G, 18 unknowns)

18

15

6

The minimum is a single constant per class: it is the value needed by the general case. With the common z-axis flag the system is smaller, so the same measurements give more redundancy.

The gyroscope classes extend the model with the g-dependent term: the stacked equations become , so each block has the columns of multiplying followed by the nine columns of multiplying , for 21 unknowns in the general case.

Conditioning

The matrix is only invertible, and well conditioned, if the true signals are diverse. If every measurement is taken with the same (for instance the sensor always lying flat), the columns multiplying , and are constant multiples of the bias columns and the bias becomes indistinguishable from the scale factors. Good data therefore needs the sensor held static in many different attitudes, covering all three axes in both directions. Measurement noise is averaged out only if the number of measurements exceeds the minimum, so use more than the bare minimum whenever possible.

Non-linear least squares (known norm only)

Why the problem becomes non-linear

The KnownGravityNorm, KnownPosition, KnownMagneticFluxDensityNorm and KnownPositionAndInstant families do not know the direction of the true signal, only its magnitude: the device is held static in unknown attitudes, so the accelerometer must read a vector of length , and the magnetometer a vector of the local field magnitude. The linear system above cannot be written (the right-hand side is unknown) and the problem is solved with an iterative non-linear fit instead.

Reparametrization used by the solver

Inverting the model (with ) gives the true signal as a function of the measurement, and the solver internally optimizes the pair , where is the bias expressed before the gain matrix:

The code comments state that this form converges better than optimizing directly. After the fit the result is converted back: and . A user-supplied initial bias and matrix are converted the same way: .

Cost function and residual

Let be the known magnitude (the gravity norm, or the field magnitude from the WMM; for KnownPosition it is computed from the position with the gravity estimator and for KnownPositionAndInstant from the world magnetic model). The model prediction for measurement is the squared norm of the corrected measurement, and the observation is the squared known magnitude:

The Levenberg-Marquardt fitter minimizes the weighted chi-square

where is the standard deviation attached to the measurement (the StandardDeviationBodyKinematics specific-force deviation, or its magnetic counterpart). Working with squared norms avoids a square root and keeps the cost smooth around zero. With the prediction is , i.e. the measurements are fitted with an ellipsoid ( lies on the ellipsoid centered at the bias with shape ) that must map onto a sphere of radius once corrected. See Magnetometer Calibration for the same picture applied to hard and soft iron.

The prediction depends on only through , which has six degrees of freedom, so replacing by (and by ) for any rotation leaves the cost unchanged. The norm constraint alone cannot fix the orientation of the sensor frame. Restricting to the upper triangular form of the common z-axis case removes exactly that freedom, which is why the common-axis problem has nine unknowns, a unique minimum and is the better conditioned choice. In the general (twelve-unknown) case the solver converges to one of the equivalent solutions, selected by the initial guess.

Jacobian, damping and iteration

Levenberg-Marquardt linearizes the model around the current estimate, using the Jacobian , and solves a damped version of the Gauss-Newton step:

If the step lowers it is accepted and the damping is decreased (the iteration behaves like Gauss-Newton); otherwise it is rejected and is increased (the step shrinks toward gradient descent). The iteration stops when no longer changes appreciably.

In this library the fitter is LevenbergMarquardtMultiDimensionFitter of irurueta-numerical-computing. For the norm-based and "Easy" calibrators the Jacobian row of each measurement is not coded analytically: the model is wrapped in a GradientEstimator that obtains the partial derivatives numerically. The KnownFrame non-linear calibrators are the exception: their model is the linear one above, evaluated by a multivariate fitter that is given the analytical Jacobian (the entries of ), and therefore converges almost immediately.

After convergence the fitter exposes the covariance matrix of the estimate, , its degrees of freedom, the reduced , the mean squared error and the goodness-of-fit probabilities; the calibrators publish these as getEstimatedCovariance(), getEstimatedChiSq(), getEstimatedReducedChiSq(), getEstimatedMse(), getEstimatedP() and getEstimatedQ(). The covariance of is propagated to through the Jacobian of the conversion above.

Initial guess and convergence

LM only finds a local minimum, so the starting point matters. The calibrators take it from the caller (setInitialBias, setInitialMa, …​ or the constructor arguments); if nothing is given the starting point is and (an identity gain), which is a sensible default because real sensors are close to ideal. A better start is any approximate estimate, for example a previous calibration, the datasheet values, or the linear solution when a KnownFrame data set is available for the same sensor. When the common z-axis flag is set, the lower triangle of the initial gain matrix is forced to zero before inverting it. The solver then needs at least one more measurement than unknowns (the minimum is ), which gives:

Family Unknowns (general) Unknowns (common z-axis) Min. (general) Min. (common z-axis)

Accelerometer KnownGravityNorm, KnownPosition; magnetometer KnownMagneticFluxDensityNorm, KnownPositionAndInstant

12

9

13

10

Same with a known bias or hard iron (only M)

9

6

10

7

Poorly spread attitudes, a bad initial guess or an inconsistent known magnitude can make LM stall at a poor minimum; the covariance and reduced are the quantities to inspect. For data sets that may contain bad static intervals use the robust wrappers described next.

Robust estimation

Every non-trivial calibrator has five Robust…​ variants (see IMU Calibration for the family tree). They all follow the same pattern. A hypothesis is computed by running the plain calibrator on a small random subset of the measurements; the hypothesis is scored by how well it explains every measurement; the best hypothesis wins; optionally the winner is refined using all the measurements it classifies as inliers.

Residuals

The residual of measurement for a hypothesis ( , ) is the squared disagreement with the known magnitude, using the user-facing parameters:

For the KnownFrame families the residual instead compares the measurement predicted by the hypothesis from the known true signal, , with the actual one. Residuals are therefore in squared units of the signal (for example ), which is the unit of the threshold parameters below. If the hypothesis matrix cannot be inverted the residual is set to the largest representable value.

Methods

Method Sample selection and scoring Main parameters

RANSAC

Random subsets. A measurement is an inlier when its residual is below threshold. The hypothesis with the most inliers wins. The number of iterations adapts to the requested confidence and the inlier ratio seen so far.

threshold (default 1e-2), confidence (0.99), maxIterations (5000)

MSAC

Same random subsets, but the score is a truncated cost: every residual is clipped at threshold and the clipped residuals are summed (smaller is better). Inliers contribute their actual error instead of a flat vote, so among hypotheses with the same inlier count the tighter one wins.

Same as RANSAC

LMedS

Random subsets, scored by the median of all residuals (smaller is better). No inlier threshold is needed because the median is robust up to about half of outliers. The best median also yields the threshold used to classify inliers afterwards.

stopThreshold (1e-4): iteration stops early when the best median falls below it; confidence, maxIterations

PROSAC

Like RANSAC, but measurements are ordered by a quality score (larger is better) and subsets are drawn first from the best-ranked measurements, growing the pool progressively. Good measurements are found much sooner when scores are informative.

threshold, plus one quality score per measurement (QualityScoredAccelerometerCalibrator and the equivalents)

PROMedS

LMedS scoring with the PROSAC progressive sampling.

stopThreshold plus quality scores

The quality score of a measurement is any number you can attach to it (for example the inverse of its standard deviation, or the length of the static interval it came from); only the ordering matters.

Flow

flowchart TD A["Measurements"] --> B["Pick a random subset
(PROSAC and PROMedS: from the best-scored first)"] B --> C["Run the plain calibrator on the subset
to obtain a hypothesis b and M"] C --> D["Compute residual r of every measurement"] D --> E{"Method"} E -->|"RANSAC"| F["Score = number of residuals below threshold"] E -->|"MSAC"| G["Score = sum of residuals clipped at threshold"] E -->|"LMedS and PROMedS"| H["Score = median residual"] F --> I{"Better than the best so far?"} G --> I H --> I I -->|"yes"| J["Keep hypothesis, inliers and residuals"] I -->|"no"| K{"Stop?
(confidence reached, max iterations
or median below stop threshold)"} J --> K K -->|"no"| B K -->|"yes"| L{"refineResult?"} L -->|"yes (default)"| M["Recalibrate using only the inliers,
starting from the best hypothesis"] L -->|"no"| N["Use the best hypothesis"] M --> O["Estimated b, M and covariance"] N --> O

Practical notes

  • The subset size defaults to the minimum number of measurements the plain calibrator needs and can be raised (setPreliminarySubsetSize), which makes each hypothesis less noisy at the cost of a lower chance of a clean sample.

  • The refinement step (refineResult, true by default) runs the plain calibrator on the inliers only, starting from the best hypothesis, and falls back to the unrefined hypothesis if it fails. The covariance is kept by default (keepCovariance).

  • The inlier flags and per-measurement residuals can be retained (computeAndKeepInliers, computeAndKeepResiduals) and are always available when refinement is on.

  • RANSAC and MSAC are sensitive to the threshold; LMedS and PROMedS need none, which is convenient when the noise level is not known beforehand.

The Tedaldi et al. method

Tedaldi, Pretto and Menegatti ([imu-tk]) describe a procedure that needs no turntable or external reference: the operator holds the IMU still for an initial period, then moves it between a set of distinct static attitudes. The accelerometer triad is calibrated from the static attitudes alone, and the gyroscope triad is then calibrated by checking that integrating the angular rate between two static attitudes reproduces the change of the gravity direction measured by the already calibrated accelerometer. The library splits this into detection, measurement generation and calibration stages.

flowchart LR S["Raw samples
(BodyKinematics or TimedBodyKinematics)"] --> D["TriadStaticIntervalDetector
(AccelerationTriadStaticIntervalDetector)"] D -->|"static / dynamic status"| G["MeasurementsGenerator
(AccelerometerMeasurementsGenerator,
GyroscopeMeasurementsGenerator)"] G -->|"one StandardDeviationBodyKinematics
per static interval"| A["Accelerometer calibrators
KnownGravityNorm, KnownPosition"] G -->|"one BodyKinematicsSequence
per dynamic interval"| E["EasyGyroscopeCalibrator
KnownBiasEasyGyroscopeCalibrator"] A -->|"b and M of the accelerometer"| E E --> R["Gyroscope b, M and G"]

Static-interval detection

Detection works on the accelerometer stream. After an initial period during which the device must not move (initialStaticSamples, default 5000 samples), the detector measures the base noise level: the Euclidean norm of the per-axis standard deviations accumulated over that period. For every new sample it computes the same norm over a sliding window (windowSize, default 101 samples) and applies a simple test:

where is the base noise level and is thresholdFactor (default 2). The library therefore compares the norm of the windowed standard deviation with . This is the same idea as the detector of the paper, which instead compares the magnitude of the windowed variances with a multiple of the one measured in the initial period. The paper estimates the multiplier automatically inside its calibration loop; the library instead exposes it as a parameter, and the generator documentation recommends repeating the calibration with several threshold factors, because the gyroscope calibration is very sensitive to where intervals start and end. Two safeguards act during initialization: if the windowed noise suddenly exceeds the accumulated one by instantaneousNoiseLevelFactor (default 2), or the base level is above baseNoiseLevelAbsoluteThreshold, the detector fails and must be reset, because the initial period was not still.

Measurements for the accelerometer

While the detector reports a static interval, the accumulated average of the accelerometer samples is the single input measurement of that interval:

When the interval ends (a transition to dynamic), AccelerometerMeasurementsGenerator emits one StandardDeviationBodyKinematics whose specific force is that mean and whose standard deviation is the average of the three per-axis deviations. Intervals shorter than minStaticSamples (default two windows) are discarded as unreliable, and a dynamic interval longer than maxDynamicSamples (default 30 windows) is skipped. Averaging suppresses the noise, so the noise term can be dropped from the model, as the paper does.

Accelerometer cost (multi-position method)

In each static attitude the corrected measurement must have the magnitude of gravity. With the paper’s model (upper triangular misalignment , diagonal scaling , bias ) the cost over the static intervals is

with nine parameters (three misalignments, three scale factors, three biases), minimized with Levenberg-Marquardt. This is exactly the cost of the norm-based formulation above: plays the role of and the paper’s bias, expressed on the measured side, is the negative of the library’s ( ), and the upper-triangular common z-axis case has the same nine unknowns. In the library it is implemented by KnownGravityNormAccelerometerCalibrator (gravity norm given) or KnownPositionAccelerometerCalibrator (gravity norm computed from the position), fed with the generator’s measurements.

Gyroscope cost (integrated rotation vs. gravity direction)

The gyroscope calibration uses the dynamic intervals between consecutive static intervals. Let be the unit gravity direction measured by the calibrated accelerometer averaged in the -th static interval, and let be an attitude integrator that, given the angular-rate samples of the motion between intervals and and the starting direction , returns the predicted direction :

The integration advances a quaternion with the kinematics equation using a fourth-order Runge-Kutta step (the paper’s RK4n, followed by a re-normalization of the quaternion).

EasyGyroscopeCalibrator implements this cost as follows. Each sequence (one BodyKinematicsSequence: the mean specific force of the preceding static interval, the samples of the movement, and the mean specific force of the following static interval) is one observation:

  1. The two static means are corrected with the accelerometer bias and cross-coupling errors supplied by the user (that is why the calibrator is an AccelerometerDependentGyroscopeCalibrator) and normalized to unit vectors, so the result does not depend on the local gravity magnitude. The pair of directions is stored as the input row, and the target is zero.

  2. For the current parameter guess, every sample of the sequence is corrected with the gyroscope model, (the same reparametrization as before, with the g-dependent term when it is being estimated).

  3. The corrected angular rates are integrated with QuaternionIntegrator using the Runge-Kutta step to obtain the rotation over the sequence.

  4. The starting gravity direction is rotated by the inverse of that attitude change (the body frame turns while gravity is fixed) and compared with the measured end direction; the residual is the Euclidean distance between the two unit vectors.

The residual is weighted by the average angular-rate standard deviation of the sequence and minimized with Levenberg-Marquardt over , (and optionally ), using the numerically estimated gradient. Two differences from the paper are worth knowing: the library takes the gyroscope bias as an unknown of the fit (the paper averages the gyroscope in the initial still period and removes it), and it has a general (full) matrix option besides the upper-triangular common z-axis form, which is the default for EasyGyroscopeCalibrator. As with any one-scalar-residual-per-observation fit, the calibrator needs one more sequence than unknowns:

Configuration Unknowns Minimum sequences

Common z-axis, no g-dependent term

9

10

General, no g-dependent term

12

13

Common z-axis, with g-dependent term

18

19

General, with g-dependent term

21

22

Each sequence must also contain a few body kinematics items (the Javadoc asks for at least three).

Putting it together

  1. Keep the device still for the initial period (long enough for initialStaticSamples).

  2. Move it to a new attitude and hold it still, many times, producing alternating static and dynamic intervals.

  3. Feed every sample through an AccelerometerAndGyroscopeMeasurementsGenerator (or the individual accelerometer and gyroscope generators); collect the generated StandardDeviationBodyKinematics and BodyKinematicsSequence instances.

  4. Calibrate the accelerometer with KnownGravityNorm/KnownPosition using the first collection.

  5. Pass the estimated accelerometer bias and Ma plus the sequences to EasyGyroscopeCalibrator (or KnownBiasEasyGyroscopeCalibrator when the gyroscope bias is known), optionally wrapped by a robust variant.

See Static/Dynamic Interval Detection and Measurement Generation for the detector and generator classes in detail.

Class Reference

Class Javadoc Source

KnownFrameAccelerometerLinearLeastSquaresCalibrator

Javadoc

Source

KnownGravityNormAccelerometerCalibrator

Javadoc

Source

KnownPositionAccelerometerCalibrator

Javadoc

Source

RobustKnownGravityNormAccelerometerCalibrator

Javadoc

Source

TriadStaticIntervalDetector

Javadoc

Source

MeasurementsGenerator

Javadoc

Source

GyroscopeMeasurementsGenerator

Javadoc

Source

EasyGyroscopeCalibrator

Javadoc

Source

Where to go next