diff --git a/AGENTS.md b/AGENTS.md index a4ceab3c..bfbe36ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -105,8 +105,12 @@ publishes events itself.** Full design: `docs/ring-comparison.md`. - **A driver publishes through `RingCommandWriter.publish`, not `PulseEventBus` directly.** The comparison client overrides it. A direct `PulseEventBus.publishBlocking` in a driver leaks a second ring of that family into the user's history. -- **`comparison_readings` is read by the comparison screen only.** Never by a score, chart, - export or the coach, and not in the backup. +- **`comparison_readings` is read by the comparison screen and the accuracy check only.** The + check grades the second ring against the same reference and stores its rows as + `CMP:` (`ComparisonRingScoring`), so the main ring's report cards, corrections and + export pause never see them. Never read by a score, chart, export or the coach, and not in the + backup. Corrections stay the main ring's: the second ring's numbers aren't used anywhere to + correct. - **Stop comparing forgets without unbinding** (`clearSavedRing`, not `forget`), so the ring stays paired to its own app. diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index ff5250d4..892d0dd9 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -314,6 +314,7 @@ "Body fat {0}%": "Gordura corporal {0}%", "Body metrics": "Medidas corporais", "Body temperature": "Temperatura corporal", + "Both rings against {0}": "Os dois anéis comparados com {0}", "Breakfast": "Café da manhã", "Breastfeeding and formula": "Amamentação e fórmula", "Breastfeeding only": "Só amamentação", @@ -398,6 +399,7 @@ "Clear demo data": "Limpar dados de demonstração", "Clear demo data?": "Limpar dados de demonstração?", "Clear plan": "Limpar plano", + "Closer to {0}: the main ring on {1}, the second ring on {2}, about the same on {3}.": "Mais próximo de {0}: o anel principal em {1}, o segundo anel em {2}, empatados em {3}.", "Coach": "Coach", "Coach Check-Ins": "Check-ins do coach", "Coach Memory": "Memória do coach", @@ -623,6 +625,7 @@ "EARLIER": "ANTERIORES", "ESTIMATED": "ESTIMADO", "Each night is compared with your own previous four weeks once there are two weeks to compare with. ": "Cada noite é comparada com suas próprias quatro semanas anteriores assim que houver duas semanas para comparar. ", + "Each ring's typical gap from {0}. Lower is closer.": "A diferença típica de cada anel em relação a {0}. Menor é mais próximo.", "Early bird": "Matutino", "Early evening, when you're under 70% of your step goal. Off in Rest Mode.": "No início da noite, quando você estiver abaixo de 70% da sua meta de passos. Desativado no Modo Descanso.", "Edit": "Editar", @@ -1061,7 +1064,9 @@ "MIN": "MIN", "MOOD CHECK-IN": "CHECK-IN DE HUMOR", "MY WEEK": "MINHA SEMANA", + "Main": "Principal", "Main ring": "Anel principal", + "Main ring is closer": "O anel principal está mais próximo", "Major signs": "Sinais fortes", "Make me a plan from my lab reports, starting with {0}.": "Monte um plano para mim a partir dos meus laudos, começando por {0}.", "Make me a plan from my lab reports.": "Monte um plano para mim a partir dos meus laudos.", @@ -1245,6 +1250,7 @@ "Not enough data for this period.": "Dados insuficientes para este período.", "Not enough data yet — battery history builds up as the ring reports its level.": "Dados insuficientes por enquanto — o histórico de bateria se forma à medida que o anel informa o nível.", "Not enough data yet: ": "Dados insuficientes por enquanto: ", + "Not enough days from both rings yet to say which is closer.": "Ainda não há dias suficientes dos dois anéis para dizer qual está mais próximo.", "Not enough free space. Free about {0} MB and try again.": "Sem espaço livre suficiente. Libere cerca de {0} MB e tente de novo.", "Not enough monthly data": "Dados mensais insuficientes", "Not enough nights yet": "Noites insuficientes por enquanto", @@ -1587,6 +1593,8 @@ "Screens in bed": "Telas na cama", "Screens that have moved to it so far: Today, Vitals, Sleep, Activity, Nutrition, My Health, Readiness, Symptom Radar, Settings and its screens.": "Telas que já usam o novo visual: Hoje, Vitais, Sono, Atividade, Nutrição, Minha saúde, Prontidão, Radar de sintomas, Configurações e suas telas.", "Searching…": "Procurando…", + "Second": "Segundo", + "Second ring is closer": "O segundo anel está mais próximo", "See Raw Packets above.": "Veja Pacotes brutos acima.", "See Ring Events above.": "Veja Eventos do anel acima.", "See and edit recent drinks": "Ver e editar bebidas recentes", @@ -2218,6 +2226,7 @@ "ring {0}": "anel {0}", "saved": "economizado", "score {0}": "pontuação {0}", + "second": "segundo", "sleep {0} h": "sono {0} h", "sleep {0}{1} min": "sono {0}{1} min", "steady": "estável", diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index 84a13eb8..7ab767ce 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -1210,6 +1210,10 @@ interface ComparisonDao { @Query("SELECT * FROM comparison_readings WHERE deviceAddress = :address AND timestamp BETWEEN :start AND :end ORDER BY timestamp") fun rangeFlow(address: String, start: Long, end: Long): Flow> + /** The comparison ring that recorded most in [start, end]: the one an accuracy check grades. */ + @Query("SELECT deviceAddress FROM comparison_readings WHERE timestamp BETWEEN :start AND :end GROUP BY deviceAddress ORDER BY COUNT(*) DESC LIMIT 1") + suspend fun mostRecordedAddress(start: Long, end: Long): String? + @Query("DELETE FROM comparison_readings WHERE deviceAddress = :address") suspend fun clear(address: String) } 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 5fab1bbe..6c659eb4 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt @@ -330,26 +330,29 @@ object AccuracyScorer { // ── Heart rate, paired sample by sample and split rest / active. var echo: EchoCheck? = null - 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 = 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 -> - when { - workouts.any { t >= it.startedAt && t <= it.endedAt!! } -> HrContext.ACTIVE - sleepWindows.any { t in it } -> HrContext.REST - else -> { - val steps = buckets[t - Math.floorMod(t, 15 * 60_000L)]?.steps ?: 0 - when { - steps >= ACTIVE_BUCKET_STEPS -> HrContext.ACTIVE - steps < REST_BUCKET_STEPS -> HrContext.REST - else -> null - } + // Rest or active at a moment: a recorded workout, a night, or the main ring's steps in that + // quarter hour. Shared with the comparison ring, which is worn by the same person. + val hrBuckets = ringBuckets.associateBy { it.startEpoch } + val hrWorkouts = db.activitySessionDao().finishedSince(from).filter { it.endedAt != null && it.startedAt < to } + val hrSleepWindows = ringNights.values.map { it.session.startAt..it.session.endAt } + val hrContextOf: (Long) -> HrContext? = { t -> + when { + hrWorkouts.any { t >= it.startedAt && t <= it.endedAt!! } -> HrContext.ACTIVE + hrSleepWindows.any { t in it } -> HrContext.REST + else -> { + val steps = hrBuckets[t - Math.floorMod(t, 15 * 60_000L)]?.steps ?: 0 + when { + steps >= ACTIVE_BUCKET_STEPS -> HrContext.ACTIVE + steps < REST_BUCKET_STEPS -> HrContext.REST + else -> null } } } + } + val hrTolerance = AccuracyComparison.tolerance(ReferenceSurveyBuilder.medianInterval(refHr.map { it.at }), 60_000L, 150_000L) + if (ReferenceMetric.HEART_RATE in compared && refHr.isNotEmpty()) { + echo = ReferenceSurveyBuilder.echoCheck(refHr, ringHr) + val pairs = AccuracyComparison.pair(ringHr, refHr, hrTolerance, zone, hrContextOf) for ((key, sums) in pairs) { val (day, ctx) = key val dayEnd = LocalDate.ofEpochDay(day).plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() @@ -376,6 +379,17 @@ object AccuracyScorer { } } + // ── The comparison ring, graded against the same reference (docs/ring-comparison.md). + rows += scoreComparisonRing( + db = db, checkId = check.id, from = from, to = to, readFrom = readFrom, readTo = readTo, + coverageEnd = coverageEnd, zone = zone, now = now, compared = compared, + refHr = refHr, hrTolerance = hrTolerance, hrContextOf = hrContextOf, + refStepItems = refStepItems, refSteps = refSteps, refGaps = refGaps, fullDays = fullDays, + refNights = refNights.mapValues { (_, r) -> toNight(r) }, + refSpo2 = ref.spo2.map { TimedValue(it.time.toEpochMilli(), it.percentage.value) }.sortedBy { it.at }, + delivered = ::delivered, + ) + echo?.let { rows += AccuracyCheckDayEntity(checkId = check.id, metric = ECHO_ROW, day = 0, pairs = it.compared, inBand = it.matching, valid = false, computedAt = now) } @@ -387,6 +401,114 @@ object AccuracyScorer { return Result.Scored(rows.size, waiting, echo) } + /** + * The comparison ring's rows for this check, tagged [ComparisonRingScoring.PREFIX]: steps, + * heart rate at rest and when active, SpO₂, and time asleep / fell asleep / woke up, by the + * same rules as the main ring's. Its wear gaps come from its own data. Empty when no second + * ring was worn during the check. + */ + private suspend fun scoreComparisonRing( + db: PulseLoopDatabase, checkId: String, from: Long, to: Long, readFrom: Long, readTo: Long, + coverageEnd: Long, zone: ZoneId, now: Long, compared: Set, + refHr: List, hrTolerance: Long, hrContextOf: (Long) -> HrContext?, + refStepItems: List, refSteps: Map, + refGaps: List, fullDays: List, refNights: Map, + refSpo2: List, delivered: (Long) -> Boolean, + ): List { + val cdao = db.comparisonDao() + val address = cdao.mostRecordedAddress(from, to) ?: return emptyList() + val hrAll = cdao.range(address, MeasurementKind.HEART_RATE.name, readFrom, readTo) + val hr = hrAll.filter { it.timestamp in from..to }.map { TimedValue(it.timestamp, it.value) }.sortedBy { it.at } + val buckets = cdao.range(address, com.pulseloop.service.ComparisonReadings.STEPS, readFrom, readTo) + val totals = cdao.range(address, com.pulseloop.service.ComparisonReadings.STEPS_TOTAL, readFrom, readTo) + val sleep = cdao.range(address, com.pulseloop.service.ComparisonReadings.SLEEP, readFrom, readTo) + val spo2 = cdao.range(address, MeasurementKind.SPO2.name, from, to).filter { it.value in 70.0..100.0 } + .map { TimedValue(it.timestamp, it.value) }.sortedBy { it.at } + val out = mutableListOf() + fun add(row: AccuracyCheckDayEntity) { out += ComparisonRingScoring.tag(row) } + + // When the comparison ring was off, from the gaps in its own data. + val evidence = buildList { + hrAll.forEach { add(it.timestamp) } + buckets.filter { it.value > 0 }.forEach { add(it.timestamp); add(it.timestamp + BUCKET_MS) } + sleep.forEach { add(it.timestamp); add(it.timestamp + 60_000L) } + } + val gaps = if (AccuracyComparison.judgeable(hrAll.map { it.timestamp })) + AccuracyComparison.offGaps(evidence, from, coverageEnd) else emptyList() + + if (ReferenceMetric.STEPS in compared) { + val bucketItems = buckets.map { AccuracyComparison.IntervalAmount(it.timestamp, it.timestamp + BUCKET_MS, it.value) } + val daily = ComparisonRingScoring.dailySteps(buckets.map { it.timestamp to it.value }, totals.associate { it.timestamp to it.value }, zone) + for (day in fullDays) { + val dayStart = java.time.LocalDate.ofEpochDay(day).atStartOfDay(zone).toInstant().toEpochMilli() + val dayEnd = java.time.LocalDate.ofEpochDay(day).plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() + val isDelivered = delivered(dayEnd) + val ringDay = daily[day] + val worn = (refSteps[day] ?: 0.0) >= MIN_REF_STEPS && (ringDay ?: 0.0) > 0 + val off = AccuracyComparison.gapsWithin(gaps + refGaps, dayStart, dayEnd) + val sharedMs = (dayEnd - dayStart) - AccuracyComparison.gapMs(off, dayStart, dayEnd) + val partial = off.isNotEmpty() + val tooPartial = partial && sharedMs < MIN_SHARED_MS + val ringSteps = if (partial) AccuracyComparison.amountWithin(bucketItems, dayStart, dayEnd, off) else ringDay + val refCompared = if (partial) AccuracyComparison.amountWithin(refStepItems, dayStart, dayEnd, off) else refSteps[day] + val note = when { + !isDelivered -> NOTE_WAITING + !worn -> NOTE_NOT_WORN + tooPartial -> NOTE_PARTLY_WORN_PREFIX + WHO_RING + ":" + (off.firstOrNull()?.first ?: dayStart) + partial -> "$NOTE_SHARED_PREFIX${sharedMs / 60_000L}" + else -> null + } + add(AccuracyComparison.dailyRow(checkId, ComparisonMetric.STEPS, day, ringSteps, refCompared, isDelivered && worn && !tooPartial, note, now)) + } + } + + if (ReferenceMetric.HEART_RATE in compared && refHr.isNotEmpty() && hr.isNotEmpty()) { + for ((key, sums) in AccuracyComparison.pair(hr, refHr, hrTolerance, zone, hrContextOf)) { + val (day, ctx) = key + val dayEnd = java.time.LocalDate.ofEpochDay(day).plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() + val metric = if (ctx == HrContext.REST) ComparisonMetric.HR_REST else ComparisonMetric.HR_ACTIVE + val isDelivered = delivered(minOf(dayEnd, to)) + val enough = sums.n >= if (ctx == HrContext.REST) MIN_HR_PAIRS_PER_DAY else 5 + add(AccuracyComparison.pairedRow(checkId, metric, day, sums, isDelivered && enough, now, + when { !isDelivered -> NOTE_WAITING; !enough -> NOTE_FEW_PAIRS; else -> null })) + } + } + + if (ReferenceMetric.OXYGEN_SATURATION in compared && refSpo2.isNotEmpty() && spo2.isNotEmpty()) { + for ((key, sums) in AccuracyComparison.pair(spo2, refSpo2, 5 * 60_000L, zone) { Unit }) { + val day = key.first + val dayEnd = java.time.LocalDate.ofEpochDay(day).plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli() + val isDelivered = delivered(minOf(dayEnd, to)) + add(AccuracyComparison.pairedRow(checkId, ComparisonMetric.SPO2, day, sums, + isDelivered && sums.n >= MIN_SPO2_PAIRS_PER_DAY, now, if (!isDelivered) NOTE_WAITING else null)) + } + } + + if (ReferenceMetric.SLEEP in compared) { + val nights = ComparisonRingScoring.nights(sleep.map { it.timestamp to it.value.toInt() }, zone) + .filter { (_, n) -> n.start >= from && n.end <= to } + for ((day, night) in nights) { + val dayMidnight = java.time.LocalDate.ofEpochDay(day).atStartOfDay(zone).toInstant().toEpochMilli() + val refNight = refNights[day] + val isDelivered = delivered(night.end) + val spanStart = minOf(night.start, refNight?.start ?: night.start) + val spanEnd = maxOf(night.end, refNight?.end ?: night.end) + val offMs = AccuracyComparison.gapMs(AccuracyComparison.gapsWithin(gaps + refGaps, spanStart, spanEnd), spanStart, spanEnd) + val note = when { + !isDelivered -> NOTE_WAITING + refNight == null -> NOTE_NO_REF_NIGHT + offMs >= NIGHT_OFF_MIN_MS -> NOTE_NIGHT_OFF_PREFIX + WHO_RING + ":" + spanStart + else -> null + } + val valid = note == null + add(AccuracyComparison.dailyRow(checkId, ComparisonMetric.SLEEP_ASLEEP, day, night.asleepMinutes.toDouble(), refNight?.asleepMinutes?.toDouble(), valid, note, now)) + add(AccuracyComparison.dailyRow(checkId, ComparisonMetric.SLEEP_ONSET, day, minutesFrom(dayMidnight, night.onset), refNight?.let { minutesFrom(dayMidnight, it.onset) }, valid, note, now)) + add(AccuracyComparison.dailyRow(checkId, ComparisonMetric.SLEEP_WAKE, day, minutesFrom(dayMidnight, night.wake), refNight?.let { minutesFrom(dayMidnight, it.wake) }, valid, note, now)) + } + } + return out + } + const val ECHO_ROW = "ECHO" const val NOTE_WAITING = "waiting" const val NOTE_NOT_WORN = "not_worn" diff --git a/app/src/main/java/com/pulseloop/health/accuracy/ComparisonRingScoring.kt b/app/src/main/java/com/pulseloop/health/accuracy/ComparisonRingScoring.kt new file mode 100644 index 00000000..e586c795 --- /dev/null +++ b/app/src/main/java/com/pulseloop/health/accuracy/ComparisonRingScoring.kt @@ -0,0 +1,77 @@ +package com.pulseloop.health.accuracy + +import com.pulseloop.data.entity.AccuracyCheckDayEntity +import com.pulseloop.ring.SleepStage +import com.pulseloop.util.TimeUtil +import java.time.ZoneId +import kotlin.math.abs + +/** + * The accuracy check for the second ring (docs/ring-comparison.md, "Graded against a watch"). The + * comparison ring is scored against the same reference in the same check, so the owner sees which + * of his two rings is closer to the watch he trusts. + * + * Its rows sit in `accuracy_check_days` beside the main ring's, under [PREFIX] + the metric name, + * so everything that reads the main ring's rows (the report cards, corrections, the export pause) + * never sees them. Pure, so it is unit-tested (`ComparisonRingScoringTest`). + */ +object ComparisonRingScoring { + const val PREFIX = "CMP:" + + fun tag(row: AccuracyCheckDayEntity) = row.copy(metric = PREFIX + row.metric) + + /** The comparison ring's rows, renamed back to plain metric names for [AccuracyComparison.summarize]. */ + fun comparisonRows(days: List) = + days.filter { it.metric.startsWith(PREFIX) }.map { it.copy(metric = it.metric.removePrefix(PREFIX)) } + + /** One night from the comparison ring's per-minute sleep rows. */ + data class Night(val start: Long, val end: Long, val asleepMinutes: Int, val onset: Long, val wake: Long) + + /** + * Nights by waking epoch day, from `(minute start, SleepStage ordinal)` rows. A night with no + * asleep minute is dropped. Onset is the first asleep minute, wake the end of the last. + */ + fun nights(minutes: List>, zone: ZoneId): Map = + minutes.groupBy { AccuracyComparison.epochDay(TimeUtil.wakingDayLocal(it.first, zone), zone) } + .mapNotNull { (day, rows) -> + val asleep = rows.filter { it.second != SleepStage.AWAKE.ordinal }.map { it.first }.sorted() + if (asleep.isEmpty()) return@mapNotNull null + day to Night( + start = rows.minOf { it.first }, end = rows.maxOf { it.first } + MINUTE, + asleepMinutes = asleep.size, onset = asleep.first(), wake = asleep.last() + MINUTE, + ) + }.toMap() + + /** + * Steps per local epoch day: the larger of the 15-minute buckets' sum and the ring's own + * running total for that day ([totals], keyed by the day's local start), since a sync can + * deliver one before the other. + */ + fun dailySteps(buckets: List>, totals: Map, zone: ZoneId): Map { + val fromBuckets = buckets.groupBy { AccuracyComparison.epochDay(it.first, zone) }.mapValues { (_, b) -> b.sumOf { it.second } } + val fromTotals = totals.mapKeys { AccuracyComparison.epochDay(it.key, zone) } + return (fromBuckets.keys + fromTotals.keys).associateWith { maxOf(fromBuckets[it] ?: 0.0, fromTotals[it] ?: 0.0) } + } + + enum class Closer { MAIN, COMPARISON, SIMILAR } + + /** + * Which ring sat closer to the reference on one metric, by the typical gap ([AccuracyComparison.Summary.mae]). + * Null unless both have enough data. "Similar" when the two gaps are within a fifth of the + * metric's band or 10 % of each other: a smaller difference than that isn't worth a winner. + */ + fun closer(main: AccuracyComparison.Summary?, cmp: AccuracyComparison.Summary?): Closer? { + if (main == null || cmp == null) return null + if (main.verdict == AccuracyComparison.Verdict.NOT_ENOUGH_DATA || cmp.verdict == AccuracyComparison.Verdict.NOT_ENOUGH_DATA) return null + val a = main.mae + val b = cmp.mae + val margin = maxOf(main.band * 0.2, 0.1 * maxOf(a, b)) + return when { + abs(a - b) <= margin -> Closer.SIMILAR + a < b -> Closer.MAIN + else -> Closer.COMPARISON + } + } + + private const val MINUTE = 60_000L +} 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 d0a9f5c2..d5207752 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt @@ -1,5 +1,11 @@ package com.pulseloop.ui.screens +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.heightIn +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.contentDescription import com.pulseloop.ui.i18n.trf import com.pulseloop.ui.components.PulseButtonStyle import com.pulseloop.ui.components.PulseButton @@ -167,6 +173,8 @@ internal fun AccuracyReportSection( } } + BothRingsCard(check, days, bands) + summaries.forEach { s -> MetricCard( check = check, @@ -457,3 +465,65 @@ internal fun AccuracyCorrectionsCard() { Text(tr("Applied to what PulseLoop shows, never to stored readings or Health Connect."), fontSize = 12.sp, color = PulseColors.textMuted) } } + + +/** + * Both rings against the reference (docs/ring-comparison.md, "Graded against a watch"): each + * ring's typical gap from it, metric by metric, the closer one in bold, and the tally in words. + * Shown only when a second ring was worn during the check. The cards below stay the main ring's. + */ +@Composable +internal fun BothRingsCard(check: AccuracyCheckEntity, days: List, bands: Map) { + val cmpDays = com.pulseloop.health.accuracy.ComparisonRingScoring.comparisonRows(days) + if (cmpDays.none { it.valid }) return + val metrics = listOf( + ComparisonMetric.HR_REST, ComparisonMetric.HR_ACTIVE, ComparisonMetric.STEPS, ComparisonMetric.SPO2, + ComparisonMetric.SLEEP_ASLEEP, ComparisonMetric.SLEEP_ONSET, ComparisonMetric.SLEEP_WAKE, + ).filter { m -> cmpDays.any { it.metric == m.name } || days.any { it.metric == m.name } } + val rows = metrics.map { m -> + val band = bands[m] ?: m.band + val main = days.takeIf { d -> d.any { it.metric == m.name } }?.let { AccuracyComparison.summarize(m, it, band) } + val cmp = cmpDays.takeIf { d -> d.any { it.metric == m.name } }?.let { AccuracyComparison.summarize(m, it, band) } + Triple(m, main to cmp, com.pulseloop.health.accuracy.ComparisonRingScoring.closer(main, cmp)) + } + val c = com.pulseloop.health.accuracy.ComparisonRingScoring.Closer.entries.associateWith { k -> rows.count { it.third == k } } + AccuracyCard { + Text(trf("Both rings against {0}", check.referenceLabel), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = com.pulseloop.ui.calm.Look.text) + Text(trf("Each ring's typical gap from {0}. Lower is closer.", check.referenceLabel), fontSize = 12.sp, color = com.pulseloop.ui.calm.Look.textMuted) + Row(Modifier.fillMaxWidth()) { + Spacer(Modifier.weight(1f)) + Text(tr("Main"), fontSize = 12.sp, color = com.pulseloop.ui.calm.Look.textSecondary, textAlign = TextAlign.End, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.width(104.dp)) + Text(tr("Second"), fontSize = 12.sp, color = com.pulseloop.ui.calm.Look.textSecondary, textAlign = TextAlign.End, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.width(104.dp)) + } + rows.forEach { (m, pair, closer) -> + val (main, cmp) = pair + fun cell(s: AccuracyComparison.Summary?) = + if (s == null || s.verdict == Verdict.NOT_ENOUGH_DATA) "—" else AccuracyReportText.magnitude(m, s.mae) + val mainWins = closer == com.pulseloop.health.accuracy.ComparisonRingScoring.Closer.MAIN + val cmpWins = closer == com.pulseloop.health.accuracy.ComparisonRingScoring.Closer.COMPARISON + Row( + Modifier.fillMaxWidth().heightIn(min = 40.dp).semantics(mergeDescendants = true) { + contentDescription = m.label + ": " + tr("main") + " " + cell(main) + ", " + tr("second") + " " + cell(cmp) + + when { mainWins -> ". " + tr("Main ring is closer"); cmpWins -> ". " + tr("Second ring is closer"); else -> "" } + }, + verticalAlignment = Alignment.CenterVertically, + ) { + Text(m.label, fontSize = 14.sp, color = com.pulseloop.ui.calm.Look.text, modifier = Modifier.weight(1f)) + Text(cell(main), fontSize = 14.sp, fontWeight = if (mainWins) FontWeight.Bold else FontWeight.Normal, + color = if (mainWins) com.pulseloop.ui.calm.Look.text else com.pulseloop.ui.calm.Look.textSecondary, + textAlign = TextAlign.End, maxLines = 1, softWrap = false, modifier = Modifier.width(104.dp)) + Text(cell(cmp), fontSize = 14.sp, fontWeight = if (cmpWins) FontWeight.Bold else FontWeight.Normal, + color = if (cmpWins) com.pulseloop.ui.calm.Look.text else com.pulseloop.ui.calm.Look.textSecondary, + textAlign = TextAlign.End, maxLines = 1, softWrap = false, modifier = Modifier.width(104.dp)) + } + } + val main = c[com.pulseloop.health.accuracy.ComparisonRingScoring.Closer.MAIN] ?: 0 + val second = c[com.pulseloop.health.accuracy.ComparisonRingScoring.Closer.COMPARISON] ?: 0 + val same = c[com.pulseloop.health.accuracy.ComparisonRingScoring.Closer.SIMILAR] ?: 0 + Text( + if (main + second + same == 0) tr("Not enough days from both rings yet to say which is closer.") + else trf("Closer to {0}: the main ring on {1}, the second ring on {2}, about the same on {3}.", check.referenceLabel, main, second, same), + fontSize = 14.sp, color = com.pulseloop.ui.calm.Look.text, + ) + } +} diff --git a/app/src/test/java/com/pulseloop/health/accuracy/ComparisonRingScoringTest.kt b/app/src/test/java/com/pulseloop/health/accuracy/ComparisonRingScoringTest.kt new file mode 100644 index 00000000..dd96bcc0 --- /dev/null +++ b/app/src/test/java/com/pulseloop/health/accuracy/ComparisonRingScoringTest.kt @@ -0,0 +1,56 @@ +package com.pulseloop.health.accuracy + +import com.pulseloop.data.entity.AccuracyCheckDayEntity +import com.pulseloop.ring.SleepStage +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZoneOffset + +class ComparisonRingScoringTest { + private val zone: ZoneId = ZoneOffset.UTC + private fun at(d: Int, h: Int, m: Int = 0) = LocalDateTime.of(2026, 11, d, h, m).atZone(zone).toInstant().toEpochMilli() + + @Test + fun `comparison rows are kept apart and read back under plain names`() { + val main = AccuracyCheckDayEntity(checkId = "c", metric = "STEPS", day = 1) + val cmp = ComparisonRingScoring.tag(main) + assertEquals("CMP:STEPS", cmp.metric) + assertEquals(listOf("STEPS"), ComparisonRingScoring.comparisonRows(listOf(main, cmp)).map { it.metric }) + // The main ring's report filters by exact name, so it never sees the tagged row. + assertEquals(1, listOf(main, cmp).count { it.metric == "STEPS" }) + } + + @Test + fun `a night's onset, wake and asleep minutes come from its asleep minutes`() { + val start = at(17, 23, 0) + val minutes = (0 until 10).map { i -> + val stage = if (i < 2 || i == 9) SleepStage.AWAKE else SleepStage.LIGHT + (start + i * 60_000L) to stage.ordinal + } + val night = ComparisonRingScoring.nights(minutes, zone).values.single() + assertEquals(7, night.asleepMinutes) + assertEquals(start + 2 * 60_000L, night.onset) + assertEquals(start + 9 * 60_000L, night.wake) + } + + @Test + fun `daily steps take the larger of buckets and the ring's own total`() { + val day = at(17, 0) + val steps = ComparisonRingScoring.dailySteps(listOf(at(17, 9) to 1000.0, at(17, 10) to 500.0), mapOf(day to 1800.0), zone) + assertEquals(1800.0, steps.values.single(), 0.0) + } + + private fun summary(mae: Double, verdict: AccuracyComparison.Verdict = AccuracyComparison.Verdict.AGREES) = + AccuracyComparison.Summary(ComparisonMetric.HR_REST, verdict, 5, 0.0, 0.0, mae, 600, 0.0, null, 5.0) + + @Test + fun `the closer ring wins only by a real margin`() { + assertEquals(ComparisonRingScoring.Closer.MAIN, ComparisonRingScoring.closer(summary(3.0), summary(8.0))) + assertEquals(ComparisonRingScoring.Closer.COMPARISON, ComparisonRingScoring.closer(summary(8.0), summary(3.0))) + assertEquals(ComparisonRingScoring.Closer.SIMILAR, ComparisonRingScoring.closer(summary(4.0), summary(4.5))) + assertNull(ComparisonRingScoring.closer(summary(3.0), summary(8.0, AccuracyComparison.Verdict.NOT_ENOUGH_DATA))) + } +} diff --git a/audits/2026-11-18-accuracy-both-rings.md b/audits/2026-11-18-accuracy-both-rings.md new file mode 100644 index 00000000..03a59273 --- /dev/null +++ b/audits/2026-11-18-accuracy-both-rings.md @@ -0,0 +1,78 @@ +# Audit: the accuracy check grades both rings + +Date: 2026-11-18 · PR: see the PR linking this file · Auditor: Claude Code. +- **impeccable:** loaded and applied to the **rendered** card. It was drawn on the JVM with + Robolectric, using five days of sample results for both rings, at 1.0× and 1.3×. The harness is + local only. +- **Device check:** owed. +- **ux-user-flows, graphic-design-fundamentals, less-is-more:** applied by hand. + +## Scope + +The owner wears a JRing (main) and a Colmi R06 (comparison) with a Huawei watch, and asked for the +accuracy check to grade both rings against the watch. Scoring: `AccuracyScorer.scoreComparisonRing`, +`ComparisonRingScoring`. UI: one new card at the top of the check's report, "Both rings against +[reference]". Nothing else on the screen changes. + +## ux-user-flows (§13 flow review checklist) + +- **Entry:** unchanged. Start a check as before; open its report. +- **Steps:** none added. The second ring is graded automatically when one was worn during the + check. +- **States:** + - no second ring, or none with valid rows: the card is absent and the report is as before; + - not enough days from both: "Not enough days from both rings yet…"; + - a measure only one ring has: "—" for the other; + - a running check: the card fills as days arrive, like the rest. +- **Exits:** unchanged. + +## impeccable + +### Audit (native, on renders) + +| # | Dimension | Score | Key finding | +|---|---|---|---| +| 1 | Accessibility | 3 | Each row reads as one sentence naming both gaps and which ring is closer; the closer value is bold as well as brighter, so colour is never the only cue. TalkBack on device owed. | +| 2 | Performance | 4 | The summaries are computed from rows already loaded for the report. | +| 3 | Appearance & theming | 4 | `AccuracyCard`, Look tokens, sizes on the scale. | +| 4 | Platform conformance | 4 | Plain rows, no new controls. | +| 5 | Adaptivity | 4 | Fixed 104dp value columns, single-line values; the labels wrap. Checked at 1.3×. | +| | **Total** | **19/20** | | + +### Critique + +| # | Heuristic | Score | Key issue | +|---|---|---|---| +| 1 | Visibility of status | 4 | The tally answers the question asked. | +| 2 | Match real world | 4 | "Typical gap", "lower is closer". | +| 4 | Consistency | 4 | Same metric names and units as the cards below. | +| 8 | Minimalist | 4 | One card; the detailed cards stay the main ring's. | +| 10 | Help | 3 | Says what the numbers are; the report's own subtitle covers "not a lab measurement". | +| | **Total (of the five that apply)** | **19/20** | | + +### Polish (from the renders) + +- [fixed] At 1.3× "22.0 bpm" wrapped inside an 88dp column. The columns are 104dp now and the + values stay on one line. +- [P3] The column heads say "Main" and "Second" rather than ring names; the names live on Compare + rings. Fine for one owner with two rings. + +No P0 or P1. + +## graphic-design-fundamentals (§13 checklist) + +- **Hierarchy:** title 16sp bold, then a 12sp explainer, the 14sp rows, and a 14sp tally. +- **Alignment:** two right-aligned numeric columns, matching across rows. +- **Colour:** no new colours; the closer value uses full-strength text, the other the secondary + colour. +- **Real size:** checked at 411dp, 1.0 and 1.3. + +## less-is-more + +| Element | Verdict | +|---|---| +| Second ring's per-measure cards and day detail | Left out: the card answers "which is closer"; detail stays on the main ring's cards | +| Second ring's corrections | Left out on purpose: its numbers aren't used anywhere | +| A winner per measure | Shown as bold, plus one tally line, not badges | + +No action gained a tap. diff --git a/docs/ring-comparison.md b/docs/ring-comparison.md index 9591ab45..1fea16ff 100644 --- a/docs/ring-comparison.md +++ b/docs/ring-comparison.md @@ -50,6 +50,30 @@ Per local day: It says plainly that neither ring is known to be right, and links the accuracy check for a watch. +## Graded against a watch ✅ + +The owner asked (2026-11-18) for the accuracy check to grade both rings. A running check now +scores the comparison ring against the same reference, in the same pass (`AccuracyScorer` → +`scoreComparisonRing`): +- **Measures:** heart rate at rest and when active (paired with the reference, same tolerance and + rest/active rule as the main ring), steps per day, SpO₂, and time asleep, fell asleep and woke + up. +- **Off time:** the comparison ring's off stretches come from its own data, and a day or night + either it or the reference was off is cut or dropped by the main ring's rules. +- **Storage:** its rows are stored as `CMP:` in `accuracy_check_days`, so nothing that + reads the main ring's rows sees them (`ComparisonRingScoring`). +- **Which ring:** the comparison ring that recorded most during the check + (`ComparisonDao.mostRecordedAddress`). + +The report opens with **Both rings against [reference]**: +- each ring's typical gap from the reference per measure (lower is closer), with the closer one + in bold; +- a one-line tally of which ring was closer on how many measures, with "about the same" when the + two gaps are within a fifth of the measure's band or 10 % of each other + (`ComparisonRingScoring.closer`). + +The per-measure cards and corrections below stay the main ring's. + ## Not yet ⬜ - The background sync worker syncs only the main ring. The second ring catches up whenever the app