How Sua Geometry works

The complete mathematics of the measurement engine — from raw sensor samples to every number on the screen — with the formulas actually implemented and the original sources.

1. Overview

A phone contains three small MEMS sensors that matter here: a gyroscope (angular rate), an accelerometer (specific force, which at rest points opposite to gravity) and a magnetometer (the Earth's magnetic field plus local disturbances). None of them alone gives a good orientation: the gyroscope is smooth and fast but drifts when integrated; the accelerometer gives an absolute vertical but is noisy and confused by any linear acceleration; the magnetometer gives an absolute heading but is easily disturbed by metal and electronics.

Sua Geometry combines them with a complementary filter on unit quaternions that runs at the sensor rate (200 Hz), and then produces the output at a lower, user-selected rate (1–50 Hz) through a window mean — which acts as an anti-aliasing decimator — and a dynamic SLERP low-pass filter. All the displayed quantities (Euler angles, heading, plane angle, level) are computed from that filtered quaternion.

Sensors gyro · accel · mag Fusion sections 5–8 Window mean section 9 SLERP filter section 9 Measurements sections 10–13 Screen · CSV section 15 200 Hz 1–50 Hz Figure 1. Processing chain and the sections of this guide that describe each block.

2. Frames and conventions

Device frame B (Android convention): x points to the right of the screen, y to the top of the screen and z out of the screen, towards the user [18]. This frame does not change when the interface rotates, which is one reason the app is locked in portrait.

x y z x: right edge y: top edge of the screen z: out of the screen (towards you)
Figure 2. Device axes used by Android and by Sua Geometry.

Local frame W: East–North–Up (ENU), a local-level frame that is treated as inertial for these short measurements (the Earth's rotation, 15°/h, is below the noise of phone gyroscopes). A Hamilton unit quaternion q = (w, x, y, z) rotates vectors from the device into the world [1, 6]:

vW=q⊗vB⊗q*,q=(w,x,y,z)

Angles are handled internally in radians and converted to degrees only for display. Positive angles follow the right-hand rule unless a measurement explicitly says “clockwise”.

3. Representing attitude

A rotation by an angle θ about a unit axis ê is represented by the unit quaternion [1, 4]:

q=(cosθ2,𝐞^sinθ2),‖q‖=1

Composition of rotations is the Hamilton product, with scalar part w and vector part v:

p⊗q=(pwqw−𝐩v·𝐪v,pw𝐪v+qw𝐩v+𝐩v×𝐪v)

The equivalent rotation matrix, used here only to explain the formulas and to initialise the filter, is [2, 3]:

𝐑(q)=[1−2(y2+z2)2(xy−wz)2(xz+wy)2(xy+wz)1−2(x2+z2)2(yz−wx)2(xz−wy)2(yz+wx)1−2(x2+y2)]

Why quaternions? They have no singularities (Euler angles lose a degree of freedom at ±90° of pitch, the “gimbal lock”), they compose with 16 multiplications, they are renormalised with a single square root, and they interpolate naturally on the sphere (SLERP). q and −q represent the same rotation; the engine always chooses the sign that keeps consecutive quaternions in the same hemisphere. The continuous kinematics with body angular rate ω is [5, 6]:

q˙=12q⊗(0,𝛚)

Code: core/quaternion.hpp (product, rotation of vectors, exponential map, SLERP, conversion from a matrix by Shepperd's method [7]).

4. Sensor models

With R = R(q) (device → world), the measurements are modelled as [16, 17]:

𝐟B=𝐑T(𝐚W+g𝐳^)+𝐛a+𝐧a𝛚m=𝛚+𝐛g+𝐧g𝐦B=𝐑T𝐦W+𝐝+𝐧m

fB is the specific force: at rest it equals g times the world vertical expressed in the device, i.e. it points up (Android convention [19]). b are slowly varying biases, n white noise and d a magnetic disturbance (hard- and soft-iron effects, nearby metal). Android delivers TYPE_ACCELEROMETER, TYPE_GYROSCOPE and TYPE_MAGNETIC_FIELD already factory-calibrated and, for the gyroscope and magnetometer, with the system's own bias compensation [19, 20, 22]; Sua Geometry adds its own bias estimate at rest (section 8), the disturbance detection of section 7 and the level calibration of section 13.

The engine requests 200 Hz for the accelerometer and gyroscope (5 ms) and 100 Hz for the magnetometer through ASensorEventQueue_registerSensor [21]. 200 Hz is the highest rate that does not require the HIGH_SAMPLING_RATE_SENSORS permission on Android 12 and later. Each batch of events is sorted by timestamp before it is processed.

5. Gyroscope prediction

Between two gyroscope samples the angular rate is assumed constant, and the kinematics of section 3 is integrated exactly with the exponential map [6]:

qk=qk−1⊗[cos(‖𝛚‖Δt2),𝛚‖𝛚‖sin(‖𝛚‖Δt2)],𝛚=𝛚m−𝐛^

where b̂ is the estimated bias. For very small angles the series expansion cos(θ/2) ≈ 1 − θ²/8, sin(θ/2)/θ ≈ 1/2 − θ²/48 avoids dividing by zero. The quaternion is renormalised after each step. Intervals longer than 100 ms (a pause in the sensor stream) are not integrated.

Code: AttitudeFilter::onGyro, expRot.

6. Tilt correction (accelerometer)

The filter follows the structure proposed by Valenti, Dryanovski and Xiao [10], a member of the family of complementary filters on SO(3) of Mahony et al. [8] (see also the gradient-descent filter of Madgwick et al. [9]). The measured “up” direction is rotated into the world with the predicted orientation and compared with the true vertical ẑ:

𝐠p=q⊗𝐚^⊗q*,𝐧=𝐠p×𝐳^=(gy,−gx,0),θ=atan2(‖𝐧‖,gz)

The axis n is always horizontal, so this correction can never change the heading. A fraction α of the full correction is applied:

Δq=exp(αθ𝐧‖𝐧‖),q←Δq⊗q,α=Δtτaf(e),e=|‖𝐚‖−g|g

Applying the rotation of angle α·θ about n is exactly a SLERP between the identity and the full correction. The adaptive factor f(e) suppresses the correction when the magnitude of the measured force differs from g, i.e. when there is linear acceleration [10]:

f(e)={1e≤0.10.2−e0.10.1<e<0.20e≥0.2

τa = 1 s in normal operation and 0.05 s during the first 1.5 s, so the filter converges quickly when the app starts. The first accelerometer sample initialises the tilt directly.

Code: AttitudeFilter::onAccel.

7. Heading correction (magnetometer)

Only the rotation about the vertical is corrected, so a magnetic disturbance can never alter the tilt [10]. The measured field is rotated into the world and its horizontal component is turned towards magnetic north (+y of ENU):

𝐥=q⊗𝐦^⊗q*,h=atan2(lx,ly),Δq=(cosβh2,0,0,sinβh2),β=Δtτm

τm = 2 s. A magnetometer sample is rejected as disturbed when its magnitude differs by more than 12 % from a slowly adapting reference, when the angle between the field and the vertical (the magnetic dip) changes by more than 6°, or when |m| is outside 15–90 µT (the Earth's field is about 25–65 µT [24]). The references adapt with a 15 s time constant, so a new, stable environment is eventually accepted. When the compass is switched off, the heading is driven by the gyroscope alone: the tilt remains exact and the heading becomes relative.

Code: AttitudeFilter::onMag, correctYaw.

8. Gyroscope bias at rest

The phone is declared still when the corrected angular rate stays below 0.03 rad/s and the accelerometer barely changes for 0.5 s. While still, the raw gyroscope reading is averaged:

𝐛^←𝐛^+k(𝛚m−𝐛^),k=max(1n,Δtτb+Δt)

The weight max(1/n, Δt/(τb+Δt)) makes it a cumulative mean at first (fast and optimal for a constant bias) and an exponential mean with memory τb = 10 s afterwards. The estimate is limited to 0.1 rad/s. A residual bias β produces a steady tilt error of about β·τa, so this step matters: in the tests, a 0.2°/s bias that would cause a 0.2° tilt error is reduced to a few hundredths of a degree within seconds.

9. Output stage

9.1 Window mean

The output rate f = 1/T is chosen by the user (1, 3, 10, 25 or 50 Hz). Windows follow a fixed rhythm (the deadline advances by exactly T), so the output does not drift below its nominal rate. All the quaternions of a window are summed with their signs aligned and normalised — the chordal mean. For orientations that are close to each other it agrees to second order with the optimal quaternion average of Markley et al. [12], at O(1) cost and without storing samples. The same sum yields the angular dispersion σ of the window:

q‾=∑siqi‖∑siqi‖,si=sign⁡(⟨q1,qi⟩),σ2≈8(1−‖∑siqi‖N)

9.2 Noise reduction

For white noise, averaging N samples divides the standard deviation by √N. For the tilt, with accelerometer noise σa:

σx‾=σN,σθ≈σagN,N=fsf

Example: σa = 0.02 m/s² gives 0.12° per sample; at 3 Hz (N ≈ 67) the window mean reduces it to about 0.014°. At 50 Hz (N = 4) it is about 0.06°, which is why the lower rates are recommended for precise static measurements.

9.3 Anti-aliasing

Taking a single sample every T seconds would fold any vibration above f/2 into the output (aliasing). Averaging the N samples of the window first is a moving-average decimator — the first-order case of the cascaded integrator-comb filters of Hogenauer [14, 15] — whose frequency response at frequency ν is:

|H(ν)|=|sin(πνN/fs)Nsin(πν/fs)|
0.0 0.2 0.4 0.6 0.8 1.0 0 3 6 9 12 15 18 21 24 27 30 zeros at 3, 6, 9… Hz output band vibration frequency ν [Hz] (fs = 200 Hz, N = 67, output 3 Hz) |H(ν)|
Figure 3. Response of the window mean at 3 Hz. Vibrations at multiples of the output rate cancel exactly; the first side lobe is at −13 dB.

In the engine tests, a 0.5° vibration sampled at 3 Hz leaves 0.03° at 9 Hz, 0.07° at 10.5 Hz and 0.04° at 37 Hz in the output, instead of up to the full 0.5° that point sampling would show. The SLERP filter that follows attenuates it further.

9.4 Dynamic SLERP filter

Spherical linear interpolation, introduced for rotations by Shoemake [11], moves along the great arc between two unit quaternions:

slerp(a,b,t)=sin((1−t)Ω)sinΩa+sin(tΩ)sinΩb,cosΩ=⟨a,b⟩

A first-order low-pass filter on the rotation group is obtained by moving from the previous output towards the new window mean by a fraction α each period:

qn=slerp(qn−1,q‾n,αn),αn=max(1−e−T/τ,clamp(δ/T−1.5°/s12°/s−1.5°/s,0,1))

τ is the “Smoothing” setting (off, 0.5, 1, 3 or 10 s). The dynamic part avoids lag when the phone is moved: δ is the angle between the previous output and the new mean, and the thresholds are angular rates (1.5 °/s and 12 °/s), so the behaviour does not depend on the output rate. If the dispersion inside the window exceeds 3 °/s·T (the phone is moving within the window), the most recent sample replaces the mean, because the mean would lag by half a period.

Code: core/smoother.cpp.

10. Orientation outputs

Euler angles, intrinsic sequence Z-Y′-X″ (yaw ψ measured counter-clockwise from East, pitch θ, roll φ), device → ENU [2, 3]:

φ=atan2(2(wx+yz),1−2(x2+y2))θ=arcsin(2(wy−zx))ψ=atan2(2(wz+xy),1−2(y2+z2))

Near θ = ±90° yaw and roll are not individually defined (gimbal lock); the quaternion is always valid and is shown alongside.

Compass heading of the top edge of the phone, clockwise from magnetic north; when the phone is almost vertical (the top edge less than ~17° from vertical) the direction of the rear camera, −z, is used instead:

𝐯=q⊗𝐲^⊗q*,A=atan2(vx,vy)mod360°

The heading is magnetic. To obtain the geographic (true) heading add the local magnetic declination, which can be obtained from the NOAA calculator based on the World Magnetic Model [23, 24].

11. Angle in a plane

When “Set zero” is pressed, the current orientation is stored as qref. The relative rotation is decomposed into a twist about the device z axis (perpendicular to the screen) and a swing about an axis lying in the screen plane [13]:

qr=qref*⊗q,γ=−2atan2(zr,wr),s=2atan2(xr2+yr2,wr2+zr2)

γ is shown clockwise as seen from the screen, in [0°, 360°) and in (−180°, 180°]; s tells how far the phone has left the reference plane and should stay close to 0°. Because only the relative rotation matters, the measurement works on any surface — horizontal, inclined or vertical — and does not need the magnetometer. Over long periods it is limited by gyroscope drift; set the zero again for long sessions.

12. Level and plumb

The world vertical expressed in the device is the third row of R:

𝐮=q*⊗𝐳^⊗q=(2(xz−wy),2(yz+wx),1−2(x2+y2))

Flat (|uz| is the largest component): elevation of the right side (a), of the top edge (b) and total tilt:

a=arcsinux,b=arcsinuy,tilt=arccos|uz|

On an edge (portrait or landscape): clockwise deviation from the nearest multiple of 90° (a) and lean of the screen out of the vertical, i.e. plumb (b):

ϕ=atan2(ux,uy),a=−(ϕ−90°·round(ϕ/90°)),b=arcsinuz

The phone position is classified into six faces (screen up, screen down, two portrait and two landscape) by the largest component of u. The two linear levels show a (bottom tube) and b (side tube) on a compressed scale, so that hundredths of a degree and several degrees are visible on the same tube:

s(v)=v|v|+1°

13. Calibration and reference

13.1 Reversal calibration

Every phone has a small accelerometer offset and a mounting misalignment between the sensor and the case, often 0.2°–1°. On the same spot, turning the phone 180° (with the same side down) changes the sign of the surface inclination s but not of the instrument error o — the classic reversal method used with precision spirit levels:

m1=s+o,m2=−s+o⇒o=m1+m22,s=m1−m22
First reading m₁ = s + o Turned 180° m₂ = −s + o Figure 4. The surface error changes sign; the instrument error does not.

An offset (a, b) is stored for each of the six faces and saved on the phone. A reading is accepted only when the phone is still and σ < 0.05°.

13.2 User reference (differential level)

“Set reference” stores the calibrated reading (ar, br) and the face; while the phone stays on that face the level shows differences, and the total tilt is recomputed consistently:

ad=a−ar,bd=b−br,tilt=arccos1−sin2ad−sin2bd

The reference lives only in memory. The CSV record always contains both the differential and the absolute (calibrated) values.

14. Accuracy

The figures below are typical orders of magnitude for phone sensors; each device is different.

Error sourceEffectWhat reduces it
Accelerometer white noise≈ 0.1° per sampleWindow mean: ≈ 0.01–0.02° at 3 Hz; SLERP smoothing
Accelerometer offset and misalignment0.2°–1° on the levelReversal calibration (section 13)
Linear acceleration (moving the phone)Several degreesAdaptive gain; read the values when “Stable” is shown
Gyroscope biasTilt error β·τa; drift of the plane angleBias estimate at rest; reset the zero in long sessions
Magnetic disturbancesHeading errors of several degreesDisturbance detection; move away from metal; figure-8 calibration
Magnetic declinationMagnetic ≠ geographic northAdd the local declination [23]
Case and camera bumpThe phone does not rest on its true facesRemove the case; use the reference or the calibration

The status line shows “Stable ±σ” with the dispersion of the last window: it is the best indicator of when a reading can be trusted.

15. CSV record

The scope mode records one row per output sample in a text file with comma separators and a decimal point [25]. The first row holds the variable names (with units); each row starts with a UTC timestamp in ISO 8601 with milliseconds [26] and the time since the first row, measured with the sensor clock, which is monotonic and does not jump if the system clock is adjusted.

ColumnsMeaning
utc_time, t_s, sensor_time_sUTC timestamp, seconds since the first row, sensor clock [s]
qw, qx, qy, qzFiltered quaternion, device → ENU
yaw_deg, pitch_deg, roll_degEuler angles Z-Y′-X″ [°]
heading_degCompass heading from magnetic north [°]
plane_deg, plane_signed_deg, plane_swing_deg, plane_has_zeroAngle in the plane and its swing; 1 if a zero is set
level_face, level_flat, level_a_deg, level_b_deg, level_total_degFace (0–5), flat (1) or edge (0), level values (differential when a reference is active)
level_calibrated, cal_state, level_ref, level_a_abs_deg, level_b_abs_degCalibration and reference states; absolute calibrated level values
rms_deg, stillDispersion of the window [°]; 1 when the phone is still
mag_status, mag_disturbed, use_magMagnetometer accuracy reported by Android (−1 to 3), disturbance flag, compass on/off
gyro_hz, sensorsMeasured gyroscope rate [Hz]; bit mask of available sensors (1 accelerometer, 2 gyroscope, 4 magnetometer)

The file is written by the engine thread into the app cache and handed over once — saved with the system document picker or shared — and then deleted. The app keeps no history.

16. Implementation

Interface (Kotlin, Android SDK) shows the snapshot, preferences, save/share the CSV JNI bridge type conversion only Core (C++17, no Android) filter · window mean · SLERP · measurements · CSV format Android platform (C++) ALooper sensor thread ASensorEventQueue CSV recorder scope queue Figure 5. The core knows nothing about the interface; the interface performs no measurement operations.
  • A dedicated native thread with its own ALooper reads the sensor queue [21]; the interface never receives raw samples, it only reads a snapshot published at the output rate.
  • No memory is allocated in the sensor loop; all the mathematics is inline double-precision code. One update costs a few hundred floating-point operations.
  • The core (core/) does not depend on Android and is tested on a PC with synthetic data: noise, gyroscope bias, rotations, vibrations and magnetic disturbances (72 checks).
  • The engine is documented with Doxygen; this guide and the README describe how to add a new measurement.

Source code: https://github.com/carlosperezco/SuaGeometry. The formulas on this page are rendered with MathML [27].

17. References

Papers and books are cited by DOI where one exists; Android documentation by its official URL.

  1. Hamilton, W. R. (1844). On quaternions; or on a new system of imaginaries in algebra. Philosophical Magazine, Series 3, 25(163), 10–13. https://doi.org/10.1080/14786444408644923
  2. Shuster, M. D. (1993). A survey of attitude representations. The Journal of the Astronautical Sciences, 41(4), 439–517.
  3. Diebel, J. (2006). Representing Attitude: Euler Angles, Unit Quaternions, and Rotation Vectors. Technical report, Stanford University.
  4. Kuipers, J. B. (1999). Quaternions and Rotation Sequences. Princeton University Press.
  5. Markley, F. L., Crassidis, J. L. (2014). Fundamentals of Spacecraft Attitude Determination and Control. Springer. https://doi.org/10.1007/978-1-4939-0802-8
  6. Solà, J. (2017). Quaternion kinematics for the error-state Kalman filter. arXiv:1711.02508. https://arxiv.org/abs/1711.02508
  7. Shepperd, S. W. (1978). Quaternion from rotation matrix. Journal of Guidance and Control, 1(3), 223–224. https://doi.org/10.2514/3.55767b
  8. Mahony, R., Hamel, T., Pflimlin, J.-M. (2008). Nonlinear complementary filters on the special orthogonal group. IEEE Transactions on Automatic Control, 53(5), 1203–1218. https://doi.org/10.1109/TAC.2008.923738
  9. Madgwick, S. O. H., Harrison, A. J. L., Vaidyanathan, R. (2011). Estimation of IMU and MARG orientation using a gradient descent algorithm. IEEE International Conference on Rehabilitation Robotics (ICORR). https://doi.org/10.1109/ICORR.2011.5975346
  10. Valenti, R. G., Dryanovski, I., Xiao, J. (2015). Keeping a good attitude: a quaternion-based orientation filter for IMUs and MARGs. Sensors, 15(8), 19302–19330. https://doi.org/10.3390/s150819302
  11. Shoemake, K. (1985). Animating rotation with quaternion curves. ACM SIGGRAPH Computer Graphics, 19(3), 245–254. https://doi.org/10.1145/325165.325242
  12. Markley, F. L., Cheng, Y., Crassidis, J. L., Oshman, Y. (2007). Averaging quaternions. Journal of Guidance, Control, and Dynamics, 30(4), 1193–1197. https://doi.org/10.2514/1.28949
  13. Dobrowolski, P. (2015). Swing-twist decomposition in Clifford algebra. arXiv:1506.05481. https://arxiv.org/abs/1506.05481
  14. Hogenauer, E. B. (1981). An economical class of digital filters for decimation and interpolation. IEEE Transactions on Acoustics, Speech, and Signal Processing, 29(2), 155–162. https://doi.org/10.1109/TASSP.1981.1163535
  15. Oppenheim, A. V., Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson.
  16. Titterton, D. H., Weston, J. L. (2004). Strapdown Inertial Navigation Technology, 2nd ed. IET.
  17. Groves, P. D. (2013). Principles of GNSS, Inertial, and Multisensor Integrated Navigation Systems, 2nd ed. Artech House.
  18. Android Developers. Sensors overview (sensor coordinate system). https://developer.android.com/develop/sensors-and-location/sensors/sensors_overview
  19. Android Developers. Motion sensors. https://developer.android.com/develop/sensors-and-location/sensors/sensors_motion
  20. Android Developers. Position sensors. https://developer.android.com/develop/sensors-and-location/sensors/sensors_position
  21. Android NDK API reference. Sensor (<android/sensor.h>). https://developer.android.com/ndk/reference/group/sensor
  22. Android Open Source Project. Sensor types. https://source.android.com/docs/core/interaction/sensors/sensor-types
  23. NOAA NCEI. Magnetic field calculators (declination). https://www.ngdc.noaa.gov/geomag/calculators/magcalc.shtml
  24. NOAA NCEI / British Geological Survey. World Magnetic Model. https://www.ncei.noaa.gov/products/world-magnetic-model
  25. Shafranovich, Y. (2005). RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files. IETF. https://www.rfc-editor.org/rfc/rfc4180
  26. ISO 8601. Date and time format. https://www.iso.org/iso-8601-date-and-time-format.html
  27. W3C. MathML Core. https://www.w3.org/TR/mathml-core/