//! How samples become a day's one number: raw quantity samples (the //! export's) by [`QuantityDays`], and the category samples every source //! sends as intervals (sleep, mindful sessions, stand hours, menstrual flow) //! by [`fold_intervals`]. use std::collections::{BTreeMap, BTreeSet}; use super::catalog::{self, Fold, Metric, SleepStage}; use super::rows::{DayRow, Instant, Source}; /// A category sample's value: HealthKit's raw number, or the export's word. #[derive(Debug, Clone, PartialEq)] pub enum CategoryValue { Raw(i64), Word(String), } /// One category sample. #[derive(Debug, Clone, PartialEq)] pub struct Interval { /// The HealthKit category type. pub healthkit: String, pub value: CategoryValue, pub start: Instant, pub end: Instant, /// The app or watch that recorded it. pub device: Option, } fn stage_of(value: &CategoryValue) -> Option { match value { CategoryValue::Raw(raw) => SleepStage::of_raw(*raw), CategoryValue::Word(word) => SleepStage::of_word(word), } } /// Stood in this hour? (`HKCategoryValueAppleStandHour.stood` is 0.) fn stood(value: &CategoryValue) -> bool { match value { CategoryValue::Raw(raw) => *raw == 0, CategoryValue::Word(word) => word == "HKCategoryValueAppleStandHourStood", } } /// The flow a menstrual sample logs, as `state` says it, with its weight /// (a day keeps its heaviest). HealthKit: unspecified 1, light 2, medium 3, /// heavy 4, none 5; the export says `HKCategoryValueVaginalBleedingLight` /// (older exports `HKCategoryValueMenstrualFlowLight`). fn flow(value: &CategoryValue) -> Option<(u8, &'static str)> { let word = match value { CategoryValue::Raw(1) => "Unspecified", CategoryValue::Raw(2) => "Light", CategoryValue::Raw(3) => "Medium", CategoryValue::Raw(4) => "Heavy", CategoryValue::Raw(5) => "None", CategoryValue::Raw(_) => return None, CategoryValue::Word(word) => word.strip_prefix("HKCategoryValueVaginalBleeding").or_else(|| word.strip_prefix("HKCategoryValueMenstrualFlow"))?, }; Some(match word { "None" => (0, "none"), "Unspecified" => (1, "unspecified"), "Light" => (2, "light"), "Medium" => (3, "medium"), "Heavy" => (4, "heavy"), _ => return None, }) } /// Minutes covered by `spans` (start, end in ms), overlaps counted once. pub fn union_minutes(spans: &mut [(i64, i64)]) -> f64 { spans.sort(); let mut total = 0i64; let mut current: Option<(i64, i64)> = None; for &(start, end) in spans.iter() { if end <= start { continue; } match current { Some((open, close)) if start <= close => current = Some((open, close.max(end))), Some((open, close)) => { total += close - open; current = Some((start, end)); } None => current = Some((start, end)), } } if let Some((open, close)) = current { total += close - open; } total as f64 / 60_000.0 } fn day_row(metric: &'static Metric, day: &str, value: Option, samples: usize, state: Option, source: Source) -> DayRow { DayRow { metric: metric.key, day: day.to_string(), value, min: None, max: None, samples: Some(samples as i64), state, source } } /// The day rows `intervals` make. Sleep lands on the day it ends (the /// morning you woke), mindful minutes, stand hours and flow on the day they /// start. Stages merge across sources: a watch and a phone saying the same /// night count it once, and `sleep_asleep` is every asleep stage merged. pub fn fold_intervals(intervals: &[Interval], source: Source) -> Vec { // (metric, day) -> spans; stand hours: (day) -> hours; flow: day -> heaviest. let mut spans: BTreeMap<(&'static str, String), Vec<(i64, i64)>> = BTreeMap::new(); let mut hours: BTreeMap> = BTreeMap::new(); let mut flows: BTreeMap = BTreeMap::new(); let mut counts: BTreeMap<(&'static str, String), usize> = BTreeMap::new(); for interval in intervals { let span = (interval.start.ms, interval.end.ms); match interval.healthkit.as_str() { catalog::SLEEP => { let Some(stage) = stage_of(&interval.value) else { continue }; let day = interval.end.day.clone(); if let Some(metric) = catalog::METRICS.iter().find(|metric| metric.stage == Some(stage)) { spans.entry((metric.key, day.clone())).or_default().push(span); } if stage.is_asleep() && stage != SleepStage::Asleep { spans.entry(("sleep_asleep", day)).or_default().push(span); } } catalog::MINDFUL => spans.entry(("mindful_minutes", interval.start.day.clone())).or_default().push(span), catalog::STAND_HOUR => { let held = hours.entry(interval.start.day.clone()).or_default(); if stood(&interval.value) { held.insert(interval.start.hour); } } catalog::MENSTRUAL_FLOW => { let Some((weight, word)) = flow(&interval.value) else { continue }; let held = flows.entry(interval.start.day.clone()).or_insert((weight, word, 0)); if weight > held.0 { *held = (weight, word, held.2); } held.2 += 1; } other => { // Every other category, by its metric's fold: minutes of // sessions merged, or a count, on the day each starts. for metric in catalog::METRICS.iter().filter(|metric| metric.healthkit == other) { match metric.fold { Fold::Minutes => spans.entry((metric.key, interval.start.day.clone())).or_default().push(span), Fold::Count => *counts.entry((metric.key, interval.start.day.clone())).or_default() += 1, _ => {} } } } } } let mut out = Vec::new(); for ((key, day), count) in counts { let metric = catalog::metric_of(key).expect("a catalogue metric"); out.push(day_row(metric, &day, Some(count as f64), count, None, source)); } for ((key, day), mut held) in spans { let metric = catalog::metric_of(key).expect("a catalogue metric"); let count = held.len(); let minutes = union_minutes(&mut held); out.push(day_row(metric, &day, Some(minutes), count, None, source)); } let stand = catalog::metric_of("stand_hours").expect("stand hours"); for (day, held) in hours { out.push(day_row(stand, &day, Some(held.len() as f64), held.len(), None, source)); } let menstrual = catalog::metric_of("menstrual_flow").expect("menstrual flow"); for (day, (_, word, count)) in flows { out.push(day_row(menstrual, &day, None, count, Some(word.to_string()), source)); } order(&mut out); out } /// Rows in the catalogue's order within each day, days ascending. pub fn order(rows: &mut [DayRow]) { let place = |metric: &str| catalog::METRICS.iter().position(|known| known.key == metric).unwrap_or(usize::MAX); rows.sort_by(|a, b| a.day.cmp(&b.day).then(place(a.metric).cmp(&place(b.metric)))); } #[derive(Debug, Default, Clone)] struct Tally { sum: f64, count: i64, min: Option, max: Option, latest: Option<(i64, f64)>, } impl Tally { fn add(&mut self, at_ms: i64, value: f64) { self.sum += value; self.count += 1; self.min = Some(self.min.map_or(value, |min| min.min(value))); self.max = Some(self.max.map_or(value, |max| max.max(value))); if self.latest.is_none_or(|(at, _)| at_ms >= at) { self.latest = Some((at_ms, value)); } } } /// Raw quantity samples folded into days, per source, as the export /// reader meets them. #[derive(Debug, Default)] pub struct QuantityDays { tallies: BTreeMap<(&'static str, String, String), Tally>, } impl QuantityDays { /// One sample of `metric`, already in its unit, made on `day`. pub fn add(&mut self, metric: &'static Metric, day: &str, device: &str, at_ms: i64, value: f64) { self.tallies.entry((metric.key, day.to_string(), device.to_string())).or_default().add(at_ms, value); } /// The day rows: a sum keeps its fullest source's total, an average every /// sample's mean with their least and most, a latest the last reading. pub fn rows(self, source: Source) -> Vec { let mut by_day: BTreeMap<(&'static str, String), Vec> = BTreeMap::new(); for ((metric, day, _), tally) in self.tallies { by_day.entry((metric, day)).or_default().push(tally); } let mut out = Vec::new(); for ((key, day), tallies) in by_day { let metric = catalog::metric_of(key).expect("a catalogue metric"); let count: i64 = tallies.iter().map(|tally| tally.count).sum(); let min = tallies.iter().filter_map(|tally| tally.min).reduce(f64::min); let max = tallies.iter().filter_map(|tally| tally.max).reduce(f64::max); let row = match metric.fold { Fold::Sum => { let fullest = tallies.iter().map(|tally| tally.sum).fold(0.0, f64::max); DayRow { metric: key, day, value: Some(fullest), min: None, max: None, samples: Some(count), state: None, source } } Fold::Average => { let sum: f64 = tallies.iter().map(|tally| tally.sum).sum(); DayRow { metric: key, day, value: Some(sum / count as f64), min, max, samples: Some(count), state: None, source } } Fold::Latest => { let latest = tallies.iter().filter_map(|tally| tally.latest).max_by_key(|(at, _)| *at).map(|(_, value)| value); DayRow { metric: key, day, value: latest, min, max, samples: Some(count), state: None, source } } _ => continue, }; out.push(row); } out } }