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
10 changes: 10 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -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}",
Expand Down Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Long>, from: Long, to: Long, maxGapMs: Long = OFF_GAP_MS): List<LongRange> {
val out = mutableListOf<LongRange>()
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<LongRange>): List<LongRange> {
val out = mutableListOf<LongRange>()
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<LongRange>, 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<LongRange>, from: Long, to: Long): List<LongRange> =
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<IntervalAmount>, from: Long, to: Long, gaps: List<LongRange>): 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<Long>): 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<Pair<Stage, Stage>, Int>) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading
Loading