diff --git a/AGENTS.md b/AGENTS.md index 244eb9fa..76a9ac1d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1009,6 +1009,16 @@ because breaking it fails silently: ring is exactly the false fix the verdict exists to refuse. Sleep stages, onset/wake, HRV and calories are report-only on purpose: vendors compute them differently, so a difference there doesn't show which device is wrong. +- **A day or night is compared only over the time both devices were on.** A flat battery or a + charger mid-day used to pass the 500-step "worn" test and read as the other device + over-counting by everything after. `AccuracyComparison.offGaps` finds each device's off + stretches (no data for over 90 minutes), but only for a device that logs heart rate at least + every 75 minutes (`judgeable`); for one that doesn't, quiet and off look alike and it is taken + as worn. A partly worn day's steps and distance are cut to the shared hours (the ring's + 15-minute buckets against the reference's records); calories can't be cut, so such a day + drops them; under 12 shared hours the day doesn't count. A night either device stopped + inside drops sleep, resting HR and HRV. Heart rate and SpO₂ need nothing: they only pair + readings taken minutes apart. The day notes say which device was off and from when. - **A running check ends the moment a different ring is paired** (`AccuracyRingWatcher`, started from `PulseLoopApplication`). Ring rows carry no device id, so a later sweep could not split the two rings' data. diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 656db096..d96db48b 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -1749,6 +1749,7 @@ "avg {0} bpm": "média {0} bpm", "bed {0}": "deitar {0}", "below": "abaixo", + "compared over the {0} h both were on": "comparado nas {0} h em que os dois estavam ligados", "daily calories": "calorias diárias", "daily calories {0} kcal": "calorias diárias {0} kcal", "day": "dia", @@ -1769,6 +1770,7 @@ "nights": "noites", "no overlap": "sem sobreposição", "not chosen": "não escolhido", + "not counted": "não contado", "nothing logged yet": "nada registrado ainda", "of {0}": "de {0}", "of {0} this week": "de {0} esta semana", @@ -1781,6 +1783,7 @@ "sleep {0} h": "sono {0} h", "sleep {0}{1} min": "sono {0}{1} min", "steps {0} a day": "passos {0} por dia", + "the ring": "o anel", "unknown error": "erro desconhecido", "up": "a mais", "up {0}": "acordar {0}", @@ -1844,10 +1847,12 @@ "{0} steps at {1}.": "{0} passos às {1}.", "{0} steps to your goal.": "Faltam {0} passos para sua meta.", "{0} steps today. {1} Time to start winding down.": "{0} passos hoje. {1} Hora de começar a relaxar.", + "{0} stopped mid-night at {1}": "{0} parou no meio da noite às {1}", "{0} swears, grumbles and judges your habits — the coach too. The numbers stay exactly as accurate, and anything serious is said plainly. If you easily get offended, maybe stick with the boring version.": "{0} xinga, resmunga e julga seus hábitos — o coach também. Os números continuam exatamente tão precisos, e tudo o que é sério é dito com clareza. Se você se ofende fácil, talvez seja melhor ficar com a versão sem graça.", "{0} unavailable": "{0} indisponível", "{0} via Health Connect": "{0} via Health Connect", "{0} vs {1}, until {2}.": "{0} vs {1}, até {2}.", + "{0} was off from {1}, too long to compare": "{0} ficou desligado a partir das {1}, tempo demais para comparar", "{0} workouts a week": "{0} treinos por semana", "{0} years": "{0} anos", "{0} {1} in the last 7 days": "{0} {1} nos últimos 7 dias", diff --git a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyComparison.kt b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyComparison.kt index e3d90038..ef37c7a1 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyComparison.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyComparison.kt @@ -160,6 +160,87 @@ object AccuracyComparison { return out } + // ── Wear coverage ────────────────────────────────────────────────────────────────────── + // + // A device that goes flat, charges or comes off mid-day keeps a day "worn" by the step test + // (it walked 500 steps before it stopped) while its totals stop counting, so the other + // device seems to over-count by everything after. Each device's off stretches are found from + // the gaps in its own data, and a day is compared only over the time both covered. + + /** No data for longer than this, from a device that otherwise logs heart rate, means it was off. */ + const val OFF_GAP_MS = 90 * 60_000L + + /** A device is judged only if it logs heart rate at least this often; sparser data can't show a gap. */ + const val MAX_JUDGED_CADENCE_MS = 75 * 60_000L + + /** + * Stretches within [from, to] longer than [maxGapMs] with no [evidence] from a device: taken + * as the device being off. The edges count too: no data until two hours in is a gap. + */ + fun offGaps(evidence: List, from: Long, to: Long, maxGapMs: Long = OFF_GAP_MS): List { + val out = mutableListOf() + var prev = from + for (t in evidence.filter { it in from..to }.sorted()) { + if (t - prev > maxGapMs) out += prev..t + prev = t + } + if (to - prev > maxGapMs) out += prev..to + return out + } + + /** [ranges] sorted and with overlaps joined. */ + fun merge(ranges: List): List { + val out = mutableListOf() + for (r in ranges.filter { it.last > it.first }.sortedBy { it.first }) { + val last = out.lastOrNull() + if (last != null && r.first <= last.last) out[out.size - 1] = last.first..maxOf(last.last, r.last) + else out += r + } + return out + } + + /** How much of [from, to) the [gaps] take up. */ + fun gapMs(gaps: List, from: Long, to: Long): Long = + merge(gaps).sumOf { (minOf(it.last, to) - maxOf(it.first, from)).coerceAtLeast(0L) } + + /** The gaps that touch [from, to), clipped to it. */ + fun gapsWithin(gaps: List, from: Long, to: Long): List = + merge(gaps).mapNotNull { g -> + val a = maxOf(g.first, from) + val b = minOf(g.last, to) + if (b > a) a..b else null + } + + /** + * The part of [items] that falls in [from, to) outside every gap, each interval counted in + * proportion to its overlap. An instant (end <= start) counts whole or not at all. + */ + fun amountWithin(items: List, from: Long, to: Long, gaps: List): Double { + val off = gapsWithin(gaps, from, to) + var total = 0.0 + for (it in items) { + if (it.end <= it.start) { + if (it.start in from until to && off.none { g -> it.start in g }) total += it.amount + continue + } + val a = maxOf(it.start, from) + val b = minOf(it.end, to) + if (b <= a) continue + val outside = (b - a) - gapMs(off, a, b) + total += it.amount * outside / (it.end - it.start).toDouble() + } + return total + } + + /** Whether a device's data is dense enough to tell "off" from "quiet". */ + fun judgeable(heartRateTimes: List): Boolean { + if (heartRateTimes.size < 12) return false + val sorted = heartRateTimes.sorted() + val gaps = sorted.zipWithNext { a, b -> b - a }.filter { it > 0 }.sorted() + if (gaps.isEmpty()) return false + return gaps[gaps.size / 2] <= MAX_JUDGED_CADENCE_MS + } + // ── Sleep ────────────────────────────────────────────────────────────────────────────── data class StageAgreement(val overlapMinutes: Int, val agreeMinutes: Int, val confusion: Map, Int>) { diff --git a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyReportText.kt b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyReportText.kt index 36994eae..0a9d55ed 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyReportText.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyReportText.kt @@ -114,8 +114,31 @@ object AccuracyReportText { } } - /** Why a day doesn't count, for the per-day rows. */ - fun dayNote(note: String?, ref: String): String? = when (note) { + /** + * What a coverage note says: which device was off and from when (`partly:` / `night_off:`), + * or how many hours a partly worn day was compared over (`shared:`). + */ + private fun coverageNote(note: String, ref: String): String? { + fun device(who: String) = if (who == AccuracyScorer.WHO_RING) com.pulseloop.ui.i18n.tr("the ring") else ref + fun time(ms: String) = ms.toLongOrNull()?.let { + java.time.Instant.ofEpochMilli(it).atZone(java.time.ZoneId.systemDefault()).format(java.time.format.DateTimeFormatter.ofPattern("HH:mm")) + } ?: "?" + return when { + note.startsWith(AccuracyScorer.NOTE_SHARED_PREFIX) -> note.removePrefix(AccuracyScorer.NOTE_SHARED_PREFIX).toLongOrNull()?.let { + com.pulseloop.ui.i18n.trf("compared over the {0} h both were on", "%.1f".format(it / 60.0)) + } + note.startsWith(AccuracyScorer.NOTE_PARTLY_WORN_PREFIX) -> note.removePrefix(AccuracyScorer.NOTE_PARTLY_WORN_PREFIX).split(':').takeIf { it.size == 2 }?.let { (who, at) -> + com.pulseloop.ui.i18n.trf("{0} was off from {1}, too long to compare", device(who), time(at)) + } + note.startsWith(AccuracyScorer.NOTE_NIGHT_OFF_PREFIX) -> note.removePrefix(AccuracyScorer.NOTE_NIGHT_OFF_PREFIX).split(':').takeIf { it.size == 2 }?.let { (who, at) -> + com.pulseloop.ui.i18n.trf("{0} stopped mid-night at {1}", device(who), time(at)) + } + else -> null + } + } + + /** Why a day doesn't count, or how it was counted, for the per-day rows. */ + fun dayNote(note: String?, ref: String): String? = note?.let { coverageNote(it, ref) } ?: when (note) { AccuracyScorer.NOTE_WAITING -> "waiting for $ref to deliver" AccuracyScorer.NOTE_NOT_WORN -> "not worn on both" AccuracyScorer.NOTE_NO_REF_NIGHT -> "no night from $ref" diff --git a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt index 920f7a12..c33dc58f 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt @@ -131,11 +131,57 @@ object AccuracyScorer { val ringHrAll = db.measurementDao().rangeReal(MeasurementKind.HEART_RATE.name, readFrom, readTo) val ringHr = ringHrAll.filter { it.timestamp in from..to }.map { TimedValue(it.timestamp, it.value) } + val ringNights = ringNights(db, from, to, zone) + val ringBuckets = fullDaysOrPartial(from, to, zone).flatMap { d -> + db.activityBucketDao().byDay(LocalDate.ofEpochDay(d).atStartOfDay(zone).toInstant().toEpochMilli()) + } + + // ── Wear coverage: when each device was off (flat, charging, taken off), from the gaps in + // its own data. Only a device that logs heart rate often enough can be judged; for one + // that doesn't, quiet and off look the same, so it is taken as worn throughout. + val coverageEnd = minOf(to, now) + val ringEvidence = buildList { + ringHrAll.forEach { add(it.timestamp) } + ringBuckets.filter { it.steps > 0 }.forEach { add(it.startEpoch); add(it.startEpoch + BUCKET_MS) } + ringNights.values.forEach { n -> n.blocks.forEach { b -> add(b.startAt); add(b.startAt + b.durationMinutes * 60_000L) } } + } + val refEvidence = buildList { + refHr.forEach { add(it.at) } + // A day-long steps record says nothing about when the device was on. + ref.steps.filter { it.endTime.toEpochMilli() - it.startTime.toEpochMilli() <= HOUR } + .forEach { add(it.startTime.toEpochMilli()); add(it.endTime.toEpochMilli()) } + ref.sleep.forEach { r -> + add(r.startTime.toEpochMilli()); add(r.endTime.toEpochMilli()) + r.stages.forEach { st -> add(st.startTime.toEpochMilli()); add(st.endTime.toEpochMilli()) } + } + ref.spo2.forEach { add(it.time.toEpochMilli()) } + ref.hrv.forEach { add(it.time.toEpochMilli()) } + } + val ringGaps = if (AccuracyComparison.judgeable(ringHrAll.map { it.timestamp })) + AccuracyComparison.offGaps(ringEvidence, from, coverageEnd) else emptyList() + val refGaps = if (AccuracyComparison.judgeable(refHr.map { it.at })) + AccuracyComparison.offGaps(refEvidence, from, coverageEnd) else emptyList() + + /** Which device was off longer within [a, b), and from when; null when both stayed on. */ + fun offNote(prefix: String, a: Long, b: Long, minMs: Long): String? { + val r = AccuracyComparison.gapsWithin(ringGaps, a, b) + val f = AccuracyComparison.gapsWithin(refGaps, a, b) + val rMs = AccuracyComparison.gapMs(r, a, b) + val fMs = AccuracyComparison.gapMs(f, a, b) + if (maxOf(rMs, fMs) < minMs) return null + val (who, gaps) = if (rMs >= fMs) WHO_RING to r else WHO_REF to f + return "$prefix$who:${gaps.first().first}" + } + // ── Daily totals: whole local days inside the window only. The day a check starts on is - // partial for whichever device went on later, so its totals aren't comparable. + // partial for whichever device went on later, so its totals aren't comparable. A day + // one device spent partly off is compared over the hours both covered, or not at all + // when that is under [MIN_SHARED_MS]. val fullDays = fullDaysIn(from, to, zone) - val refSteps = AccuracyComparison.dailyTotals(ref.steps.map { AccuracyComparison.IntervalAmount(it.startTime.toEpochMilli(), it.endTime.toEpochMilli(), it.count.toDouble()) }, zone) - val refDist = AccuracyComparison.dailyTotals(ref.distance.map { AccuracyComparison.IntervalAmount(it.startTime.toEpochMilli(), it.endTime.toEpochMilli(), it.distance.inMeters) }, zone) + val refStepItems = ref.steps.map { AccuracyComparison.IntervalAmount(it.startTime.toEpochMilli(), it.endTime.toEpochMilli(), it.count.toDouble()) } + val refDistItems = ref.distance.map { AccuracyComparison.IntervalAmount(it.startTime.toEpochMilli(), it.endTime.toEpochMilli(), it.distance.inMeters) } + val refSteps = AccuracyComparison.dailyTotals(refStepItems, zone) + val refDist = AccuracyComparison.dailyTotals(refDistItems, zone) val refCal = AccuracyComparison.dailyTotals(ref.calories.map { AccuracyComparison.IntervalAmount(it.startTime.toEpochMilli(), it.endTime.toEpochMilli(), it.energy.inKilocalories) }, zone) for (day in fullDays) { val dayStart = LocalDate.ofEpochDay(day).atStartOfDay(zone).toInstant().toEpochMilli() @@ -146,27 +192,51 @@ object AccuracyScorer { val refStepsDay = refSteps[day] // Worn on both: the reference walked a real day and the ring recorded something. val worn = (refStepsDay ?: 0.0) >= MIN_REF_STEPS && (ringDay?.steps ?: 0) > 0 + val off = AccuracyComparison.gapsWithin(ringGaps + refGaps, dayStart, dayEnd) + val sharedMs = (dayEnd - dayStart) - AccuracyComparison.gapMs(off, dayStart, dayEnd) + val partial = off.isNotEmpty() + val tooPartial = partial && sharedMs < MIN_SHARED_MS + val partlyNote = offNote(NOTE_PARTLY_WORN_PREFIX, dayStart, dayEnd, 1L) val note = when { !isDelivered -> NOTE_WAITING !worn -> NOTE_NOT_WORN + tooPartial -> partlyNote + partial -> "$NOTE_SHARED_PREFIX${sharedMs / 60_000L}" else -> null } + // Over the shared hours only: the ring's 15-minute buckets and the reference's + // records, each cut to the time both devices were on. + val ringItems = ringBuckets.filter { it.startEpoch in dayStart until dayEnd } + fun ringWithin(value: (com.pulseloop.data.entity.ActivityBucketEntity) -> Double) = + AccuracyComparison.amountWithin(ringItems.map { AccuracyComparison.IntervalAmount(it.startEpoch, it.startEpoch + BUCKET_MS, value(it)) }, dayStart, dayEnd, off) if (ReferenceMetric.STEPS in compared) { - rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.STEPS, day, ringDay?.steps?.toDouble(), refStepsDay, isDelivered && worn, note, now) + val ringSteps = if (partial) ringWithin { it.steps.toDouble() } else ringDay?.steps?.toDouble() + val refStepsCompared = if (partial) AccuracyComparison.amountWithin(refStepItems, dayStart, dayEnd, off) else refStepsDay + rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.STEPS, day, ringSteps, refStepsCompared, isDelivered && worn && !tooPartial, note, now) } if (ReferenceMetric.DISTANCE in compared) { - val ringDist = ringDay?.distanceMeters?.takeIf { it > 0 } - rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.DISTANCE, day, ringDist, refDist[day], isDelivered && (worn || ReferenceMetric.STEPS !in compared), note, now) + // Only the ring's buckets can be cut to the shared hours; without bucket distance + // a partial day can't be compared. + val bucketDist = if (partial) ringWithin { it.distanceMeters }.takeIf { it > 0 } else null + val ringDist = if (partial) bucketDist else ringDay?.distanceMeters?.takeIf { it > 0 } + val refDistCompared = if (partial) AccuracyComparison.amountWithin(refDistItems, dayStart, dayEnd, off) else refDist[day] + val ok = !tooPartial && (!partial || bucketDist != null) + rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.DISTANCE, day, ringDist, refDistCompared, + isDelivered && (worn || ReferenceMetric.STEPS !in compared) && ok, + if (partial && !ok && note?.startsWith(NOTE_SHARED_PREFIX) == true) partlyNote else note, now) } if (ReferenceMetric.ACTIVE_CALORIES in compared) { + // The ring's calories are one figure for the whole day, so a partly worn day can't be cut. val ringCal = ringDay?.let { DailyCalorieEstimator.effectiveActiveCalories(it) } - rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.ACTIVE_CALORIES, day, ringCal, refCal[day], isDelivered && (worn || ReferenceMetric.STEPS !in compared), note, now) + rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.ACTIVE_CALORIES, day, ringCal, refCal[day], + isDelivered && (worn || ReferenceMetric.STEPS !in compared) && !partial, + if (partial && note?.startsWith(NOTE_SHARED_PREFIX) == true) partlyNote else note, now) } } // ── Sleep, per waking day. The ring's main night is its longest session that day, the - // same night Readiness uses. - val ringNights = ringNights(db, from, to, zone) + // same night Readiness uses. A night either device stopped partway through isn't + // compared: a watch flat at 3 am makes the ring look like it over-reports sleep. val needsNights = ReferenceMetric.SLEEP in compared || ReferenceMetric.RESTING_HEART_RATE in compared || ReferenceMetric.HRV in compared val refNights = ref.sleep.groupBy { AccuracyComparison.epochDay(TimeUtil.wakingDayLocal(it.startTime.toEpochMilli(), zone), zone) } .mapValues { (_, s) -> s.maxBy { it.endTime.toEpochMilli() - it.startTime.toEpochMilli() } } @@ -174,15 +244,20 @@ object AccuracyScorer { for ((day, night) in ringNights) { val dayMidnight = LocalDate.ofEpochDay(day).atStartOfDay(zone).toInstant().toEpochMilli() val isDelivered = delivered(night.session.endAt) + val refRecForSpan = refNights[day] + val spanStart = minOf(night.session.startAt, refRecForSpan?.startTime?.toEpochMilli() ?: night.session.startAt) + val spanEnd = maxOf(night.session.endAt, refRecForSpan?.endTime?.toEpochMilli() ?: night.session.endAt) + val nightOff = offNote(NOTE_NIGHT_OFF_PREFIX, spanStart, spanEnd, NIGHT_OFF_MIN_MS) if (ReferenceMetric.SLEEP in compared) { val refRec = refNights[day] val refNight = refRec?.let(::toNight) val note = when { !isDelivered -> NOTE_WAITING refNight == null -> NOTE_NO_REF_NIGHT + nightOff != null -> nightOff else -> null } - val valid = isDelivered && refNight != null + val valid = isDelivered && refNight != null && nightOff == null val ringAsleep = (if (night.blocks.isEmpty()) night.session.totalMinutes else asleepMinutes(night.blocks)).toDouble() rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.SLEEP_ASLEEP, day, ringAsleep, refNight?.asleepMinutes?.toDouble(), valid, note, now) rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.SLEEP_ONSET, day, @@ -211,14 +286,14 @@ object AccuracyScorer { val refRhr = ref.resting.filter { AccuracyComparison.epochDay(it.time.toEpochMilli(), zone) == day } .maxByOrNull { it.time }?.beatsPerMinute?.toDouble() rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.RESTING_HR, day, summary.restingHr, refRhr, - isDelivered, if (!isDelivered) NOTE_WAITING else null, now) + isDelivered && nightOff == null, if (!isDelivered) NOTE_WAITING else nightOff, now) } if (ReferenceMetric.HRV in compared) { val window = (night.session.startAt - HOUR)..(night.session.endAt + HOUR) val refHrvNight = ref.hrv.filter { it.time.toEpochMilli() in window }.map { it.heartRateVariabilityMillis }.sorted() val refMedian = refHrvNight.takeIf { it.isNotEmpty() }?.let { it[it.size / 2] } rows += AccuracyComparison.dailyRow(check.id, ComparisonMetric.HRV, day, summary.hrv, refMedian, - isDelivered, if (!isDelivered) NOTE_WAITING else null, now) + isDelivered && nightOff == null, if (!isDelivered) NOTE_WAITING else nightOff, now) } } } @@ -228,9 +303,7 @@ object AccuracyScorer { if (ReferenceMetric.HEART_RATE in compared && refHr.isNotEmpty()) { echo = ReferenceSurveyBuilder.echoCheck(refHr, ringHr) val tol = AccuracyComparison.tolerance(ReferenceSurveyBuilder.medianInterval(refHr.map { it.at }), 60_000L, 150_000L) - val buckets = fullDaysOrPartial(from, to, zone).flatMap { d -> - db.activityBucketDao().byDay(LocalDate.ofEpochDay(d).atStartOfDay(zone).toInstant().toEpochMilli()) - }.associateBy { it.startEpoch } + val buckets = ringBuckets.associateBy { it.startEpoch } val workouts = db.activitySessionDao().finishedSince(from).filter { it.endedAt != null && it.startedAt < to } val sleepWindows = ringNights.values.map { it.session.startAt..it.session.endAt } val pairs = AccuracyComparison.pair(ringHr, refHr, tol, zone) { t -> @@ -289,6 +362,19 @@ object AccuracyScorer { const val NOTE_NO_REF_NIGHT = "no_ref_night" const val NOTE_NO_REF_STAGES = "no_ref_stages" const val NOTE_FEW_PAIRS = "few_pairs" + /** `partly::`: that device was off from then, for too much of the day. */ + const val NOTE_PARTLY_WORN_PREFIX = "partly:" + /** `night_off::`: that device stopped partway through the night. */ + const val NOTE_NIGHT_OFF_PREFIX = "night_off:" + /** `shared:`: counted, but only over the minutes both devices were on. */ + const val NOTE_SHARED_PREFIX = "shared:" + const val WHO_RING = "ring" + const val WHO_REF = "ref" + /** A partly worn day still counts with this much time both devices covered. */ + const val MIN_SHARED_MS = 12 * HOUR + /** A night is dropped when either device was off for this long inside it. */ + const val NIGHT_OFF_MIN_MS = 15 * 60_000L + private const val BUCKET_MS = 15 * 60_000L private data class RefData( val steps: List, diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt index a073fda5..c7aeac80 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt @@ -265,7 +265,9 @@ private fun roundBand(m: ComparisonMetric, v: Double): Double = @Composable private fun DayRow(m: ComparisonMetric, d: AccuracyCheckDayEntity, ref: String) { val date = LocalDate.ofEpochDay(d.day).format(DateTimeFormatter.ofPattern("EEE d MMM")) - val note = if (d.valid) null else AccuracyReportText.dayNote(d.note, ref) ?: "not counted" + // A counted day still says so when it was compared over only the hours both devices were on. + val note = if (d.valid) AccuracyReportText.dayNote(d.note?.takeIf { it.startsWith(com.pulseloop.health.accuracy.AccuracyScorer.NOTE_SHARED_PREFIX) }, ref) + else AccuracyReportText.dayNote(d.note, ref) ?: tr("not counted") val text = when (m.kind) { ComparisonMetric.Kind.DAILY -> { val diff = AccuracyComparison.diff(m, d.ringValue, d.refValue) diff --git a/app/src/test/java/com/pulseloop/health/accuracy/AccuracyComparisonTest.kt b/app/src/test/java/com/pulseloop/health/accuracy/AccuracyComparisonTest.kt index 7469f6d6..61178616 100644 --- a/app/src/test/java/com/pulseloop/health/accuracy/AccuracyComparisonTest.kt +++ b/app/src/test/java/com/pulseloop/health/accuracy/AccuracyComparisonTest.kt @@ -277,4 +277,48 @@ class AccuracyComparisonTest { assertTrue(text, text.contains("Steps: −19 % on average, consistently low (4 days)")) assertFalse(text, text.contains("7123") || text.contains("7,123") || text.contains("8765") || text.contains("8,765")) } + + // ── wear coverage ── + + @Test + fun aDeviceThatStopsAtThreeIsOffFromThenToTheEndOfTheDay() { + // Heart rate every 5 minutes from midnight until 15:00, then nothing. + val hr = (0 until 15 * 12).map { day0 + it * 5 * min } + val gaps = AccuracyComparison.offGaps(hr, day0, day0 + 24 * h) + assertEquals(1, gaps.size) + assertEquals(day0 + 15 * h - 5 * min, gaps[0].first) + assertEquals(day0 + 24 * h, gaps[0].last) + } + + @Test + fun anHourlyMonitorIsQuietNotOff() { + val hr = (0..24).map { day0 + it * h } + assertTrue(AccuracyComparison.offGaps(hr, day0, day0 + 24 * h).isEmpty()) + assertTrue(AccuracyComparison.judgeable(hr)) + } + + @Test + fun sparseOrMissingHeartRateCannotBeJudged() { + assertFalse(AccuracyComparison.judgeable(emptyList())) + // Every three hours: too sparse to tell a flat battery from a quiet afternoon. + assertFalse(AccuracyComparison.judgeable((0..20).map { day0 + it * 3 * h })) + } + + @Test + fun totalsAreCutToTheTimeBothDevicesWereOn() { + // A watch that counted 600 steps an hour all day; the ring was off from 15:00. + val items = (0 until 24).map { AccuracyComparison.IntervalAmount(day0 + it * h, day0 + (it + 1) * h, 600.0) } + val off = listOf((day0 + 15 * h)..(day0 + 24 * h)) + assertEquals(15 * 600.0, AccuracyComparison.amountWithin(items, day0, day0 + 24 * h, off), 1e-6) + // Half an interval inside a gap counts half. + val half = listOf((day0 + 30 * min)..(day0 + h)) + assertEquals(300.0, AccuracyComparison.amountWithin(items.take(1), day0, day0 + 24 * h, half), 1e-6) + } + + @Test + fun overlappingGapsFromBothDevicesAreCountedOnce() { + val gaps = listOf((day0 + h)..(day0 + 3 * h), (day0 + 2 * h)..(day0 + 4 * h)) + assertEquals(3 * h, AccuracyComparison.gapMs(gaps, day0, day0 + 24 * h)) + assertEquals(listOf((day0 + h)..(day0 + 4 * h)), AccuracyComparison.merge(gaps)) + } } diff --git a/docs/accuracy-check-plan.md b/docs/accuracy-check-plan.md index e4b25a3f..26ea0e66 100644 --- a/docs/accuracy-check-plan.md +++ b/docs/accuracy-check-plan.md @@ -38,6 +38,21 @@ the screen (foreground) and from the worker when Health Connect allows backgroun **Scoring** (`AccuracyScorer`, foreground, re-read at most every 30 min unless "Recompute"): - Daily totals count only whole local days inside the window. A day is dropped when the reference has fewer than 500 steps or the ring has none (not worn on both). +- **Wear coverage (added 2026-10-23).** A device that went flat or was charged partway through a + day passed the 500-step test, so the other device read as over-counting by everything after. + Each device's off stretches now come from the gaps in its own data: no heart rate, steps, sleep + or SpO₂ for over 90 min (`AccuracyComparison.offGaps`). Only a device that logs heart rate at + least every 75 min is judged (`judgeable`); otherwise it is taken as worn throughout, as before. + - A day with any off stretch is compared over the time both covered: the reference's step and + distance records and the ring's 15-minute buckets, each cut to the shared hours + (`amountWithin`). Active calories can't be cut (the ring keeps one daily figure), so a partly + worn day leaves them out. Under 12 shared hours the day doesn't count at all. + - A night either device stopped inside for 15 min or more (over the span both nights cover) is + dropped for sleep, resting heart rate and HRV. + - Heart rate and SpO₂ were already safe: they pair readings minutes apart, so time one device + was off simply yields no pairs. + - The day rows say which device was off and from when ("Fitbit stopped mid-night at 03:10"), + and a counted partial day says how many hours it was compared over. - A day is scored once the reference has delivered past its end, or 24 h after it ends. Until then it shows "waiting for ". - Sleep: the ring's longest session per waking day vs the reference's, by time asleep, onset and