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
19 changes: 18 additions & 1 deletion app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ import com.pulseloop.data.entity.*
CoachGoalEntity::class,
FoodPreferenceEntity::class,
DrinkEntryEntity::class,
FindingEntity::class,
],
version = 32,
version = 33,
exportSchema = false,
)
abstract class PulseLoopDatabase : RoomDatabase() {
Expand Down Expand Up @@ -78,6 +79,8 @@ abstract class PulseLoopDatabase : RoomDatabase() {
abstract fun foodPreferenceDao(): FoodPreferenceDao
/** Drinks (docs/drinks-plan.md, v32). */
abstract fun drinkDao(): DrinkDao
/** "What changed" findings (v33). */
abstract fun findingDao(): FindingDao
abstract fun coachSummaryDao(): CoachSummaryDao
abstract fun wearableLogDao(): WearableLogDao
abstract fun rawPacketDao(): RawPacketDao
Expand Down Expand Up @@ -129,6 +132,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
"coach_goals",
"food_preferences",
"drink_entries",
"findings",
)

@Volatile private var INSTANCE: PulseLoopDatabase? = null
Expand Down Expand Up @@ -597,6 +601,18 @@ abstract class PulseLoopDatabase : RoomDatabase() {
}
}

/** v32 → v33: the "what changed" findings log. */
private val MIGRATION_32_33 = object : Migration(32, 33) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `findings` (`id` TEXT NOT NULL, `day` INTEGER NOT NULL, `kind` TEXT NOT NULL, " +
"`title` TEXT NOT NULL, `detail` TEXT NOT NULL, `positive` INTEGER NOT NULL, " +
"`algorithmVersion` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))"
)
db.execSQL("CREATE INDEX IF NOT EXISTS `index_findings_day` ON `findings` (`day`)")
}
}

private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) {
db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`")
db.execSQL(
Expand Down Expand Up @@ -695,6 +711,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
MIGRATION_29_30,
MIGRATION_30_31,
MIGRATION_31_32,
MIGRATION_32_33,
)
// Downgrades only (sideloading an older APK). A blanket destructive
// fallback would silently wipe every measurement, sleep session, and
Expand Down
15 changes: 15 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 @@ -965,3 +965,18 @@ interface DrinkDao {
@Query("DELETE FROM drink_entries")
suspend fun clear()
}

@Dao
interface FindingDao {
@Query("SELECT * FROM findings WHERE day >= :from ORDER BY day DESC, kind ASC")
fun sinceFlow(from: Long): Flow<List<FindingEntity>>

@Query("SELECT * FROM findings WHERE day >= :from ORDER BY day DESC, kind ASC")
suspend fun since(from: Long): List<FindingEntity>

@Query("DELETE FROM findings WHERE day >= :from AND algorithmVersion = :version")
suspend fun deleteWindow(from: Long, version: Int)

@Upsert
suspend fun upsertAll(rows: List<FindingEntity>)
}
16 changes: 16 additions & 0 deletions app/src/main/java/com/pulseloop/data/entity/CoreEntities.kt
Original file line number Diff line number Diff line change
Expand Up @@ -416,3 +416,19 @@ data class FoodPreferenceEntity(
fun idFor(slot: String, item: String, action: String) = "$slot:${item.trim().lowercase()}:$action"
}
}

/**
* One "what changed" finding (service/Findings.kt): one row per day and kind, stamped with the
* formula version that produced it. Derived and recomputable, so it isn't in the backup archive.
*/
@Entity(tableName = "findings", indices = [Index("day")])
data class FindingEntity(
@PrimaryKey val id: String,
val day: Long,
val kind: String,
val title: String,
val detail: String,
val positive: Boolean,
val algorithmVersion: Int,
val createdAt: Long = System.currentTimeMillis(),
)
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork
val local = Instant.ofEpochMilli(now).atZone(zone)
val today = local.toLocalDate()
val inputs = runCatching { ReadinessRepository.loadInputs(db, now, zone) }.getOrNull() ?: return Result.success()
// Keep the "what changed" log current even when the screen isn't opened.
runCatching { com.pulseloop.service.FindingsRepository.refresh(db, now, zone) }

// 1. Something's off — once a day, during waking hours, once last night has synced.
val night = inputs.lastNight
Expand Down
27 changes: 27 additions & 0 deletions app/src/main/java/com/pulseloop/service/Algorithms.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.pulseloop.service

/**
* The version of PulseLoop's scoring and insight formulas. Bump it whenever a change would make a
* past day's number differ if it were computed again. Findings are stamped with it, the "data
* behind this score" view shows it, and comparisons never reach back across a bump, so an app
* update is never reported as a change in the person (OpenStrap Edge's rule).
*/
object Algorithms {
const val VERSION = 3

/** What each version changed, newest first, for the data view. */
val HISTORY = listOf(
3 to "HRV withheld when sparse, flat or scattered; readiness withheld below half its weight; corrected journal statistics",
2 to "Readiness gained body temperature and recovery index; sleep scored against learned sleep need",
1 to "First readiness, sleep and activity scores",
)

/** When the current version first ran on this device; findings before it aren't compared across. */
fun firstRunOfCurrent(context: android.content.Context): Long {
val p = context.applicationContext.getSharedPreferences("algorithms", android.content.Context.MODE_PRIVATE)
if (p.getInt("version", 0) != VERSION) {
p.edit().putInt("version", VERSION).putLong("since", System.currentTimeMillis()).apply()
}
return p.getLong("since", System.currentTimeMillis())
}
}
133 changes: 133 additions & 0 deletions app/src/main/java/com/pulseloop/service/Findings.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package com.pulseloop.service

import java.time.LocalDate
import kotlin.math.abs
import kotlin.math.roundToInt

/*
* "What changed": each night compared with the user's own trailing history, written down so it
* can be browsed later instead of living only in a notification (OpenStrap Edge's findings log).
* A day where nothing stood out is a complete answer, not an empty state.
*/

data class Finding(
val day: LocalDate,
/** Stable per day: one row per kind per day, so a re-run replaces rather than duplicates. */
val kind: Kind,
val title: String,
val detail: String,
) {
enum class Kind(val positive: Boolean) {
RESTING_HR_UP(false), RESTING_HR_DOWN(true),
HRV_DOWN(false), HRV_UP(true),
TEMPERATURE_UP(false),
SLEEP_SHORT(false), SLEEP_LONGER(true),
RADAR(false),
}
}

object Findings {
/** Nights of history needed before any comparison is made. */
const val MIN_BASELINE = 14
private const val BASELINE_DAYS = 28L

private fun median(v: List<Double>): Double? {
if (v.isEmpty()) return null
val s = v.sorted(); val m = s.size / 2
return if (s.size % 2 == 1) s[m] else (s[m - 1] + s[m]) / 2
}

/** Median absolute deviation, floored so a very steady baseline can't make noise look big. */
private fun mad(v: List<Double>, floor: Double): Double {
val m = median(v) ?: return floor
return maxOf(median(v.map { abs(it - m) }) ?: floor, floor)
}

/**
* Findings for [day] (a waking day), from nights up to and including it. Recent windows are
* compared with the 28 nights before them; each detector needs a 14-night baseline and a
* change that is both big in absolute terms and large against the user's usual spread.
*/
fun forDay(day: LocalDate, nights: List<NightSummary>, radar: SymptomRadar.Level? = null): List<Finding> {
val upTo = nights.filter { !it.day.isAfter(day) }.sortedBy { it.day }
fun recent(n: Long) = upTo.filter { it.day.isAfter(day.minusDays(n)) }
fun baseline(n: Long) = upTo.filter { !it.day.isAfter(day.minusDays(n)) && it.day.isAfter(day.minusDays(n + BASELINE_DAYS)) }
val out = mutableListOf<Finding>()

// Resting heart rate: the last 3 nights against the 28 before.
run {
val now = recent(3).mapNotNull { it.restingHr }
val base = baseline(3).mapNotNull { it.restingHr }
if (now.size < 2 || base.size < MIN_BASELINE) return@run
val m = median(now)!!; val b = median(base)!!
val delta = m - b
if (delta >= 3 && delta >= 2 * mad(base, 1.0)) {
out += Finding(day, Finding.Kind.RESTING_HR_UP, "Resting heart rate up",
"${m.roundToInt()} bpm over the last 3 nights against your usual ${b.roundToInt()}. Illness, alcohol, stress, heat or hard training can all raise it.")
}
}
// Resting heart rate trending down over two weeks: usually fitness or recovery.
run {
val now = recent(14).mapNotNull { it.restingHr }
val base = baseline(14).mapNotNull { it.restingHr }
if (now.size < 10 || base.size < MIN_BASELINE) return@run
val delta = median(now)!! - median(base)!!
if (delta <= -3) {
out += Finding(day, Finding.Kind.RESTING_HR_DOWN, "Resting heart rate trending down",
"${abs(delta).roundToInt()} bpm lower over two weeks than the four before. Often a sign of improving fitness or recovery.")
}
}
// HRV: the last 3 nights against the 28 before.
run {
val now = recent(3).mapNotNull { it.hrv }
val base = baseline(3).mapNotNull { it.hrv }
if (now.size < 2 || base.size < MIN_BASELINE) return@run
val m = median(now)!!; val b = median(base)!!
if (b <= 0) return@run
if (m <= b * 0.85 && b - m >= 2 * mad(base, 2.0)) {
out += Finding(day, Finding.Kind.HRV_DOWN, "HRV lower than usual",
"${m.roundToInt()} ms over the last 3 nights against your usual ${b.roundToInt()} (${((m - b) / b * 100).roundToInt()}%). Your body may be under extra load.")
}
}
run {
val now = recent(14).mapNotNull { it.hrv }
val base = baseline(14).mapNotNull { it.hrv }
if (now.size < 10 || base.size < MIN_BASELINE) return@run
val m = median(now)!!; val b = median(base)!!
if (b > 0 && m >= b * 1.10) {
out += Finding(day, Finding.Kind.HRV_UP, "HRV trending up",
"${((m - b) / b * 100).roundToInt()}% higher over two weeks than the four before.")
}
}
// Skin temperature: last night against the 28 before.
run {
val t = upTo.lastOrNull { it.day == day }?.temperature ?: return@run
val base = baseline(1).mapNotNull { it.temperature }
if (base.size < MIN_BASELINE) return@run
val b = median(base)!!
val delta = t - b
if (delta >= 0.5 && delta >= 2 * mad(base, 0.1)) {
out += Finding(day, Finding.Kind.TEMPERATURE_UP, "Skin temperature up",
"+%.1f °C last night against your usual. Can come with illness, a late workout, alcohol or the menstrual cycle.".format(delta))
}
}
// Sleep: the last 7 nights against the 28 before.
run {
val now = recent(7).map { it.asleepMinutes.toDouble() }.filter { it > 0 }
val base = baseline(7).map { it.asleepMinutes.toDouble() }.filter { it > 0 }
if (now.size < 5 || base.size < MIN_BASELINE) return@run
val delta = now.average() - median(base)!!
if (delta <= -45) {
out += Finding(day, Finding.Kind.SLEEP_SHORT, "Sleeping less this week",
"${abs(delta).roundToInt()} min a night less than your usual over the last 7 nights.")
} else if (delta >= 45) {
out += Finding(day, Finding.Kind.SLEEP_LONGER, "Sleeping more this week",
"${delta.roundToInt()} min a night more than your usual over the last 7 nights.")
}
}
if (radar != null && radar != SymptomRadar.Level.NONE) {
out += Finding(day, Finding.Kind.RADAR, "Symptom Radar: ${radar.label.lowercase()}", radar.summary)
}
return out
}
}
41 changes: 41 additions & 0 deletions app/src/main/java/com/pulseloop/service/FindingsRepository.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.pulseloop.service

import com.pulseloop.data.PulseLoopDatabase
import com.pulseloop.data.entity.FindingEntity
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId

/** Recomputes the last [WINDOW_DAYS] of findings and stores them; older rows are history. */
object FindingsRepository {
const val WINDOW_DAYS = 30L

fun dayKey(d: LocalDate, zone: ZoneId) = d.atStartOfDay(zone).toInstant().toEpochMilli()
fun dateOf(ms: Long, zone: ZoneId): LocalDate = Instant.ofEpochMilli(ms).atZone(zone).toLocalDate()

suspend fun refresh(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()) {
val inputs = ReadinessRepository.loadInputs(db, now, zone)
val nights = inputs.history + listOfNotNull(inputs.lastNight)
val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate()
val radarToday = runCatching { HealthInsightsRepository.load(db, now, zone).radar?.level }.getOrNull()
val rows = (0 until WINDOW_DAYS).flatMap { back ->
val day = today.minusDays(back)
Findings.forDay(day, nights, radar = if (back == 0L) radarToday else null).map { f ->
FindingEntity(
id = "${dayKey(day, zone)}:${f.kind.name}",
day = dayKey(day, zone),
kind = f.kind.name,
title = f.title,
detail = f.detail,
positive = f.kind.positive,
algorithmVersion = Algorithms.VERSION,
)
}
}
val from = dayKey(today.minusDays(WINDOW_DAYS - 1), zone)
// Today's Symptom Radar row is only computed for today; keep earlier days' radar rows.
val keptRadar = db.findingDao().since(from).filter { it.kind == Finding.Kind.RADAR.name && it.day != dayKey(today, zone) }
db.findingDao().deleteWindow(from, Algorithms.VERSION)
db.findingDao().upsertAll(rows + keptRadar)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ object HealthInsightsRepository {
val expected = profile?.age?.let { CardioCapacity.expectedVo2(it, profile?.sex?.lowercase() == "female") }
val score = expected?.let { HealthArea.scoreOf(c.vo2max / it * 0.85) } ?: 60
add(HealthArea("Heart health", HealthArea.rate(score), score, weekly { it.restingHr },
"Cardio capacity ${c.level.label.lowercase()}" + (c.cardioAge?.let { ", cardiovascular age about $it" } ?: "")))
"Cardio capacity ${c.level.label.lowercase()}, estimated from resting heart rate and age"))
}
}

Expand Down
Loading
Loading