@sctg/openclaw-coach 0.1.0 → 2.1.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.
Files changed (64) hide show
  1. package/README.md +323 -66
  2. package/assets/fonts/Inter_400Regular.ttf +0 -0
  3. package/assets/fonts/Inter_600SemiBold.ttf +0 -0
  4. package/assets/fonts/LICENSE.txt +93 -0
  5. package/assets/icon.png +0 -0
  6. package/assets/logo.png +0 -0
  7. package/assets/logo.svg +62 -0
  8. package/dist/charts/build.d.ts +71 -0
  9. package/dist/charts/build.js +276 -0
  10. package/dist/charts/labels.d.ts +38 -0
  11. package/dist/charts/labels.js +73 -0
  12. package/dist/charts/render.d.ts +10 -0
  13. package/dist/charts/render.js +26 -0
  14. package/dist/charts/svg.d.ts +47 -0
  15. package/dist/charts/svg.js +92 -0
  16. package/dist/config.d.ts +25 -0
  17. package/dist/config.js +38 -0
  18. package/dist/dates.d.ts +22 -0
  19. package/dist/dates.js +71 -0
  20. package/dist/email.d.ts +58 -0
  21. package/dist/email.js +188 -0
  22. package/dist/garmin/gc.d.ts +25 -0
  23. package/dist/garmin/gc.js +81 -0
  24. package/dist/garmin/normalize.d.ts +20 -0
  25. package/dist/garmin/normalize.js +132 -0
  26. package/dist/index.js +207 -163
  27. package/dist/profile.d.ts +4 -0
  28. package/dist/profile.js +43 -0
  29. package/dist/science/associations.d.ts +56 -0
  30. package/dist/science/associations.js +102 -0
  31. package/dist/science/healthspan.d.ts +25 -0
  32. package/dist/science/healthspan.js +89 -0
  33. package/dist/science/hrv.d.ts +61 -0
  34. package/dist/science/hrv.js +119 -0
  35. package/dist/science/load.d.ts +107 -0
  36. package/dist/science/load.js +228 -0
  37. package/dist/science/performance.d.ts +93 -0
  38. package/dist/science/performance.js +191 -0
  39. package/dist/science/readiness.d.ts +47 -0
  40. package/dist/science/readiness.js +97 -0
  41. package/dist/science/recovery.d.ts +74 -0
  42. package/dist/science/recovery.js +173 -0
  43. package/dist/science/sleep.d.ts +79 -0
  44. package/dist/science/sleep.js +165 -0
  45. package/dist/science/stats.d.ts +50 -0
  46. package/dist/science/stats.js +201 -0
  47. package/dist/science/strength.d.ts +47 -0
  48. package/dist/science/strength.js +120 -0
  49. package/dist/store.d.ts +36 -0
  50. package/dist/store.js +78 -0
  51. package/dist/sync.d.ts +36 -0
  52. package/dist/sync.js +145 -0
  53. package/dist/tools.d.ts +463 -0
  54. package/dist/tools.js +792 -0
  55. package/dist/types.d.ts +143 -0
  56. package/dist/types.js +2 -0
  57. package/docs/SCIENCE.md +721 -0
  58. package/examples/ATHLETE-fr.md +72 -0
  59. package/examples/ATHLETE.md +74 -0
  60. package/examples/PLAN-fr.md +55 -0
  61. package/examples/PLAN.md +55 -0
  62. package/openclaw.plugin.json +158 -5
  63. package/package.json +14 -3
  64. package/skills/coach/SKILL.md +291 -208
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Long-term health markers that a watch can follow, compared with published
3
+ * thresholds. No "biological age": each marker is shown as it is, with its
4
+ * evidence, because a composite age needs blood biomarkers and a validated
5
+ * model (Levine 2018) that wearable data cannot replace.
6
+ */
7
+ import { analyzeSleep } from "./sleep.js";
8
+ import { isNum, mean, median, round, roundOrNull, slope, valid } from "./stats.js";
9
+ export const HEALTHSPAN_ALGORITHM = {
10
+ id: "healthspan-markers",
11
+ version: "1.0.0",
12
+ refs: ["bull2020", "kodama2009", "mandsager2018", "zhang2016", "windred2024", "watson2015"],
13
+ };
14
+ const STRENGTH_TYPES = /strength|weight|pilates|yoga|climbing|bouldering|hiit|crossfit/i;
15
+ export function healthspanMarkers(days, activities, profile) {
16
+ const last28 = days.slice(-28);
17
+ const moderate = valid(last28.map((day) => day.activity?.moderateMin));
18
+ const vigorous = valid(last28.map((day) => day.activity?.vigorousMin));
19
+ // WHO counts one vigorous minute as two moderate minutes.
20
+ const weeklyEquivalent = moderate.length >= 14 ? round(((mean(moderate) ?? 0) + 2 * (mean(vigorous) ?? 0)) * 7, 0) : null;
21
+ const since = last28[0]?.date;
22
+ const strengthSessions = since ? activities.filter((activity) => activity.date >= since && STRENGTH_TYPES.test(activity.type)).length : 0;
23
+ const strengthPerWeek = last28.length >= 14 ? round(strengthSessions / (last28.length / 7), 1) : null;
24
+ const rhr = days.map((day) => day.restingHr);
25
+ const rhr28 = median(valid(rhr.slice(-28)));
26
+ const rhrSlope = slope(rhr.slice(-90));
27
+ const vo2 = activities.filter((activity) => isNum(activity.vo2max)).sort((a, b) => a.date.localeCompare(b.date));
28
+ const vo2Latest = vo2.length ? vo2[vo2.length - 1].vo2max : null;
29
+ const vo2First = vo2.length > 1 ? vo2[0].vo2max : null;
30
+ const sleep = analyzeSleep(days, profile);
31
+ const markers = [
32
+ {
33
+ marker: "Aerobic activity",
34
+ value: weeklyEquivalent,
35
+ unit: "moderate-equivalent min/week (4-week mean)",
36
+ reference: "WHO 2020: 150-300 min/week of moderate activity, or 75-150 min vigorous",
37
+ met: weeklyEquivalent === null ? null : weeklyEquivalent >= 150,
38
+ refs: ["bull2020"],
39
+ },
40
+ {
41
+ marker: "Muscle-strengthening sessions",
42
+ value: strengthPerWeek,
43
+ unit: "sessions/week (4-week mean)",
44
+ reference: "WHO 2020: at least 2 days/week",
45
+ met: strengthPerWeek === null ? null : strengthPerWeek >= 2,
46
+ refs: ["bull2020"],
47
+ },
48
+ {
49
+ marker: "Cardiorespiratory fitness (Garmin VO2max estimate)",
50
+ value: roundOrNull(vo2Latest, 0),
51
+ unit: "ml/kg/min",
52
+ reference: "Each +3.5 ml/kg/min (1 MET) goes with about 13 % lower all-cause mortality; no upper limit of benefit observed",
53
+ met: null,
54
+ trend: vo2Latest !== null && vo2First !== null ? `${round(vo2Latest - vo2First, 0)} over the stored history` : null,
55
+ refs: ["kodama2009", "mandsager2018"],
56
+ },
57
+ {
58
+ marker: "Resting heart rate",
59
+ value: roundOrNull(rhr28, 0),
60
+ unit: "bpm (28-day median)",
61
+ reference: "Lower is associated with lower mortality in population studies (+9 % per +10 bpm)",
62
+ met: null,
63
+ trend: rhrSlope === null ? null : `${round(rhrSlope * 30, 1)} bpm per 30 days`,
64
+ refs: ["zhang2016"],
65
+ },
66
+ {
67
+ marker: "Sleep duration",
68
+ value: sleep.avg14H,
69
+ unit: "h/night (14-night mean)",
70
+ reference: "Adults: 7 h or more per night",
71
+ met: sleep.avg14H === null ? null : sleep.avg14H >= 7,
72
+ refs: ["watson2015"],
73
+ },
74
+ {
75
+ marker: "Sleep regularity index",
76
+ value: sleep.regularity?.sri ?? null,
77
+ unit: "0-100 (main sleep period)",
78
+ reference: "Higher regularity goes with lower all-cause mortality, more strongly than duration",
79
+ met: null,
80
+ refs: ["windred2024"],
81
+ },
82
+ ];
83
+ return {
84
+ algorithm: HEALTHSPAN_ALGORITHM,
85
+ windowDays: last28.length,
86
+ markers,
87
+ caveat: "Population associations, not individual predictions. Garmin's VO2max is an estimate (typical error about 5 %), and its 'fitness age' is not a validated biological age.",
88
+ };
89
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Heart-rate variability: individual baseline, rolling trend and stability.
3
+ *
4
+ * Input: Garmin's overnight HRV average (rMSSD, ms). It is log-transformed
5
+ * (ln rMSSD) because rMSSD is right-skewed and its day-to-day changes are
6
+ * proportional to its level.
7
+ *
8
+ * Model (Plews 2012, 2013; Buchheit 2014):
9
+ * - trend = 7-day rolling mean of ln rMSSD, more informative than one night;
10
+ * - normal = personal baseline (60 preceding days) +/- the smallest worthwhile
11
+ * change, SWC = 0.5 x between-day SD (Hopkins 2009);
12
+ * - CV = coefficient of variation of the last 7 nights: day-to-day stability.
13
+ */
14
+ import type { AlgorithmTag, DataStatus, DayRecord } from "../types.ts";
15
+ export declare const HRV_ALGORITHM: AlgorithmTag;
16
+ export declare const HRV_BASELINE_DAYS = 60;
17
+ export declare const HRV_TREND_DAYS = 7;
18
+ /** Nights needed in the baseline window before the normal range is used. */
19
+ export declare const HRV_MIN_BASELINE_NIGHTS = 14;
20
+ /** Nights needed among the last 7 for a trend (Plews 2014: 3 to 5 per week). */
21
+ export declare const HRV_MIN_TREND_NIGHTS = 3;
22
+ export declare const HRV_GOOD_TREND_NIGHTS = 5;
23
+ export type HrvTrend = "below" | "within" | "above";
24
+ export type HrvAnalysis = {
25
+ status: DataStatus;
26
+ algorithm: AlgorithmTag;
27
+ lastNightMs: number | null;
28
+ lastNightLn: number | null;
29
+ /** z-score of last night against the personal baseline (acute change). */
30
+ acuteZ: number | null;
31
+ rolling7Ln: number | null;
32
+ rolling7Ms: number | null;
33
+ nightsInTrend: number;
34
+ baseline: {
35
+ meanLn: number;
36
+ sdLn: number;
37
+ lowLn: number;
38
+ highLn: number;
39
+ /** The same range expressed in ms, for display. */
40
+ lowMs: number;
41
+ highMs: number;
42
+ nights: number;
43
+ days: number;
44
+ } | null;
45
+ /** Position of the 7-day mean relative to baseline +/- SWC. */
46
+ trend: HrvTrend | null;
47
+ cv7Pct: number | null;
48
+ cvBaselinePct: number | null;
49
+ /** Change of the 7-day mean over the last 7 days, in percent of rMSSD. */
50
+ weekChangePct: number | null;
51
+ /** Consecutive days (ending today) with the 7-day mean below the normal range. */
52
+ daysBelow: number;
53
+ garminStatus: string | null;
54
+ notes: string[];
55
+ };
56
+ export declare function lnRmssd(day: DayRecord | undefined): number | null;
57
+ /**
58
+ * @param days Consecutive days in ascending order; the last one is the day being assessed
59
+ * (its HRV is the night that just ended).
60
+ */
61
+ export declare function analyzeHrv(days: readonly DayRecord[]): HrvAnalysis;
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Heart-rate variability: individual baseline, rolling trend and stability.
3
+ *
4
+ * Input: Garmin's overnight HRV average (rMSSD, ms). It is log-transformed
5
+ * (ln rMSSD) because rMSSD is right-skewed and its day-to-day changes are
6
+ * proportional to its level.
7
+ *
8
+ * Model (Plews 2012, 2013; Buchheit 2014):
9
+ * - trend = 7-day rolling mean of ln rMSSD, more informative than one night;
10
+ * - normal = personal baseline (60 preceding days) +/- the smallest worthwhile
11
+ * change, SWC = 0.5 x between-day SD (Hopkins 2009);
12
+ * - CV = coefficient of variation of the last 7 nights: day-to-day stability.
13
+ */
14
+ import { isNum, mean, median, robustBaseline, round, roundOrNull, sd, valid, zScore } from "./stats.js";
15
+ export const HRV_ALGORITHM = {
16
+ id: "hrv-baseline",
17
+ version: "1.0.0",
18
+ refs: ["plews2012", "plews2013", "plews2014", "buchheit2014", "hopkins2009"],
19
+ };
20
+ export const HRV_BASELINE_DAYS = 60;
21
+ export const HRV_TREND_DAYS = 7;
22
+ /** Nights needed in the baseline window before the normal range is used. */
23
+ export const HRV_MIN_BASELINE_NIGHTS = 14;
24
+ /** Nights needed among the last 7 for a trend (Plews 2014: 3 to 5 per week). */
25
+ export const HRV_MIN_TREND_NIGHTS = 3;
26
+ export const HRV_GOOD_TREND_NIGHTS = 5;
27
+ const SWC_FACTOR = 0.5;
28
+ /** Smallest between-day SD of ln rMSSD accepted, to avoid over-reacting to noise. */
29
+ const LN_RMSSD_SD_FLOOR = 0.05;
30
+ export function lnRmssd(day) {
31
+ const value = day?.hrv?.lastNightAvgMs;
32
+ return isNum(value) && value > 0 ? Math.log(value) : null;
33
+ }
34
+ function rollingMean(values, end, size, minN) {
35
+ const window = valid(values.slice(Math.max(0, end - size + 1), end + 1));
36
+ return window.length >= minN ? mean(window) : null;
37
+ }
38
+ function cvPct(values) {
39
+ const m = mean(values);
40
+ const s = sd(values);
41
+ return m && s !== null ? (s / m) * 100 : null;
42
+ }
43
+ /**
44
+ * @param days Consecutive days in ascending order; the last one is the day being assessed
45
+ * (its HRV is the night that just ended).
46
+ */
47
+ export function analyzeHrv(days) {
48
+ const series = days.map(lnRmssd);
49
+ const last = series.length - 1;
50
+ const today = last >= 0 ? series[last] : null;
51
+ const notes = [];
52
+ const baselineWindow = series.slice(Math.max(0, last - HRV_BASELINE_DAYS), Math.max(0, last));
53
+ const robust = robustBaseline(baselineWindow, LN_RMSSD_SD_FLOOR, HRV_MIN_BASELINE_NIGHTS);
54
+ const trendNights = valid(series.slice(Math.max(0, last - HRV_TREND_DAYS + 1), last + 1));
55
+ const rolling7 = trendNights.length >= HRV_MIN_TREND_NIGHTS ? mean(trendNights) : null;
56
+ let baseline = null;
57
+ let trend = null;
58
+ let daysBelow = 0;
59
+ if (robust) {
60
+ const swc = SWC_FACTOR * robust.scale;
61
+ const lowLn = robust.center - swc;
62
+ const highLn = robust.center + swc;
63
+ baseline = {
64
+ meanLn: round(robust.center, 3),
65
+ sdLn: round(robust.scale, 3),
66
+ lowLn: round(lowLn, 3),
67
+ highLn: round(highLn, 3),
68
+ lowMs: round(Math.exp(lowLn), 0),
69
+ highMs: round(Math.exp(highLn), 0),
70
+ nights: robust.n,
71
+ days: baselineWindow.length,
72
+ };
73
+ if (rolling7 !== null)
74
+ trend = rolling7 < lowLn ? "below" : rolling7 > highLn ? "above" : "within";
75
+ // The baseline is kept fixed while walking back: the question is how long the
76
+ // trend has been below today's normal range.
77
+ for (let index = last; index >= 0; index -= 1) {
78
+ const value = rollingMean(series, index, HRV_TREND_DAYS, HRV_MIN_TREND_NIGHTS);
79
+ if (value === null || value >= lowLn)
80
+ break;
81
+ daysBelow += 1;
82
+ }
83
+ }
84
+ const cv7 = trendNights.length >= HRV_MIN_TREND_NIGHTS ? cvPct(trendNights) : null;
85
+ const pastCvs = [];
86
+ for (let index = Math.max(HRV_TREND_DAYS - 1, last - HRV_BASELINE_DAYS); index < last; index += 1) {
87
+ const window = valid(series.slice(index - HRV_TREND_DAYS + 1, index + 1));
88
+ const value = window.length >= HRV_GOOD_TREND_NIGHTS ? cvPct(window) : null;
89
+ if (value !== null)
90
+ pastCvs.push(value);
91
+ }
92
+ const cvBaseline = pastCvs.length >= 7 ? median(pastCvs) : null;
93
+ const previous7 = last >= HRV_TREND_DAYS ? rollingMean(series, last - HRV_TREND_DAYS, HRV_TREND_DAYS, HRV_MIN_TREND_NIGHTS) : null;
94
+ const weekChangePct = rolling7 !== null && previous7 !== null ? (Math.exp(rolling7 - previous7) - 1) * 100 : null;
95
+ if (trendNights.length > 0 && trendNights.length < HRV_GOOD_TREND_NIGHTS) {
96
+ notes.push(`Only ${trendNights.length} of the last 7 nights have an HRV value: the trend is less reliable.`);
97
+ }
98
+ if (today === null)
99
+ notes.push("No HRV value for last night (watch not worn, or sleep too short).");
100
+ const status = !baseline ? (valid(series).length ? "calibrating" : "insufficient_data") : rolling7 === null ? "insufficient_data" : "ready";
101
+ return {
102
+ status,
103
+ algorithm: HRV_ALGORITHM,
104
+ lastNightMs: roundOrNull(days[last]?.hrv?.lastNightAvgMs, 0),
105
+ lastNightLn: roundOrNull(today, 3),
106
+ acuteZ: roundOrNull(zScore(today, robust), 2),
107
+ rolling7Ln: roundOrNull(rolling7, 3),
108
+ rolling7Ms: rolling7 === null ? null : round(Math.exp(rolling7), 0),
109
+ nightsInTrend: trendNights.length,
110
+ baseline,
111
+ trend,
112
+ cv7Pct: roundOrNull(cv7, 1),
113
+ cvBaselinePct: roundOrNull(cvBaseline, 1),
114
+ weekChangePct: roundOrNull(weekChangePct, 1),
115
+ daysBelow,
116
+ garminStatus: days[last]?.hrv?.status ?? null,
117
+ notes,
118
+ };
119
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Training load.
3
+ *
4
+ * Session load: Banister's training impulse (TRIMP), the dose unit of the
5
+ * fitness-fatigue model (Banister 1991, Morton 1990):
6
+ * TRIMP = minutes x HRr x a x exp(b x HRr), HRr = (HR - HRrest) / (HRmax - HRrest)
7
+ * with (a, b) = (0.64, 1.92) for men and (0.86, 1.67) for women. When the time
8
+ * in each heart-rate zone is known, the formula is applied zone by zone, which
9
+ * counts interval sessions correctly (the mean heart rate of an interval session
10
+ * under-weights its hard parts). Edwards' zone score (Edwards 1993) and Garmin's
11
+ * own load are reported next to it for comparison.
12
+ *
13
+ * Daily loads feed two exponentially weighted averages (Calvert 1976; the
14
+ * simplified form popularized as the "performance manager"):
15
+ * fitness (CTL), time constant 42 days; fatigue (ATL), time constant 7 days;
16
+ * form (TSB) = yesterday's fitness - yesterday's fatigue.
17
+ *
18
+ * Descriptive indicators: monotony and strain (Foster 1998), week-on-week
19
+ * change, and an uncoupled acute:chronic ratio. The acute:chronic ratio is
20
+ * reported as a description of load progression only: its use as an injury
21
+ * predictor is not supported (Impellizzeri 2020, Lolli 2019).
22
+ */
23
+ import type { Activity, AlgorithmTag, DataStatus, Profile, Sex } from "../types.ts";
24
+ export declare const LOAD_ALGORITHM: AlgorithmTag;
25
+ export declare const CTL_TAU_DAYS = 42;
26
+ export declare const ATL_TAU_DAYS = 7;
27
+ /** Days of history before fitness (CTL) has absorbed ~63 % / ~88 % of its inputs. */
28
+ export declare const LOAD_MIN_DAYS = 28;
29
+ export declare const LOAD_GOOD_DAYS = 90;
30
+ /** Banister weighting of one minute at heart-rate reserve fraction `hrr`. */
31
+ export declare function banisterPerMinute(hrr: number, sex: Sex | null): number;
32
+ export type SessionLoad = {
33
+ /** Banister TRIMP (arbitrary units), or null when heart rate or anchors are missing. */
34
+ trimp: number | null;
35
+ method: "zones" | "mean-hr" | null;
36
+ edwards: number | null;
37
+ garmin: number | null;
38
+ };
39
+ export declare function sessionLoad(activity: Activity, profile: Profile): SessionLoad;
40
+ /** Load of a planned session, on the same scale as recorded sessions. */
41
+ export declare function plannedSessionLoad(minutes: number, zone: number, profile: Profile): number | null;
42
+ export type DailyLoad = {
43
+ date: string;
44
+ load: number;
45
+ sessions: number;
46
+ unscored: number;
47
+ };
48
+ /** One entry per calendar day from `start` to `end`; a day without activity has load 0. */
49
+ export declare function dailyLoads(activities: readonly Activity[], profile: Profile, start: string, end: string): DailyLoad[];
50
+ export type LoadPoint = {
51
+ date: string;
52
+ load: number;
53
+ ctl: number;
54
+ atl: number;
55
+ tsb: number;
56
+ };
57
+ /** Fitness-fatigue curves. TSB of a day uses the previous day's CTL and ATL. */
58
+ export declare function fitnessFatigue(loads: readonly {
59
+ date: string;
60
+ load: number;
61
+ }[]): LoadPoint[];
62
+ /** Continue the curves over planned loads, to see where a plan leads. */
63
+ export declare function projectLoads(last: LoadPoint, planned: readonly {
64
+ date: string;
65
+ load: number;
66
+ }[]): LoadPoint[];
67
+ export type IntensityDistribution = {
68
+ totalMin: number;
69
+ /** Percent of heart-rate zone time in Garmin zones 1 to 5. */
70
+ zonesPct: number[];
71
+ /** Three-zone grouping: low = zones 1-3, moderate = zone 4, high = zone 5 (percent-of-HRmax zones). */
72
+ lowPct: number;
73
+ moderatePct: number;
74
+ highPct: number;
75
+ /** Polarization index (Treff 2019); above 2.0 the distribution is polarized. */
76
+ polarizationIndex: number | null;
77
+ };
78
+ export declare function intensityDistribution(activities: readonly Activity[]): IntensityDistribution | null;
79
+ export type LoadAnalysis = {
80
+ status: DataStatus;
81
+ algorithm: AlgorithmTag;
82
+ unit: "TRIMP (Banister)";
83
+ historyDays: number;
84
+ today: LoadPoint | null;
85
+ /** Fitness (CTL) change over the last 7 days, absolute and in percent. */
86
+ rampPerWeek: number | null;
87
+ rampPctPerWeek: number | null;
88
+ last7: number | null;
89
+ previous7: number | null;
90
+ weekChangePct: number | null;
91
+ /** 7-day mean daily load / mean daily load of the 21 days before (uncoupled). */
92
+ acuteChronicRatio: number | null;
93
+ monotony: number | null;
94
+ strain: number | null;
95
+ sessions7: number;
96
+ unscoredSessions28: number;
97
+ restDays7: number;
98
+ intensity28: IntensityDistribution | null;
99
+ flags: string[];
100
+ notes: string[];
101
+ };
102
+ /**
103
+ * @param loads Daily loads in ascending order, ending on the assessed day.
104
+ */
105
+ export declare function analyzeLoad(loads: readonly DailyLoad[], activities: readonly Activity[], profile: Profile): LoadAnalysis;
106
+ /** Dates following `after`, for building projections. */
107
+ export declare function nextDates(after: string, count: number): string[];
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Training load.
3
+ *
4
+ * Session load: Banister's training impulse (TRIMP), the dose unit of the
5
+ * fitness-fatigue model (Banister 1991, Morton 1990):
6
+ * TRIMP = minutes x HRr x a x exp(b x HRr), HRr = (HR - HRrest) / (HRmax - HRrest)
7
+ * with (a, b) = (0.64, 1.92) for men and (0.86, 1.67) for women. When the time
8
+ * in each heart-rate zone is known, the formula is applied zone by zone, which
9
+ * counts interval sessions correctly (the mean heart rate of an interval session
10
+ * under-weights its hard parts). Edwards' zone score (Edwards 1993) and Garmin's
11
+ * own load are reported next to it for comparison.
12
+ *
13
+ * Daily loads feed two exponentially weighted averages (Calvert 1976; the
14
+ * simplified form popularized as the "performance manager"):
15
+ * fitness (CTL), time constant 42 days; fatigue (ATL), time constant 7 days;
16
+ * form (TSB) = yesterday's fitness - yesterday's fatigue.
17
+ *
18
+ * Descriptive indicators: monotony and strain (Foster 1998), week-on-week
19
+ * change, and an uncoupled acute:chronic ratio. The acute:chronic ratio is
20
+ * reported as a description of load progression only: its use as an injury
21
+ * predictor is not supported (Impellizzeri 2020, Lolli 2019).
22
+ */
23
+ import { addDays, dateRange } from "../dates.js";
24
+ import { clamp, ewma, isNum, mean, round, roundOrNull, sd, sum } from "./stats.js";
25
+ export const LOAD_ALGORITHM = {
26
+ id: "training-load",
27
+ version: "1.0.0",
28
+ refs: ["banister1991", "morton1990", "edwards1993", "calvert1976", "foster1998", "impellizzeri2020", "lolli2019", "nielsen2014", "treff2019"],
29
+ };
30
+ export const CTL_TAU_DAYS = 42;
31
+ export const ATL_TAU_DAYS = 7;
32
+ /** Days of history before fitness (CTL) has absorbed ~63 % / ~88 % of its inputs. */
33
+ export const LOAD_MIN_DAYS = 28;
34
+ export const LOAD_GOOD_DAYS = 90;
35
+ const BANISTER = {
36
+ male: { a: 0.64, b: 1.92 },
37
+ female: { a: 0.86, b: 1.67 },
38
+ };
39
+ /** Banister weighting of one minute at heart-rate reserve fraction `hrr`. */
40
+ export function banisterPerMinute(hrr, sex) {
41
+ const x = clamp(hrr, 0, 1);
42
+ const { a, b } = BANISTER[sex ?? "male"];
43
+ return x * a * Math.exp(b * x);
44
+ }
45
+ export function sessionLoad(activity, profile) {
46
+ const zones = activity.hrZonesS;
47
+ const zoneSeconds = zones ? sum(zones.filter(isNum)) : 0;
48
+ const edwards = zones && zoneSeconds > 0 ? round(sum(zones.map((seconds, index) => ((seconds || 0) / 60) * (index + 1))), 1) : null;
49
+ const garmin = roundOrNull(activity.garminLoad, 0);
50
+ const { hrMax, hrRest } = profile;
51
+ if (!isNum(hrMax) || !isNum(hrRest) || hrMax <= hrRest)
52
+ return { trimp: null, method: null, edwards, garmin };
53
+ const reserve = hrMax - hrRest;
54
+ if (zones && zoneSeconds > 0) {
55
+ const floors = profile.hrZoneFloorsPctMax;
56
+ let trimp = 0;
57
+ zones.forEach((seconds, index) => {
58
+ const low = floors[index] ?? 50 + index * 10;
59
+ const high = floors[index + 1] ?? 100;
60
+ const midHr = ((low + high) / 200) * hrMax;
61
+ trimp += ((seconds || 0) / 60) * banisterPerMinute((midHr - hrRest) / reserve, profile.sex);
62
+ });
63
+ return { trimp: round(trimp, 1), method: "zones", edwards, garmin };
64
+ }
65
+ if (isNum(activity.avgHr) && isNum(activity.durationS)) {
66
+ const minutes = (activity.movingS ?? activity.durationS) / 60;
67
+ return {
68
+ trimp: round(minutes * banisterPerMinute((activity.avgHr - hrRest) / reserve, profile.sex), 1),
69
+ method: "mean-hr",
70
+ edwards,
71
+ garmin,
72
+ };
73
+ }
74
+ return { trimp: null, method: null, edwards, garmin };
75
+ }
76
+ /** Load of a planned session, on the same scale as recorded sessions. */
77
+ export function plannedSessionLoad(minutes, zone, profile) {
78
+ const { hrMax, hrRest } = profile;
79
+ if (!isNum(hrMax) || !isNum(hrRest) || hrMax <= hrRest)
80
+ return null;
81
+ const index = clamp(Math.round(zone), 1, 5) - 1;
82
+ const floors = profile.hrZoneFloorsPctMax;
83
+ const midHr = (((floors[index] ?? 50 + index * 10) + (floors[index + 1] ?? 100)) / 200) * hrMax;
84
+ return round(minutes * banisterPerMinute((midHr - hrRest) / (hrMax - hrRest), profile.sex), 1);
85
+ }
86
+ /** One entry per calendar day from `start` to `end`; a day without activity has load 0. */
87
+ export function dailyLoads(activities, profile, start, end) {
88
+ const byDate = new Map();
89
+ for (const date of dateRange(start, end))
90
+ byDate.set(date, { date, load: 0, sessions: 0, unscored: 0 });
91
+ for (const activity of activities) {
92
+ const day = byDate.get(activity.date);
93
+ if (!day)
94
+ continue;
95
+ const { trimp } = sessionLoad(activity, profile);
96
+ day.sessions += 1;
97
+ if (trimp === null)
98
+ day.unscored += 1;
99
+ else
100
+ day.load += trimp;
101
+ }
102
+ return [...byDate.values()];
103
+ }
104
+ /** Fitness-fatigue curves. TSB of a day uses the previous day's CTL and ATL. */
105
+ export function fitnessFatigue(loads) {
106
+ if (!loads.length)
107
+ return [];
108
+ const values = loads.map((day) => day.load);
109
+ // Start from the mean of the first two weeks instead of 0, so that the first
110
+ // weeks of the window are not read as a fitness build-up from nothing.
111
+ const seed = mean(values.slice(0, Math.min(14, values.length))) ?? 0;
112
+ const ctl = ewma(values, CTL_TAU_DAYS, seed);
113
+ const atl = ewma(values, ATL_TAU_DAYS, seed);
114
+ return loads.map((day, index) => ({
115
+ date: day.date,
116
+ load: round(day.load, 1),
117
+ ctl: round(ctl[index], 1),
118
+ atl: round(atl[index], 1),
119
+ tsb: round((index ? ctl[index - 1] : seed) - (index ? atl[index - 1] : seed), 1),
120
+ }));
121
+ }
122
+ /** Continue the curves over planned loads, to see where a plan leads. */
123
+ export function projectLoads(last, planned) {
124
+ const out = [];
125
+ let ctl = last.ctl;
126
+ let atl = last.atl;
127
+ const kc = 1 - Math.exp(-1 / CTL_TAU_DAYS);
128
+ const ka = 1 - Math.exp(-1 / ATL_TAU_DAYS);
129
+ for (const day of planned) {
130
+ const tsb = ctl - atl;
131
+ ctl += (day.load - ctl) * kc;
132
+ atl += (day.load - atl) * ka;
133
+ out.push({ date: day.date, load: round(day.load, 1), ctl: round(ctl, 1), atl: round(atl, 1), tsb: round(tsb, 1) });
134
+ }
135
+ return out;
136
+ }
137
+ export function intensityDistribution(activities) {
138
+ const totals = [0, 0, 0, 0, 0];
139
+ for (const activity of activities)
140
+ activity.hrZonesS?.forEach((seconds, index) => (totals[index] += seconds || 0));
141
+ const total = sum(totals);
142
+ if (total < 600)
143
+ return null;
144
+ const pct = totals.map((seconds) => round((seconds / total) * 100, 0));
145
+ const low = (totals[0] + totals[1] + totals[2]) / total;
146
+ const moderate = totals[3] / total;
147
+ const high = totals[4] / total;
148
+ // Treff 2019: PI = log10(low / moderate x high x 100), with shares as fractions.
149
+ // By definition PI = 0 when there is no high-intensity time or when high > low,
150
+ // and a zero moderate share is replaced by 0.01.
151
+ const polarizationIndex = high <= 0 || high >= low ? 0 : round(Math.log10((low / Math.max(moderate, 0.01)) * high * 100), 2);
152
+ return {
153
+ totalMin: round(total / 60, 0),
154
+ zonesPct: pct,
155
+ lowPct: round(low * 100, 0),
156
+ moderatePct: round(moderate * 100, 0),
157
+ highPct: round(high * 100, 0),
158
+ polarizationIndex,
159
+ };
160
+ }
161
+ /**
162
+ * @param loads Daily loads in ascending order, ending on the assessed day.
163
+ */
164
+ export function analyzeLoad(loads, activities, profile) {
165
+ const notes = [];
166
+ const flags = [];
167
+ const curve = fitnessFatigue(loads);
168
+ const today = curve.length ? curve[curve.length - 1] : null;
169
+ const values = loads.map((day) => day.load);
170
+ const tail = (count, offset = 0) => values.slice(Math.max(0, values.length - offset - count), values.length - offset);
171
+ const week = tail(7);
172
+ const last7 = week.length === 7 ? sum(week) : null;
173
+ const before = tail(7, 7);
174
+ const previous7 = before.length === 7 ? sum(before) : null;
175
+ const chronic = tail(21, 7);
176
+ const chronicMean = chronic.length === 21 ? mean(chronic) : null;
177
+ const acuteChronicRatio = last7 !== null && chronicMean ? round(last7 / 7 / chronicMean, 2) : null;
178
+ const weekSd = week.length === 7 ? sd(week) : null;
179
+ const monotony = last7 !== null && weekSd ? round(last7 / 7 / weekSd, 2) : null;
180
+ const weekAgo = curve.length > 7 ? curve[curve.length - 8] : null;
181
+ const rampPerWeek = today && weekAgo ? round(today.ctl - weekAgo.ctl, 1) : null;
182
+ if (!isNum(profile.hrMax) || !isNum(profile.hrRest)) {
183
+ notes.push("Maximum or resting heart rate unknown: sessions cannot be scored. Set hrMax in the plugin config or ATHLETE.md.");
184
+ }
185
+ if (!profile.sex)
186
+ notes.push("Sex not configured: the male TRIMP coefficients are used.");
187
+ if (profile.hrMaxSource === "age-formula") {
188
+ notes.push("Maximum heart rate comes from an age formula (SD about 10 bpm): loads are approximate until a measured value is set.");
189
+ }
190
+ const unscored28 = sum(loads.slice(-28).map((day) => day.unscored));
191
+ if (unscored28)
192
+ notes.push(`${unscored28} session(s) in the last 28 days have no heart-rate data and count as zero load.`);
193
+ if (monotony !== null && monotony > 2)
194
+ flags.push("high_monotony");
195
+ if (acuteChronicRatio !== null && acuteChronicRatio > 1.5)
196
+ flags.push("load_spike");
197
+ if (last7 !== null && previous7 !== null && previous7 > 0 && last7 / previous7 > 1.3 && acuteChronicRatio !== null && acuteChronicRatio > 1.2) {
198
+ flags.push("fast_weekly_increase");
199
+ }
200
+ const last28 = loads.length >= 28 ? loads[loads.length - 28].date : loads[0]?.date;
201
+ const recentActivities = last28 ? activities.filter((activity) => activity.date >= last28) : [];
202
+ const status = !today || !isNum(profile.hrMax) ? "insufficient_data" : loads.length < LOAD_MIN_DAYS ? "insufficient_data" : loads.length < LOAD_GOOD_DAYS ? "calibrating" : "ready";
203
+ return {
204
+ status,
205
+ algorithm: LOAD_ALGORITHM,
206
+ unit: "TRIMP (Banister)",
207
+ historyDays: loads.length,
208
+ today,
209
+ rampPerWeek,
210
+ rampPctPerWeek: rampPerWeek !== null && weekAgo && weekAgo.ctl > 0 ? round((rampPerWeek / weekAgo.ctl) * 100, 0) : null,
211
+ last7: roundOrNull(last7, 0),
212
+ previous7: roundOrNull(previous7, 0),
213
+ weekChangePct: last7 !== null && previous7 ? round((last7 / previous7 - 1) * 100, 0) : null,
214
+ acuteChronicRatio,
215
+ monotony,
216
+ strain: monotony !== null && last7 !== null ? round(last7 * monotony, 0) : null,
217
+ sessions7: sum(loads.slice(-7).map((day) => day.sessions)),
218
+ unscoredSessions28: unscored28,
219
+ restDays7: loads.slice(-7).filter((day) => day.sessions === 0).length,
220
+ intensity28: intensityDistribution(recentActivities),
221
+ flags,
222
+ notes,
223
+ };
224
+ }
225
+ /** Dates following `after`, for building projections. */
226
+ export function nextDates(after, count) {
227
+ return Array.from({ length: count }, (_, index) => addDays(after, index + 1));
228
+ }