Magnetometer Calibration

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

The com.irurueta.navigation.inertial.calibration.magnetometer package (79 classes) estimates the magnetometer’s hard iron bias and soft iron scale-factor/cross-coupling matrix . Its structure closely mirrors the accelerometer package: 6 distinct algorithms, differing in how the ground-truth field is obtained and whether hard iron is already known, each wrapped by the same 5 robust-estimator variants (see robust estimation).

Hard-iron and soft-iron model

A magnetometer does not read the Earth’s field directly. Two families of disturbance, both fixed to the device body, distort it:

  • Hard iron is a permanent offset added to every reading, produced by magnetized parts (speaker magnets, battery leads, ferromagnetic screws) that rotate with the sensor. It is a constant vector in body axes.

  • Soft iron is the response of non-permanently-magnetized ferromagnetic material (and of the sensor’s own axis gains and misalignments) to the ambient field. It reshapes the field linearly, so it is a matrix.

With the Earth’s field resolved in body axes and white noise (the same form of error model as in the data model):

The diagonal terms are scale-factor errors and the off-diagonal terms are cross-couplings. The calibrators estimate and ; a fixer (see Fixers: Undoing the Sensor Error Model) later inverts the model to recover the true field:

The magnetic flux density is expressed in teslas (T) throughout the code; the Earth’s field is roughly 25 to 65 microteslas depending on location.

Families at a glance

All numbers below were checked against the MINIMUM_MEASUREMENTS* constants and the unknown counts in the source.

Family How is obtained Solves for Min. measurements

KnownFrame

Directly: the full frame (position, orientation) and the date are known at each measurement, so the WMM gives the true field in NED and it is rotated into body axes.

+ (12 unknowns, or 9 with common z-axis)

4 (linear and non-linear)

KnownHardIronAndFrame

Same as above

Only (hard iron given; 9 unknowns, or 6 with common z-axis)

3 (linear and non-linear)

KnownMagneticFluxDensityNorm

Indirectly: only the magnitude of the Earth’s field is known, at several unknown orientations.

+ (12 unknowns, or 9 with common z-axis)

13 (10 with common z-axis)

KnownHardIronMagneticFluxDensityNorm

Same as above

Only (9 unknowns, or 6 with common z-axis)

10 (7 with common z-axis)

KnownPositionAndInstant

Indirectly: measurement position and date known; the field magnitude is computed from the WMM instead of being given directly.

+ (12 unknowns, or 9 with common z-axis)

13 (10 with common z-axis)

KnownHardIronPositionAndInstant

Same as above

Only (9 unknowns, or 6 with common z-axis)

10 (7 with common z-axis)

For the norm-based and position-based families the minimum is the number of unknowns plus one (MINIMUM_MEASUREMENTS_GENERAL and MINIMUM_MEASUREMENTS_COMMON_Z_AXIS); isReady() is false until at least that many measurements are present. For the frame families the constant is fixed (4 and 3) because every measurement contributes three equations; the linear-system counting argument is in linear least squares. The common z-axis flag defaults to true (DEFAULT_USE_COMMON_Z_AXIS) in the norm-based and position-and-instant families (including their robust variants), and to false in the frame-based families. It restricts to an upper-triangular matrix (the lower off-diagonal terms are forced to zero). The norm constraint is invariant to a rotation of the sensor frame, so in the general (full 3x3) mode of the norm-based families, still available with setCommonAxisUsed(false), the estimated is defined only up to a rotation and its covariance is singular in those directions; the upper-triangular default is the observable model. Code that relied on the previous default (false) now needs 10 / 7 measurements instead of 13 / 10 and obtains an upper-triangular matrix.

Javadoc and source links for every class used in the examples below are collected in the Class Reference table at the end of this page.

The ellipsoid view of norm-based calibration

When the frame is unknown, the direction of is lost, but its length is not: the Earth’s field has the same magnitude at a given place and time no matter how the device is turned. Rotating the device through many orientations therefore makes the true field sweep out a sphere of radius , and the measured readings sweep out the image of that sphere under the affine map of the error model. An affine image of a sphere is an ellipsoid:

  • The ellipsoid’s centre is the hard iron . Without disturbance the readings would be centred at the origin.

  • Its semi-axes are times the singular values of , and its orientation is given by the left singular vectors. Scale-factor errors stretch the axes; cross-couplings tilt them.

  • Calibration is the search for the offset and the matrix that turn the measured ellipsoid back into a sphere centred at the origin.

Two-dimensional cross-section: measured readings lie on an offset

The picture is the geometric reading of the cost used by the solver, described in non-linear least squares (the same rotation ambiguity discussed there applies: the norm constraint alone cannot determine the sensor-frame orientation, and the common z-axis form removes it).

KnownHardIronMagneticFluxDensityNorm: soft iron only

Here the hard iron is given, so the ellipsoid centre is known and only the shape matrix is estimated. The implementation optimizes the full matrix (9 parameters; 6 for the upper-triangular common z-axis form), initialized from with the initial soft iron (the setInitialMm value). For each measurement it predicts the squared norm of the corrected vector and compares it to the squared known magnitude:

is the standard deviation of the squared norm. Each StandardDeviationBodyMagneticFluxDensity carries the standard deviation of the field itself, and for a squared norm of magnitude the calibrator hands the fitter ( alone gave a chi-square and covariance that were off by a factor of about ). The squared-norm residual is kept unchanged. The solver is Levenberg-Marquardt (LevenbergMarquardtMultiDimensionFitter), and the Jacobian is not analytical: each evaluation obtains the gradient of with respect to the parameters with GradientEstimator, i.e. by numerical differences. After the fit the code subtracts the identity, so getEstimatedMm() returns and not , and the fit covariance is kept unchanged because only a constant is subtracted. For the common z-axis case the covariance is additionally mapped into the nine-parameter general layout with a constant selection matrix.

KnownMagneticFluxDensityNorm: hard iron and soft iron

When the hard iron is unknown too, the solver works with the reparametrization , so that the centre is . The twelve parameters are the entries of and (nine with the common z-axis form), the prediction is

and after the fit the code converts back with and , propagating the covariance through the Jacobian of that conversion. The initial hard iron and soft iron seed the search ( ); also here the gradient is numerical. See non-linear least squares for the damping and iteration details shared with the accelerometer.

Linear and non-linear variants as implemented

  • The norm-based and position-and-instant families exist only as non-linear (Levenberg-Marquardt) calibrators. There is no closed-form linear ellipsoid fit in the package: because the unknowns enter the cost through the inverse , the constraint is not linear in them.

  • The frame-based families offer both variants. The linear one stacks three equations per measurement into a system that is linear in and (rows of the form with known) and solves it directly; the non-linear one minimizes the same residual iteratively and, unlike the norm-based solvers, supplies an analytical Jacobian.

  • Robust wrappers (RANSAC, LMedS, MSAC, PROSAC, PROMedS) fit the inner non-linear calibrator on random subsets (default subset size equals the minimum of the configured model: 7 for hard-iron-known and 10 for hard-iron-unknown with the default common z-axis, 10 and 13 in the general mode) and score every measurement with the non-squared norm discrepancy , which is not identical to the squared-norm cost minimized by the inner solver. DEFAULT_THRESHOLD of the RANSAC wrapper is 1e-9. See robust estimation.

The WMM-based families

KnownFrame* and KnownHardIronAndFrame* use the WMM to get the full true field vector; the KnownPositionAndInstant and KnownHardIronPositionAndInstant families use it only to get the field magnitude. In both cases the reference comes from WMMEarthMagneticFluxDensityEstimator of the wmm package, which returns an NEDMagneticFluxDensity in teslas.

Family Reference computed as

KnownFrame, KnownHardIronAndFrame

For each measurement: convert the ECEF frame to NED to obtain latitude, longitude, height and the body attitude, evaluate the WMM at that position and the measurement’s own year to get , then rotate it into body axes with the inverse of the frame’s body-to-NED rotation, giving the vector used in the linear equations or the non-linear residual.

KnownPositionAndInstant, KnownHardIronPositionAndInstant

Once, in onBeforeCalibrate() (so every calibrate() call recomputes it): evaluate the WMM at the configured NEDPosition (latitude, longitude, height) and decimal year, and keep only the Euclidean norm of the NED vector as the ground-truth magnitude . The direction is never used, so no attitude is needed.

Practical points verified in the source:

  • The instant is stored as a decimal year. setTime(…​) accepts epoch milliseconds, a Date or a GregorianCalendar, and setYear(…​) takes the decimal year directly. If nothing is set it defaults to the time at which the calibrator was constructed.

  • isReady() for these families additionally requires a position and a year; without an explicit WorldMagneticModel the default coefficient file is loaded, and an I/O failure surfaces as a CalibrationException.

  • Measurements must be taken at that one position within a short time span, so the field can be treated as constant.

  • The WMM describes the main (core) field only. Crustal anomalies, nearby structures and the device’s own electronics change the magnitude actually present, so a norm taken from the model is a reference, not exact truth; where a locally measured magnitude is available, use the KnownMagneticFluxDensityNorm families with that value instead.

flowchart TD A["Magnetometer readings"] --> B{"Is the body frame known?"} B -->|"Yes"| C["KnownFrame / KnownHardIronAndFrame: WMM vector rotated into body axes"] B -->|"No"| D{"Where does the field magnitude come from?"} D -->|"A given value B"| E["KnownMagneticFluxDensityNorm / KnownHardIronMagneticFluxDensityNorm"] D -->|"Position and date"| F["KnownPositionAndInstant / KnownHardIronPositionAndInstant: WMM norm"] C --> G["Linear or Levenberg-Marquardt fit"] E --> H["Ellipsoid-to-sphere Levenberg-Marquardt fit"] F --> H

Example: KnownFrameMagnetometerLinearLeastSquaresCalibrator

Each measurement pairs a raw magnetometer reading with the full frame (position, velocity, orientation) at which it was taken, so the true field can be derived directly from the WMM without any non-linear solving:

// Each measurement pairs a raw body magnetic flux density reading with the
// known frame (position/velocity/orientation) at which it was taken.
final List<FrameBodyMagneticFluxDensity> measurements = new ArrayList<>();
for (int i = 0; i < numMeasurements; i++) {
    final NEDFrame frame = ...; // known position, velocity and orientation
    final BodyMagneticFluxDensity measuredB = ...; // raw magnetometer reading
    measurements.add(new FrameBodyMagneticFluxDensity(measuredB, frame));
}

final var calibrator = new KnownFrameMagnetometerLinearLeastSquaresCalibrator(
        measurements, true); // assume common z-axis

calibrator.calibrate();

final double[] estimatedHardIron = calibrator.getEstimatedHardIron();
final Matrix estimatedMm = calibrator.getEstimatedMm();

KnownFrameMagnetometerNonLinearLeastSquaresCalibrator exposes the same constructors and getters, using Levenberg-Marquardt instead of a closed-form solution.

Two family pairs share a common abstract base — KnownHardIronMagneticFluxDensityNorm and KnownHardIronPositionAndInstant both extend BaseKnownHardIronMagneticFluxDensityNormMagnetometerCalibrator; KnownMagneticFluxDensityNorm and KnownPositionAndInstant both extend BaseMagneticFluxDensityNormMagnetometerCalibrator — since they differ only in where the field norm comes from (a direct value vs. a WMM lookup from position/date), not in the fitting algorithm itself. The four norm-based and position-based families are Levenberg-Marquardt non-linear solvers only; the two frame-based families offer both a linear least-squares and a non-linear variant, exactly as in the accelerometer package.

Example: KnownHardIronMagneticFluxDensityNormMagnetometerCalibrator

Here only the field magnitude is known (e.g. a local reference value), the device is held static at several unknown orientations, and the hard iron is already known — so only is solved for:

// Measurements taken at a single unknown position/instant, each with the
// magnetometer's standard deviation.
final List<StandardDeviationBodyMagneticFluxDensity> measurements = new ArrayList<>();
for (int i = 0; i < numMeasurements; i++) {
    final BodyMagneticFluxDensity measuredB = ...; // raw magnetometer reading
    measurements.add(new StandardDeviationBodyMagneticFluxDensity(measuredB, noiseStd));
}

final double groundTruthNorm = ...; // known Earth field magnitude, in Teslas
final double[] knownHardIron = ...; // already-known hard iron, length 3

final var calibrator = new KnownHardIronMagneticFluxDensityNormMagnetometerCalibrator(
        groundTruthNorm, measurements, false, knownHardIron);

calibrator.calibrate();

final Matrix estimatedMm = calibrator.getEstimatedMm();

KnownHardIronPositionAndInstant and the "hard iron unknown" siblings (KnownMagneticFluxDensityNorm, KnownPositionAndInstant) follow the same shape, adding getEstimatedHardIron()/getEstimatedHardIronAsMatrix() getters when the hard iron is solved for too.

Example: KnownPositionAndInstantMagnetometerCalibrator

This family only needs a known geodetic position and timestamp; only the field magnitude is derived internally via the WMM (the direction is not used, see The WMM-based families):

final NEDPosition position = new NEDPosition(latitude, longitude, height);
final Date timestamp = ...; // instant at which measurements were taken

final List<StandardDeviationBodyMagneticFluxDensity> measurements = new ArrayList<>();
for (int i = 0; i < numMeasurements; i++) {
    final BodyMagneticFluxDensity measuredB = ...; // raw magnetometer reading
    measurements.add(new StandardDeviationBodyMagneticFluxDensity(measuredB, noiseStd));
}

// initialHardIron/initialMm seed the Levenberg-Marquardt search since both are unknown.
final Matrix initialHardIron = ...;
final Matrix initialMm = ...;
final var calibrator = new KnownPositionAndInstantMagnetometerCalibrator(
        position, measurements, false, initialHardIron, initialMm);
calibrator.setTime(timestamp);

calibrator.calibrate();

final Matrix estimatedHardIron = calibrator.getEstimatedHardIronAsMatrix();
final Matrix estimatedMm = calibrator.getEstimatedMm();

Supporting interfaces

Class group Purpose

MagnetometerCalibrator, MagnetometerNonLinearCalibrator, MagnetometerCalibratorMeasurementType

Root marker interfaces / enum implemented by every calibrator.

KnownHardIronMagnetometerCalibrator

Mixin exposing known hard-iron getters/setters — implemented by the 3 "hard iron known" families.

UnknownHardIronMagnetometerCalibrator, UnknownHardIronNonLinearMagnetometerCalibrator

Mixin exposing estimated hard-iron getters — implemented by the 3 "hard iron unknown" families.

QualityScoredMagnetometerCalibrator

Interface required by measurement collections used with PROSAC/PROMedS robust variants.

OrderedStandardDeviationBodyMagneticFluxDensityMagnetometerCalibrator, OrderedStandardDeviationFrameBodyMagneticFluxDensityMagnetometerCalibrator

Interfaces for calibrators needing an ordered measurement list (RANSAC/PROSAC-style robust variants).

UnorderedFrameBodyMagneticFluxDensityMagnetometerCalibrator, UnorderedStandardDeviationBodyMagneticFluxDensityMagnetometerCalibrator, UnorderedStandardDeviationFrameBodyMagneticFluxDensityMagnetometerCalibrator

Interfaces for calibrators taking a plain, unordered measurement collection.

Example: a RANSAC robust wrapper

Robust variants take the same measurement/hard-iron/initial-soft-iron arguments as their plain counterpart, plus an inlier threshold (setThreshold(…​), or DEFAULT_THRESHOLD if left unset) used to decide whether a candidate solution’s residual for a given measurement is small enough to count as an inlier:

final Matrix knownHardIron = ...; // already-known hard iron, as a 3x1 matrix
final Matrix initialMm = ...; // initial soft-iron guess seeding the LM search

final var calibrator = new RANSACRobustKnownHardIronMagneticFluxDensityNormMagnetometerCalibrator(
        groundTruthNorm, measurements, false, knownHardIron, initialMm);
calibrator.setThreshold(1e-9); // residual threshold to accept a measurement as an inlier

calibrator.calibrate();

final Matrix estimatedMm = calibrator.getEstimatedMm();

MSACRobust*, LMedSRobust*, PROSACRobust* and PROMedSRobust* mirror this shape for the same family; PROSACRobust*/PROMedSRobust* additionally require measurements implementing QualityScoredMagnetometerCalibrator to supply per-sample quality scores.

Class Reference

Javadoc and source links for the classes used in the examples above:

Class Javadoc Source

com.irurueta.navigation.inertial.calibration.magnetometer (79 classes)

Javadoc

Source

KnownFrameMagnetometerLinearLeastSquaresCalibrator

Javadoc

Source

KnownFrameMagnetometerNonLinearLeastSquaresCalibrator

Javadoc

Source

KnownHardIronMagneticFluxDensityNormMagnetometerCalibrator

Javadoc

Source

KnownPositionAndInstantMagnetometerCalibrator

Javadoc

Source

RANSACRobustKnownHardIronMagneticFluxDensityNormMagnetometerCalibrator

Javadoc

Source

BodyMagneticFluxDensity

Javadoc

Source

FrameBodyMagneticFluxDensity

Javadoc

Source

StandardDeviationBodyMagneticFluxDensity

Javadoc

Source

Where to go next