@sctg/openclaw-coach 0.1.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +296 -66
- package/assets/fonts/Inter_400Regular.ttf +0 -0
- package/assets/fonts/Inter_600SemiBold.ttf +0 -0
- package/assets/fonts/LICENSE.txt +93 -0
- package/assets/logo.png +0 -0
- package/assets/logo.svg +62 -0
- package/dist/charts/build.d.ts +71 -0
- package/dist/charts/build.js +276 -0
- package/dist/charts/labels.d.ts +38 -0
- package/dist/charts/labels.js +73 -0
- package/dist/charts/render.d.ts +10 -0
- package/dist/charts/render.js +26 -0
- package/dist/charts/svg.d.ts +47 -0
- package/dist/charts/svg.js +92 -0
- package/dist/config.d.ts +25 -0
- package/dist/config.js +38 -0
- package/dist/dates.d.ts +22 -0
- package/dist/dates.js +71 -0
- package/dist/garmin/gc.d.ts +25 -0
- package/dist/garmin/gc.js +81 -0
- package/dist/garmin/normalize.d.ts +20 -0
- package/dist/garmin/normalize.js +132 -0
- package/dist/index.js +188 -163
- package/dist/profile.d.ts +4 -0
- package/dist/profile.js +43 -0
- package/dist/science/associations.d.ts +56 -0
- package/dist/science/associations.js +102 -0
- package/dist/science/healthspan.d.ts +25 -0
- package/dist/science/healthspan.js +89 -0
- package/dist/science/hrv.d.ts +61 -0
- package/dist/science/hrv.js +119 -0
- package/dist/science/load.d.ts +107 -0
- package/dist/science/load.js +228 -0
- package/dist/science/performance.d.ts +93 -0
- package/dist/science/performance.js +191 -0
- package/dist/science/readiness.d.ts +47 -0
- package/dist/science/readiness.js +97 -0
- package/dist/science/recovery.d.ts +74 -0
- package/dist/science/recovery.js +173 -0
- package/dist/science/sleep.d.ts +79 -0
- package/dist/science/sleep.js +165 -0
- package/dist/science/stats.d.ts +50 -0
- package/dist/science/stats.js +201 -0
- package/dist/science/strength.d.ts +47 -0
- package/dist/science/strength.js +120 -0
- package/dist/store.d.ts +36 -0
- package/dist/store.js +78 -0
- package/dist/sync.d.ts +36 -0
- package/dist/sync.js +145 -0
- package/dist/tools.d.ts +427 -0
- package/dist/tools.js +721 -0
- package/dist/types.d.ts +143 -0
- package/dist/types.js +2 -0
- package/docs/SCIENCE.md +717 -0
- package/examples/ATHLETE-fr.md +72 -0
- package/examples/ATHLETE.md +74 -0
- package/examples/PLAN-fr.md +55 -0
- package/examples/PLAN.md +55 -0
- package/openclaw.plugin.json +152 -5
- package/package.json +14 -3
- package/skills/coach/SKILL.md +283 -208
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sleep: sufficiency against the individual need, running debt, continuity,
|
|
3
|
+
* and regularity of timing.
|
|
4
|
+
*
|
|
5
|
+
* - Need: Garmin's nightly personal need when the watch reports it, otherwise the
|
|
6
|
+
* configured need (default 8 h; adults need at least 7 h, Watson 2015; athletes
|
|
7
|
+
* often more, Walsh 2021).
|
|
8
|
+
* - Debt: running balance of (need - sleep) over the last 14 nights, floored at 0.
|
|
9
|
+
* Deficits accumulate (Van Dongen 2003) and are repaid slowly (Kitamura 2016).
|
|
10
|
+
* This balance is a bookkeeping heuristic, not a measured physiological quantity.
|
|
11
|
+
* - Regularity: Sleep Regularity Index (Phillips 2017) computed on the main sleep
|
|
12
|
+
* period, and the SD of sleep onset / midpoint (Huang 2020). Irregular sleep
|
|
13
|
+
* predicts mortality better than short sleep (Windred 2024).
|
|
14
|
+
* - Stages (deep/REM) are reported but not scored: wrist staging agrees only
|
|
15
|
+
* moderately with polysomnography (de Zambotti 2019, Chinoy 2021).
|
|
16
|
+
*/
|
|
17
|
+
import type { AlgorithmTag, DataStatus, DayRecord, Profile } from "../types.ts";
|
|
18
|
+
export declare const SLEEP_ALGORITHM: AlgorithmTag;
|
|
19
|
+
export declare const SLEEP_DEBT_NIGHTS = 14;
|
|
20
|
+
export declare const SLEEP_REGULARITY_NIGHTS = 14;
|
|
21
|
+
export type SleepNight = {
|
|
22
|
+
date: string;
|
|
23
|
+
durationH: number | null;
|
|
24
|
+
needH: number;
|
|
25
|
+
needSource: "garmin" | "profile";
|
|
26
|
+
/** Sleep duration divided by need. */
|
|
27
|
+
sufficiency: number | null;
|
|
28
|
+
/** Sleep time / (sleep time + awake time): continuity of the sleep period. */
|
|
29
|
+
efficiencyPct: number | null;
|
|
30
|
+
deepPct: number | null;
|
|
31
|
+
remPct: number | null;
|
|
32
|
+
awakeMin: number | null;
|
|
33
|
+
bedtime: string | null;
|
|
34
|
+
wakeTime: string | null;
|
|
35
|
+
garminScore: number | null;
|
|
36
|
+
};
|
|
37
|
+
export type SleepAnalysis = {
|
|
38
|
+
status: DataStatus;
|
|
39
|
+
algorithm: AlgorithmTag;
|
|
40
|
+
lastNight: SleepNight | null;
|
|
41
|
+
/** Running sleep debt in hours, and how it was built. */
|
|
42
|
+
debtH: number | null;
|
|
43
|
+
debtNights: number;
|
|
44
|
+
avg7H: number | null;
|
|
45
|
+
avg14H: number | null;
|
|
46
|
+
avgNeedH: number | null;
|
|
47
|
+
regularity: {
|
|
48
|
+
nights: number;
|
|
49
|
+
/** Sleep Regularity Index, 0-100 (main sleep period only). */
|
|
50
|
+
sri: number | null;
|
|
51
|
+
onsetSdMin: number | null;
|
|
52
|
+
wakeSdMin: number | null;
|
|
53
|
+
midpointSdMin: number | null;
|
|
54
|
+
meanBedtime: string | null;
|
|
55
|
+
meanWakeTime: string | null;
|
|
56
|
+
/** Midpoint difference between nights ending on Saturday/Sunday and other nights. */
|
|
57
|
+
socialJetlagMin: number | null;
|
|
58
|
+
} | null;
|
|
59
|
+
notes: string[];
|
|
60
|
+
};
|
|
61
|
+
export declare function describeNight(day: DayRecord | undefined, profile: Profile): SleepNight | null;
|
|
62
|
+
/** Running balance of need minus sleep; a night without data leaves the balance unchanged. */
|
|
63
|
+
export declare function sleepDebtHours(days: readonly DayRecord[], profile: Profile): {
|
|
64
|
+
debtH: number | null;
|
|
65
|
+
nights: number;
|
|
66
|
+
};
|
|
67
|
+
type Interval = {
|
|
68
|
+
date: string;
|
|
69
|
+
start: number;
|
|
70
|
+
end: number;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Sleep Regularity Index: probability of being in the same state (asleep/awake)
|
|
74
|
+
* at two times 24 h apart, rescaled to 0-100 (100 = identical days).
|
|
75
|
+
* Computed in closed form from the main sleep intervals of consecutive nights.
|
|
76
|
+
*/
|
|
77
|
+
export declare function sleepRegularityIndex(nights: readonly Interval[]): number | null;
|
|
78
|
+
export declare function analyzeSleep(days: readonly DayRecord[], profile: Profile): SleepAnalysis;
|
|
79
|
+
export {};
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sleep: sufficiency against the individual need, running debt, continuity,
|
|
3
|
+
* and regularity of timing.
|
|
4
|
+
*
|
|
5
|
+
* - Need: Garmin's nightly personal need when the watch reports it, otherwise the
|
|
6
|
+
* configured need (default 8 h; adults need at least 7 h, Watson 2015; athletes
|
|
7
|
+
* often more, Walsh 2021).
|
|
8
|
+
* - Debt: running balance of (need - sleep) over the last 14 nights, floored at 0.
|
|
9
|
+
* Deficits accumulate (Van Dongen 2003) and are repaid slowly (Kitamura 2016).
|
|
10
|
+
* This balance is a bookkeeping heuristic, not a measured physiological quantity.
|
|
11
|
+
* - Regularity: Sleep Regularity Index (Phillips 2017) computed on the main sleep
|
|
12
|
+
* period, and the SD of sleep onset / midpoint (Huang 2020). Irregular sleep
|
|
13
|
+
* predicts mortality better than short sleep (Windred 2024).
|
|
14
|
+
* - Stages (deep/REM) are reported but not scored: wrist staging agrees only
|
|
15
|
+
* moderately with polysomnography (de Zambotti 2019, Chinoy 2021).
|
|
16
|
+
*/
|
|
17
|
+
import { addDays, formatClock, localEpochMinutes, weekdayIndex } from "../dates.js";
|
|
18
|
+
import { isNum, mean, round, roundOrNull, sd } from "./stats.js";
|
|
19
|
+
export const SLEEP_ALGORITHM = {
|
|
20
|
+
id: "sleep-balance",
|
|
21
|
+
version: "1.0.0",
|
|
22
|
+
refs: ["watson2015", "walsh2021", "vandongen2003", "kitamura2016", "phillips2017", "windred2024", "huang2020", "dezambotti2019"],
|
|
23
|
+
};
|
|
24
|
+
export const SLEEP_DEBT_NIGHTS = 14;
|
|
25
|
+
export const SLEEP_REGULARITY_NIGHTS = 14;
|
|
26
|
+
const MIN_REGULARITY_NIGHTS = 5;
|
|
27
|
+
const MINUTES_PER_DAY = 1440;
|
|
28
|
+
function needSeconds(day, profile) {
|
|
29
|
+
const garmin = day.sleep?.needS;
|
|
30
|
+
// A need outside 5-11 h is treated as a payload unit problem, not as physiology.
|
|
31
|
+
if (isNum(garmin) && garmin >= 5 * 3600 && garmin <= 11 * 3600)
|
|
32
|
+
return { seconds: garmin, source: "garmin" };
|
|
33
|
+
return { seconds: profile.sleepNeedS, source: "profile" };
|
|
34
|
+
}
|
|
35
|
+
export function describeNight(day, profile) {
|
|
36
|
+
const sleep = day?.sleep;
|
|
37
|
+
if (!day || !sleep || !isNum(sleep.durationS))
|
|
38
|
+
return null;
|
|
39
|
+
const need = needSeconds(day, profile);
|
|
40
|
+
const awake = sleep.awakeS;
|
|
41
|
+
const pct = (part) => (isNum(part) && sleep.durationS ? round((part / sleep.durationS) * 100, 0) : null);
|
|
42
|
+
return {
|
|
43
|
+
date: day.date,
|
|
44
|
+
durationH: round(sleep.durationS / 3600, 2),
|
|
45
|
+
needH: round(need.seconds / 3600, 2),
|
|
46
|
+
needSource: need.source,
|
|
47
|
+
sufficiency: round(sleep.durationS / need.seconds, 2),
|
|
48
|
+
efficiencyPct: isNum(awake) ? round((sleep.durationS / (sleep.durationS + awake)) * 100, 0) : null,
|
|
49
|
+
deepPct: pct(sleep.deepS),
|
|
50
|
+
remPct: pct(sleep.remS),
|
|
51
|
+
awakeMin: isNum(awake) ? round(awake / 60, 0) : null,
|
|
52
|
+
bedtime: sleep.startLocal ? sleep.startLocal.slice(11, 16) : null,
|
|
53
|
+
wakeTime: sleep.endLocal ? sleep.endLocal.slice(11, 16) : null,
|
|
54
|
+
garminScore: sleep.score,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Running balance of need minus sleep; a night without data leaves the balance unchanged. */
|
|
58
|
+
export function sleepDebtHours(days, profile) {
|
|
59
|
+
let debt = 0;
|
|
60
|
+
let nights = 0;
|
|
61
|
+
for (const day of days.slice(-SLEEP_DEBT_NIGHTS)) {
|
|
62
|
+
const duration = day.sleep?.durationS;
|
|
63
|
+
if (!isNum(duration))
|
|
64
|
+
continue;
|
|
65
|
+
nights += 1;
|
|
66
|
+
debt = Math.max(0, debt + needSeconds(day, profile).seconds - duration);
|
|
67
|
+
}
|
|
68
|
+
return { debtH: nights >= 3 ? round(debt / 3600, 1) : null, nights };
|
|
69
|
+
}
|
|
70
|
+
function intervals(days) {
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const day of days) {
|
|
73
|
+
const start = localEpochMinutes(day.sleep?.startLocal);
|
|
74
|
+
const end = localEpochMinutes(day.sleep?.endLocal);
|
|
75
|
+
if (start !== null && end !== null && end > start && end - start < MINUTES_PER_DAY)
|
|
76
|
+
out.push({ date: day.date, start, end });
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Sleep Regularity Index: probability of being in the same state (asleep/awake)
|
|
82
|
+
* at two times 24 h apart, rescaled to 0-100 (100 = identical days).
|
|
83
|
+
* Computed in closed form from the main sleep intervals of consecutive nights.
|
|
84
|
+
*/
|
|
85
|
+
export function sleepRegularityIndex(nights) {
|
|
86
|
+
const agreements = [];
|
|
87
|
+
for (let index = 0; index + 1 < nights.length; index += 1) {
|
|
88
|
+
const a = nights[index];
|
|
89
|
+
const b = nights[index + 1];
|
|
90
|
+
if (addDays(a.date, 1) !== b.date)
|
|
91
|
+
continue;
|
|
92
|
+
const shiftedStart = b.start - MINUTES_PER_DAY;
|
|
93
|
+
const shiftedEnd = b.end - MINUTES_PER_DAY;
|
|
94
|
+
const overlap = Math.max(0, Math.min(a.end, shiftedEnd) - Math.max(a.start, shiftedStart));
|
|
95
|
+
const mismatch = a.end - a.start + (shiftedEnd - shiftedStart) - 2 * overlap;
|
|
96
|
+
agreements.push(1 - mismatch / MINUTES_PER_DAY);
|
|
97
|
+
}
|
|
98
|
+
if (agreements.length < MIN_REGULARITY_NIGHTS - 1)
|
|
99
|
+
return null;
|
|
100
|
+
return round(-100 + 200 * mean(agreements), 0);
|
|
101
|
+
}
|
|
102
|
+
/** Clock time as minutes relative to the midnight that starts the wake-up date. */
|
|
103
|
+
function relativeMinutes(night, which) {
|
|
104
|
+
const midnight = localEpochMinutes(`${night.date}T00:00:00`);
|
|
105
|
+
const value = which === "start" ? night.start : which === "end" ? night.end : (night.start + night.end) / 2;
|
|
106
|
+
return value - midnight;
|
|
107
|
+
}
|
|
108
|
+
export function analyzeSleep(days, profile) {
|
|
109
|
+
const notes = [];
|
|
110
|
+
const lastNight = describeNight(days[days.length - 1], profile);
|
|
111
|
+
const { debtH, nights: debtNights } = sleepDebtHours(days, profile);
|
|
112
|
+
const hours = (count) => {
|
|
113
|
+
const values = days
|
|
114
|
+
.slice(-count)
|
|
115
|
+
.map((day) => day.sleep?.durationS)
|
|
116
|
+
.filter(isNum)
|
|
117
|
+
.map((seconds) => seconds / 3600);
|
|
118
|
+
return values.length >= Math.ceil(count / 2) ? mean(values) : null;
|
|
119
|
+
};
|
|
120
|
+
const needs = days.slice(-SLEEP_DEBT_NIGHTS).filter((day) => isNum(day.sleep?.durationS)).map((day) => needSeconds(day, profile).seconds / 3600);
|
|
121
|
+
const recent = intervals(days.slice(-SLEEP_REGULARITY_NIGHTS));
|
|
122
|
+
let regularity = null;
|
|
123
|
+
if (recent.length >= MIN_REGULARITY_NIGHTS) {
|
|
124
|
+
const onsets = recent.map((night) => relativeMinutes(night, "start"));
|
|
125
|
+
const wakes = recent.map((night) => relativeMinutes(night, "end"));
|
|
126
|
+
const mids = recent.map((night) => relativeMinutes(night, "mid"));
|
|
127
|
+
const free = recent.filter((night) => weekdayIndex(night.date) >= 5).map((night) => relativeMinutes(night, "mid"));
|
|
128
|
+
const work = recent.filter((night) => weekdayIndex(night.date) < 5).map((night) => relativeMinutes(night, "mid"));
|
|
129
|
+
regularity = {
|
|
130
|
+
nights: recent.length,
|
|
131
|
+
sri: sleepRegularityIndex(recent),
|
|
132
|
+
onsetSdMin: roundOrNull(sd(onsets), 0),
|
|
133
|
+
wakeSdMin: roundOrNull(sd(wakes), 0),
|
|
134
|
+
midpointSdMin: roundOrNull(sd(mids), 0),
|
|
135
|
+
meanBedtime: formatClock(mean(onsets)),
|
|
136
|
+
meanWakeTime: formatClock(mean(wakes)),
|
|
137
|
+
socialJetlagMin: free.length >= 2 && work.length >= 2 ? round(Math.abs(mean(free) - mean(work)), 0) : null,
|
|
138
|
+
};
|
|
139
|
+
if (isNum(regularity.onsetSdMin) && regularity.onsetSdMin > 60) {
|
|
140
|
+
notes.push(`Bedtime varies by ${regularity.onsetSdMin} min (SD) over ${recent.length} nights: irregular timing.`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (lastNight) {
|
|
144
|
+
if (isNum(lastNight.durationH) && lastNight.durationH < 7)
|
|
145
|
+
notes.push(`Short night: ${lastNight.durationH} h (adults need at least 7 h).`);
|
|
146
|
+
if (isNum(lastNight.efficiencyPct) && lastNight.efficiencyPct < 85)
|
|
147
|
+
notes.push(`Fragmented night: sleep efficiency ${lastNight.efficiencyPct} %.`);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
notes.push("No sleep recorded for last night.");
|
|
151
|
+
}
|
|
152
|
+
const status = lastNight ? (debtNights >= 7 ? "ready" : "calibrating") : debtNights >= 7 ? "calibrating" : "insufficient_data";
|
|
153
|
+
return {
|
|
154
|
+
status,
|
|
155
|
+
algorithm: SLEEP_ALGORITHM,
|
|
156
|
+
lastNight,
|
|
157
|
+
debtH,
|
|
158
|
+
debtNights,
|
|
159
|
+
avg7H: roundOrNull(hours(7), 2),
|
|
160
|
+
avg14H: roundOrNull(hours(14), 2),
|
|
161
|
+
avgNeedH: roundOrNull(mean(needs), 2),
|
|
162
|
+
regularity,
|
|
163
|
+
notes,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small statistics toolbox used by every model. Pure functions, no dependency.
|
|
3
|
+
* `null` always means "no measurement": it is skipped, never read as 0.
|
|
4
|
+
*/
|
|
5
|
+
export type Maybe = number | null | undefined;
|
|
6
|
+
export declare function isNum(value: unknown): value is number;
|
|
7
|
+
export declare function valid(values: readonly Maybe[]): number[];
|
|
8
|
+
export declare function round(value: number, digits?: number): number;
|
|
9
|
+
export declare function roundOrNull(value: Maybe, digits?: number): number | null;
|
|
10
|
+
export declare function clamp(value: number, low: number, high: number): number;
|
|
11
|
+
export declare function sum(values: readonly number[]): number;
|
|
12
|
+
export declare function mean(values: readonly number[]): number | null;
|
|
13
|
+
/** Sample standard deviation (n - 1). Needs at least two values. */
|
|
14
|
+
export declare function sd(values: readonly number[]): number | null;
|
|
15
|
+
export declare function quantile(values: readonly number[], q: number): number | null;
|
|
16
|
+
export declare function median(values: readonly number[]): number | null;
|
|
17
|
+
/** Median absolute deviation scaled to estimate a standard deviation (x 1.4826). */
|
|
18
|
+
export declare function madSd(values: readonly number[]): number | null;
|
|
19
|
+
export type Baseline = {
|
|
20
|
+
center: number;
|
|
21
|
+
scale: number;
|
|
22
|
+
n: number;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Robust personal baseline: median and MAD-based SD, so that a few sick or
|
|
26
|
+
* hung-over nights do not widen the "normal" range. `scaleFloor` is the
|
|
27
|
+
* smallest scale accepted: it prevents a very regular person from getting
|
|
28
|
+
* huge z-scores out of measurement noise.
|
|
29
|
+
*/
|
|
30
|
+
export declare function robustBaseline(values: readonly Maybe[], scaleFloor: number, minN: number): Baseline | null;
|
|
31
|
+
export declare function zScore(value: Maybe, baseline: Baseline | null): number | null;
|
|
32
|
+
/** Standard normal cumulative distribution (Abramowitz & Stegun 7.1.26, |error| < 1.5e-7). */
|
|
33
|
+
export declare function normalCdf(z: number): number;
|
|
34
|
+
/**
|
|
35
|
+
* Exponentially weighted moving average with time constant `tau` (days):
|
|
36
|
+
* x[t] = x[t-1] + (v[t] - x[t-1]) * (1 - exp(-1 / tau)).
|
|
37
|
+
*/
|
|
38
|
+
export declare function ewma(values: readonly number[], tau: number, seed: number): number[];
|
|
39
|
+
/** Ordinary least squares slope of y against its index (units of y per step). */
|
|
40
|
+
export declare function slope(values: readonly Maybe[]): number | null;
|
|
41
|
+
/** Deterministic pseudo-random generator (mulberry32): resampling results are reproducible. */
|
|
42
|
+
export declare function seededRandom(seed: number): () => number;
|
|
43
|
+
/** Hedges' g: standardized mean difference (a - b) with the small-sample correction. */
|
|
44
|
+
export declare function hedgesG(a: readonly number[], b: readonly number[]): number | null;
|
|
45
|
+
/** Percentile bootstrap confidence interval of mean(a) - mean(b). */
|
|
46
|
+
export declare function bootstrapDiffCi(a: readonly number[], b: readonly number[], iterations?: number, level?: number, seed?: number): [number, number] | null;
|
|
47
|
+
/** Two-sided permutation p-value of the difference of means. */
|
|
48
|
+
export declare function permutationP(a: readonly number[], b: readonly number[], iterations?: number, seed?: number): number | null;
|
|
49
|
+
/** Benjamini-Hochberg adjusted p-values (false discovery rate), same order as the input. */
|
|
50
|
+
export declare function benjaminiHochberg(pValues: readonly number[]): number[];
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small statistics toolbox used by every model. Pure functions, no dependency.
|
|
3
|
+
* `null` always means "no measurement": it is skipped, never read as 0.
|
|
4
|
+
*/
|
|
5
|
+
export function isNum(value) {
|
|
6
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
7
|
+
}
|
|
8
|
+
export function valid(values) {
|
|
9
|
+
return values.filter(isNum);
|
|
10
|
+
}
|
|
11
|
+
export function round(value, digits = 1) {
|
|
12
|
+
const factor = 10 ** digits;
|
|
13
|
+
return Math.round(value * factor) / factor;
|
|
14
|
+
}
|
|
15
|
+
export function roundOrNull(value, digits = 1) {
|
|
16
|
+
return isNum(value) ? round(value, digits) : null;
|
|
17
|
+
}
|
|
18
|
+
export function clamp(value, low, high) {
|
|
19
|
+
return Math.min(high, Math.max(low, value));
|
|
20
|
+
}
|
|
21
|
+
export function sum(values) {
|
|
22
|
+
let total = 0;
|
|
23
|
+
for (const value of values)
|
|
24
|
+
total += value;
|
|
25
|
+
return total;
|
|
26
|
+
}
|
|
27
|
+
export function mean(values) {
|
|
28
|
+
return values.length ? sum(values) / values.length : null;
|
|
29
|
+
}
|
|
30
|
+
/** Sample standard deviation (n - 1). Needs at least two values. */
|
|
31
|
+
export function sd(values) {
|
|
32
|
+
if (values.length < 2)
|
|
33
|
+
return null;
|
|
34
|
+
const m = sum(values) / values.length;
|
|
35
|
+
let squares = 0;
|
|
36
|
+
for (const value of values)
|
|
37
|
+
squares += (value - m) ** 2;
|
|
38
|
+
return Math.sqrt(squares / (values.length - 1));
|
|
39
|
+
}
|
|
40
|
+
export function quantile(values, q) {
|
|
41
|
+
if (!values.length)
|
|
42
|
+
return null;
|
|
43
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
44
|
+
const position = (sorted.length - 1) * clamp(q, 0, 1);
|
|
45
|
+
const low = Math.floor(position);
|
|
46
|
+
const high = Math.ceil(position);
|
|
47
|
+
return sorted[low] + (sorted[high] - sorted[low]) * (position - low);
|
|
48
|
+
}
|
|
49
|
+
export function median(values) {
|
|
50
|
+
return quantile(values, 0.5);
|
|
51
|
+
}
|
|
52
|
+
/** Median absolute deviation scaled to estimate a standard deviation (x 1.4826). */
|
|
53
|
+
export function madSd(values) {
|
|
54
|
+
const center = median(values);
|
|
55
|
+
if (center === null || values.length < 2)
|
|
56
|
+
return null;
|
|
57
|
+
const deviation = median(values.map((value) => Math.abs(value - center)));
|
|
58
|
+
return deviation === null ? null : deviation * 1.4826;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Robust personal baseline: median and MAD-based SD, so that a few sick or
|
|
62
|
+
* hung-over nights do not widen the "normal" range. `scaleFloor` is the
|
|
63
|
+
* smallest scale accepted: it prevents a very regular person from getting
|
|
64
|
+
* huge z-scores out of measurement noise.
|
|
65
|
+
*/
|
|
66
|
+
export function robustBaseline(values, scaleFloor, minN) {
|
|
67
|
+
const clean = valid(values);
|
|
68
|
+
if (clean.length < minN)
|
|
69
|
+
return null;
|
|
70
|
+
const center = median(clean);
|
|
71
|
+
if (center === null)
|
|
72
|
+
return null;
|
|
73
|
+
// MAD is 0 when more than half the values are identical (integer heart rates):
|
|
74
|
+
// fall back on the interquartile range, then on the floor. The classic SD is
|
|
75
|
+
// never used: a few outliers would inflate it.
|
|
76
|
+
const mad = madSd(clean) ?? 0;
|
|
77
|
+
const iqr = (quantile(clean, 0.75) - quantile(clean, 0.25)) / 1.349;
|
|
78
|
+
const scale = Math.max(mad > 0 ? mad : iqr, scaleFloor);
|
|
79
|
+
return { center, scale, n: clean.length };
|
|
80
|
+
}
|
|
81
|
+
export function zScore(value, baseline) {
|
|
82
|
+
if (!isNum(value) || !baseline)
|
|
83
|
+
return null;
|
|
84
|
+
return (value - baseline.center) / baseline.scale;
|
|
85
|
+
}
|
|
86
|
+
/** Standard normal cumulative distribution (Abramowitz & Stegun 7.1.26, |error| < 1.5e-7). */
|
|
87
|
+
export function normalCdf(z) {
|
|
88
|
+
const x = Math.abs(z) / Math.SQRT2;
|
|
89
|
+
const t = 1 / (1 + 0.3275911 * x);
|
|
90
|
+
const poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t;
|
|
91
|
+
const erf = 1 - poly * Math.exp(-x * x);
|
|
92
|
+
return z >= 0 ? 0.5 * (1 + erf) : 0.5 * (1 - erf);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Exponentially weighted moving average with time constant `tau` (days):
|
|
96
|
+
* x[t] = x[t-1] + (v[t] - x[t-1]) * (1 - exp(-1 / tau)).
|
|
97
|
+
*/
|
|
98
|
+
export function ewma(values, tau, seed) {
|
|
99
|
+
const alpha = 1 - Math.exp(-1 / tau);
|
|
100
|
+
const out = [];
|
|
101
|
+
let current = seed;
|
|
102
|
+
for (const value of values) {
|
|
103
|
+
current += (value - current) * alpha;
|
|
104
|
+
out.push(current);
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
/** Ordinary least squares slope of y against its index (units of y per step). */
|
|
109
|
+
export function slope(values) {
|
|
110
|
+
const points = [];
|
|
111
|
+
values.forEach((value, index) => {
|
|
112
|
+
if (isNum(value))
|
|
113
|
+
points.push([index, value]);
|
|
114
|
+
});
|
|
115
|
+
if (points.length < 3)
|
|
116
|
+
return null;
|
|
117
|
+
const mx = sum(points.map((p) => p[0])) / points.length;
|
|
118
|
+
const my = sum(points.map((p) => p[1])) / points.length;
|
|
119
|
+
let num = 0;
|
|
120
|
+
let den = 0;
|
|
121
|
+
for (const [x, y] of points) {
|
|
122
|
+
num += (x - mx) * (y - my);
|
|
123
|
+
den += (x - mx) ** 2;
|
|
124
|
+
}
|
|
125
|
+
return den === 0 ? null : num / den;
|
|
126
|
+
}
|
|
127
|
+
/** Deterministic pseudo-random generator (mulberry32): resampling results are reproducible. */
|
|
128
|
+
export function seededRandom(seed) {
|
|
129
|
+
let state = seed >>> 0;
|
|
130
|
+
return () => {
|
|
131
|
+
state = (state + 0x6d2b79f5) >>> 0;
|
|
132
|
+
let t = state;
|
|
133
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
134
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
135
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/** Hedges' g: standardized mean difference (a - b) with the small-sample correction. */
|
|
139
|
+
export function hedgesG(a, b) {
|
|
140
|
+
const ma = mean(a);
|
|
141
|
+
const mb = mean(b);
|
|
142
|
+
const sa = sd(a);
|
|
143
|
+
const sb = sd(b);
|
|
144
|
+
if (ma === null || mb === null || sa === null || sb === null)
|
|
145
|
+
return null;
|
|
146
|
+
const df = a.length + b.length - 2;
|
|
147
|
+
const pooled = Math.sqrt(((a.length - 1) * sa ** 2 + (b.length - 1) * sb ** 2) / df);
|
|
148
|
+
if (pooled === 0)
|
|
149
|
+
return null;
|
|
150
|
+
return ((ma - mb) / pooled) * (1 - 3 / (4 * df - 1));
|
|
151
|
+
}
|
|
152
|
+
/** Percentile bootstrap confidence interval of mean(a) - mean(b). */
|
|
153
|
+
export function bootstrapDiffCi(a, b, iterations = 2000, level = 0.95, seed = 20261115) {
|
|
154
|
+
if (a.length < 2 || b.length < 2)
|
|
155
|
+
return null;
|
|
156
|
+
const random = seededRandom(seed);
|
|
157
|
+
const resampleMean = (values) => {
|
|
158
|
+
let total = 0;
|
|
159
|
+
for (let i = 0; i < values.length; i += 1)
|
|
160
|
+
total += values[Math.floor(random() * values.length)];
|
|
161
|
+
return total / values.length;
|
|
162
|
+
};
|
|
163
|
+
const diffs = [];
|
|
164
|
+
for (let i = 0; i < iterations; i += 1)
|
|
165
|
+
diffs.push(resampleMean(a) - resampleMean(b));
|
|
166
|
+
const tail = (1 - level) / 2;
|
|
167
|
+
return [quantile(diffs, tail), quantile(diffs, 1 - tail)];
|
|
168
|
+
}
|
|
169
|
+
/** Two-sided permutation p-value of the difference of means. */
|
|
170
|
+
export function permutationP(a, b, iterations = 5000, seed = 20261115) {
|
|
171
|
+
if (a.length < 2 || b.length < 2)
|
|
172
|
+
return null;
|
|
173
|
+
const observed = Math.abs(mean(a) - mean(b));
|
|
174
|
+
const pool = [...a, ...b];
|
|
175
|
+
const random = seededRandom(seed);
|
|
176
|
+
let extreme = 0;
|
|
177
|
+
for (let i = 0; i < iterations; i += 1) {
|
|
178
|
+
// Partial Fisher-Yates shuffle: the first a.length items form the permuted group.
|
|
179
|
+
for (let j = 0; j < a.length; j += 1) {
|
|
180
|
+
const k = j + Math.floor(random() * (pool.length - j));
|
|
181
|
+
[pool[j], pool[k]] = [pool[k], pool[j]];
|
|
182
|
+
}
|
|
183
|
+
const groupSum = sum(pool.slice(0, a.length));
|
|
184
|
+
const diff = Math.abs(groupSum / a.length - (sum(pool) - groupSum) / b.length);
|
|
185
|
+
if (diff >= observed - 1e-12)
|
|
186
|
+
extreme += 1;
|
|
187
|
+
}
|
|
188
|
+
return (extreme + 1) / (iterations + 1);
|
|
189
|
+
}
|
|
190
|
+
/** Benjamini-Hochberg adjusted p-values (false discovery rate), same order as the input. */
|
|
191
|
+
export function benjaminiHochberg(pValues) {
|
|
192
|
+
const order = pValues.map((p, index) => ({ p, index })).sort((x, y) => x.p - y.p);
|
|
193
|
+
const adjusted = new Array(pValues.length);
|
|
194
|
+
let running = 1;
|
|
195
|
+
for (let rank = order.length; rank >= 1; rank -= 1) {
|
|
196
|
+
const { p, index } = order[rank - 1];
|
|
197
|
+
running = Math.min(running, (p * order.length) / rank);
|
|
198
|
+
adjusted[index] = running;
|
|
199
|
+
}
|
|
200
|
+
return adjusted;
|
|
201
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strength sessions: volume load, estimated one-repetition maximum, weekly sets
|
|
3
|
+
* per muscle group.
|
|
4
|
+
*
|
|
5
|
+
* Deliberately descriptive. There is no "muscle freshness" score: no published
|
|
6
|
+
* model predicts local muscular recovery from sets and reps alone, and the watch
|
|
7
|
+
* records neither proximity to failure nor exercise technique.
|
|
8
|
+
*/
|
|
9
|
+
import type { AlgorithmTag } from "../types.ts";
|
|
10
|
+
export declare const STRENGTH_ALGORITHM: AlgorithmTag;
|
|
11
|
+
/** Epley (1985): 1RM = w x (1 + reps / 30). */
|
|
12
|
+
export declare function epley1Rm(weightKg: number, reps: number): number;
|
|
13
|
+
/** Brzycki (1993): 1RM = w x 36 / (37 - reps). */
|
|
14
|
+
export declare function brzycki1Rm(weightKg: number, reps: number): number;
|
|
15
|
+
/** Mean of both formulas; null above 10 repetitions, where they stop being accurate. */
|
|
16
|
+
export declare function estimated1Rm(weightKg: number, reps: number): number | null;
|
|
17
|
+
export type StrengthSet = {
|
|
18
|
+
category: string | null;
|
|
19
|
+
name: string | null;
|
|
20
|
+
reps: number | null;
|
|
21
|
+
weightKg: number | null;
|
|
22
|
+
durationS: number | null;
|
|
23
|
+
};
|
|
24
|
+
export type ExerciseSummary = {
|
|
25
|
+
exercise: string;
|
|
26
|
+
muscleGroup: string | null;
|
|
27
|
+
sets: number;
|
|
28
|
+
reps: number;
|
|
29
|
+
volumeKg: number | null;
|
|
30
|
+
topSet: {
|
|
31
|
+
weightKg: number;
|
|
32
|
+
reps: number;
|
|
33
|
+
} | null;
|
|
34
|
+
estimated1RmKg: number | null;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Reads Garmin's exercise-set payload. Garmin stores weights in grams; rest sets
|
|
38
|
+
* and sets without repetitions are skipped.
|
|
39
|
+
*/
|
|
40
|
+
export declare function parseExerciseSets(payload: unknown): StrengthSet[];
|
|
41
|
+
export declare function summarizeStrength(sets: readonly StrengthSet[]): {
|
|
42
|
+
exercises: ExerciseSummary[];
|
|
43
|
+
totalSets: number;
|
|
44
|
+
totalVolumeKg: number | null;
|
|
45
|
+
setsByMuscleGroup: Record<string, number>;
|
|
46
|
+
unidentifiedSets: number;
|
|
47
|
+
};
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strength sessions: volume load, estimated one-repetition maximum, weekly sets
|
|
3
|
+
* per muscle group.
|
|
4
|
+
*
|
|
5
|
+
* Deliberately descriptive. There is no "muscle freshness" score: no published
|
|
6
|
+
* model predicts local muscular recovery from sets and reps alone, and the watch
|
|
7
|
+
* records neither proximity to failure nor exercise technique.
|
|
8
|
+
*/
|
|
9
|
+
import { isNum, round } from "./stats.js";
|
|
10
|
+
export const STRENGTH_ALGORITHM = {
|
|
11
|
+
id: "strength-summary",
|
|
12
|
+
version: "1.0.0",
|
|
13
|
+
refs: ["epley1985", "brzycki1993", "schoenfeld2017", "acsm2009"],
|
|
14
|
+
};
|
|
15
|
+
/** Epley (1985): 1RM = w x (1 + reps / 30). */
|
|
16
|
+
export function epley1Rm(weightKg, reps) {
|
|
17
|
+
return reps <= 1 ? weightKg : weightKg * (1 + reps / 30);
|
|
18
|
+
}
|
|
19
|
+
/** Brzycki (1993): 1RM = w x 36 / (37 - reps). */
|
|
20
|
+
export function brzycki1Rm(weightKg, reps) {
|
|
21
|
+
return reps <= 1 ? weightKg : (weightKg * 36) / (37 - reps);
|
|
22
|
+
}
|
|
23
|
+
/** Mean of both formulas; null above 10 repetitions, where they stop being accurate. */
|
|
24
|
+
export function estimated1Rm(weightKg, reps) {
|
|
25
|
+
if (!(weightKg > 0) || !(reps >= 1) || reps > 10)
|
|
26
|
+
return null;
|
|
27
|
+
return round((epley1Rm(weightKg, reps) + brzycki1Rm(weightKg, reps)) / 2, 1);
|
|
28
|
+
}
|
|
29
|
+
/** Coarse mapping from Garmin exercise categories to the main muscle group trained. */
|
|
30
|
+
const MUSCLE_GROUP = {
|
|
31
|
+
BENCH_PRESS: "chest",
|
|
32
|
+
PUSH_UP: "chest",
|
|
33
|
+
FLYE: "chest",
|
|
34
|
+
ROW: "back",
|
|
35
|
+
PULL_UP: "back",
|
|
36
|
+
LAT_PULLDOWN: "back",
|
|
37
|
+
HYPEREXTENSION: "lower back",
|
|
38
|
+
DEADLIFT: "posterior chain",
|
|
39
|
+
SHOULDER_PRESS: "shoulders",
|
|
40
|
+
LATERAL_RAISE: "shoulders",
|
|
41
|
+
SHRUG: "shoulders",
|
|
42
|
+
CURL: "biceps",
|
|
43
|
+
TRICEPS_EXTENSION: "triceps",
|
|
44
|
+
SQUAT: "quadriceps and glutes",
|
|
45
|
+
LUNGE: "quadriceps and glutes",
|
|
46
|
+
LEG_PRESS: "quadriceps and glutes",
|
|
47
|
+
HIP_RAISE: "glutes",
|
|
48
|
+
LEG_CURL: "hamstrings",
|
|
49
|
+
CALF_RAISE: "calves",
|
|
50
|
+
PLANK: "core",
|
|
51
|
+
CRUNCH: "core",
|
|
52
|
+
SIT_UP: "core",
|
|
53
|
+
CORE: "core",
|
|
54
|
+
LEG_RAISE: "core",
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Reads Garmin's exercise-set payload. Garmin stores weights in grams; rest sets
|
|
58
|
+
* and sets without repetitions are skipped.
|
|
59
|
+
*/
|
|
60
|
+
export function parseExerciseSets(payload) {
|
|
61
|
+
const list = payload?.exerciseSets;
|
|
62
|
+
if (!Array.isArray(list))
|
|
63
|
+
return [];
|
|
64
|
+
const out = [];
|
|
65
|
+
for (const raw of list) {
|
|
66
|
+
if (raw?.setType !== "ACTIVE")
|
|
67
|
+
continue;
|
|
68
|
+
const exercises = Array.isArray(raw.exercises) ? raw.exercises : [];
|
|
69
|
+
const best = exercises[0];
|
|
70
|
+
const grams = raw.weight;
|
|
71
|
+
out.push({
|
|
72
|
+
category: typeof best?.category === "string" ? best.category : null,
|
|
73
|
+
name: typeof best?.name === "string" ? best.name : null,
|
|
74
|
+
reps: isNum(raw.repetitionCount) && raw.repetitionCount > 0 ? raw.repetitionCount : null,
|
|
75
|
+
weightKg: isNum(grams) && grams > 0 ? round(grams / 1000, 2) : null,
|
|
76
|
+
durationS: isNum(raw.duration) ? round(raw.duration, 0) : null,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
export function summarizeStrength(sets) {
|
|
82
|
+
const byExercise = new Map();
|
|
83
|
+
const setsByMuscleGroup = {};
|
|
84
|
+
let totalVolume = 0;
|
|
85
|
+
let hasVolume = false;
|
|
86
|
+
let unidentified = 0;
|
|
87
|
+
for (const set of sets) {
|
|
88
|
+
const key = set.name ?? set.category ?? "UNKNOWN";
|
|
89
|
+
if (key === "UNKNOWN")
|
|
90
|
+
unidentified += 1;
|
|
91
|
+
const group = set.category ? (MUSCLE_GROUP[set.category] ?? null) : null;
|
|
92
|
+
if (group)
|
|
93
|
+
setsByMuscleGroup[group] = (setsByMuscleGroup[group] ?? 0) + 1;
|
|
94
|
+
let summary = byExercise.get(key);
|
|
95
|
+
if (!summary) {
|
|
96
|
+
summary = { exercise: key, muscleGroup: group, sets: 0, reps: 0, volumeKg: null, topSet: null, estimated1RmKg: null };
|
|
97
|
+
byExercise.set(key, summary);
|
|
98
|
+
}
|
|
99
|
+
summary.sets += 1;
|
|
100
|
+
summary.reps += set.reps ?? 0;
|
|
101
|
+
if (isNum(set.reps) && isNum(set.weightKg)) {
|
|
102
|
+
const volume = set.reps * set.weightKg;
|
|
103
|
+
summary.volumeKg = round((summary.volumeKg ?? 0) + volume, 0);
|
|
104
|
+
totalVolume += volume;
|
|
105
|
+
hasVolume = true;
|
|
106
|
+
const estimate = estimated1Rm(set.weightKg, set.reps);
|
|
107
|
+
if (estimate !== null && (summary.estimated1RmKg === null || estimate > summary.estimated1RmKg)) {
|
|
108
|
+
summary.estimated1RmKg = estimate;
|
|
109
|
+
summary.topSet = { weightKg: set.weightKg, reps: set.reps };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
exercises: [...byExercise.values()],
|
|
115
|
+
totalSets: sets.length,
|
|
116
|
+
totalVolumeKg: hasVolume ? round(totalVolume, 0) : null,
|
|
117
|
+
setsByMuscleGroup,
|
|
118
|
+
unidentifiedSets: unidentified,
|
|
119
|
+
};
|
|
120
|
+
}
|