dashboard/app/lib/health/cycle_model.dart
bashynx fb3c01cdd7 dashPi: a self-hosted home dashboard, its sync server and phone app
The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:56:19 +02:00

334 lines
15 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The cycle tracker's numbers — a port of the dashboard's plugins/cycle/views.py (keep them in
// step: same rules, same results as the web page) + db.save_day's rules for writing a day.
//
// Data: synced rows "cycle.day", id "day:YYYY-MM-DD": {day, period 0/1, flow 1–5, pain 1–5,
// pain_len, tags "a,b", note, source, updated}. Days are UTC dates here (no DST surprises).
import 'dart:math';
import '../sync/store.dart';
const history = 12; // cycles averaged (at most)
const halfLife = 180; // days: a cycle this much older counts half as much
const maxCycle = 60; // longer "cycles" are gaps in logging
const luteal = 14; // ovulation -> next period, days
const gap = 2; // unmarked days that don't split a period
const painLen = {'0-1': 'under 1 h', '1-3': '1–3 h', '3-6': '3–6 h', '6-24': '6–24 h'};
const tagGroups = {
'Symptoms': {
'spotting': 'Spotting', 'headache': 'Headache', 'backache': 'Backache', 'tiredness': 'Tiredness',
'bloating': 'Bloating', 'breasts': 'Tender breasts', 'acne': 'Acne', 'nausea': 'Nausea',
'cravings': 'Cravings', 'stomach': 'Upset stomach', 'sleep': 'Poor sleep', 'dizzy': 'Dizziness'},
'Mood': {
'happy': 'Happy', 'calm': 'Calm', 'energetic': 'Energetic', 'sensitive': 'Sensitive',
'irritable': 'Irritable', 'anxious': 'Anxious', 'sad': 'Sad', 'swings': 'Mood swings',
'stressed': 'Stressed', 'unmotivated': 'Unmotivated'},
'Sex': {
'sex_prot': 'Sex, protected', 'sex_unprot': 'Sex, unprotected', 'drive': 'Sex drive',
'drive_low': 'Low sex drive', 'solo': 'Masturbation', 'sex_pain': 'Pain during sex'},
};
const flowNames = ['very light', 'light', 'medium', 'heavy', 'very heavy'];
const sources = {
'xiaomi': ('⌚', 'Imported from Xiaomi (Mi Fitness)'),
'mymonthlycycles': ('📱', 'Imported from My Monthly Cycles'),
'calculated': ('≈', 'Calculated: not logged, placed between the periods around it'),
};
/// Calendar symbols for some tags: (tags, glyph, label); "spot" = a small droplet.
const symbols = [
({'sex_prot', 'sex_unprot'}, '♥', 'had sex'),
({'happy', 'calm', 'energetic'}, '☺', 'good mood'),
({'sensitive', 'irritable', 'anxious', 'sad', 'swings', 'stressed', 'unmotivated'}, '☹', 'low mood'),
({'spotting'}, 'spot', 'spotting'),
({'tiredness'}, '💤', 'tired'),
({'headache'}, '⚡', 'headache'),
];
DateTime day(DateTime d) => DateTime.utc(d.year, d.month, d.day);
/// Python's round(): halves go to the even number (round(28.5) == 28), so averages match the web page.
int pyRound(double x) {
final f = x.floorToDouble(), diff = x - f;
if (diff > 0.5) return f.toInt() + 1;
if (diff < 0.5) return f.toInt();
return f.toInt().isEven ? f.toInt() : f.toInt() + 1;
}
DateTime today() => day(DateTime.now());
DateTime parseDay(String s) => DateTime.parse('${s}T00:00:00Z');
String iso(DateTime d) => d.toIso8601String().substring(0, 10);
int daysBetween(DateTime a, DateTime b) => b.difference(a).inDays; // b - a
DateTime plus(DateTime d, int n) => d.add(Duration(days: n));
class CycleSettings {
const CycleSettings({this.cycleLength = 28, this.periodLength = 5, this.showFertile = true});
final int cycleLength, periodLength;
final bool showFertile;
}
class DayLog {
DayLog(this.row);
final Map<String, dynamic> row;
bool get period => (row['period'] ?? 0) == 1;
int? get flow => row['flow'] as int?;
int? get pain => row['pain'] as int?;
String? get painLength => row['pain_len'] as String?;
List<String> get tags => ((row['tags'] as String?) ?? '').split(',').where((t) => t.isNotEmpty).toList();
String get note => (row['note'] as String?) ?? '';
String? get source => row['source'] as String?;
bool get hasLog => pain != null || tags.isNotEmpty || note.isNotEmpty;
String summary() {
final names = {for (final g in tagGroups.values) ...g};
return [
if (pain != null) 'pain $pain/5${painLen[painLength] != null ? ' (${painLen[painLength]})' : ''}',
...tags.where(names.containsKey).map((t) => names[t]!),
if (note.isNotEmpty) note,
if (sources[source] != null) sources[source]!.$2,
].join(' · ');
}
List<(String, String)> get symbolList =>
[for (final (ts, g, label) in symbols) if (ts.intersection(tags.toSet()).isNotEmpty) (g, label)];
}
class Period {
Period(this.start, this.end, this.calc);
DateTime start, end;
bool calc;
int get length => daysBetween(start, end) + 1;
}
class CycleStats {
CycleStats(this.cycle, this.period, this.cycles, this.fromData);
final int cycle, period;
final List<int> cycles;
final bool fromData;
}
int _avg(List<(int, DateTime)> xs, int fallback, DateTime now) {
final last = xs.length > history ? xs.sublist(xs.length - history) : xs;
if (last.isEmpty) return fallback;
final w = [for (final (_, d) in last) pow(0.5, max(0, daysBetween(d, now)) / halfLife).toDouble()];
var s = 0.0;
for (var i = 0; i < last.length; i++) {
s += last[i].$1 * w[i];
}
return pyRound(s / w.reduce((a, b) => a + b));
}
/// Sorted period days -> runs; up to [gap] unmarked days inside one don't split it.
List<Period> periodsOf(List<DateTime> days, Set<DateTime> calc) {
final out = <Period>[];
for (final d in days) {
if (out.isNotEmpty && daysBetween(out.last.end, d) <= gap + 1) {
out.last.end = d;
out.last.calc = out.last.calc && calc.contains(d);
} else {
out.add(Period(d, d, calc.contains(d)));
}
}
return out;
}
bool going(Period p, DateTime now) => !p.end.isBefore(plus(now, -1));
/// (length, start of the next period) between consecutive logged periods.
List<(int, DateTime)> realCycles(List<Period> ps) => [
for (var i = 0; i + 1 < ps.length; i++)
if (!ps[i].calc && !ps[i + 1].calc) (daysBetween(ps[i].start, ps[i + 1].start), ps[i + 1].start)
];
CycleStats stats(List<Period> ps, CycleSettings s, DateTime now) {
final cyc = realCycles(ps);
final ok = [for (final c in cyc) if (c.$1 >= 15 && c.$1 <= maxCycle) c];
final lens = [for (final p in ps) if (!going(p, now) && !p.calc) (p.length, p.start)];
return CycleStats(_avg(ok, s.cycleLength, now), _avg(lens, s.periodLength, now), [for (final c in cyc) c.$1],
ok.isNotEmpty);
}
/// The next n predicted periods (start, end) + days late (0 = not late).
(List<(DateTime, DateTime)>, int) predict(List<Period> ps, CycleStats st, DateTime now, {int n = 4}) {
if (ps.isEmpty) return (const [], 0);
var next = plus(ps.last.start, st.cycle);
final late = next.isBefore(now) ? daysBetween(next, now) : 0;
if (late > 0) next = plus(now, st.cycle); // overdue: "any day now"; the one after counts from today
return ([for (var k = 0; k < n; k++) (plus(next, k * st.cycle), plus(next, k * st.cycle + st.period - 1))], late);
}
/// {day: "ovul" | "fertile"} before each given period start.
Map<DateTime, String> fertile(List<DateTime> starts) {
final out = <DateTime, String>{};
for (final a in starts) {
final ov = plus(a, -luteal);
for (var k = -5; k <= 1; k++) {
out[plus(ov, k)] = 'fertile';
}
out[ov] = 'ovul';
}
return out;
}
enum Status { empty, period, late, wait }
/// Everything the Cycle page shows, from the synced rows.
class CycleView {
CycleView(SyncStore store, this.s, {DateTime? now}) : now = now ?? today() {
for (final r in store.rows('cycle.day')) {
final d = parseDay(r['day'] as String);
logs[d] = DayLog(r);
}
final days = [for (final e in logs.entries) if (e.value.period) e.key]..sort();
marked = days.toSet();
final calc = {for (final e in logs.entries) if (e.value.source == 'calculated') e.key};
periods = periodsOf(days, calc);
st = stats(periods, s, this.now);
final (p, l) = predict(periods, st, this.now);
preds = p;
late = l;
final last = periods.isEmpty ? null : periods.last;
if (last != null) {
cycleDay = daysBetween(last.start, this.now) + 1;
status = going(last, this.now) ? Status.period : late > 0 ? Status.late : Status.wait;
}
predDays = {for (final (a, z) in preds) for (var k = 0; k <= daysBetween(a, z); k++) plus(a, k)};
if (status == Status.period) {
for (var k = 0; k < st.period; k++) {
if (plus(last!.start, k).isAfter(last.end)) predDays.add(plus(last.start, k));
}
}
final starts = [for (final (a, _) in preds) a];
if (last != null) starts.add(plus(last.start, st.cycle));
fert = s.showFertile ? fertile(starts) : {};
}
final CycleSettings s;
final DateTime now;
final logs = <DateTime, DayLog>{};
late final Set<DateTime> marked;
late final List<Period> periods;
late final CycleStats st;
late final List<(DateTime, DateTime)> preds;
late final int late;
late final Set<DateTime> predDays;
late final Map<DateTime, String> fert;
Status status = Status.empty;
int? cycleDay;
Period? get last => periods.isEmpty ? null : periods.last;
bool get todayOn => marked.contains(now);
DateTime? get expected => last == null ? null : plus(last!.start, st.cycle);
int? get daysToNext => preds.isEmpty ? null : daysBetween(now, preds.first.$1);
/// The fertile window that matters now (this cycle's if not over, else the next one's).
(DateTime, DateTime, DateTime)? fertileWindow() {
if (last == null || !s.showFertile) return null;
for (final a in [plus(last!.start, st.cycle), ...preds.map((p) => p.$1)]) {
final ov = plus(a, -luteal);
if (!plus(ov, 1).isBefore(now)) return (plus(ov, -5), plus(ov, 1), ov);
}
return null;
}
}
// ---- for a doctor (views.history's doctor part + views.flags) --------------------------------
const doctorMonths = 12;
class Doctor {
Doctor({required this.since, required this.now, required this.last, required this.periods, required this.cycle,
required this.cycleRange, required this.period, required this.periodRange, required this.symptoms,
required this.painDays, required this.painAvg, required this.flags});
final DateTime since, now;
final DateTime? last;
final int periods, painDays;
final int? cycle, period;
final (int, int)? cycleRange, periodRange;
final List<(String, int)> symptoms;
final double? painAvg;
final List<String> flags;
}
(int, int)? _spread(List<int> xs) => xs.isEmpty ? null : (xs.reduce(min), xs.reduce(max));
/// Things worth mentioning to a doctor (common guidance, not a diagnosis).
List<String> flags(List<Period> ps, List<int> cycles, Map<DateTime, DayLog> logs, DateTime now) {
final out = <String>[];
final within = cycles.where((c) => c <= maxCycle).toList(); // longer = a gap in logging
final recent = within.length > 6 ? within.sublist(within.length - 6) : within;
final short = recent.where((c) => c < 21).length, long = recent.where((c) => c > 35).length;
if (short >= 2) out.add('$short of the last ${recent.length} cycles were shorter than 21 days.');
if (long >= 2) out.add('$long of the last ${recent.length} cycles were longer than 35 days.');
if (recent.length >= 3 && recent.reduce(max) - recent.reduce(min) > 7) {
out.add('Cycle length varies a lot: ${recent.reduce(min)}–${recent.reduce(max)} days.');
}
final finished = ps.where((p) => !going(p, now)).toList();
final done = finished.length > 6 ? finished.sublist(finished.length - 6) : finished;
final longp = done.where((p) => p.length > 7).length;
if (longp > 0) out.add('$longp of the last ${done.length} periods lasted more than 7 days.');
bool inside(Period p, DateTime d) => !d.isBefore(p.start) && !d.isAfter(p.end);
final heavy = done.where((p) => logs.entries.where((e) => inside(p, e.key) && (e.value.flow ?? 0) >= 4).length >= 3).length;
if (heavy > 0) out.add('$heavy of the last ${done.length} periods had 3 or more heavy days.');
final since = plus(now, -90);
final spot = logs.entries.where((e) => !e.key.isBefore(since) && e.value.tags.contains('spotting') && !e.value.period).length;
if (spot > 0) out.add('Spotting between periods on $spot day${spot != 1 ? 's' : ''} in the last 3 months.');
final strong = logs.entries.where((e) => !e.key.isBefore(since) && (e.value.pain ?? 0) >= 4).length;
if (strong >= 3) out.add('Strong pain (4–5 of 5) on $strong days in the last 3 months.');
if (ps.isNotEmpty && daysBetween(ps.last.start, now) > 90) out.add('No period for ${daysBetween(ps.last.start, now)} days.');
return out;
}
Doctor doctor(CycleView v) {
final now = v.now, since = plus(now, -doctorMonths * 30);
final real = v.periods.where((p) => !p.calc).toList();
final dp = real.where((p) => !p.start.isBefore(since)).toList();
final dcycles = [
for (final (c, d) in realCycles(v.periods))
if (!d.isBefore(since) && c <= maxCycle && !plus(d, -c).isBefore(since)) c
];
final dlens = [for (final p in dp) if (!going(p, now)) p.length];
final names = {for (final g in tagGroups.values) ...g};
final counts = <String, int>{};
final pains = <int>[];
for (final e in v.logs.entries.where((e) => !e.key.isBefore(since))) {
for (final t in e.value.tags) {
if (tagGroups['Symptoms']!.containsKey(t) || tagGroups['Mood']!.containsKey(t)) counts[t] = (counts[t] ?? 0) + 1;
}
if (e.value.pain != null) pains.add(e.value.pain!);
}
final sym = [for (final e in counts.entries) (names[e.key]!, e.value)]..sort((a, b) => b.$2.compareTo(a.$2));
return Doctor(
since: dp.isNotEmpty && dp.first.start.isAfter(since) ? dp.first.start : since,
now: now,
last: real.isEmpty ? null : real.last.start,
periods: dp.length,
cycle: dcycles.isEmpty ? null : pyRound(dcycles.reduce((a, b) => a + b) / dcycles.length),
cycleRange: _spread(dcycles),
period: dlens.isEmpty ? null : pyRound(dlens.reduce((a, b) => a + b) / dlens.length),
periodRange: _spread(dlens),
symptoms: sym.take(10).toList(),
painDays: pains.length,
painAvg: pains.isEmpty ? null : pyRound(pains.reduce((a, b) => a + b) / pains.length * 10) / 10,
flags: flags(real, v.st.cycles, v.logs, now),
);
}
/// db.save_day: set the given fields of a day (the rest stay); a day with nothing left is deleted.
void saveDay(SyncStore store, DateTime d, Map<String, dynamic> fields) {
if (d.isAfter(today())) throw ArgumentError("That day hasn't happened yet.");
final u = 'day:${iso(d)}';
final row = store.row('cycle.day', u) ??
{'day': iso(d), 'period': 0, 'note': '', 'flow': null, 'pain': null, 'pain_len': null, 'tags': '', 'source': null};
row.addAll(fields);
if (fields.containsKey('tags')) {
final picked = (fields['tags'] as List).cast<String>().toSet();
row['tags'] = [for (final g in tagGroups.values) ...g.keys.where(picked.contains)].join(','); // stable order
}
final now = DateTime.now();
row['updated'] = '${iso(now)} ${now.toIso8601String().substring(11, 19)}';
final empty = row['period'] != 1 && (row['note'] ?? '') == '' && row['flow'] == null && row['pain'] == null &&
row['pain_len'] == null && (row['tags'] ?? '') == '';
if (empty) {
if (store.row('cycle.day', u) != null) store.delete('cycle.day', u);
} else {
store.put('cycle.day', u, row);
}
}