Colota - Android GPS Location tracker
fix(trips): average speed from distance and time, charts by time and distance (#964)
Max Dietrich045b6d9403a5
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 6b770fb1..d6a47a71 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -399,7 +399,7 @@ Supporting utilities in `mapUtils.ts`:| `LogExportMerger` (Kotlin, `util/`) | Interleaves the app log into the recorded segments by timestamp while streaming them to the SAF document, so an export is one timeline and never holds a multi-megabyte file in memory. The merge is native because the segments are copied natively and the bridge only hands JS a capped tail of them, so a JS-side merge would truncate the file it completes || `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. 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 |+| `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 as distance over elapsed time, elevation gain/loss), the chart series (speed in buckets of equal time, elevation in buckets of equal distance), 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 the segmentation and distance for the calendar and summary || `dashboardState` | Pure functions behind the Dashboard: `pickBannerCondition` ranks the one banner slot (location grant, background grant while tracking, location services, battery), `describeState` turns tracking, pause and fix state into the dock's state line, `intervalLines` and `formatLastFix` || `settingsValidation` | URL validation and security checks for endpoint configuration |diff --git a/apps/mobile/src/components/features/inspector/InteractiveLineChart.tsx b/apps/mobile/src/components/features/inspector/InteractiveLineChart.tsxindex a74aabcc..fe245803 100644--- a/apps/mobile/src/components/features/inspector/InteractiveLineChart.tsx+++ b/apps/mobile/src/components/features/inspector/InteractiveLineChart.tsx@@ -16,8 +16,6 @@ interface InteractiveLineChartProps {backgroundColor: stringformatValue: (value: number) => stringheight?: number- activeIndex?: number | null- onActiveIndexChange?: (index: number | null) => void}const CHART_PADDING = { top: 24, bottom: 20, left: 40, right: 0 }@@ -31,14 +29,10 @@ export function InteractiveLineChart({textColor,backgroundColor,formatValue,- height = 140,- activeIndex: externalIndex,- onActiveIndexChange+ height = 140}: InteractiveLineChartProps) {const [chartWidth, setChartWidth] = useState(0)- const [internalIndex, setInternalIndex] = useState<number | null>(null)- const activeIndex = externalIndex !== undefined ? externalIndex : internalIndex- const setActiveIndex = onActiveIndexChange ?? setInternalIndex+ const [activeIndex, setActiveIndex] = useState<number | null>(null)const widthRef = useRef(0)const dataRef = useRef(data)dataRef.current = datadiff --git a/apps/mobile/src/components/features/inspector/TripRow.tsx b/apps/mobile/src/components/features/inspector/TripRow.tsxindex 016441fe..c53d010a 100644--- a/apps/mobile/src/components/features/inspector/TripRow.tsx+++ b/apps/mobile/src/components/features/inspector/TripRow.tsx@@ -3,7 +3,7 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useMemo } from "react"+import React from "react"import { Pressable, StyleSheet, Text, View } from "react-native"import { Check } from "lucide-react-native"import { radius } from "@colota/shared"@@ -11,7 +11,7 @@ import { useTheme } from "../../../hooks/useTheme"import { fontSizes, fonts, lineHeights } from "../../../styles/typography"import { size, space, STATE_LAYER_ALPHA } from "../../../constants"import { formatDistance, formatDuration, formatSpeed, formatTime, spokenDistance } from "../../../utils/geo"-import { computeTripStats, getTripColor } from "../../../utils/trips"+import { getTripColor } from "../../../utils/trips"import type { Trip } from "../../../types/global"import { t } from "../../../i18n/t"import { useTranslation } from "../../../i18n/useTranslation"@@ -45,7 +45,7 @@ export function TripRow({ trip, index, selected, selecting, onPress, onLongPressconst { colors } = useTheme()useTranslation()const duration = trip.endTime - trip.startTime- const avgSpeed = useMemo(() => computeTripStats(trip.locations).avgSpeed, [trip.locations])+ const avgSpeed = duration > 0 ? trip.distance / duration : 0const start = formatTime(trip.startTime)const end = formatTime(trip.endTime)const detail = [formatDistance(trip.distance), formatDuration(duration), avgSpeed > 0 ? formatSpeed(avgSpeed) : null]diff --git a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsxindex 333053ff..e4fa4ba8 100644--- a/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx+++ b/apps/mobile/src/components/features/inspector/__tests__/TripList.test.tsx@@ -17,8 +17,7 @@ jest.mock("../../../../utils/geo", () => ({}))jest.mock("../../../../utils/trips", () => ({- getTripColor: (i: number) => `#color${i}`,- computeTripStats: () => ({ avgSpeed: 0, elevationGain: 0, elevationLoss: 0 })+ getTripColor: (i: number) => `#color${i}`}))jest.mock("lucide-react-native", () => {diff --git a/apps/mobile/src/components/features/inspector/__tests__/TripRow.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/TripRow.test.tsxindex c1f89101..88fa010f 100644--- a/apps/mobile/src/components/features/inspector/__tests__/TripRow.test.tsx+++ b/apps/mobile/src/components/features/inspector/__tests__/TripRow.test.tsx@@ -33,16 +33,15 @@ const START = 8 * 3600 + 12 * 60const END = START + 6 * 60function makeTrip(): Trip {- const speed = 17 / 3.6return {index: 2,locations: [- { latitude: 0, longitude: 0, timestamp: START, speed },- { latitude: 0.01, longitude: 0, timestamp: END, speed }+ { latitude: 0, longitude: 0, timestamp: START },+ { latitude: 0.01, longitude: 0, timestamp: END }],startTime: START,endTime: END,- distance: 1100,+ distance: 1700,locationCount: 2,startIndex: 5}@@ -68,7 +67,7 @@ describe("TripRow", () => {const { getByText } = renderRow()expect(getByText("Trip 2")).toBeTruthy()- expect(getByText("1.1 km · 6min · 17.0 km/h")).toBeTruthy()+ expect(getByText("1.7 km · 6min · 17.0 km/h")).toBeTruthy()})it("speaks the whole row with units a screen reader can say, and offers the details it opens", () => {@@ -76,7 +75,7 @@ describe("TripRow", () => {const row = getByTestId("trip-row")expect(row.props.accessibilityRole).toBe("button")- expect(row.props.accessibilityLabel).toBe("Trip 2, 08:12 to 08:18, 1.1 kilometres, 6 minutes")+ expect(row.props.accessibilityLabel).toBe("Trip 2, 08:12 to 08:18, 1.7 kilometres, 6 minutes")expect(row.props.accessibilityHint).toBe("Opens trip details")})@@ -135,7 +134,7 @@ describe("TripRow", () => {const { View } = require("react-native")expect(getByText("Trip 2").props.numberOfLines).toBeUndefined()- expect(getByText("1.1 km · 6min · 17.0 km/h").props.numberOfLines).toBeUndefined()+ expect(getByText("1.7 km · 6min · 17.0 km/h").props.numberOfLines).toBeUndefined()const titleRow = UNSAFE_getAllByType(View).find((v: any) => StyleSheet.flatten(v.props.style)?.flexWrap === "wrap")expect(titleRow).toBeTruthy()expect(StyleSheet.flatten(getByText("Trip 2").props.style).flexShrink).toBeUndefined()diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsxindex 60a48d5a..6bf8d716 100644--- a/apps/mobile/src/screens/TripDetailScreen.tsx+++ b/apps/mobile/src/screens/TripDetailScreen.tsx@@ -23,7 +23,14 @@ import { TripSwatch } from "../components/features/inspector/TripRow"import { ExportFormatDialog } from "../components/ui/ExportFormatDialog"import { InspectorDock } from "../components/features/inspector/InspectorDock"import { InteractiveLineChart } from "../components/features/inspector/InteractiveLineChart"-import { getTripColor, computeTripStats, buildBoundaryOverrideMap, splitBlockedReason } from "../utils/trips"+import {+ getTripColor,+ computeTripStats,+ buildSpeedProfile,+ buildElevationProfile,+ buildBoundaryOverrideMap,+ splitBlockedReason+} from "../utils/trips"import { formatDate, formatDistance, formatDuration, formatShortDistance, formatSpeed, formatTime } from "../utils/geo"import { EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"import { size, space } from "../constants"@@ -37,21 +44,6 @@ import { useTranslation } from "../i18n/useTranslation"const MAX_BARS = 120-/** Downsample an array to at most maxBars entries by averaging buckets. */-function downsample(values: number[], maxBars: number): number[] {- if (values.length <= maxBars) return values- const bucketSize = values.length / maxBars- const result: number[] = []- for (let i = 0; i < maxBars; i++) {- const start = Math.floor(i * bucketSize)- const end = Math.floor((i + 1) * bucketSize)- let sum = 0- for (let j = start; j < end; j++) sum += values[j]- result.push(sum / (end - start))- }- return result-}-const MAP_VIEWPORT_SHARE = 0.5// The point card may cover this much of the map; a band of tiles always stays above it.const DOCK_MAP_SHARE = 0.6@@ -78,7 +70,6 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip Deconst displayName = t("history.trip", { index: trip.index })const [exportOpen, setExportOpen] = useState(false)- const [chartActiveIndex, setChartActiveIndex] = useState<number | null>(null)// Without these, a boundary the user merged reads as a plain gap and refuses to splitconst [boundaryOverrides, setBoundaryOverrides] = useState<Map<string, BoundaryAction>>(() => new Map())// Splitting before they arrive would judge a merged boundary as a plain gap and refuse a legal split@@ -118,7 +109,6 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De// Reset transient UI state when switching to a different trip.useEffect(() => {- setChartActiveIndex(null)setExportOpen(false)setSelectedPointId(null)}, [trip.index])@@ -261,24 +251,17 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip Denavigation.setOptions({ headerRight })}, [navigation, headerRight])- const speedProfile = useMemo(() => {- const raw = trip.locations.filter((loc) => loc.speed != null).map((loc) => loc.speed ?? 0)- return downsample(raw, MAX_BARS)- }, [trip])-- const elevationProfile = useMemo(() => {- const raw = trip.locations.filter((loc) => loc.altitude != null).map((loc) => loc.altitude ?? 0)- return downsample(raw, MAX_BARS)- }, [trip])+ const speedProfile = useMemo(() => buildSpeedProfile(trip.locations, MAX_BARS), [trip])+ const elevationProfile = useMemo(() => buildElevationProfile(trip.locations, MAX_BARS), [trip])- const maxSpeed = useMemo(() => speedProfile.reduce((max, v) => Math.max(max, v), 0), [speedProfile])+ const maxSpeed = useMemo(() => trip.locations.reduce((max, loc) => Math.max(max, loc.speed ?? 0), 0), [trip])const minElevation = useMemo(- () => elevationProfile.reduce((min, v) => Math.min(min, v), Infinity),- [elevationProfile]+ () => trip.locations.reduce((min, loc) => Math.min(min, loc.altitude ?? Infinity), Infinity),+ [trip])const maxElevation = useMemo(- () => elevationProfile.reduce((max, v) => Math.max(max, v), -Infinity),- [elevationProfile]+ () => trip.locations.reduce((max, loc) => Math.max(max, loc.altitude ?? -Infinity), -Infinity),+ [trip])const elevationRange = maxElevation - minElevation@@ -399,8 +382,6 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip DetextColor={colors.text}backgroundColor={colors.card}formatValue={(v) => formatSpeed(v, 0)}- activeIndex={chartActiveIndex}- onActiveIndexChange={setChartActiveIndex}/></View><View style={styles.chartLabels}>@@ -430,8 +411,6 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip DetextColor={colors.text}backgroundColor={colors.card}formatValue={formatShortDistance}- activeIndex={chartActiveIndex}- onActiveIndexChange={setChartActiveIndex}/><View style={styles.chartLabels}>{[0, 0.25, 0.5, 0.75, 1].map((frac) => (diff --git a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsxindex 2f41e6a8..177f855b 100644--- a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx@@ -56,7 +56,7 @@ jest.mock("react-native-safe-area-context", () => ({jest.mock("../../components/features/inspector/InteractiveLineChart", () => {const R = require("react")const { View } = require("react-native")- return { InteractiveLineChart: (_props: any) => R.createElement(View, { testID: "Chart" }) }+ return { InteractiveLineChart: (props: any) => R.createElement(View, { testID: "Chart", data: props.data }) }})jest.mock("../../components/ui/ExportFormatDialog", () => {@@ -384,6 +384,59 @@ describe("TripDetailScreen - header and stepper", () => {})})+describe("TripDetailScreen - charts", () => {+ beforeEach(async () => {+ ;(NativeLocationService.getSetting as jest.Mock).mockImplementation((key: string) =>+ Promise.resolve(key === "unitSystem" ? "metric" : "")+ )+ await loadDisplayPreferences()+ })++ afterEach(async () => {+ ;(NativeLocationService.getSetting as jest.Mock).mockResolvedValue("")+ await loadDisplayPreferences()+ })++ it("draws speed on the first chart and elevation on the second, since each sits over its own axis labels", async () => {+ const trip = makeTrip(6)+ trip.locations = trip.locations.map((l, i) => ({ ...l, speed: i + 1, altitude: 100 + i * 10 }))++ const { getAllByTestId } = render(<TripDetailScreen {...makeProps(trip)} />)+ await act(async () => {})++ const [speed, elevation] = getAllByTestId("Chart")+ expect(speed.props.data).toEqual([1, 2, 3, 4, 5, 6])+ expect(elevation.props.data.map(Math.round)).toEqual([100, 110, 120, 130, 140, 150])+ })++ it("reads the peak speed and the elevation range from the points, not from the averaged chart", async () => {+ // Four fixes a second and a metre apart share one chart bucket, so the chart shows their mean+ const dense = [0, 1, 2, 3].map((i) => ({+ id: i + 1,+ latitude: 52.52 + i * 0.00001,+ longitude: 13.405,+ timestamp: 1000 + i,+ speed: i === 1 ? 30 : 2,+ altitude: i === 1 ? 500 : 100+ }))+ const sparse = [1, 2].map((i) => ({+ id: i + 4,+ latitude: 52.52 + i * 0.5,+ longitude: 13.405,+ timestamp: 1000 + i * 1000,+ speed: 2,+ altitude: 100+ }))+ const trip = { ...makeTrip(6), locations: [...dense, ...sparse] }++ const { getByText } = render(<TripDetailScreen {...makeProps(trip)} />)+ await act(async () => {})++ expect(getByText(/^max 108[.,]0 km\/h$/)).toBeTruthy()+ expect(getByText(/^100 ?m - 500 ?m$/)).toBeTruthy()+ })+})+describe("TripDetailScreen - elevation", () => {afterEach(async () => {;(NativeLocationService.getSetting as jest.Mock).mockResolvedValue("")diff --git a/apps/mobile/src/utils/__tests__/trips.test.ts b/apps/mobile/src/utils/__tests__/trips.test.tsindex b2b5e3e7..c9e9b25e 100644--- a/apps/mobile/src/utils/__tests__/trips.test.ts+++ b/apps/mobile/src/utils/__tests__/trips.test.ts@@ -3,6 +3,8 @@ import {getTripColor,TRIP_COLORS,computeTripStats,+ buildSpeedProfile,+ buildElevationProfile,buildBoundaryOverrideMap,gapsBetweenTrips,boundarySplits,@@ -484,43 +486,39 @@ describe("computeTripStats", () => {expect(stats.elevationLoss).toBe(0)})- it("computes average speed from non-zero values", () => {- const locations = [- { latitude: 0, longitude: 0, speed: 2 },- { latitude: 0, longitude: 0, speed: 4 },- { latitude: 0, longitude: 0, speed: 6 }- ]- const stats = computeTripStats(locations)- expect(stats.avgSpeed).toBe(4) // (2+4+6)/3+ it("does not let a densely recorded slow stretch outweigh a sparse fast one", () => {+ // 50 fixes a second apart cover ~270m, then 3 fixes ten minutes apart cover ~400km+ const slow = Array.from({ length: 50 }, (_, i) => ({+ latitude: i * 0.00005,+ longitude: 0,+ timestamp: 1000 + i,+ speed: 5+ }))+ const fast = Array.from({ length: 3 }, (_, i) => ({+ latitude: 0.00245 + (i + 1) * 1.2,+ longitude: 0,+ timestamp: 1049 + (i + 1) * 600,+ speed: 250+ }))+ // ~400.6km in 1849s+ expect(computeTripStats([...slow, ...fast]).avgSpeed).toBeCloseTo(216.6, 0)})- it("excludes zero and null speeds from average", () => {+ it("divides distance by elapsed time, whatever speeds the fixes report", () => {const locations = [- { latitude: 0, longitude: 0, speed: 0 },- { latitude: 0, longitude: 0, speed: undefined },- { latitude: 0, longitude: 0, speed: 10 }+ { latitude: 52.52, longitude: 13.405, timestamp: 1000, speed: 3 },+ { latitude: 52.53, longitude: 13.405, timestamp: 1050, speed: 3 }]- const stats = computeTripStats(locations)- expect(stats.avgSpeed).toBe(10) // only the 10 counts+ // ~1112m in 50s+ expect(computeTripStats(locations).avgSpeed).toBeCloseTo(22.24, 2)})- it("derives average speed from position when no point has a usable speed", () => {+ it("reports no average speed when the trip spans no time", () => {const locations = [- { latitude: 52.52, longitude: 13.405, timestamp: 1000, speed: 0 },- { latitude: 52.521, longitude: 13.405, timestamp: 1050, speed: 0 }+ { latitude: 52.52, longitude: 13.405, speed: 3 },+ { latitude: 52.53, longitude: 13.405, speed: 3 }]- // 0.001 degrees of latitude is ~111.2m, covered in 50s- const stats = computeTripStats(locations)- expect(stats.avgSpeed).toBeCloseTo(2.224, 3)- })-- it("prefers reported speeds over the position-derived fallback", () => {- const locations = [- { latitude: 52.52, longitude: 13.405, timestamp: 1000, speed: 3 },- { latitude: 52.53, longitude: 13.405, timestamp: 1050, speed: 3 }- ]- // Position implies ~22 m/s over these 50s, so a flipped precedence would be visible- expect(computeTripStats(locations).avgSpeed).toBe(3)+ expect(computeTripStats(locations).avgSpeed).toBe(0)})it("rejects alternating altitude noise instead of counting it as climb", () => {@@ -680,3 +678,101 @@ describe("split refusal wording", () => {expect(t(SPLIT_BLOCKED_TOO_SHORT)).toMatch(/^A split needs at least two points on each side/)})})++describe("buildSpeedProfile", () => {+ it("gives a stretch its share of the time, not its share of the points", () => {+ // 91 fixes in the first 90s, 9 over the next 810s+ const dense = Array.from({ length: 91 }, (_, i) => ({ latitude: 0, longitude: 0, timestamp: 1000 + i, speed: 1 }))+ const sparse = Array.from({ length: 9 }, (_, i) => ({+ latitude: 0,+ longitude: 0,+ timestamp: 1090 + (i + 1) * 90,+ speed: 100+ }))++ expect(buildSpeedProfile([...dense, ...sparse], 11)).toEqual([1, 1, 100, 100, 100, 100, 100, 100, 100, 100, 100])+ })++ it("draws a straight line across time no fix was recorded in", () => {+ const locations = [+ { latitude: 0, longitude: 0, timestamp: 1000, speed: 10 },+ { latitude: 0, longitude: 0, timestamp: 1001, speed: 10 },+ { latitude: 0, longitude: 0, timestamp: 1002, speed: 10 },+ { latitude: 0, longitude: 0, timestamp: 4000, speed: 40 }+ ]+ const profile = buildSpeedProfile(locations, 120)++ expect(profile).toHaveLength(4)+ profile.forEach((value, i) => expect(value).toBeCloseTo([10, 20, 30, 40][i], 6))+ })++ it("keeps a stop on the chart for as long as it lasted", () => {+ // Moving for 100s, stopped for 800s with only two fixes, moving again for 100s+ const locations = [+ ...Array.from({ length: 11 }, (_, i) => ({ latitude: 0, longitude: 0, timestamp: 1000 + i * 10, speed: 10 })),+ { latitude: 0, longitude: 0, timestamp: 1200, speed: 0 },+ { latitude: 0, longitude: 0, timestamp: 1800, speed: 0 },+ ...Array.from({ length: 11 }, (_, i) => ({ latitude: 0, longitude: 0, timestamp: 1900 + i * 10, speed: 10 }))+ ]+ const profile = buildSpeedProfile(locations, 11)++ expect(profile.slice(2, 9)).toEqual([0, 0, 0, 0, 0, 0, 0])+ })++ it("places a speed by its own time when earlier points reported none", () => {+ const locations = Array.from({ length: 20 }, (_, i) => ({+ latitude: 0,+ longitude: 0,+ timestamp: 1000 + i * 10,+ speed: i < 10 ? undefined : i+ }))+ expect(buildSpeedProfile(locations, 10)).toEqual([10.5, 10.5, 10.5, 10.5, 10.5, 10.5, 12.5, 14.5, 16.5, 18.5])+ })++ it("returns nothing when too few points carry a speed to draw a line", () => {+ const locations = Array.from({ length: 10 }, (_, i) => ({+ latitude: 0,+ longitude: 0,+ timestamp: 1000 + i,+ speed: i < 2 ? 5 : undefined+ }))+ expect(buildSpeedProfile(locations, 120)).toEqual([])+ })++ it("spreads the points evenly when the trip spans no time", () => {+ const locations = [1, 2, 3, 4].map((speed) => ({ latitude: 0, longitude: 0, speed }))+ expect(buildSpeedProfile(locations, 120)).toEqual([1, 2, 3, 4])+ })+})++describe("buildElevationProfile", () => {+ it("gives a stretch its share of the distance, not its share of the points", () => {+ // 91 fixes over the first tenth of the route, 9 over the rest+ const dense = Array.from({ length: 91 }, (_, i) => ({ latitude: i * 0.0001, longitude: 0, altitude: 0 }))+ const sparse = Array.from({ length: 9 }, (_, i) => ({+ latitude: 0.009 + (i + 1) * 0.009,+ longitude: 0,+ altitude: 1000+ }))++ expect(buildElevationProfile([...dense, ...sparse], 11)).toEqual([+ 0, 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000+ ])+ })++ it("measures distance over every point, including those with no altitude", () => {+ const locations = Array.from({ length: 20 }, (_, i) => ({+ latitude: i * 0.001,+ longitude: 0,+ altitude: i < 10 ? undefined : 100 + i+ }))+ expect(buildElevationProfile(locations, 10)).toEqual([+ 110.5, 110.5, 110.5, 110.5, 110.5, 110.5, 112.5, 114.5, 116.5, 118.5+ ])+ })++ it("spreads the points evenly when the trip covers no distance", () => {+ const locations = [1, 2, 3, 4].map((altitude) => ({ latitude: 52.52, longitude: 13.405, altitude }))+ expect(buildElevationProfile(locations, 120)).toEqual([1, 2, 3, 4])+ })+})diff --git a/apps/mobile/src/utils/trips.ts b/apps/mobile/src/utils/trips.tsindex fea57798..3e37c462 100644--- a/apps/mobile/src/utils/trips.ts+++ b/apps/mobile/src/utils/trips.ts@@ -278,18 +278,9 @@ function smoothAltitudes(altitudes: number[], timestamps: number[]): number[] {}export function computeTripStats(locations: LocationCoords[]): TripStats {- let speedSum = 0- let speedCount = 0let elevationGain = 0let elevationLoss = 0- for (const loc of locations) {- if (loc.speed != null && loc.speed > 0) {- speedSum += loc.speed- speedCount++- }- }-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@@ -307,14 +298,9 @@ export function computeTripStats(locations: LocationCoords[]): TripStats {}}+ // Elapsed time, so stopped time countslet avgSpeed = 0- if (speedCount > 0) {- avgSpeed = speedSum / speedCount- } else if (locations.length > 1) {- // Points reach here with no usable speed three ways: a chip reporting 0 on every fix, an- // update interval past applySpeedFallback's 60s window, or an import whose source file- // carried none. Without this the trip reads 0 next to a correct distance. Note this counts- // stopped time, unlike the reported-speed branch above, which averages moving fixes only.+ if (locations.length > 1) {const seconds = (locations[locations.length - 1].timestamp ?? 0) - (locations[0].timestamp ?? 0)if (seconds > 0) avgSpeed = computeTotalDistance(locations) / seconds}@@ -325,3 +311,72 @@ export function computeTripStats(locations: LocationCoords[]): TripStats {elevationLoss}}++const MIN_PROFILE_SAMPLES = 3++/** Bucket means along an axis. An empty bucket sits on the line between its filled neighbours. */+function bucketProfile(+ positions: number[],+ values: number[],+ start: number,+ span: number,+ maxBuckets: number+): number[] {+ const samples = values.length+ if (samples < MIN_PROFILE_SAMPLES) return []++ const buckets = Math.min(maxBuckets, samples)+ const sums = new Array<number>(buckets).fill(0)+ const counts = new Array<number>(buckets).fill(0)+ for (let i = 0; i < samples; i++) {+ const fraction = span > 0 ? (positions[i] - start) / span : i / (samples - 1)+ const bucket = Math.max(0, Math.min(buckets - 1, Math.round(fraction * (buckets - 1))))+ sums[bucket] += values[i]+ counts[bucket]+++ }++ const filled: number[] = []+ for (let i = 0; i < buckets; i++) if (counts[i] > 0) filled.push(i)+ const profile = new Array<number>(buckets)+ for (const i of filled) profile[i] = sums[i] / counts[i]+ profile.fill(profile[filled[0]], 0, filled[0])+ profile.fill(profile[filled[filled.length - 1]], filled[filled.length - 1] + 1)+ for (let k = 1; k < filled.length; k++) {+ const from = filled[k - 1]+ const to = filled[k]+ for (let i = from + 1; i < to; i++) {+ profile[i] = profile[from] + ((profile[to] - profile[from]) * (i - from)) / (to - from)+ }+ }+ return profile+}++export function buildSpeedProfile(locations: LocationCoords[], maxBuckets: number): number[] {+ if (locations.length === 0) return []+ const start = locations[0].timestamp ?? 0+ const span = (locations[locations.length - 1].timestamp ?? 0) - start+ const positions: number[] = []+ const values: number[] = []+ for (const loc of locations) {+ if (loc.speed == null) continue+ positions.push(loc.timestamp ?? start)+ values.push(loc.speed)+ }+ return bucketProfile(positions, values, start, span, maxBuckets)+}++export function buildElevationProfile(locations: LocationCoords[], maxBuckets: number): number[] {+ const positions: number[] = []+ const values: number[] = []+ let travelled = 0+ locations.forEach((loc, i) => {+ if (i > 0) {+ const prev = locations[i - 1]+ travelled += haversine(prev.latitude, prev.longitude, loc.latitude, loc.longitude)+ }+ if (loc.altitude == null) return+ positions.push(travelled)+ values.push(loc.altitude)+ })+ return bucketProfile(positions, values, 0, travelled, maxBuckets)+}diff --git a/fastlane/metadata/android/en-US/changelogs/53.txt b/fastlane/metadata/android/en-US/changelogs/53.txtindex 8eb1447c..3af31061 100644--- a/fastlane/metadata/android/en-US/changelogs/53.txt+++ b/fastlane/metadata/android/en-US/changelogs/53.txt@@ -1 +1,2 @@- Less memory used when opening a day with many points and when sending a large upload backlog+- Fixed a trip's average speed and its speed and elevation charts being skewed towards stretches recorded with more points