Merge remote-tracking branch 'pr/44'
This commit is contained in:
commit
7e60ac20f2
22 files changed
+1402
-37
No files matched your search
@@ -119,11 +119,31 @@ export const loadOfActive = active =>
|
||||
loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).length })))
|
||||
|
||||
/**
|
||||
* Shade buckets 0–4 per muscle, relative to the hardest-worked muscle in the same
|
||||
* window. Relative rather than absolute on purpose: the map answers "is my training
|
||||
* balanced", which only means anything as a comparison within one period.
|
||||
* Shade buckets 0–4 per muscle.
|
||||
*
|
||||
* With no `thresholds`, levels remain relative to the hardest-worked muscle in the same
|
||||
* window. This is the original balance-map behavior. When `thresholds` is supplied, levels
|
||||
* use an absolute scale instead: it is an ordered array of `{ at, level, exclusive? }` rules,
|
||||
* and the last matching rule wins. An exclusive rule matches values strictly greater than
|
||||
* `at`; otherwise the boundary is inclusive. Values below the first matching rule are l0.
|
||||
* Absolute rules let recovery views keep fixed semantic bands instead of renormalizing to the
|
||||
* strongest muscle on screen.
|
||||
*/
|
||||
export function levelsOf(load) {
|
||||
export function levelsOf(load, thresholds) {
|
||||
if (thresholds) {
|
||||
const lv = {}
|
||||
MUSCLES.forEach(m => {
|
||||
const value = Number(load[m] || 0)
|
||||
let level = 0
|
||||
for (const rule of thresholds) {
|
||||
const matches = rule.exclusive ? value > rule.at : value >= rule.at
|
||||
if (matches) level = Math.max(0, Math.min(4, rule.level))
|
||||
}
|
||||
lv[m] = level
|
||||
})
|
||||
return lv
|
||||
}
|
||||
|
||||
const max = Math.max(0, ...MUSCLES.map(m => load[m] || 0))
|
||||
const lv = {}
|
||||
MUSCLES.forEach(m => {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { FATIGUE_STATES } from './recovery.js'
|
||||
|
||||
/**
|
||||
* Select the consumer-facing fatigue state for one numeric recovery value.
|
||||
* Values below .25 are ready, .25 through .5 are recovering, and values above .5 are fatigued.
|
||||
* Keeping this boundary selector in production code prevents views and tests from drifting apart.
|
||||
*
|
||||
* @param {number} value Numeric fatigue value from fatigueOf().
|
||||
* @returns {'ready'|'recovering'|'fatigued'} The stable state label for the UI.
|
||||
*/
|
||||
export function fatigueStateOf(value) {
|
||||
return value < 0.25
|
||||
? FATIGUE_STATES.READY
|
||||
: value <= 0.5
|
||||
? FATIGUE_STATES.RECOVERING
|
||||
: FATIGUE_STATES.FATIGUED
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { FATIGUE_STATES, fatigueOf, strengthOf } from './recovery.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
import { MUSCLES, levelsOf } from './muscles.js'
|
||||
|
||||
const FATIGUE_BANDS = [
|
||||
{ at: 0, level: 4 },
|
||||
{ at: 0.25, level: 2 },
|
||||
{ at: 0.5, level: 0, exclusive: true },
|
||||
]
|
||||
const STRENGTH_BANDS = [
|
||||
{ at: 0.5, level: 0 },
|
||||
{ at: 0.625, level: 1 },
|
||||
{ at: 0.75, level: 2 },
|
||||
{ at: 0.875, level: 3 },
|
||||
{ at: 1, level: 4 },
|
||||
]
|
||||
|
||||
describe('production recovery view selectors', () => {
|
||||
it('preserves the relative balance scale when no thresholds are supplied', () => {
|
||||
const levels = levelsOf({ chest: 10, biceps: 5 })
|
||||
expect(levels.chest).toBe(4)
|
||||
expect(levels.biceps).toBe(2)
|
||||
})
|
||||
|
||||
it('uses the production fatigue selector at both approved boundaries', () => {
|
||||
expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
|
||||
expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
})
|
||||
|
||||
it('renders fatigue bands on a fixed absolute scale rather than relative to the map maximum', () => {
|
||||
const levels = levelsOf({
|
||||
chest: 0.25,
|
||||
biceps: 0.6,
|
||||
triceps: 0.1,
|
||||
}, FATIGUE_BANDS)
|
||||
expect(levels.chest).toBe(2)
|
||||
expect(levels.biceps).toBe(0)
|
||||
expect(levels.triceps).toBe(4)
|
||||
})
|
||||
|
||||
it('renders strength on fixed .5-to-1 bands with full retention at l4', () => {
|
||||
const levels = levelsOf({ chest: 0.9, biceps: 1, triceps: 0.5 }, STRENGTH_BANDS)
|
||||
expect(levels.chest).toBe(3)
|
||||
expect(levels.biceps).toBe(4)
|
||||
expect(levels.triceps).toBe(0)
|
||||
})
|
||||
|
||||
it('keeps selectors tied to the same render-time clock', () => {
|
||||
const now = Date.UTC(2026, 0, 22)
|
||||
const workout = { start: now - 15 * 86400000, d: '2026-01-07', entries: [] }
|
||||
expect(strengthOf([workout], now).chest).toBe(0.5)
|
||||
expect(fatigueOf([workout], now).chest).toBe(0)
|
||||
expect(strengthOf([workout], now + 7 * 86400000).chest).toBe(0.5)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,197 @@
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
/** Completed-workout window used when calculating current fatigue. */
|
||||
// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve
|
||||
// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting
|
||||
// fatigue level without ever pinning it, and the value can then fade asymptotically.
|
||||
export const FATIGUE_REF_VOLUME = 3
|
||||
// Computational bound for the stimulus scan, not a semantic cliff: after 30 days (20
|
||||
// half-lives) a session contributes below 1e-6 to the accumulated value.
|
||||
export const FATIGUE_SCAN_MS = 30 * 24 * 60 * 60 * 1000
|
||||
|
||||
/** Exponential half-life for fatigue stimulus. */
|
||||
export const FATIGUE_HALF_LIFE_MS = 129600000
|
||||
|
||||
/** Period after training during which retained strength remains at full value. */
|
||||
export const STRENGTH_FULL_MS = 1209600000
|
||||
|
||||
/** Exponential half-life for retained strength after the full-retention period. */
|
||||
export const STRENGTH_HALF_LIFE_MS = 2419200000
|
||||
|
||||
/** Minimum retained-strength value for an untrained or fully detrained muscle. */
|
||||
export const STRENGTH_FLOOR = 0.5
|
||||
|
||||
/**
|
||||
* Stable labels for consumer fatigue buckets: values below 0.25 are ready, values from 0.25
|
||||
* through 0.5 are recovering, and values above 0.5 are fatigued.
|
||||
*/
|
||||
export const FATIGUE_STATES = Object.freeze({
|
||||
READY: 'ready',
|
||||
RECOVERING: 'recovering',
|
||||
FATIGUED: 'fatigued',
|
||||
})
|
||||
|
||||
/**
|
||||
* Return exponential decay expressed as a fraction of one half-life.
|
||||
*
|
||||
* @param {number} ageMs Elapsed age of the stimulus in milliseconds.
|
||||
* @param {number} halfLifeMs Duration of one half-life in milliseconds.
|
||||
* @returns {number} Remaining fraction, using the exact `0.5 ** (age / halfLife)` formula.
|
||||
*/
|
||||
export function halfLifeDecay(ageMs, halfLifeMs) {
|
||||
return 0.5 ** (ageMs / halfLifeMs)
|
||||
}
|
||||
|
||||
// The v2 data contract has one timestamp per workout, not per set. Keep this fallback in one
|
||||
// place so fatigue and strength use exactly the same stimulus time as effort.js.
|
||||
function workoutTimestamp(workout) {
|
||||
const timestamp = workout?.start || new Date(workout?.d).getTime()
|
||||
return Number.isFinite(timestamp) ? timestamp : Number(timestamp)
|
||||
}
|
||||
|
||||
function emptyMuscleMap(value) {
|
||||
return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
|
||||
}
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(max, Math.max(min, value))
|
||||
}
|
||||
|
||||
// Yield one weighted stimulus per completed set. Repeating the exercise's muscle weights for
|
||||
// every done set is equivalent to multiplying musclesOf(ex) by the completed-set count while
|
||||
// preserving the workout/set shape already used by the app.
|
||||
function completedStimuli(workouts, include) {
|
||||
const stimuli = []
|
||||
for (const workout of workouts || []) {
|
||||
const timestamp = workoutTimestamp(workout)
|
||||
if (!Number.isFinite(timestamp) || !include(timestamp)) continue
|
||||
for (const entry of workout.entries || []) {
|
||||
const weights = musclesOf(EXIDX[entry.id])
|
||||
for (const set of entry.sets || []) {
|
||||
if (set?.done !== true) continue
|
||||
for (const [slug, weight] of Object.entries(weights)) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) {
|
||||
stimuli.push({ slug, timestamp, stimulus: weight })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return stimuli
|
||||
}
|
||||
|
||||
const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true]))
|
||||
|
||||
function fatigueValue(events, now) {
|
||||
if (!events.length) return 0
|
||||
events.sort((a, b) => a.timestamp - b.timestamp)
|
||||
|
||||
let value = 0
|
||||
let lastTimestamp = events[0].timestamp
|
||||
for (const event of events) {
|
||||
value *= halfLifeDecay(event.timestamp - lastTimestamp, FATIGUE_HALF_LIFE_MS)
|
||||
value += event.stimulus
|
||||
lastTimestamp = event.timestamp
|
||||
}
|
||||
value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS)
|
||||
// Normalise the accumulated stimulus to a saturating fatigue level: more volume starts
|
||||
// higher but never pins, and the value fades asymptotically - no window-edge cliff.
|
||||
return 1 - Math.exp(-value / FATIGUE_REF_VOLUME)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate current per-muscle fatigue from completed sets in the recent window.
|
||||
*
|
||||
* Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed
|
||||
* set contributes the exercise's `musclesOf` weights; the scan is bounded to FATIGUE_SCAN_MS for
|
||||
* performance, not semantics. Stimuli are accumulated chronologically with a 36-hour half-life,
|
||||
* decayed to `now`, and normalised with the saturation curve 1 - exp(-v / FATIGUE_REF_VOLUME).
|
||||
* The result always contains every drawable muscle slug.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
|
||||
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
|
||||
* @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function fatigueOf(workouts, now) {
|
||||
const current = Number(now)
|
||||
const cutoff = current - FATIGUE_SCAN_MS
|
||||
const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff)
|
||||
const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
|
||||
for (const stimulus of stimuli) byMuscle[stimulus.slug].push(stimulus)
|
||||
|
||||
const result = emptyMuscleMap(0)
|
||||
if (!Number.isFinite(current)) return result
|
||||
for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate retained per-muscle strength from the latest completed stimulus in all history.
|
||||
*
|
||||
* A muscle with no completed set starts at the 0.5 floor. After a completed set, strength is
|
||||
* 1.0 through 14 days old, then decays toward the floor with a 28-day half-life. Any later
|
||||
* completed set becomes the new latest stimulus and resets the 14-day full-retention period.
|
||||
* The result always contains every drawable muscle slug.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
|
||||
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
|
||||
* @returns {Record<string, number>} Retained-strength values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function strengthOf(workouts, now) {
|
||||
const current = Number(now)
|
||||
const latest = Object.fromEntries(MUSCLES.map(slug => [slug, -Infinity]))
|
||||
const stimuli = completedStimuli(workouts, () => true)
|
||||
for (const stimulus of stimuli) {
|
||||
if (stimulus.timestamp > latest[stimulus.slug]) latest[stimulus.slug] = stimulus.timestamp
|
||||
}
|
||||
|
||||
const result = emptyMuscleMap(STRENGTH_FLOOR)
|
||||
if (!Number.isFinite(current)) return result
|
||||
for (const slug of MUSCLES) {
|
||||
const lastTimestamp = latest[slug]
|
||||
if (!Number.isFinite(lastTimestamp)) continue
|
||||
const age = current - lastTimestamp
|
||||
if (age <= STRENGTH_FULL_MS) {
|
||||
result[slug] = 1
|
||||
} else {
|
||||
result[slug] = Math.max(
|
||||
STRENGTH_FLOOR,
|
||||
halfLifeDecay(age - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS),
|
||||
)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* List muscles currently above the fatigued threshold.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history passed to {@link fatigueOf}.
|
||||
* @param {number} now Current time in milliseconds passed to {@link fatigueOf}.
|
||||
* @returns {string[]} Muscle slugs whose fatigue value is greater than 0.5, in `MUSCLES`
|
||||
* head-to-toe order.
|
||||
* @example
|
||||
* const avoid = fatiguedMuscles(workouts, now)
|
||||
*/
|
||||
export function fatiguedMuscles(workouts, now) {
|
||||
return Object.entries(fatigueOf(workouts, now))
|
||||
.filter(([, value]) => value > 0.5)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
|
||||
/**
|
||||
* List muscles whose retained strength is below full retention.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history passed to {@link strengthOf}.
|
||||
* @param {number} now Current time in milliseconds passed to {@link strengthOf}.
|
||||
* @returns {string[]} Muscle slugs whose retained strength is less than 1.0, in `MUSCLES`
|
||||
* head-to-toe order; never-trained muscles are included at the 0.5 floor.
|
||||
* @example
|
||||
* const targets = detrainedMuscles(workouts, now)
|
||||
*/
|
||||
export function detrainedMuscles(workouts, now) {
|
||||
return Object.entries(strengthOf(workouts, now))
|
||||
.filter(([, value]) => value < 1)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
FATIGUE_HALF_LIFE_MS,
|
||||
FATIGUE_REF_VOLUME,
|
||||
FATIGUE_SCAN_MS,
|
||||
FATIGUE_STATES,
|
||||
STRENGTH_FLOOR,
|
||||
STRENGTH_FULL_MS,
|
||||
STRENGTH_HALF_LIFE_MS,
|
||||
detrainedMuscles,
|
||||
fatiguedMuscles,
|
||||
fatigueOf,
|
||||
halfLifeDecay,
|
||||
strengthOf,
|
||||
} from './recovery.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
|
||||
const HOUR = 60 * 60 * 1000
|
||||
const DAY = 24 * HOUR
|
||||
const NOW = Date.UTC(2026, 0, 1, 12)
|
||||
|
||||
// Keep fixtures tied to the shipped catalogue while making the expected stimulus explicit.
|
||||
const SINGLE = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
return ex.bp !== 'cardio' && Object.keys(weights).length === 1 && Object.values(weights)[0] === 1
|
||||
})
|
||||
const WEIGHTED = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
return ex.bp !== 'cardio' && Object.values(weights).includes(0.4)
|
||||
})
|
||||
if (!SINGLE || !WEIGHTED) throw new Error('recovery tests require single- and secondary-weight fixtures')
|
||||
|
||||
const SINGLE_WEIGHTS = musclesOf(SINGLE)
|
||||
const WEIGHTED_WEIGHTS = musclesOf(WEIGHTED)
|
||||
const SINGLE_SLUG = Object.keys(SINGLE_WEIGHTS)[0]
|
||||
const WEIGHTED_PRIMARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 1)
|
||||
const SECONDARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 0.4)
|
||||
if (!WEIGHTED_PRIMARY_SLUG || !SECONDARY_SLUG) throw new Error('recovery tests require weighted primary and secondary fixtures')
|
||||
|
||||
const workoutAt = (id, start, sets = [{ done: true }]) => ({
|
||||
d: new Date(start).toISOString(),
|
||||
start,
|
||||
entries: [{ id, sets: sets.map(set => ({ ...set })) }],
|
||||
})
|
||||
const doneWorkoutAt = (id, start, count = 1) =>
|
||||
workoutAt(id, start, Array.from({ length: count }, () => ({ done: true })))
|
||||
const zeroFatigue = () => Object.fromEntries(MUSCLES.map(slug => [slug, 0]))
|
||||
const floorStrength = () => Object.fromEntries(MUSCLES.map(slug => [slug, STRENGTH_FLOOR]))
|
||||
|
||||
// Numeric fatigue remains the math API; the UI boundary selector is imported from production.
|
||||
const stableFloat = value => Number(value.toFixed(12))
|
||||
|
||||
describe('recovery constants', () => {
|
||||
it('exports the pinned windows, half-lives, floor, and state labels', () => {
|
||||
expect(FATIGUE_REF_VOLUME).toBe(3)
|
||||
expect(FATIGUE_SCAN_MS).toBe(30 * DAY)
|
||||
expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR)
|
||||
expect(STRENGTH_FULL_MS).toBe(14 * DAY)
|
||||
expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY)
|
||||
expect(STRENGTH_FLOOR).toBe(0.5)
|
||||
expect(FATIGUE_STATES).toEqual({ READY: 'ready', RECOVERING: 'recovering', FATIGUED: 'fatigued' })
|
||||
expect(halfLifeDecay(FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS)).toBe(0.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fatigueOf and strengthOf', () => {
|
||||
it('returns every muscle, ready/floor defaults, and hook defaults for empty history', () => {
|
||||
const fatigue = fatigueOf([], NOW)
|
||||
const strength = strengthOf([], NOW)
|
||||
|
||||
expect(Object.keys(fatigue)).toEqual(MUSCLES)
|
||||
expect(fatigue).toEqual(zeroFatigue())
|
||||
expect(Object.values(fatigue).map(fatigueStateOf)).toEqual(
|
||||
MUSCLES.map(() => FATIGUE_STATES.READY),
|
||||
)
|
||||
expect(Object.keys(strength)).toEqual(MUSCLES)
|
||||
expect(strength).toEqual(floorStrength())
|
||||
expect(fatiguedMuscles([], NOW)).toEqual([])
|
||||
expect(detrainedMuscles([], NOW)).toEqual(MUSCLES)
|
||||
})
|
||||
|
||||
it('applies one completed set to each of the exercise muscle weights', () => {
|
||||
const workouts = [doneWorkoutAt(WEIGHTED.id, NOW)]
|
||||
const fatigue = fatigueOf(workouts, NOW)
|
||||
const strength = strengthOf(workouts, NOW)
|
||||
|
||||
for (const slug of MUSCLES) {
|
||||
const weight = WEIGHTED_WEIGHTS[slug] || 0
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight / FATIGUE_REF_VOLUME), 10)
|
||||
expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
|
||||
}
|
||||
// one set never crosses the fatigued threshold on the saturating curve
|
||||
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
|
||||
})
|
||||
|
||||
it('raises starting fatigue with volume, never pins, and fades without a cliff', () => {
|
||||
const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG]
|
||||
expect(at0(1)).toBeCloseTo(1 - Math.exp(-1 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(12)).toBeGreaterThan(at0(5))
|
||||
expect(at0(5)).toBeGreaterThan(at0(1))
|
||||
expect(at0(12)).toBeLessThan(1)
|
||||
// one half-life later the gradient is still visible at any volume
|
||||
const later = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS, 12)], NOW)[SINGLE_SLUG]
|
||||
expect(later).toBeCloseTo(1 - Math.exp(-6 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(later).toBeLessThan(at0(12))
|
||||
// no cliff: 72h keeps decaying instead of snapping to zero
|
||||
const old = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)], NOW)[SINGLE_SLUG]
|
||||
expect(old).toBeGreaterThan(0)
|
||||
expect(old).toBeLessThan(0.25)
|
||||
})
|
||||
|
||||
it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => {
|
||||
for (const age of [FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS / 2]) {
|
||||
const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)
|
||||
const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS)
|
||||
for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) {
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight * expectedDecay / FATIGUE_REF_VOLUME), 10)
|
||||
}
|
||||
if (age === FATIGUE_HALF_LIFE_MS) {
|
||||
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-0.5 / FATIGUE_REF_VOLUME), 10)
|
||||
}
|
||||
if (age === FATIGUE_HALF_LIFE_MS / 2) {
|
||||
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-(0.5 ** 0.5) / FATIGUE_REF_VOLUME), 10)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('fades a 72-hour-old set below the ready threshold instead of hard-cutting', () => {
|
||||
const workouts = [doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)]
|
||||
const value = fatigueOf(workouts, NOW)[SINGLE_SLUG]
|
||||
expect(value).toBeGreaterThan(0)
|
||||
expect(value).toBeLessThan(0.25)
|
||||
expect(fatigueStateOf(value)).toBe(FATIGUE_STATES.READY)
|
||||
expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
|
||||
})
|
||||
|
||||
it('ignores sets whose done flag is false for both axes', () => {
|
||||
const workouts = [workoutAt(WEIGHTED.id, NOW, [{ done: false }])]
|
||||
expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue())
|
||||
expect(strengthOf(workouts, NOW)).toEqual(floorStrength())
|
||||
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
|
||||
expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fatigue state boundaries', () => {
|
||||
// Inverse of the saturation curve: raw stimulus needed to land exactly on a target level.
|
||||
const rawAt = target => -FATIGUE_REF_VOLUME * Math.log(1 - target)
|
||||
|
||||
it('classifies exactly .25 as recovering and .2499 as ready', () => {
|
||||
const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
|
||||
const sets = 3
|
||||
const valueAt = target => {
|
||||
const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * weight / rawAt(target))
|
||||
const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG]
|
||||
expect(value).toBeCloseTo(target, 10)
|
||||
return stableFloat(value)
|
||||
}
|
||||
|
||||
expect(fatigueStateOf(valueAt(0.25))).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(valueAt(0.2499))).toBe(FATIGUE_STATES.READY)
|
||||
})
|
||||
|
||||
it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => {
|
||||
const sets = 3
|
||||
const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.4999)), sets)]
|
||||
const aboveHalf = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.5001)), sets),
|
||||
]
|
||||
const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG]
|
||||
const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG]
|
||||
|
||||
expect(half).toBeCloseTo(0.4999, 10)
|
||||
expect(fatigueStateOf(stableFloat(half))).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatiguedMuscles(atHalf, NOW)).toEqual([])
|
||||
expect(above).toBeCloseTo(0.5001, 10)
|
||||
expect(fatigueStateOf(stableFloat(above))).toBe(FATIGUE_STATES.FATIGUED)
|
||||
expect(fatiguedMuscles(aboveHalf, NOW)).toEqual([SINGLE_SLUG])
|
||||
})
|
||||
})
|
||||
|
||||
describe('strengthOf', () => {
|
||||
const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG]
|
||||
|
||||
it('stays at full retention through 14 days and decays from 15 days by the 28-day half-life', () => {
|
||||
expect(strengthAt(STRENGTH_FULL_MS)).toBe(1)
|
||||
expect(strengthAt(15 * DAY)).toBeCloseTo(0.5 ** (1 / 28), 10)
|
||||
})
|
||||
|
||||
it('clamps the 42-day half-life point and later 56-day value at the .5 floor', () => {
|
||||
expect(strengthAt(42 * DAY)).toBe(0.5)
|
||||
expect(strengthAt(56 * DAY)).toBe(STRENGTH_FLOOR)
|
||||
})
|
||||
|
||||
it('resets retained strength when a later completed session retrains the muscle', () => {
|
||||
const workouts = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - 20 * DAY),
|
||||
doneWorkoutAt(SINGLE.id, NOW),
|
||||
]
|
||||
expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accumulation and purity', () => {
|
||||
it('matches the saturated sum of independently decayed stimuli in chronological order', () => {
|
||||
const ages = [64 * HOUR, 40 * HOUR]
|
||||
const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age))
|
||||
const raw = ages.reduce(
|
||||
(sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
|
||||
0,
|
||||
)
|
||||
const expected = 1 - Math.exp(-raw / FATIGUE_REF_VOLUME)
|
||||
|
||||
expect(raw).toBeLessThan(FATIGUE_REF_VOLUME)
|
||||
expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
|
||||
expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
|
||||
})
|
||||
|
||||
it('saturates without pinning and returns identical results without mutating inputs or sharing state', () => {
|
||||
const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)]
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(1 - Math.exp(-2 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1)
|
||||
|
||||
const workouts = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - 64 * HOUR),
|
||||
doneWorkoutAt(SINGLE.id, NOW - 40 * HOUR),
|
||||
]
|
||||
const before = JSON.parse(JSON.stringify(workouts))
|
||||
const firstFatigue = fatigueOf(workouts, NOW)
|
||||
const firstStrength = strengthOf(workouts, NOW)
|
||||
const secondFatigue = fatigueOf(workouts, NOW)
|
||||
const secondStrength = strengthOf(workouts, NOW)
|
||||
|
||||
expect(secondFatigue).toEqual(firstFatigue)
|
||||
expect(secondStrength).toEqual(firstStrength)
|
||||
expect(workouts).toEqual(before)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user