+
YOUR TRAINING OVER TIMERunning fitness
+
Accumulated running effort, fatigue and form. Scores describe training load, alongside your performance trends.
+
{{ data.zones.source }} · Edit fitness zones
+
{% for label in data.zones.labels %}Z{{ loop.index }}: {{ label }} bpm{{ ' · ' if not loop.last }}{% endfor %}
+{% if data.series %}
+{% set latest = data.series[-1] %}
+
{% for key in ['fitness', 'fatigue', 'form'] %}
{{ key|upper }}
{{ '%.1f'|format(latest[key]) }}
{{ 'Provisional estimate' if latest.provisional else 'Running load estimate' }}
{% endfor %}
+
Fitness, fatigue & form
+{% endif %}
+
{{ data.runs|length }} historical runs · {{ data.unscored }} unscored. Runs missing sufficient HR remain unscored. On those days the model uses only known effort, so subsequent values may underestimate load.
+
How these scores work
Effort v1 adds recorded moving minutes in Z1–Z5 with weights 1, 2, 3, 4 and 5. At each boundary HR belongs to the higher zone. At least 80% of timer time must have usable HR; missing time is not extrapolated. Recording breaks, stops and suspect HR are excluded by the recording analysis.
Each calendar day in your timezone updates fitness by (daily effort − previous fitness) × (1 − exp(−1/42)); fatigue uses 7 instead of 42. Form is same-day fitness minus fatigue. Multiple runs are summed; rest days contribute zero. The full history is calculated before choosing the visible range.
The model starts at zero at your earliest imported run; its first 126 days are provisional. Missing runs and unscored sessions can understate load. Only running is included. Changing HR zones recalculates all history with those zones. These are Stride estimates, with their own scale, rather than exact Strava scores.
+
Run effort
| Date | Run | Effort | HR coverage |
{% for run in data.runs %}| {{ run.day }} | {{ run.title }} | {{ '%.1f'|format(run.score) if run.score is not none else 'Unscored' }} | {{ run.coverage }}% |
{% else %}| Import runs to build your fitness history. |
{% endfor %}
+
+{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/training.py b/app/training.py
index 24e5ac1..8bb7673 100644
--- a/app/training.py
+++ b/app/training.py
@@ -1,6 +1,6 @@
"""Private training preferences and session observations."""
-from flask import Blueprint, abort, flash, redirect, request, url_for
+from flask import Blueprint, abort, flash, jsonify, redirect, render_template, request, url_for
from flask_login import current_user, login_required
from .extensions import db
@@ -9,6 +9,68 @@ from .models import Activity
training = Blueprint("training", __name__)
+@training.get("/fitness")
+@login_required
+def fitness():
+ from .fitness import history
+
+ return render_template("fitness.html", data=history(current_user))
+
+
+@training.get("/fitness/data")
+@login_required
+def fitness_data():
+ from .fitness import history
+
+ return jsonify(history(current_user))
+
+
+@training.app_context_processor
+def fitness_helpers():
+ from .fitness import effort
+ from .heart_rate import zones
+
+ return {"run_effort": effort, "fitness_zones": zones}
+
+
+@training.post("/training/zones")
+@login_required
+def zones():
+ from datetime import date, datetime
+ from zoneinfo import ZoneInfo
+
+ mode = request.form.get("mode")
+ if mode not in {"auto", "max", "custom"}:
+ abort(400)
+ config = {"mode": mode}
+ try:
+ birthday = request.form.get("birthday", "").strip()
+ if birthday:
+ birthday_date = date.fromisoformat(birthday)
+ today = datetime.now(ZoneInfo(current_user.timezone)).date()
+ age = today.year - birthday_date.year - ((today.month, today.day) <
+ (birthday_date.month, birthday_date.day))
+ if not 5 <= age <= 110:
+ abort(400)
+ config["birthday"] = birthday
+ if mode == "max":
+ maximum = int(request.form.get("max_hr", ""))
+ if not 100 <= maximum <= 230:
+ abort(400)
+ config["max_hr"] = maximum
+ if mode == "custom":
+ boundaries = [int(request.form.get(f"z{i}", "")) for i in range(2, 6)]
+ if not 30 <= boundaries[0] < boundaries[1] < boundaries[2] < boundaries[3] <= 230:
+ abort(400)
+ config["boundaries"] = boundaries
+ except (ValueError, TypeError):
+ abort(400)
+ current_user.hr_zones = config
+ db.session.commit()
+ flash("Fitness zones saved. Your full fitness history recalculates automatically.")
+ return redirect(url_for("training.fitness"))
+
+
@training.post("/training/bands")
@login_required
def bands():
diff --git a/docs/fitness.md b/docs/fitness.md
new file mode 100644
index 0000000..6bf5c92
--- /dev/null
+++ b/docs/fitness.md
@@ -0,0 +1,74 @@
+# Running fitness
+
+Open **Fitness** in the navigation. Choose automatic or manual five-zone settings in
+Settings. Existing recordings are scored immediately;
+no Strava connection or download is needed. Run detail pages show the same score.
+
+## Effort v1
+
+Recorded moving minutes in Z1–Z5 have weights 1, 2, 3, 4 and 5 respectively.
+An exact boundary belongs to the higher zone. Scores use their own scale and do not
+reproduce Strava numbers. The account's supplied boundaries are 122, 152, 167 and 181
+bpm (181 belongs to Z5 to avoid leaving a gap after Z4's 180).
+
+Three setting modes are supported:
+
+- Automatic: maximum HR is 220 minus age, updated on birthdays, or 190 without a birthday.
+- Manual maximum: the supplied maximum HR is fixed until edited.
+- Custom: four manually supplied boundaries are fixed until edited.
+
+The first two modes generate boundaries at 65%, 80%, 87% and 95% of maximum HR,
+rounded to the nearest bpm. These are explicit Stride defaults and may differ from
+Strava's unpublished zone boundary calculation. No peak-HR detection from recordings
+is performed. Existing three-band Stats settings remain independent.
+
+The calculation uses persisted `analysis_summary.intervals[].hr_seconds`, which
+exclude recording breaks, stops and suspect HR. Usable seconds must cover at least
+80% of the run's timer duration. The remainder is not extrapolated. Without adequate
+coverage the run remains unscored. Perceived effort is not used
+as a fallback because it has a different scale.
+
+## Daily model
+
+All recorded runs for the owner are grouped by their local calendar day. Daily load
+is the sum of scored effort. Fitness and fatigue start at zero at the earliest
+imported run and update every day, including rest days:
+
+```
+fitness += (load - fitness) * (1 - exp(-1 / 42))
+fatigue += (load - fatigue) * (1 - exp(-1 / 7))
+form = fitness - fatigue
+```
+
+The first 126 days (three fitness time constants) are marked provisional. An unscored
+run marks that day and all subsequent estimates provisional: the model continues
+using known effort only, while the day's complete load remains unavailable. Missing
+imports cannot be detected. Other sports are excluded. Values are calculated with
+full precision, rounded for display. Range controls trim only the displayed series.
+
+## Historical backfill
+
+The graph replays the complete stored history on each visit. Imports, deleted runs,
+timezone changes and zone edits therefore recalculate the history automatically.
+The open page checks for changes on focus and every five minutes while visible.
+There is no additional score cache. The `8da41b79e632` database migration adds the
+private `user.hr_zones` JSON configuration. Run `flask --app run db upgrade` before
+starting the updated app. Current zones apply to all dates; historical changes in
+zones are not reconstructed. This retrospective recalculation is a deliberate
+difference from Strava's documented future-only handling of subsequent zone edits.
+
+For older imports without current recording summaries, use the existing resumable
+command (take the normal database backup before operational maintenance):
+
+```
+python -m flask --app run backfill-analysis --owner-id OWNER_ID
+```
+
+If a current-version summary was damaged or lacks intervals despite usable samples,
+add `--force` to rebuild it. This regenerates the app's existing analysis summaries,
+charts and routes as well. Runs without usable original samples remain unscored.
+
+Local data audit during implementation: 18 running activities, all with current
+recording intervals; 17 meet the 80% HR coverage requirement (one has 78.5%).
+The supplied five zones were saved in custom mode and history replayed over 109
+calendar days. A SQLite backup was taken before applying the configuration migration.
diff --git a/migrations/versions/8da41b79e632_fitness_zones.py b/migrations/versions/8da41b79e632_fitness_zones.py
new file mode 100644
index 0000000..62148e4
--- /dev/null
+++ b/migrations/versions/8da41b79e632_fitness_zones.py
@@ -0,0 +1,19 @@
+"""Personal five-zone fitness settings."""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "8da41b79e632"
+down_revision = "7c6e32b491ad"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ with op.batch_alter_table("user") as batch:
+ batch.add_column(sa.Column("hr_zones", sa.JSON()))
+
+
+def downgrade():
+ with op.batch_alter_table("user") as batch:
+ batch.drop_column("hr_zones")
diff --git a/tests/test_fitness.py b/tests/test_fitness.py
new file mode 100644
index 0000000..b5ababc
--- /dev/null
+++ b/tests/test_fitness.py
@@ -0,0 +1,126 @@
+from datetime import UTC, date, datetime
+from math import exp
+from types import SimpleNamespace
+
+from test_app import login
+
+from app.extensions import db
+from app.fitness import effort, history
+from app.heart_rate import zones
+from app.models import Activity, User
+
+pytest_plugins = ("test_app",)
+
+
+def run(seconds=600, histogram=None):
+ return SimpleNamespace(
+ sport="running",
+ duration_s=seconds,
+ analysis_summary={"intervals": [{"hr_seconds": histogram or {}}]},
+ )
+
+
+def test_effort_boundaries_weights_and_coverage():
+ scored = effort(run(histogram={"120": 200, "140": 200, "160": 200}), [140, 160])
+ assert scored["score"] == 20
+ assert scored["coverage"] == 100
+ assert effort(run(histogram={"140": 479}), [140, 160])["score"] is None
+ assert effort(run(histogram={"140": 480}), [140, 160])["score"] == 16
+ assert effort(run(histogram={"140": 600}), None)["score"] is None
+ assert effort(run(histogram={"140": 600}), None)["coverage"] == 100
+ assert effort(run(histogram={"250": 600}), [140, 160])["score"] is None
+ five = effort(
+ run(histogram={"121": 120, "122": 120, "152": 120, "167": 120, "181": 120}),
+ [122, 152, 167, 181],
+ )
+ assert five["score"] == 30
+ assert five["zone_minutes"] == [2, 2, 2, 2, 2]
+
+
+def test_automatic_zones_update_on_birthday_manual_overrides():
+ user = SimpleNamespace(
+ timezone="Australia/Sydney", hr_zones={"mode": "auto", "birthday": "1990-10-22"}
+ )
+ assert zones(user, date(2026, 10, 21))["max_hr"] == 185
+ assert zones(user, date(2026, 10, 22))["max_hr"] == 184
+ user.hr_zones = {"mode": "max", "max_hr": 195, "birthday": "1990-10-22"}
+ assert zones(user, date(2026, 10, 22))["max_hr"] == 195
+ user.hr_zones = None
+ assert zones(user)["max_hr"] == 190
+ user.hr_zones = {"mode": "custom", "boundaries": [122, 152, 167, 181]}
+ assert zones(user)["labels"] == ["0–121", "122–151", "152–166", "167–180", "181+"]
+
+
+def test_history_local_days_sum_decay_missing_and_owner_scope(app):
+ with app.app_context():
+ db.session.delete(db.session.get(Activity, 1))
+ user = db.session.get(User, 1)
+ user.hr_zones = {"mode": "custom", "boundaries": [140, 160, 180, 200]}
+ for key, owner, hour, histogram in [
+ ("a", 1, 13, {"140": 600}),
+ ("b", 1, 14, {"140": 600}),
+ ("other", 2, 14, {"160": 600}),
+ ("missing", 1, 15, {}),
+ ]:
+ row = Activity(
+ owner_id=owner,
+ source_key=key,
+ title=key,
+ sport="running",
+ started_at=datetime(2026, 1, 1, hour, tzinfo=UTC),
+ duration_s=600,
+ analysis_summary=run(histogram=histogram).analysis_summary,
+ )
+ db.session.add(row)
+ db.session.commit()
+ data = history(user, date(2026, 1, 3))
+ assert len(data["runs"]) == 3
+ assert data["series"][0]["day"] == "2026-01-02"
+ first, second = data["series"]
+ assert first["load"] is None
+ assert first["missing"] == 1
+ assert first["fitness"] == round(40 * (1 - exp(-1 / 42)), 2)
+ assert first["fatigue"] == round(40 * (1 - exp(-1 / 7)), 2)
+ assert first["form"] == round(40 * (exp(-1 / 7) - exp(-1 / 42)), 2)
+ assert second["load"] == 0
+ assert second["fitness"] == round(40 * (1 - exp(-1 / 42)) * exp(-1 / 42), 2)
+ assert second["provisional"]
+ assert history(user, date(2026, 1, 3)) == data
+ user.hr_zones = {"mode": "custom", "boundaries": [160, 180, 200, 220]}
+ recalculated = history(user, date(2026, 1, 3))
+ assert recalculated["series"][0]["fitness"] == round(20 * (1 - exp(-1 / 42)), 2)
+ assert history(user, date(2026, 1, 1))["series"] == []
+
+
+def test_fitness_page_private_and_renders_history(app):
+ client = app.test_client()
+ assert client.get("/fitness").status_code == 302
+ assert client.get("/fitness/data").status_code == 302
+ login(client)
+ response = client.get("/fitness")
+ assert response.status_code == 200
+ assert len(client.get("/fitness/data").json["runs"]) == 1
+ assert b"A quiet morning run" in response.data
+ with app.app_context():
+ db.session.get(User, 1).hr_bands = [140, 160]
+ db.session.commit()
+ assert b"fitness-chart" in client.get("/fitness").data
+ assert b"Run effort:" in client.get("/activities/1").data
+
+
+def test_zone_settings_validation_persistence_and_privacy(app):
+ client = app.test_client()
+ assert client.post("/training/zones", data={"mode": "auto"}).status_code == 302
+ login(client)
+ valid = {"mode": "custom", "z2": "122", "z3": "152", "z4": "167", "z5": "181"}
+ assert client.post("/training/zones", data=valid).status_code == 302
+ assert client.post("/training/zones", data={**valid, "z3": "100"}).status_code == 400
+ assert client.post("/training/zones", data={"mode": "max", "max_hr": "999"}).status_code == 400
+ assert (
+ client.post("/training/zones", data={"mode": "auto", "birthday": "2099-01-01"}).status_code
+ == 400
+ )
+ with app.app_context():
+ assert db.session.get(User, 1).hr_zones["boundaries"] == [122, 152, 167, 181]
+ assert db.session.get(User, 2).hr_zones is None
+ assert b"Manual zone boundaries" in client.get("/settings").data