
Adaptive Early-Heading Estimator
Implementation-Ready iOS Engineering Design
Recommended v1: a minimal two-state yaw/gyro-bias EKF, with independently quality-gated observations from the magnetometer, GNSS course, pedestrian stride-direction estimation, and vehicle constraints. PCA should not be the primary initializer. Instead, it should be treated as a conditional and potentially bimodal travel-direction observation. Apple’s attitude solution can provide roll/pitch and coordinate transformation while AEHE maintains its own true-north travel-heading state and uncertainty.
Core Estimator
The estimator state consists of true-north travel heading plus vertical gyroscope bias. The gyroscope predicts heading changes, while accepted absolute or relative observations correct the estimate.
Primary Design Rule
Never convert weak motion into false certainty. Low excitation, unresolved phone-to-body alignment, magnetic interference, or poor GNSS geometry must increase uncertainty rather than produce an artificially precise heading.
Key Qualification
A claim such as “reliable heading within 1–3 meters” should be treated as an engineering target rather than a universal guarantee. Activation should depend on measured information quality rather than distance alone.
Apple distinguishes heading, which describes device orientation, from course, which describes movement direction independently of device orientation. Core Location supplies course when sufficient location information exists. AEHE therefore avoids assuming a universal fixed distance before GNSS course becomes usable.
1. Evidence Review and Required Qualifications
| Draft Premise | Assessment | Engineering Treatment |
|---|---|---|
| GNSS course needs several to approximately 10 meters | Qualify. A universal distance threshold should not be assumed. | Gate course using validity, course accuracy, speed, displacement-to-uncertainty ratio, freshness, and consistency. |
| GNSS course becomes unreliable at low speed | Supported in principle. | Increase GNSS course uncertainty as speed approaches zero. |
| PCA can determine direction from 1–3 meters | Not reliable as a universal claim. | Use PCA only after excitation and carrying-mode checks and preserve the 180° ambiguity until independently resolved. |
| Magnetic residual filtering can improve heading accuracy | Supported under appropriate conditions. | Use residual and anomaly gating rather than assuming a fixed improvement percentage. |
| Device heading equals travel heading | False except under alignment constraints. | Maintain separate device and travel frames. |
| Visual augmentation can help | Supported as an optional extension. | Use ARKit or visual-inertial methods only as optional sources. |
2. Coordinate Frames and Conventions
2.1 Frames
- Device frame D: iPhone sensor coordinates.
- Core Motion local-level frame L: use
.xArbitraryZVertical, with the vertical axis gravity-aligned. - Navigation frame N: East-North-Up, or ENU.
- Travel frame T: forward axis tangent to pedestrian or vehicle motion.
Define heading ψ clockwise from true north:
The corresponding unit travel vector in ENU coordinates is:
Normalize angular quantities to the interval [−π, π):
2.2 Transforming Motion Data
Let CLD rotate device-frame vectors into the Core Motion local-level frame.
aL = CLDaD
ωL = CLDωD
The vertical angular rate used for yaw propagation is:
CMDeviceMotion supplies attitude, rotation rate, gravity, user acceleration, and calibrated magnetic-field information. Use userAcceleration, transform it into the local-level frame, convert to SI units where required, and retain the horizontal components for motion-direction processing.
2.3 True Versus Magnetic North
CLLocation.courserepresents direction of travel relative to true north when valid.CLHeading.trueHeadingcan provide true-north device orientation when sufficient location information is available.- An independently calculated magnetic heading should apply an appropriate geomagnetic declination model.
3. AEHE Estimator
3.1 State Vector
Use a minimal two-state Kalman filter:
where ψ is the estimated travel heading and bg is the vertical gyroscope bias.
A full three-axis magnetometer-bias state is not recommended for the v1 main filter because it may be poorly observable during short, weakly excited starts. Magnetic bias and anomaly estimation can instead operate as a separate subsystem.
3.2 Gyroscope Propagation
The predicted heading is:
ψk−
=
wrap[
ψk−1+
+
(ωU,k − bg,k−1+)Δt
]
The gyroscope-bias prediction is:
bg,k−
=
bg,k−1+
The state-transition Jacobian is:
Fk =
| 1 | −Δt |
| 0 | 1 |
A practical discrete process-noise covariance is:
Qk =
| σω2Δt2 + (1/3)qbΔt3 | −(1/2)qbΔt2 |
| −(1/2)qbΔt2 | qbΔt |
Covariance propagation is:
Pk−
=
Fk
Pk−1+
FkT
+
Qk
Increase process noise when the phone is being repositioned, carrying mode is uncertain, or pedestrian turn dynamics invalidate the current phone-to-body relationship.
3.3 Generic Heading Measurement Update
Every accepted heading source supplies an observation zi and measurement variance Ri.
The circular innovation is:
The observation matrix is:
The innovation covariance is:
Si
=
HP−HT
+
Ri
The normalized innovation squared is:
NISi
=
ri2 / Si
Reject an observation when its NIS exceeds the source-specific gate. For a scalar observation, useful initial chi-square gates are approximately 6.63 at 99% and 10.83 at 99.9%.
The Kalman gain is:
K = P−HTS−1
The state update is:
x+ = x− + Kr
Use the numerically stable Joseph covariance update:
P+
=
(I − KH)P−(I − KH)T
+
KRKT
After every update, symmetrize P, enforce a small positive eigenvalue floor, and wrap ψ.
4. Observation Sources
4.1 Magnetometer and Magnetic-Anomaly Handling
Compute the expected geomagnetic field from an appropriate geomagnetic model when a sufficiently accurate location is available. The model represents the Earth’s main magnetic field rather than local disturbances from buildings, vehicles, electronics, or nearby ferromagnetic structures.
For calibrated magnetic-field vector mD, calculate a normalized field-magnitude residual:
eF
=
| ||mD|| − FWMM |
/
FWMM
The inclination residual is:
eI
=
wrap(Imeasured − IWMM)
The anomaly detector should combine:
- field-magnitude residual;
- inclination residual;
- heading innovation NIS;
- Core Motion magnetic calibration accuracy;
- temporal magnetic-field derivative.
suspect if magnitude_bad OR inclination_bad OR NIS > gate
enter INTERFERED after:
0.3–0.8 s persistent suspicion
exit INTERFERED only after:
1.5–3.0 s clean magnetic data
AND low turn rate
AND consistent heading
- CLEAN: normal magnetometer measurement variance.
- SUSPECT: inflate magnetometer variance by approximately 10–100×.
- INTERFERED: reject absolute magnetic updates.
- RECOVERY: begin with large measurement variance and reduce it over several accepted observations rather than snapping the heading.
4.2 Pedestrian Inertial Travel Direction
For a stride-aligned window of horizontal acceleration samples:
ai
=
[ax,i, ay,i]T
Compute the sample mean:
ā
=
(1/n)
Σi=1n
ai
Then compute the horizontal acceleration covariance:
Ca
=
[1/(n − 1)]
Σi=1n
(ai − ā)
(ai − ā)T
Let λ1 ≥ λ2 be the eigenvalues and v1 the principal eigenvector. Define directional anisotropy:
A
=
(λ1 − λ2)
/
(λ1 + λ2 + ε)
The principal axis produces two possible travel directions separated by 180°. Resolve the ambiguity using the following hierarchy:
- Accepted GNSS displacement or course.
- Previous high-confidence travel heading.
- Route-edge direction when one candidate is overwhelmingly more plausible.
- Pocket stride or gyroscope phase heuristic.
- Otherwise retain both hypotheses and do not issue a single-heading EKF update.
A practical adaptive inertial-direction variance is:
Rinertial
=
σmin2
+
kA(1 − A)2
+
ke/E
+
kt|Δψwindow|
where excitation energy is:
E
=
Σi=1n
||ai − ā||2
Reject PCA-derived direction during stationary periods, phone repositioning, turns, irregular stair motion, elevator or escalator motion, low-excitation carrying, or vehicle operation. PCA estimates an acceleration-pattern axis; it does not universally measure the travel vector.
4.3 Vehicle Observation Model
For a fixed dashboard or console mount, define the device-to-travel heading offset δDT:
ψT
=
wrap(ψD + δDT)
Estimate the mount offset only during sustained, accepted GNSS course with low yaw rate. Freeze the estimate during turns, reversing, phone handling, or GNSS degradation.
4.4 GNSS Course Activation and Handoff
For two accepted position fixes p1 and p2, define displacement:
d = ||p2 − p1||
Define a displacement-to-position-uncertainty ratio:
ρd
=
d / √(h12 + h22)
A conservative position-derived bearing uncertainty approximation is:
σψ,pos
≈
atan2(
√(h12 + h22),
d
)
Candidate GNSS heading variance is:
RGNSS
=
max(
σfloor2,
σcourse2,
σψ,pos2
)
Accept GNSS course only when:
- the location timestamp is fresh;
- course and course accuracy are valid;
- speed exceeds the mode-specific threshold and is materially above speed uncertainty;
- the displacement-to-noise ratio exceeds its threshold;
- multiple consecutive course observations are mutually consistent;
- the course passes the filter innovation gate;
- there is no immediate reverse or U-turn conflict.
After approximately three to five accepted GNSS observations, transition to GNSS_LOCKED and gradually reduce the influence of early-heading sources. Do not directly overwrite the filter state with GNSS course.
5. Confidence and Guidance Interface
Extract heading standard deviation directly from the filter covariance:
σψ = √Pψψ
An interpretable confidence score is the estimated Gaussian probability that heading error lies within ±20°:
C20
=
2Φ(20° / σψ) − 1
struct HeadingEstimate {
let trueHeadingDegrees: Double
let sigmaDegrees: Double
let probabilityWithin20Degrees: Double
let dominantSource: Source
let anomalyFlags: Set<QualityFlag>
let mode: TravelMode
let isTravelDirectionObservable: Bool
}
| Confidence Band | Entry Condition | Exit Hysteresis | Guidance Behavior |
|---|---|---|---|
| Low | C20 < 0.50 | Remain until > 0.60 | Wide or faded cone; avoid aggressive wrong-way rerouting. |
| Medium | 0.50–0.80 | Approximately ±0.08 | Normal route display with cautious initial-turn behavior. |
| High | C20 > 0.80 | Fall only below 0.70 | Full heading arrow and normal rerouting behavior. |
Confidence should be calibrated using held-out ground-truth data. Predictions can be grouped by claimed probability and compared with the empirical frequency at which actual heading error remains within ±20°. If covariance is systematically overconfident, an empirical calibration layer such as isotonic or logistic calibration can be applied.
6. iOS Architecture
6.1 Sensor Configuration
motion.deviceMotionUpdateInterval = 1.0 / 50.0
motion.startDeviceMotionUpdates(
using: .xArbitraryZVertical,
to: motionQueue,
withHandler: ingestMotion
)
location.delegate = coordinator
location.desiredAccuracy = kCLLocationAccuracyBestForNavigation
location.distanceFilter = kCLDistanceFilterNone
location.activityType =
mode == .vehicle
? .automotiveNavigation
: .fitness
location.startUpdatingLocation()
location.startUpdatingHeading()
Check available Core Motion attitude reference frames before selecting one. Configure Core Location accuracy, activity type, heading updates, automatic pausing, and background behavior according to the navigation mode.
6.2 Timestamp Synchronization
- Convert Core Motion and Core Location timestamps into a common session-monotonic timeline.
- Maintain approximately three to five seconds of ring-buffer history.
- Interpolate attitude to the timestamp of each acceleration or magnetic sample.
- For GNSS, use the measurement timestamp rather than callback-arrival time.
- Reject stale fixes, time reversals, and samples predating the active navigation session.
6.3 Concurrency
- Use one serial
SensorIngestQueue. - Use one serial
EstimatorQueue. - Do not mutate filter state from other queues.
- Publish UI estimates at approximately 5–10 Hz on the main actor.
- Use a separate bounded logging queue.
- Drop nonessential debug records rather than blocking sensor processing.
6.4 Permissions and Graceful Degradation
The implementation should explicitly check motion and location availability and authorization before starting the estimator. If a required source becomes unavailable, AEHE should increase uncertainty and continue with the remaining qualified sources rather than preserving stale confidence.
- If motion data is unavailable, disable inertial propagation and pedestrian motion-direction estimation.
- If location permission is unavailable, disable GNSS course and true-north corrections that depend on location.
- If heading data is unavailable or magnetically corrupted, continue with gyroscope propagation and other qualified observations.
- If the application is suspended and high-rate motion updates are interrupted, reinitialize timing and increase covariance when execution resumes.
6.5 Third-Party App Versus Apple Maps Integration
A third-party iOS application can implement AEHE inside its own navigation engine and user interface. Public iOS APIs do not provide a mechanism for a third-party application to replace Apple Maps’ internal heading estimator, navigation arrow, rerouting logic, or first-turn guidance. Direct integration into Apple Maps would require Apple-internal implementation.
7. Swift-Like Pipeline Pseudocode
7.1 Estimator Startup
func start(mode: Mode) {
state = .starting
filter = EKF(
psi: initialHeadingCandidate(),
bias: 0.0,
covariance: Matrix2x2(
rad(90.0) * rad(90.0), 0.0,
0.0, rad(2.0) * rad(2.0)
)
)
motionBuffer.removeAll()
locationBuffer.removeAll()
motion.deviceMotionUpdateInterval = 1.0 / 50.0
motion.startDeviceMotionUpdates(
using: .xArbitraryZVertical,
to: motionQueue
) { [weak self] deviceMotion, error in
guard let self = self,
let deviceMotion = deviceMotion,
error == nil
else {
return
}
self.onMotion(deviceMotion)
}
startLocation(mode: mode)
}
7.2 Motion Processing
func onMotion(_ dm: CMDeviceMotion) {
let t = clock.motionTime(dm.timestamp)
let rotation =
transforms.deviceToLocal(
attitude: dm.attitude
)
let accelerationDevice = Vector3(
dm.userAcceleration.x,
dm.userAcceleration.y,
dm.userAcceleration.z
)
let rotationRateDevice = Vector3(
dm.rotationRate.x,
dm.rotationRate.y,
dm.rotationRate.z
)
let accelerationLocal =
rotation * accelerationDevice * g0
let rotationRateLocal =
rotation * rotationRateDevice
let horizontalAcceleration = Vector2(
accelerationLocal.x,
accelerationLocal.y
)
let omegaU = rotationRateLocal.z
estimatorQueue.async {
let dt =
max(
0.001,
min(
0.1,
t - self.lastIMUTime
)
)
self.lastIMUTime = t
self.filter.predict(
omegaU: omegaU,
dt: dt,
processNoise:
self.adaptiveProcessNoise()
)
self.motionBuffer.append(
MotionSample(
time: t,
horizontalAcceleration:
horizontalAcceleration,
verticalAngularRate: omegaU,
attitude: dm.attitude,
magneticField:
dm.magneticField
)
)
self.carryingMode.update(
self.motionBuffer
)
self.processMagnetometer(dm)
if self.mode == .pedestrian {
self.processPedestrianDirection()
}
self.publishEstimate()
}
}
7.3 GNSS Processing
func onLocation(_ location: CLLocation) {
let t =
clock.locationTime(
location.timestamp
)
estimatorQueue.async {
guard self.isFresh(t),
location.horizontalAccuracy >= 0.0
else {
return
}
self.locationBuffer.append(location)
let result =
self.gnssGate.evaluate(
location: location,
history: self.locationBuffer,
predictedHeading:
self.filter.heading,
predictedVariance:
self.filter.headingVariance,
mode: self.mode
)
if result.accepted {
self.filter.updateHeading(
measurement:
radians(location.course),
variance:
result.variance,
nisGate:
self.chiSquare999
)
self.acceptedGNSSCount += 1
} else {
self.acceptedGNSSCount =
max(
0,
self.acceptedGNSSCount - 1
)
}
self.updateStateMachine()
self.publishEstimate()
}
}
7.4 Heading Measurement Update
func updateHeading(
measurement z: Double,
variance R: Double,
nisGate: Double
) {
let residual =
wrapAngle(
z - state.heading
)
let innovationVariance =
covariance.m00 + R
guard innovationVariance > 0.0
else {
return
}
let nis =
(residual * residual)
/ innovationVariance
guard nis <= nisGate
else {
return
}
let kHeading =
covariance.m00
/ innovationVariance
let kBias =
covariance.m10
/ innovationVariance
state.heading =
wrapAngle(
state.heading
+ kHeading * residual
)
state.gyroBias +=
kBias * residual
let K = Vector2(
kHeading,
kBias
)
let H = RowVector2(
1.0,
0.0
)
let identity =
Matrix2x2.identity
let correction =
identity - outer(K, H)
covariance =
correction
* covariance
* correction.transposed()
+ outer(K, K) * R
covariance =
makePositiveDefinite(
symmetrize(covariance)
)
}
7.5 Angle Wrapping
func wrapAngle(_ angle: Double) -> Double {
var value = angle
while value >= Double.pi {
value -= 2.0 * Double.pi
}
while value < -Double.pi {
value += 2.0 * Double.pi
}
return value
}
7.6 PCA Direction Extraction
func pcaDirection(
samples: [Vector2]
) -> PCAObservation? {
guard samples.count >= minimumSamples
else {
return nil
}
let excitation =
rmsMagnitude(samples)
guard excitation > excitationMinimum
else {
return nil
}
let mean =
vectorMean(samples)
let centered =
samples.map {
$0 - mean
}
let covariance =
covarianceMatrix(centered)
let decomposition =
eigenDecomposition(covariance)
let lambda1 =
decomposition.maximumEigenvalue
let lambda2 =
decomposition.minimumEigenvalue
let principalVector =
decomposition.maximumEigenvector
let denominator =
lambda1
+ lambda2
+ epsilon
guard denominator > 0.0
else {
return nil
}
let anisotropy =
(lambda1 - lambda2)
/ denominator
guard anisotropy > anisotropyMinimum
else {
return nil
}
let firstDirection =
atan2(
principalVector.x,
principalVector.y
)
let oppositeDirection =
wrapAngle(
firstDirection
+ Double.pi
)
let candidates = [
firstDirection,
oppositeDirection
]
return resolveDirectionSign(
candidates: candidates,
gnssHistory: locationBuffer,
priorHeading: filter.heading,
priorVariance:
filter.headingVariance,
routeGeometry: routeGeometry
)
}
7.7 Magnetic Anomaly Gate
func evaluateMagneticField(
measuredMagnitude: Double,
expectedMagnitude: Double,
measuredInclination: Double,
expectedInclination: Double,
headingResidual: Double,
headingInnovationVariance: Double
) -> MagneticQuality {
guard expectedMagnitude > 0.0,
headingInnovationVariance > 0.0
else {
return .interfered
}
let magnitudeResidual =
abs(
measuredMagnitude
- expectedMagnitude
)
/ expectedMagnitude
let inclinationResidual =
abs(
wrapAngle(
measuredInclination
- expectedInclination
)
)
let nis =
headingResidual
* headingResidual
/ headingInnovationVariance
let magnitudeBad =
magnitudeResidual
> magneticMagnitudeThreshold
let inclinationBad =
inclinationResidual
> magneticInclinationThreshold
let innovationBad =
nis > magneticNISGate
if magnitudeBad
|| inclinationBad
|| innovationBad {
return .suspect
}
return .clean
}
7.8 GNSS Course Gate
func evaluateGNSSCourse(
current: CLLocation,
previous: CLLocation?,
mode: TravelMode
) -> GNSSCourseResult {
guard current.course >= 0.0,
current.courseAccuracy >= 0.0,
current.speed >= 0.0
else {
return .rejected
}
let minimumSpeed =
mode == .vehicle
? vehicleMinimumCourseSpeed
: pedestrianMinimumCourseSpeed
guard current.speed >= minimumSpeed
else {
return .rejected
}
guard let previous = previous
else {
return .rejected
}
let displacement =
current.distance(
from: previous
)
let combinedAccuracy =
sqrt(
previous.horizontalAccuracy
* previous.horizontalAccuracy
+
current.horizontalAccuracy
* current.horizontalAccuracy
)
guard combinedAccuracy > 0.0
else {
return .rejected
}
let displacementRatio =
displacement
/ combinedAccuracy
guard displacementRatio
>= minimumDisplacementRatio
else {
return .rejected
}
let positionBearingSigma =
atan2(
combinedAccuracy,
max(displacement, 0.01)
)
let reportedCourseSigma =
radians(
current.courseAccuracy
)
let variance =
max(
minimumGNSSVariance,
reportedCourseSigma
* reportedCourseSigma,
positionBearingSigma
* positionBearingSigma
)
return GNSSCourseResult(
accepted: true,
variance: variance
)
}
7.9 State Machine
STARTING
|
v
EXCITING
|
v
FUSING
|
v
GNSS_LOCKED
|
v
LOW_POWER
Any active state
|
v
DEGRADED
when observations, permissions,
or sensor quality become insufficient.
GNSS_LOCKED
|
v
FUSING
when GNSS course quality fails
for N consecutive fixes.
8. Starting Tuning Values
Important: these values are prototype starting points rather than universal constants.
| Parameter | Pedestrian Start | Vehicle Start |
|---|---|---|
| Device motion | 50 Hz; test 100 Hz offline | 50 Hz |
| Filter publication | 10 Hz | 10–20 Hz |
| PCA window | 1.5–3 s or approximately two strides | Disabled |
| PCA anisotropy A | 0.35–0.60 | — |
| Minimum horizontal RMS excitation | 0.10–0.25 m/s² | Vehicle-specific |
| Heading process noise | 0.5–2°/√s | 0.2–1°/√s |
| Bias random walk | 0.01–0.10°/s/√s | Same initial range; tune per device |
| Magnetic magnitude deviation | Suspect at 15–25% | 10–20% near mount |
| Inclination deviation | 10–20° | 8–15° |
| GNSS speed gate | 0.7–1.2 m/s | 1.5–2.5 m/s |
| Displacement/noise ratio ρd | 2.5–3.5 | 3–4 |
| Course accuracy | Initially ≤25–35° | ≤15–25° |
| Consistent fixes | 2–3 | 3 |
| GNSS lock | 3–5 accepted observations | 3–5 accepted observations |
| GNSS unlock | 2–3 rejected observations | 3–5 rejected observations |
Estimate actual gyroscope noise and bias using stationary recordings and Allan-deviation analysis for each iPhone model. Tune process and measurement covariance using held-out routes rather than optimizing directly against the final evaluation set.
9. Test Harness and Evaluation
9.1 Logging Schema
Record the following information for every test session:
- session-monotonic timestamp;
- original API timestamp;
- raw and transformed acceleration;
- raw and transformed gyroscope data;
- attitude quaternion or rotation matrix;
- magnetic vector and calibration state;
- geomagnetic-model expectation;
- location, course, speed, and associated accuracy values;
- carrying mode;
- magnetic anomaly scores;
- candidate observations and rejection reasons;
- EKF state and covariance;
- confidence score;
- state-machine state;
- CPU utilization;
- thermal state;
- battery level.
Use an append-only binary log with CSV or Parquet export. Build an offline replay engine that executes the same estimator code using deterministic timestamps and externally configurable tuning parameters.
9.2 Ground Truth
Preferred ground-truth methods, in descending order of accuracy, are:
- Survey-grade dual-antenna GNSS/INS for vehicle testing.
- ARKit/VIO combined with surveyed landmarks for short pedestrian sequences.
- Precisely marked paths with synchronized overhead video.
- Human-labelled travel direction only for coarse wrong-way scoring.
9.3 Controlled Test Scenarios
- building exits;
- metal doors and structural steel;
- parking structures;
- urban canyons;
- open-sky suburban environments;
- rural environments;
- stationary navigation starts;
- phone rotation without translation;
- handheld walking;
- pocket walking;
- swinging-hand walking;
- running;
- stairs;
- elevators;
- escalators;
- dashboard-mounted vehicle starts;
- vehicle reversing;
- immediate turns after route start;
- immediate U-turns;
- phone handling while the vehicle is moving.
9.4 Primary Metrics
- Circular heading RMSE over the first 5, 10, and 20 meters.
- Time to sustained heading error below 15°.
- Distance to sustained heading error below 15°.
- Time to sustained heading error below 20°.
- Distance to sustained heading error below 20°.
- Correct forward hemisphere within the first 2, 5, and 10 meters.
- Wrong-initial-direction rate.
- Confidence reliability.
- Expected calibration error.
- Magnetic false-reject rate.
- Magnetic false-accept rate.
- CPU utilization.
- Energy consumption.
- Memory consumption.
- Thermal impact.
9.5 Ablation Tests
Run the same test corpus with individual AEHE components disabled to quantify their contribution:
- magnetic anomaly detection removed;
- pedestrian inertial direction removed;
- adaptive measurement covariance replaced with fixed covariance;
- carrying-mode logic removed;
- GNSS consistency gating removed;
- confidence-aware guidance removed;
- route prior removed, if implemented;
- visual augmentation removed, if implemented.
9.6 Comparison With Existing Navigation Applications
A comparison with Apple Maps or Google Maps can measure externally observable behavior such as displayed-arrow error, initial-direction correctness, and first-instruction outcomes using synchronized screen recordings and repeated matched starts.
Such comparisons should not claim to identify the internal algorithms used by those applications because their internal sensor-fusion implementations are not publicly observable.
10. Failure-Safe Behavior
| Condition | Detection | Safe Fallback |
|---|---|---|
| Stationary user or phone-only rotation | No meaningful displacement or translational excitation | Mark travel direction unobservable rather than treating device heading as travel heading. |
| Immediate U-turn | Large integrated yaw combined with changing path | Suspend PCA and GNSS stability counting, propagate gyroscope heading, and widen covariance. |
| GNSS multipath or urban canyon | Poor accuracy, inconsistent course, or repeated innovation rejection | Reject GNSS course and retain gyroscope plus qualified absolute references. |
| Strong magnetic corruption | Persistent field-magnitude, inclination, or innovation failures | Reject magnetic updates until another absolute source or a clean magnetic interval appears. |
| Steady low-motion walking | Weak stride excitation | Suppress PCA and wait for stronger motion or GNSS evidence. |
| Running | Higher cadence and acceleration amplitude | Use running-specific stride windows and increase process noise during rapid turns. |
| Pocket-to-hand transition | Acceleration and orientation discontinuity | Inflate process noise, freeze questionable observations, and reclassify carrying mode. |
| Stairs | Strong vertical acceleration and altered gait pattern | Reduce or suppress PCA direction confidence until normal horizontal gait resumes. |
| Elevator or escalator | Vertical-motion pattern with insufficient horizontal displacement | Suppress travel-heading observations. |
| Vehicle reversing | Course approximately opposite mount-forward direction | Represent reverse travel separately rather than corrupting mount alignment. |
| Phone handled while driving | Mount-attitude discontinuity | Invalidate mount alignment and rely on qualified GNSS course. |
| Permission or sensor loss | Authorization or availability callback | Publish degraded status with increased uncertainty and never preserve stale high confidence. |
| Sensor dropout | Unexpected timestamp gap or missing callback sequence | Increase covariance according to elapsed time and revalidate observations after recovery. |
| Reference-frame restart | Motion-session interruption or reinitialization | Reinitialize the local-frame anchor and covariance without introducing a hidden yaw jump. |
11. Optional Extensions
11.1 Route and Map Priors
The planned route can provide a useful directional prior, particularly when the user is near a path or road segment with only a small number of plausible travel directions.
However, route geometry should be treated as a probabilistic prior rather than a hard heading correction. A route prior must not overpower contradictory high-quality sensor evidence.
For example, if a route segment permits headings of approximately 40° and 220°, the route engine can help resolve a PCA-generated 180° ambiguity without pretending that the route itself proves which direction the user is facing.
11.2 ARKit and Visual-Inertial Odometry
ARKit can provide short-term relative translation and rotation through visual-inertial tracking. This can be valuable during the exact interval in which GNSS course is still weak.
Visual augmentation should remain optional because it introduces additional constraints:
- camera permission;
- privacy considerations;
- lighting dependence;
- motion blur;
- scene-texture requirements;
- additional CPU and GPU load;
- additional battery consumption.
When ARKit reports degraded tracking quality, its observations should be down-weighted or rejected in the same manner as other uncertain sources.
11.3 Learned Carrying-Mode Classification
A lightweight on-device classifier could distinguish broad carrying modes such as:
- aligned handheld;
- swinging hand;
- pocket;
- bag or loosely carried device;
- fixed vehicle mount;
- phone being actively repositioned.
The initial implementation should avoid an unnecessarily large classification taxonomy. The primary purpose of carrying-mode classification is to determine which heading observations are physically meaningful.
11.4 User-Specific Adaptation
AEHE can gradually learn user-specific characteristics locally on the device, including:
- typical walking cadence;
- stride acceleration patterns;
- common phone orientation;
- typical handheld offset;
- gyroscope-bias stability;
- confidence calibration.
User adaptation should modify uncertainty and source weighting rather than silently overriding physically measured observations.
11.5 External GNSS and CarPlay
External positioning sources should be treated as independent observations with their own:
- timestamps;
- latency characteristics;
- accuracy estimates;
- coordinate frames;
- lever-arm assumptions;
- source provenance.
AEHE should not assume that an external GNSS source has the same timing or uncertainty characteristics as the iPhone’s internal Core Location solution.
12. Concrete V1 Build Sequence
- Implement coordinate transforms. Establish device, local-level, navigation, and travel frames and verify them with unit tests.
- Implement timestamp synchronization. Convert Core Motion and Core Location observations into a common session timeline.
- Implement deterministic logging and replay. Ensure recorded sessions can be replayed through exactly the same estimator code.
- Implement the two-state yaw/gyro-bias filter. Include circular innovations, covariance propagation, Joseph covariance updates, and numerical-stability checks.
- Add GNSS course gating. Use speed, course accuracy, horizontal accuracy, displacement-to-noise ratio, consistency, and innovation testing.
- Add smooth GNSS handoff. Transition toward GNSS dominance only after repeated accepted observations.
- Add magnetic anomaly detection. Combine field magnitude, inclination, temporal consistency, and innovation statistics.
- Add hysteretic magnetic recovery. Prevent heading jumps when magnetic observations become usable again.
- Add explicit handheld and fixed-vehicle-mount alignment.
- Add pedestrian step detection.
- Add two-hypothesis PCA or RMPCA direction estimation. Preserve the 180° ambiguity until another source resolves it.
- Add carrying-mode classification. Begin with a small number of physically meaningful modes.
- Add confidence calculation. Derive uncertainty from filter covariance and source-quality indicators.
- Add confidence-aware navigation behavior. Modify heading-arrow presentation, first-turn behavior, and rerouting aggressiveness according to confidence.
- Run controlled replay tuning.
- Run blinded real-world field evaluation.
- Only after the baseline system is calibrated, evaluate route priors, ARKit, learned models, and user-specific adaptation.
13. Recommended AEHE V1 Architecture
Estimator
Use a two-state heading and gyroscope-bias Kalman filter:
x = [ ψ, bg ]T
Prediction Source
Use the gravity-aligned vertical gyroscope rate as the continuous short-term heading propagation source.
Observation Priority
- Qualified GNSS course when speed, accuracy, displacement, consistency, and innovation tests pass.
- Qualified magnetometer heading when magnetic anomaly tests pass.
- Pedestrian inertial direction when stride excitation, anisotropy, carrying mode, and 180° ambiguity resolution are sufficient.
- Vehicle mount alignment when the phone is known to be fixed relative to the vehicle.
- Optional route or visual-inertial observations when independently qualified.
State Machine
STARTING
|
v
EXCITING
|
v
FUSING
|
v
GNSS_LOCKED
|
v
LOW_POWER
+----------------+
| |
v |
DEGRADED -----------+
DEGRADED is entered whenever
the available observations are
insufficient to justify the
current confidence level.
Confidence Interface
The navigation engine should receive more than a single heading angle. The AEHE output should include:
- true-north travel heading;
- heading standard deviation;
- probability that heading error is within a defined angular tolerance;
- dominant observation source;
- magnetic anomaly status;
- GNSS course status;
- carrying or mount mode;
- whether travel direction is currently observable.
Pedestrian Mode
Pedestrian mode should emphasize:
- step and stride detection;
- carrying-mode classification;
- conditional PCA or RMPCA direction estimation;
- explicit handling of the 180° ambiguity;
- rapid rejection of phone-repositioning events;
- conservative GNSS activation at walking speeds.
Vehicle Mode
Vehicle mode should emphasize:
- stable mount-angle estimation;
- GNSS course as the eventual dominant absolute travel-direction source;
- vehicle-specific speed thresholds;
- reversing detection;
- phone-handling detection;
- suppression of pedestrian PCA logic.
14. Practical Interpretation of the “Micro-Movement Amplification” Concept
The original intuition behind AEHE is that very small movements contain directional information before conventional navigation systems appear willing to trust a course estimate.
The correct implementation is not to geometrically multiply a one-meter GNSS displacement and pretend that it represents a longer baseline.
Instead, AEHE performs statistical amplification.
Multiple weak observations are accumulated and evaluated according to their information content:
- gyroscope measurements constrain short-term heading change;
- stride acceleration can reveal a dominant motion axis;
- magnetic measurements can provide absolute orientation when the field is clean;
- GNSS displacement gradually constrains absolute travel direction;
- route geometry can reduce ambiguity without becoming a hard measurement;
- confidence increases only when independent evidence becomes mutually consistent.
In this formulation, a small movement is useful not because its geometry has been artificially enlarged, but because multiple sensor observations collected during that movement jointly reduce uncertainty.
15. Final Engineering Principle
The recommended AEHE v1 should promise earlier, better-calibrated travel-heading estimation when the available evidence supports it, rather than guaranteeing a reliable heading after a particular distance.
The central engineering principle is that the system must be capable of refusing false certainty.
Gyroscope propagation provides short-term continuity. Magnetic observations provide absolute information only when environmental consistency tests pass. Pedestrian inertial direction contributes only when motion contains sufficient directional structure. Vehicle alignment contributes only when the phone-to-vehicle relationship is observable. GNSS course becomes dominant only after its measured quality supports that transition.
The most important improvement is therefore not simply extracting directional information a few meters earlier. It is combining early directional evidence with an explicit, calibrated representation of uncertainty so that the navigation engine knows when to trust the heading—and when not to.
That distinction turns the original “amplify micro-movements” idea into a practical sensor-fusion architecture: extract every defensible piece of directional information available during the first seconds of motion, quantify how trustworthy each piece is, reject corrupted evidence, and allow confidence to rise only as the observations become mutually consistent.