Skip to content

Colota - Android GPS Location tracker

fix(trips): smooth altitude over a time window before summing elevation (#591)

Max Dietrich56cafd06d353
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index dcdec646..31c14aea 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -370,7 +370,7 @@ Supporting utilities in `mapUtils.ts`:
| `logger` | Environment-aware logging - suppresses debug/info console output in production via `__DEV__`, always logs warn/error to console. All levels are always captured in a ring buffer (2000 entries) for the Logging screen |
| `geo` | Haversine distance, speed/distance/duration/time formatting with configurable unit system (metric/imperial) and time format (12h/24h), auto-detected from locale on first use |
| `exportConverters` | Export-format metadata (labels, icons, extensions, MIME types) for the export UI. Serialization itself is native - see `ExportConverters.kt` |
-| `trips` | Trip segmentation via time-gap detection (15-min threshold), dropping segments whose bounding box spans under 100 m so stationary heartbeat runs do not become trips, plus distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment. Manual `trip_boundary_overrides` take priority over the gap threshold, and a segment abutting a forced split is exempt from the 100 m filter so an explicit edit is never silently dropped. `getDailyStats` in `DatabaseHelper.kt` mirrors all of this for the calendar and summary |
+| `trips` | Trip segmentation via time-gap detection (15-min threshold), dropping segments whose bounding box spans under 100 m so stationary heartbeat runs do not become trips, plus distance computation, trip stats (avg speed, elevation gain/loss), and trip color assignment. Elevation is smoothed over a time window before accumulating, since raw altitude swings between fixes overstate the climb. Manual `trip_boundary_overrides` take priority over the gap threshold, and a segment abutting a forced split is exempt from the 100 m filter so an explicit edit is never silently dropped. `getDailyStats` in `DatabaseHelper.kt` mirrors all of this for the calendar and summary |
| `queueStatus` | Maps sync queue size to color indicators for the dashboard |
| `settingsValidation` | URL validation and security checks for endpoint configuration |
diff --git a/apps/mobile/src/utils/__tests__/trips.test.ts b/apps/mobile/src/utils/__tests__/trips.test.ts
index 641ba9e3..feea186d 100644
--- a/apps/mobile/src/utils/__tests__/trips.test.ts
+++ b/apps/mobile/src/utils/__tests__/trips.test.ts
@@ -522,16 +522,51 @@ describe("computeTripStats", () => {
expect(computeTripStats(locations).avgSpeed).toBe(3)
})
- it("computes elevation gain and loss", () => {
- const locations = [
- { latitude: 0, longitude: 0, altitude: 100 },
- { latitude: 0, longitude: 0, altitude: 150 }, // +50
- { latitude: 0, longitude: 0, altitude: 120 }, // -30
- { latitude: 0, longitude: 0, altitude: 200 } // +80
- ]
+ it("rejects alternating altitude noise instead of counting it as climb", () => {
+ // Noise alternating with the true value turns a steady 20m climb into a swing many times its
+ // size, which the raw sum counted as ascent
+ const locations = Array.from({ length: 41 }, (_, i) => ({
+ latitude: 0,
+ longitude: 0,
+ altitude: i % 2 === 0 ? 500 + i / 2 : 480,
+ timestamp: 1000 + i * 6
+ }))
const stats = computeTripStats(locations)
- expect(stats.elevationGain).toBe(130) // 50 + 80
- expect(stats.elevationLoss).toBe(30)
+ expect(stats.elevationGain).toBeLessThan(30)
+ expect(stats.elevationLoss).toBeLessThan(15)
+ })
+
+ it("keeps sustained climb after smoothing", () => {
+ // A real ascent must survive the filter that rejects the noise above. Smoothing shortens the
+ // span slightly at both ends, so allow a small shortfall but never an overcount.
+ const locations = Array.from({ length: 201 }, (_, i) => ({
+ latitude: 0,
+ longitude: 0,
+ altitude: 500 + i * 0.5,
+ timestamp: 1000 + i * 6
+ }))
+ const stats = computeTripStats(locations)
+ expect(stats.elevationGain).toBeGreaterThan(95)
+ expect(stats.elevationGain).toBeLessThanOrEqual(100)
+ expect(stats.elevationLoss).toBe(0)
+ })
+
+ it("reports the same climb whatever the fix interval", () => {
+ // The window is in seconds, not samples, so doubling the tracking rate must not change the
+ // answer. A sample-width window reported wildly different numbers for the same terrain.
+ const climbAt = (intervalSeconds: number, points: number) =>
+ computeTripStats(
+ Array.from({ length: points }, (_, i) => ({
+ latitude: 0,
+ longitude: 0,
+ altitude: 500 + i * (120 / (points - 1)),
+ timestamp: 1000 + i * intervalSeconds
+ }))
+ ).elevationGain
+
+ const slow = climbAt(6, 101) // 600s of climbing, 6s fixes
+ const fast = climbAt(3, 201) // same 600s and same 120m, 3s fixes
+ expect(Math.abs(fast - slow)).toBeLessThan(3)
})
it("ignores elevation diff when altitude is null", () => {
@@ -546,6 +581,39 @@ describe("computeTripStats", () => {
expect(stats.elevationLoss).toBe(0)
})
+ it("does not bridge across a point with no altitude", () => {
+ // Two descents separated by a missing altitude. Smoothing must not join them: the 200m step
+ // up across the gap is not climb the user did, and would read as such if the runs merged.
+ const descent = (base: number, from: number) =>
+ Array.from({ length: 15 }, (_, i) => ({
+ latitude: 0,
+ longitude: 0,
+ altitude: base - i * 2,
+ timestamp: from + i * 6
+ }))
+ const stats = computeTripStats([
+ ...descent(500, 1000),
+ { latitude: 0, longitude: 0, altitude: undefined, timestamp: 1090 },
+ ...descent(700, 1100)
+ ])
+ expect(stats.elevationGain).toBe(0)
+ expect(stats.elevationLoss).toBeLessThan(56) // two runs of at most 28m, not the 256m bridged
+ })
+
+ it("leaves sparsely sampled tracks unsmoothed", () => {
+ // Points minutes apart carry no per-fix noise, so smoothing would remove real terrain
+ const altitudes = [500, 520, 540, 560, 540, 530, 540, 550, 560]
+ const locations = altitudes.map((altitude, i) => ({
+ latitude: 0,
+ longitude: 0,
+ altitude,
+ timestamp: 1000 + i * 300
+ }))
+ const stats = computeTripStats(locations)
+ expect(stats.elevationGain).toBe(90)
+ expect(stats.elevationLoss).toBe(30)
+ })
+
it("handles flat terrain (no gain or loss)", () => {
const locations = [
{ latitude: 0, longitude: 0, altitude: 500 },
diff --git a/apps/mobile/src/utils/trips.ts b/apps/mobile/src/utils/trips.ts
index f6357a0a..cc04aa8a 100644
--- a/apps/mobile/src/utils/trips.ts
+++ b/apps/mobile/src/utils/trips.ts
@@ -209,25 +209,102 @@ export interface TripStats {
elevationLoss: number // meters
}
+// Reported altitude swings up and down between consecutive fixes, so adding the raw differences
+// counts each swing as both a climb and a descent and badly overstates them. The window is in
+// seconds rather than samples so the amount of smoothing does not change with the fix interval.
+const ELEVATION_SMOOTHING_HALF_WINDOW_SECONDS = 12
+// One pass leaves a ripple behind when the noise alternates on every fix.
+const ELEVATION_SMOOTHING_PASSES = 2
+// Smoothing cannot fully flatten the wobble, so ignore what is left rather than accumulate it
+// over thousands of points.
+const ELEVATION_THRESHOLD_METERS = 1
+
+interface AltitudeRun {
+ altitudes: number[]
+ /** Null when any point lacks a timestamp, which leaves the run unsmoothed. */
+ timestamps: number[] | null
+}
+
+/** Runs of consecutive altitudes, broken wherever a point reports none. */
+function altitudeRuns(locations: LocationCoords[]): AltitudeRun[] {
+ const runs: AltitudeRun[] = []
+ let altitudes: number[] = []
+ let timestamps: number[] = []
+ let timed = true
+
+ const flush = () => {
+ if (altitudes.length > 0) runs.push({ altitudes, timestamps: timed ? timestamps : null })
+ altitudes = []
+ timestamps = []
+ timed = true
+ }
+
+ for (const loc of locations) {
+ if (loc.altitude == null) {
+ flush()
+ continue
+ }
+ altitudes.push(loc.altitude)
+ if (loc.timestamp == null) timed = false
+ else timestamps.push(loc.timestamp)
+ }
+ flush()
+ return runs
+}
+
+/**
+ * Centered moving average over a fixed time window. Points with no neighbour inside the window
+ * keep their own value, so sparsely sampled tracks such as imports pass through untouched.
+ */
+function smoothAltitudes(altitudes: number[], timestamps: number[]): number[] {
+ const half = ELEVATION_SMOOTHING_HALF_WINDOW_SECONDS
+ let smoothed = altitudes
+
+ for (let pass = 0; pass < ELEVATION_SMOOTHING_PASSES; pass++) {
+ const source = smoothed
+ smoothed = source.map((_, i) => {
+ let sum = source[i]
+ let count = 1
+ for (let j = i - 1; j >= 0 && timestamps[i] - timestamps[j] <= half; j--) {
+ sum += source[j]
+ count++
+ }
+ for (let j = i + 1; j < source.length && timestamps[j] - timestamps[i] <= half; j++) {
+ sum += source[j]
+ count++
+ }
+ return sum / count
+ })
+ }
+ return smoothed
+}
+
export function computeTripStats(locations: LocationCoords[]): TripStats {
let speedSum = 0
let speedCount = 0
let elevationGain = 0
let elevationLoss = 0
- for (let i = 0; i < locations.length; i++) {
- const loc = locations[i]
+ for (const loc of locations) {
if (loc.speed != null && loc.speed > 0) {
speedSum += loc.speed
speedCount++
}
- if (i > 0) {
- const prevAlt = locations[i - 1].altitude
- const currAlt = loc.altitude
- if (prevAlt != null && currAlt != null) {
- const diff = currAlt - prevAlt
- if (diff > 0) elevationGain += diff
- else elevationLoss += Math.abs(diff)
+ }
+
+ for (const run of altitudeRuns(locations)) {
+ const series = run.timestamps ? smoothAltitudes(run.altitudes, run.timestamps) : run.altitudes
+ // Measure from the last altitude committed rather than the previous point, so wobble under
+ // the threshold is skipped instead of being carried into the next comparison.
+ let reference = series[0]
+ for (let i = 1; i < series.length; i++) {
+ const diff = series[i] - reference
+ if (diff > ELEVATION_THRESHOLD_METERS) {
+ elevationGain += diff
+ reference = series[i]
+ } else if (diff < -ELEVATION_THRESHOLD_METERS) {
+ elevationLoss += Math.abs(diff)
+ reference = series[i]
}
}
}
diff --git a/fastlane/metadata/android/en-US/changelogs/45.txt b/fastlane/metadata/android/en-US/changelogs/45.txt
index 5dd3f85a..2c68ab95 100644
--- a/fastlane/metadata/android/en-US/changelogs/45.txt
+++ b/fastlane/metadata/android/en-US/changelogs/45.txt
@@ -4,5 +4,6 @@
- Merge adjacent trips from the Trips selection bar when one journey got split up
- Split a trip by tapping the point on the map where the new trip should start
- Trips show an average speed instead of 0 km/h when the points carry no speed, including imported tracks
+- Elevation gain and loss no longer count altitude noise as climb
- Tracking no longer gets stuck on Pause after a geofence is deleted or its motionless pause is turned off
- Tracking restarts itself when the phone stops delivering locations, instead of staying silent until you reinstall