Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<metric>` (`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.

Expand Down
9 changes: 9 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/pulseloop/data/dao/Daos.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<List<ComparisonReadingEntity>>

/** 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)
}
156 changes: 139 additions & 17 deletions app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)
}
Expand All @@ -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<ReferenceMetric>,
refHr: List<TimedValue>, hrTolerance: Long, hrContextOf: (Long) -> HrContext?,
refStepItems: List<AccuracyComparison.IntervalAmount>, refSteps: Map<Long, Double>,
refGaps: List<LongRange>, fullDays: List<Long>, refNights: Map<Long, SleepNight>,
refSpo2: List<TimedValue>, delivered: (Long) -> Boolean,
): List<AccuracyCheckDayEntity> {
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<AccuracyCheckDayEntity>()
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"
Expand Down
Loading
Loading