Windows installer; ship the dashboard template
- packaging/: PyInstaller spec (one folder, windowed, Python included), Inno Setup script (per-user install, Start menu, optional desktop icon, WebView2 check), build.ps1, app icon. - Bundled exe also runs the CLI (output to %LOCALAPPDATA%\myGarmin\cli.log). - Fix: .gitignore pattern dashboard*.html also hid src/mygarmin/report/dashboard.html, so the template was never committed and fresh clones could not build a dashboard. Patterns anchored; data file types (*.gpx, *.csv, *.json, *.gz, *.log) ignored too. - Self-test runs beside an open app (own WebView2 data folder, no single-instance check). - Neutral example values in a docstring and the tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
12
.gitignore
vendored
12
.gitignore
vendored
@@ -8,7 +8,8 @@
|
|||||||
*.trk
|
*.trk
|
||||||
*.ldk
|
*.ldk
|
||||||
*.zip
|
*.zip
|
||||||
dashboard*.html
|
/dashboard*.html
|
||||||
|
/*.html
|
||||||
settings.json
|
settings.json
|
||||||
.garminconnect/
|
.garminconnect/
|
||||||
garmin_tokens.json
|
garmin_tokens.json
|
||||||
@@ -16,6 +17,12 @@ library/
|
|||||||
originals/
|
originals/
|
||||||
exports/
|
exports/
|
||||||
inbox/
|
inbox/
|
||||||
|
*.gpx
|
||||||
|
*.csv
|
||||||
|
*.json
|
||||||
|
*.gz
|
||||||
|
*.log
|
||||||
|
build_log.txt
|
||||||
# synthetic test fixtures are allowed
|
# synthetic test fixtures are allowed
|
||||||
!tests/data/**
|
!tests/data/**
|
||||||
|
|
||||||
@@ -26,3 +33,6 @@ build/
|
|||||||
dist/
|
dist/
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
.venv/
|
.venv/
|
||||||
|
|
||||||
|
# packaging output and generated files
|
||||||
|
packaging/version_info.txt
|
||||||
|
|||||||
16
README.md
16
README.md
@@ -9,7 +9,12 @@ Everything stays on your PC: there is no server and no account, and nothing is u
|
|||||||
> Status: early (phase 0/1 of [docs/PLAN.md](docs/PLAN.md)), command line only. A desktop window and installer come next.
|
> Status: early (phase 0/1 of [docs/PLAN.md](docs/PLAN.md)), command line only. A desktop window and installer come next.
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
Python 3.12 or newer:
|
**Windows:** download `myGarmin-setup-<version>.exe` from the releases page and run it. No admin rights or Python needed;
|
||||||
|
it installs for your user only and adds myGarmin to the Start menu. The app window needs Microsoft Edge WebView2,
|
||||||
|
which Windows 11 includes (setup checks and points you to Microsoft's download if it is missing).
|
||||||
|
Uninstalling removes the program only; your library folder stays where you put it.
|
||||||
|
|
||||||
|
**From source** (any OS with Python 3.12 or newer; the app window and watch-over-USB are Windows-first):
|
||||||
```
|
```
|
||||||
pip install -e . # from a checkout of this repo
|
pip install -e . # from a checkout of this repo
|
||||||
pip install -e ".[api]" # also the Garmin Connect API (optional)
|
pip install -e ".[api]" # also the Garmin Connect API (optional)
|
||||||
@@ -53,7 +58,14 @@ mygarmin update D:\myGarmin # all of the above + build + export
|
|||||||
This repository never contains personal data. Your library folder holds your health data: keep it private.
|
This repository never contains personal data. Your library folder holds your health data: keep it private.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
`pip install -e ".[dev]"` then `pytest`. Tests use synthetic files only.
|
`pip install -e ".[dev,app]"`, then `pytest` (tests use synthetic files only) and `mygarmin-app` for the window.
|
||||||
|
|
||||||
|
Build the Windows installer (needs `pip install pyinstaller` and Inno Setup 6):
|
||||||
|
```
|
||||||
|
powershell -ExecutionPolicy Bypass -File packaging\build.ps1 # -> build\installer\myGarmin-setup-<version>.exe
|
||||||
|
```
|
||||||
|
The bundled `myGarmin.exe` also runs the command line (`myGarmin.exe status <library>`); as it has no console, output
|
||||||
|
goes to `%LOCALAPPDATA%\myGarmin\cli.log`. `MYGARMIN_SELFTEST=<file>` makes the window write what it shows and close.
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
MIT, see [LICENSE](LICENSE).
|
MIT, see [LICENSE](LICENSE).
|
||||||
|
|||||||
26
packaging/build.ps1
Normal file
26
packaging/build.ps1
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Build myGarmin-setup-<version>.exe: PyInstaller (one folder, Python included) -> Inno Setup installer.
|
||||||
|
# Needs: pip install pyinstaller ; Inno Setup 6 (winget install JRSoftware.InnoSetup).
|
||||||
|
# usage (from the repo): powershell -ExecutionPolicy Bypass -File packaging\build.ps1
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
|
Set-Location $here
|
||||||
|
$version = (Select-String -Path ..\pyproject.toml -Pattern '^version = "(.+)"').Matches[0].Groups[1].Value
|
||||||
|
$v4 = (($version -split '\.') + @('0', '0', '0'))[0..3] -join ', '
|
||||||
|
|
||||||
|
# Windows file version resource for myGarmin.exe
|
||||||
|
@"
|
||||||
|
VSVersionInfo(ffi=FixedFileInfo(filevers=($v4), prodvers=($v4)),
|
||||||
|
kids=[StringFileInfo([StringTable('040904B0', [StringStruct('ProductName', 'myGarmin'), StringStruct('FileDescription', 'myGarmin activity and health logbook'),
|
||||||
|
StringStruct('FileVersion', '$version'), StringStruct('ProductVersion', '$version'), StringStruct('LegalCopyright', 'MIT licence')])]),
|
||||||
|
VarFileInfo([VarStruct('Translation', [1033, 1200])])])
|
||||||
|
"@ | Out-File -Encoding utf8 version_info.txt
|
||||||
|
|
||||||
|
python -m PyInstaller --noconfirm --clean --distpath ..\build\dist --workpath ..\build\work myGarmin.spec
|
||||||
|
if ($LASTEXITCODE) { throw 'PyInstaller failed' }
|
||||||
|
|
||||||
|
$iscc = @("$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe", "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe", "$env:ProgramFiles\Inno Setup 6\ISCC.exe") |
|
||||||
|
Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||||
|
if (-not $iscc) { throw 'Inno Setup 6 not found (winget install JRSoftware.InnoSetup)' }
|
||||||
|
& $iscc "/DAppVersion=$version" myGarmin.iss
|
||||||
|
if ($LASTEXITCODE) { throw 'Inno Setup failed' }
|
||||||
|
Get-Item ..\build\installer\*.exe | Select-Object Name, @{n='MB'; e={[math]::Round($_.Length / 1MB, 1)}}
|
||||||
19
packaging/launcher.py
Normal file
19
packaging/launcher.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# Entry point of the bundled myGarmin.exe (PyInstaller).
|
||||||
|
# No arguments: the app window. With arguments: the mygarmin command line (myGarmin.exe import <library> <path> ...);
|
||||||
|
# the exe has no console, so its output goes to %LOCALAPPDATA%\myGarmin\cli.log.
|
||||||
|
import os, sys
|
||||||
|
|
||||||
|
if len(sys.argv) > 1:
|
||||||
|
log = os.path.join(os.environ.get('LOCALAPPDATA', os.path.expanduser('~')), 'myGarmin', 'cli.log')
|
||||||
|
os.makedirs(os.path.dirname(log), exist_ok=True)
|
||||||
|
sys.stdout = sys.stderr = open(log, 'a', encoding='utf-8', buffering=1)
|
||||||
|
print('>', ' '.join(sys.argv[1:]))
|
||||||
|
from mygarmin.cli import main
|
||||||
|
try: main(sys.argv[1:])
|
||||||
|
except SystemExit as e:
|
||||||
|
if e.code not in (None, 0): print('exit:', e.code); raise
|
||||||
|
except Exception:
|
||||||
|
import traceback; traceback.print_exc(); sys.exit(1)
|
||||||
|
else:
|
||||||
|
from mygarmin.app import main
|
||||||
|
main()
|
||||||
BIN
packaging/myGarmin.ico
Normal file
BIN
packaging/myGarmin.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
69
packaging/myGarmin.iss
Normal file
69
packaging/myGarmin.iss
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
; Inno Setup script for myGarmin. Built by packaging\build.ps1 (passes /DAppVersion=x.y.z).
|
||||||
|
; Installs per user (no admin rights) into %LOCALAPPDATA%\Programs\myGarmin. The user's library folder,
|
||||||
|
; settings and Garmin token live elsewhere and are never touched by setup or uninstall.
|
||||||
|
#ifndef AppVersion
|
||||||
|
#define AppVersion "0.0.0"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
[Setup]
|
||||||
|
AppId={{6B0E8C5A-3F2D-4C1B-9E7A-2D5F8A1C4B90}
|
||||||
|
AppName=myGarmin
|
||||||
|
AppVersion={#AppVersion}
|
||||||
|
AppVerName=myGarmin {#AppVersion}
|
||||||
|
AppPublisher=myGarmin (open source, MIT)
|
||||||
|
AppPublisherURL=https://services.doorduin.co.za/gitea/public/myGarminApp
|
||||||
|
DefaultDirName={autopf}\myGarmin
|
||||||
|
DefaultGroupName=myGarmin
|
||||||
|
DisableProgramGroupPage=yes
|
||||||
|
PrivilegesRequired=lowest
|
||||||
|
PrivilegesRequiredOverridesAllowed=dialog
|
||||||
|
ArchitecturesAllowed=x64compatible
|
||||||
|
ArchitecturesInstallIn64BitMode=x64compatible
|
||||||
|
MinVersion=10.0
|
||||||
|
OutputDir=..\build\installer
|
||||||
|
OutputBaseFilename=myGarmin-setup-{#AppVersion}
|
||||||
|
SetupIconFile=myGarmin.ico
|
||||||
|
UninstallDisplayIcon={app}\myGarmin.exe
|
||||||
|
LicenseFile=..\LICENSE
|
||||||
|
Compression=lzma2/max
|
||||||
|
SolidCompression=yes
|
||||||
|
WizardStyle=modern
|
||||||
|
CloseApplications=yes
|
||||||
|
|
||||||
|
[Tasks]
|
||||||
|
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"
|
||||||
|
|
||||||
|
[Files]
|
||||||
|
Source: "..\build\dist\myGarmin\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
|
||||||
|
|
||||||
|
[Icons]
|
||||||
|
Name: "{group}\myGarmin"; Filename: "{app}\myGarmin.exe"
|
||||||
|
Name: "{group}\Uninstall myGarmin"; Filename: "{uninstallexe}"
|
||||||
|
Name: "{autodesktop}\myGarmin"; Filename: "{app}\myGarmin.exe"; Tasks: desktopicon
|
||||||
|
|
||||||
|
[Run]
|
||||||
|
Filename: "{app}\myGarmin.exe"; Description: "{cm:LaunchProgram,myGarmin}"; Flags: nowait postinstall skipifsilent
|
||||||
|
|
||||||
|
[Code]
|
||||||
|
// The app window uses Microsoft Edge WebView2 (part of Windows 11; usually present on Windows 10).
|
||||||
|
function HasWebView2(): Boolean;
|
||||||
|
var v: String;
|
||||||
|
begin
|
||||||
|
Result := RegQueryStringValue(HKLM, 'SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', 'pv', v)
|
||||||
|
or RegQueryStringValue(HKCU, 'Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}', 'pv', v);
|
||||||
|
Result := Result and (v <> '') and (v <> '0.0.0.0');
|
||||||
|
end;
|
||||||
|
|
||||||
|
function InitializeSetup(): Boolean;
|
||||||
|
var code: Integer;
|
||||||
|
begin
|
||||||
|
Result := True;
|
||||||
|
if not HasWebView2() then
|
||||||
|
if MsgBox('myGarmin needs the Microsoft Edge WebView2 Runtime, which is not installed on this PC.' + #13#10#13#10 +
|
||||||
|
'Open the Microsoft download page now? (Install the "Evergreen Bootstrapper", then run this setup again.)',
|
||||||
|
mbConfirmation, MB_YESNO) = IDYES then
|
||||||
|
begin
|
||||||
|
ShellExec('open', 'https://developer.microsoft.com/microsoft-edge/webview2/', '', '', SW_SHOWNORMAL, ewNoWait, code);
|
||||||
|
Result := False;
|
||||||
|
end;
|
||||||
|
end;
|
||||||
BIN
packaging/myGarmin.png
Normal file
BIN
packaging/myGarmin.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
16
packaging/myGarmin.spec
Normal file
16
packaging/myGarmin.spec
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# PyInstaller spec: one-folder, windowed build of the myGarmin app. Build with packaging\build.ps1.
|
||||||
|
from PyInstaller.utils.hooks import collect_all, collect_data_files
|
||||||
|
|
||||||
|
datas = collect_data_files('mygarmin', includes=['**/*.html'])
|
||||||
|
datas += collect_data_files('timezonefinder') + collect_data_files('tzdata')
|
||||||
|
binaries, hidden = [], []
|
||||||
|
for pkg in ('webview', 'clr_loader', 'pythonnet', 'garminconnect', 'curl_cffi', 'timezonefinder'): # js files, .NET bridge, native libs, tz data (needs numpy)
|
||||||
|
d, b, h = collect_all(pkg); datas += d; binaries += b; hidden += h
|
||||||
|
|
||||||
|
a = Analysis(['launcher.py'], pathex=['../src'], binaries=binaries, datas=datas,
|
||||||
|
hiddenimports=hidden + ['mygarmin.sources.garmin_api', 'mygarmin.sources.watch', 'mygarmin.cli', 'mygarmin.export', 'mygarmin.report', 'mygarmin.dedupe', 'clr'],
|
||||||
|
excludes=['tkinter', 'matplotlib', 'pandas', 'PIL', 'pytest'], noarchive=False)
|
||||||
|
pyz = PYZ(a.pure)
|
||||||
|
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='myGarmin', icon='myGarmin.ico',
|
||||||
|
console=False, upx=False, version='version_info.txt')
|
||||||
|
coll = COLLECT(exe, a.binaries, a.datas, name='myGarmin', upx=False)
|
||||||
@@ -222,7 +222,9 @@ def _main():
|
|||||||
from webview.dom import DOMEventHandler
|
from webview.dom import DOMEventHandler
|
||||||
except ImportError:
|
except ImportError:
|
||||||
raise SystemExit('The app window needs pywebview: pip install "mygarmin[app]"')
|
raise SystemExit('The app window needs pywebview: pip install "mygarmin[app]"')
|
||||||
if sys.platform == 'win32': # a second window would share (and block on) the same browser data folder
|
selftest_out = os.environ.get('MYGARMIN_SELFTEST') # developer check, runs beside an open app with its own browser data
|
||||||
|
storage = os.path.join(os.path.dirname(STATE), 'webview-selftest' if selftest_out else 'webview')
|
||||||
|
if sys.platform == 'win32' and not selftest_out: # a second window would share (and block on) the same browser data folder
|
||||||
import ctypes
|
import ctypes
|
||||||
main._mutex = ctypes.windll.kernel32.CreateMutexW(None, False, 'Local\\myGarminApp')
|
main._mutex = ctypes.windll.kernel32.CreateMutexW(None, False, 'Local\\myGarminApp')
|
||||||
if ctypes.windll.kernel32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
if ctypes.windll.kernel32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||||
@@ -242,11 +244,11 @@ def _main():
|
|||||||
el.events.dragover += DOMEventHandler(lambda e: None, prevent_default=True)
|
el.events.dragover += DOMEventHandler(lambda e: None, prevent_default=True)
|
||||||
el.events.drop += DOMEventHandler(on_drop, prevent_default=True, stop_propagation=True)
|
el.events.drop += DOMEventHandler(on_drop, prevent_default=True, stop_propagation=True)
|
||||||
win.events.loaded += loaded
|
win.events.loaded += loaded
|
||||||
if os.environ.get('MYGARMIN_SELFTEST'): # developer check: does the page render through the real bridge?
|
if selftest_out: # does the page render through the real bridge?
|
||||||
def selftest():
|
def selftest():
|
||||||
import time; time.sleep(6)
|
import time; time.sleep(6)
|
||||||
r = win.evaluate_js("[document.getElementById('home').className, document.getElementById('setup').className, "
|
r = win.evaluate_js("[document.getElementById('home').className, document.getElementById('setup').className, "
|
||||||
"document.getElementById('tiles').innerText.replace(/\\s+/g, ' ').slice(0, 120)].join(' | ')")
|
"document.getElementById('tiles').innerText.replace(/\\s+/g, ' ').slice(0, 120)].join(' | ')")
|
||||||
open(os.environ['MYGARMIN_SELFTEST'], 'w', encoding='utf-8').write(str(r)); win.destroy()
|
open(selftest_out, 'w', encoding='utf-8').write(str(r)); win.destroy()
|
||||||
threading.Thread(target=selftest, daemon=True).start()
|
threading.Thread(target=selftest, daemon=True).start()
|
||||||
webview.start(private_mode=False, storage_path=os.path.join(os.path.dirname(STATE), 'webview'))
|
webview.start(private_mode=False, storage_path=storage)
|
||||||
|
|||||||
528
src/mygarmin/report/dashboard.html
Normal file
528
src/mygarmin/report/dashboard.html
Normal file
@@ -0,0 +1,528 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>__TITLE__</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,600&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap">
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css">
|
||||||
|
<style>
|
||||||
|
/* Layout: one reading column of sections (summary -> trends -> map -> month table -> activity log); field-notebook feel */
|
||||||
|
:root {
|
||||||
|
--bg: #f7f7f4; --surface: #ffffff; --fg: #171a17; --muted: #5d625c; --rule: #dfe1db; --accent: #1f6f5c;
|
||||||
|
--s1: #2a78d6; --s2: #eb6834; --s3: #1baf7a; --s4: #eda100; --s5: #e87ba4; --s6: #008300; --s7: #6250d6; --s8: #8a8f88;
|
||||||
|
--display: "Fraunces", Georgia, serif; --body: "IBM Plex Sans", system-ui, sans-serif; --mono: "IBM Plex Mono", ui-monospace, monospace;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) {
|
||||||
|
--bg: #141613; --surface: #1c1f1b; --fg: #eceee9; --muted: #a4a9a2; --rule: #2f332e; --accent: #5fc2a6;
|
||||||
|
--s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500; --s5: #d55181; --s6: #2f9a2f; --s7: #9085e9; --s8: #8f948d; color-scheme: dark } }
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--bg: #141613; --surface: #1c1f1b; --fg: #eceee9; --muted: #a4a9a2; --rule: #2f332e; --accent: #5fc2a6;
|
||||||
|
--s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500; --s5: #d55181; --s6: #2f9a2f; --s7: #9085e9; --s8: #8f948d; color-scheme: dark }
|
||||||
|
* { box-sizing: border-box }
|
||||||
|
body { margin: 0; background: var(--bg); color: var(--fg); font: 15px/1.5 var(--body) }
|
||||||
|
main { max-width: 1180px; margin: 0 auto; padding-inline: 16px; padding-block: 32px 64px; display: grid; gap: 40px }
|
||||||
|
h1, h2 { font-family: var(--display); font-weight: 600; text-wrap: balance; margin: 0 }
|
||||||
|
h1 { font-size: clamp(28px, 4vw, 42px); line-height: 1.1 }
|
||||||
|
h2 { font-size: 22px }
|
||||||
|
.eyebrow { font: 500 12px var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--muted) }
|
||||||
|
.lede { color: var(--muted); max-width: 70ch; margin: 8px 0 0 }
|
||||||
|
section { display: grid; gap: 14px; min-width: 0 }
|
||||||
|
.note { color: var(--muted); font-size: 13px; max-width: 75ch; margin: 0 }
|
||||||
|
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px }
|
||||||
|
.tile { background: var(--surface); border: 1px solid var(--rule); border-radius: 8px; padding: 14px 16px }
|
||||||
|
.tile b { display: block; font: 600 28px var(--display); font-variant-numeric: tabular-nums }
|
||||||
|
.tile span { color: var(--muted); font-size: 13px }
|
||||||
|
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 460px), 1fr)); gap: 16px }
|
||||||
|
.card { background: var(--surface); border: 1px solid var(--rule); border-radius: 8px; padding: 16px; min-width: 0; display: grid; gap: 8px }
|
||||||
|
.card h3 { margin: 0; font: 600 15px var(--body) }
|
||||||
|
.chartbox { position: relative; height: 260px }
|
||||||
|
.chartbox.tall { height: 320px }
|
||||||
|
.legend { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 13px; color: var(--muted) }
|
||||||
|
.legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 6px; vertical-align: -1px }
|
||||||
|
.controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center }
|
||||||
|
.chip { font: 500 13px var(--body); border: 1px solid var(--rule); background: var(--surface); color: var(--fg); border-radius: 999px; padding: 5px 12px; cursor: pointer }
|
||||||
|
.chip[aria-pressed="true"] { background: var(--fg); color: var(--bg); border-color: var(--fg) }
|
||||||
|
.chip:focus-visible, select:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px }
|
||||||
|
.chip i { display: inline-block; width: 9px; height: 9px; border-radius: 50%; margin-right: 6px }
|
||||||
|
select, input[type=search] { font: 14px var(--body); background: var(--surface); color: var(--fg); border: 1px solid var(--rule); border-radius: 6px; padding: 5px 8px }
|
||||||
|
#map { height: min(70vh, 640px); border-radius: 8px; border: 1px solid var(--rule); z-index: 0 }
|
||||||
|
.scroll { overflow-x: auto; border: 1px solid var(--rule); border-radius: 8px; background: var(--surface) }
|
||||||
|
.scroll.capped { max-height: 520px; overflow-y: auto }
|
||||||
|
table { border-collapse: collapse; width: 100%; font-size: 13px; font-variant-numeric: tabular-nums }
|
||||||
|
th, td { padding: 6px 10px; text-align: right; white-space: nowrap; border-bottom: 1px solid var(--rule) }
|
||||||
|
th:first-child, td:first-child, td.l, th.l { text-align: left }
|
||||||
|
thead th { position: sticky; top: 0; background: var(--surface); font-weight: 600; cursor: pointer; z-index: 1 }
|
||||||
|
tbody tr:hover { background: color-mix(in srgb, var(--accent) 8%, transparent) }
|
||||||
|
td.dim { color: var(--muted) }
|
||||||
|
tr.year td { font-weight: 600; background: color-mix(in srgb, var(--fg) 5%, transparent) }
|
||||||
|
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px }
|
||||||
|
.findings { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); gap: 12px }
|
||||||
|
.findings article { background: var(--surface); border: 1px solid var(--rule); border-radius: 8px; padding: 14px 16px; min-width: 0 }
|
||||||
|
.findings h3 { margin: 0 0 6px; font: 600 15px var(--body) }
|
||||||
|
.findings p { margin: 0; color: var(--muted); font-size: 14px }
|
||||||
|
.findings b { color: var(--fg); font-variant-numeric: tabular-nums }
|
||||||
|
h3.sub { margin: 8px 0 0; font: 600 16px var(--body) }
|
||||||
|
.bands { font-size: 12px; color: var(--muted) }
|
||||||
|
.bands i { display: inline-block; width: 16px; border-top: 2px dashed var(--muted); margin-right: 6px; vertical-align: middle }
|
||||||
|
.leaflet-popup-content { font: 13px/1.45 var(--body) }
|
||||||
|
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important } }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<header>
|
||||||
|
<div class="eyebrow" id="eyebrow"></div>
|
||||||
|
<h1 id="title"></h1>
|
||||||
|
<p class="lede" id="lede"></p>
|
||||||
|
<p class="note" id="headNote"></p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<div class="tiles" id="tiles"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="findings">
|
||||||
|
<h2>What the data says about fitness and age</h2>
|
||||||
|
<p class="note" id="ageNote"></p>
|
||||||
|
<div class="findings" id="find"></div>
|
||||||
|
<h3 class="sub">Year by year</h3>
|
||||||
|
<div class="scroll"><table id="tYear"></table></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Activity per month</h2>
|
||||||
|
<div class="controls" id="volMode">
|
||||||
|
<button class="chip" aria-pressed="true" data-m="hours">Hours</button>
|
||||||
|
<button class="chip" aria-pressed="false" data-m="km">Distance (km)</button>
|
||||||
|
<button class="chip" aria-pressed="false" data-m="count">Sessions</button>
|
||||||
|
</div>
|
||||||
|
<div class="card"><div class="legend" id="legendVol"></div><div class="chartbox tall"><canvas id="cVol" role="img" aria-label="Monthly activity volume stacked by sport"></canvas></div></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="markers">
|
||||||
|
<h2>Fitness markers from the activities</h2>
|
||||||
|
<p class="note">From the values stamped into each activity file. VO2max is Garmin's running estimate (updated on outdoor runs with GPS and heart rate). Higher efficiency means more distance per heartbeat, a sign of aerobic fitness. Charts without data are left out.</p>
|
||||||
|
<div class="grid2">
|
||||||
|
<div class="card" id="kVo2"><h3>VO2max (ml/kg/min)</h3><div class="bands" id="vo2Bands"></div><div class="chartbox"><canvas id="cVo2" role="img" aria-label="VO2max over time"></canvas></div></div>
|
||||||
|
<div class="card" id="kEff"><h3>Running efficiency (metres per heartbeat), each run</h3><div class="chartbox"><canvas id="cEff" role="img" aria-label="Running distance per heartbeat per run"></canvas></div></div>
|
||||||
|
<div class="card" id="kPace"><h3>Running: average pace (min/km), each run</h3><p class="note">Runs slower than 12 min/km (paused recordings) and runs with GPS errors are left out.</p><div class="chartbox"><canvas id="cPace" role="img" aria-label="Running pace per run"></canvas></div></div>
|
||||||
|
<div class="card" id="kRunHr"><h3>Running: average heart rate (bpm), each run</h3><div class="chartbox"><canvas id="cRunHr" role="img" aria-label="Running average heart rate per run"></canvas></div></div>
|
||||||
|
<div class="card" id="kTe"><h3>Aerobic training effect, monthly average</h3><div class="chartbox"><canvas id="cTe" role="img" aria-label="Average aerobic training effect per month"></canvas></div></div>
|
||||||
|
<div class="card" id="kAsc"><h3>Climbing per month (m ascent, all sports)</h3><div class="chartbox"><canvas id="cAsc" role="img" aria-label="Total ascent per month"></canvas></div></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="health" hidden>
|
||||||
|
<h2>Sleep and health</h2>
|
||||||
|
<p class="note" id="hNote"></p>
|
||||||
|
<div class="tiles" id="hTiles"></div>
|
||||||
|
<div class="findings" id="hFind"></div>
|
||||||
|
<div class="grid2">
|
||||||
|
<div class="card" data-k="sleep"><h3>Sleep per night, monthly average (hours)</h3><div class="legend" id="hSleepLeg"></div><div class="chartbox"><canvas id="cSleep" role="img" aria-label="Average hours of deep, light, REM sleep and awake time per month"></canvas></div></div>
|
||||||
|
<div class="card" data-k="sscore"><h3>Sleep score and training readiness, 30-day average</h3><div class="legend" id="hScoreLeg"></div><div class="chartbox"><canvas id="cScore" role="img" aria-label="Sleep score and training readiness over time"></canvas></div></div>
|
||||||
|
<div class="card" data-k="bed"><h3>Bedtime and wake-up, monthly median</h3><div class="legend" id="hBedLeg"></div><div class="chartbox"><canvas id="cBed" role="img" aria-label="Median bedtime and wake-up time per month"></canvas></div></div>
|
||||||
|
<div class="card" data-k="sleep"><h3>Average sleep by night of the week (hours)</h3><div class="chartbox"><canvas id="cWeek" role="img" aria-label="Average hours of sleep by night of the week"></canvas></div></div>
|
||||||
|
<div class="card" data-k="rhr"><h3>Resting heart rate (bpm)</h3><p class="note">Garmin's 7-day average per day; the line is the 30-day average.</p><div class="chartbox"><canvas id="cRhr" role="img" aria-label="Daily resting heart rate"></canvas></div></div>
|
||||||
|
<div class="card" data-k="hrvW"><h3>Heart rate variability overnight (ms)</h3><p class="note">Line: Garmin's 7-day average. Dots: single nights, where stored. Higher is generally better.</p><div class="chartbox"><canvas id="cHrv" role="img" aria-label="Overnight heart rate variability"></canvas></div></div>
|
||||||
|
<div class="card" data-k="stress"><h3>Stress and Body Battery, 30-day average</h3><div class="legend" id="hStressLeg"></div><div class="chartbox"><canvas id="cStress" role="img" aria-label="All-day stress and daily Body Battery peak"></canvas></div></div>
|
||||||
|
<div class="card" data-k="fage"><h3>Fitness age against real age (years)</h3><div class="legend" id="hAgeLeg"></div><div class="chartbox"><canvas id="cAge" role="img" aria-label="Garmin fitness age and real age"></canvas></div></div>
|
||||||
|
<div class="card" data-k="p5k"><h3>5 km: Garmin's prediction against actual 5 km races</h3><div class="legend" id="hPredLeg"></div><div class="chartbox"><canvas id="cPred" role="img" aria-label="Predicted 5 km time and actual race times"></canvas></div></div>
|
||||||
|
<div class="card" data-k="acute"><h3>Training load: last 7 days against your usual (acute vs chronic)</h3><div class="legend" id="hLoadLeg"></div><div class="chartbox"><canvas id="cLoad" role="img" aria-label="Acute and chronic training load"></canvas></div></div>
|
||||||
|
</div>
|
||||||
|
<div id="bpBlock" hidden>
|
||||||
|
<h3 class="sub">Blood pressure and haemoglobin (entered by hand)</h3>
|
||||||
|
<div class="grid2">
|
||||||
|
<div class="card" style="align-content:start"><div class="legend" id="hBpLeg"></div><div class="chartbox"><canvas id="cBp" role="img" aria-label="Blood pressure and haemoglobin readings"></canvas></div></div>
|
||||||
|
<div class="scroll"><table id="tBp"></table></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="races" hidden>
|
||||||
|
<h2>Races</h2>
|
||||||
|
<p class="note">From races.csv in the library, entered by hand. Age grade compares a time with the world best for your age and sex, so it already allows for getting older. Where an activity was recorded that day, its heart rate is shown.</p>
|
||||||
|
<div class="tiles" id="prTiles"></div>
|
||||||
|
<div class="grid2">
|
||||||
|
<div class="card"><h3>Finish time</h3><div class="legend" id="prLegend"></div><div class="chartbox"><canvas id="cPrTime" role="img" aria-label="Race finish time per race"></canvas></div></div>
|
||||||
|
<div class="card" id="prAgCard"><h3>Age grade (%)</h3><p class="note">Higher is better. On the usual scale 60% is local class, 70% regional, 80% national.</p><div class="chartbox"><canvas id="cPrAg" role="img" aria-label="Race age grade per race"></canvas></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="scroll"><table id="tPr"></table></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Where you went</h2>
|
||||||
|
<div class="controls" id="mapSports"></div>
|
||||||
|
<div class="controls"><label for="mapYear">Year</label><select id="mapYear"></select><span class="note" id="mapCount"></span></div>
|
||||||
|
<div id="map"></div>
|
||||||
|
<p class="note">Tracks are simplified to about 400 points each for speed; full-resolution tracks are in the exports folder (GPX and AlpineQuest). Click a track for details. Switch between street, topographic and satellite maps at the top right of the map.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Month by month</h2>
|
||||||
|
<div class="scroll"><table id="tMonth"></table></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>All activities</h2>
|
||||||
|
<div class="controls"><input type="search" id="q" placeholder="Filter, e.g. hiking or 2024-06" aria-label="Filter activities"><span class="note" id="qCount"></span></div>
|
||||||
|
<div class="scroll capped"><table id="tAct"></table></div>
|
||||||
|
</section>
|
||||||
|
<p class="note" id="foot"></p>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
|
||||||
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
|
||||||
|
<script>
|
||||||
|
const DATA = __DATA__;
|
||||||
|
const P = DATA.profile, ACTS = DATA.acts, TRACKS = DATA.tracks, HEALTH = DATA.health, RACES = DATA.races || [];
|
||||||
|
const GROUPS = [
|
||||||
|
['Cycling', a => a.sport === 'cycling'], ['Running', a => a.sport === 'running'], ['Hiking', a => a.sport === 'hiking' || a.sport === 'mountaineering'],
|
||||||
|
['Walking', a => a.sport === 'walking'], ['Swimming', a => a.sport === 'swimming'], ['Gym & classes', a => ['fitness_equipment', 'training'].includes(a.sport)],
|
||||||
|
['Climbing', a => a.sport === 'rock_climbing'], ['Other', a => true]];
|
||||||
|
const SRC = { fit: 'Garmin (FIT)', tcx: 'Garmin (TCX)', alpinequest: 'AlpineQuest', strava: 'Strava', gpx: 'GPX' };
|
||||||
|
const css = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
const color = i => css('--s' + (i + 1));
|
||||||
|
const fmtD = t => new Date(t).toISOString().slice(0, 10);
|
||||||
|
const sum = (arr, k) => arr.reduce((s, a) => s + (a[k] || 0), 0);
|
||||||
|
const med = x => { if (!x.length) return null; const y = [...x].sort((a, b) => a - b), m = y.length >> 1; return y.length % 2 ? y[m] : (y[m - 1] + y[m]) / 2 };
|
||||||
|
const avg = x => x.length ? x.reduce((s, v) => s + v, 0) / x.length : null;
|
||||||
|
const pace = m => `${Math.floor(m)}:${String(Math.round((m % 1) * 60)).padStart(2, '0')}`;
|
||||||
|
const mmss = s => `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, '0')}`;
|
||||||
|
const range = xs => { const a = Math.min(...xs), b = Math.max(...xs); return a === b ? String(a) : `${a}–${b}` };
|
||||||
|
const ageIn = y => P.birth_year ? y - P.birth_year : null;
|
||||||
|
const you = P.name ? P.name + "'s" : 'My';
|
||||||
|
const goodRun = a => a.sport === 'running' && a.sub_sport !== 'suspect GPS' && a.dist_km > 1 && a.moving_min / a.dist_km >= 3 && a.moving_min / a.dist_km <= 12;
|
||||||
|
ACTS.forEach(a => { a.g = GROUPS.findIndex(([, f]) => f(a)); a.month = a.start_local.slice(0, 7); a.t = Date.parse(a.start_utc); a.srcl = SRC[a.src] || a.src;
|
||||||
|
a.grp = GROUPS[a.g][0] + (a.sub_sport && !['generic', 'None', 'tagged', 'guessed by speed'].includes(a.sub_sport) ? ' · ' + a.sub_sport.replace('_', ' ') : ''); });
|
||||||
|
ACTS.sort((x, y) => x.t - y.t);
|
||||||
|
document.title = `${you} activity logbook`; $('title').textContent = `${you} activity logbook`;
|
||||||
|
|
||||||
|
// months, with long empty stretches collapsed into one gap label
|
||||||
|
const allMonths = []; { let [y, m] = ACTS[0].month.split('-').map(Number); const [ye, me] = ACTS.at(-1).month.split('-').map(Number);
|
||||||
|
while (y < ye || (y === ye && m <= me)) { allMonths.push(`${y}-${String(m).padStart(2, '0')}`); m++; if (m > 12) { m = 1; y++ } } }
|
||||||
|
const active = new Set(ACTS.map(a => a.month)); const months = [], gaps = [];
|
||||||
|
for (let i = 0; i < allMonths.length;) {
|
||||||
|
let j = i; while (j < allMonths.length && !active.has(allMonths[j])) j++;
|
||||||
|
if (j - i > 6) { months.push(`no data ${allMonths[i]} to ${allMonths[j - 1]}`); gaps.push([allMonths[i], allMonths[j - 1]]); i = j } else { months.push(allMonths[i]); i++ }
|
||||||
|
}
|
||||||
|
const years = [...new Set(ACTS.map(a => a.start_local.slice(0, 4)))];
|
||||||
|
|
||||||
|
// header: which sources cover which years
|
||||||
|
const spans = Object.keys(SRC).map(s => { const x = ACTS.filter(a => a.src === s); return x.length ? `${SRC[s]} (${range([...new Set([x[0].start_local.slice(0, 4), x.at(-1).start_local.slice(0, 4)])].map(Number))})` : null }).filter(Boolean);
|
||||||
|
const hd = HEALTH && HEALTH.days.length ? HEALTH.days : null;
|
||||||
|
$('eyebrow').textContent = `${[...new Set(spans.map(s => s.split(' (')[0]))].join(' + ')}${hd ? ' + Garmin Connect health' : ''} · ${ACTS[0].month} to ${ACTS.at(-1).month}`;
|
||||||
|
$('lede').textContent = `Every activity rebuilt from the original files: ${spans.join(', ')}${hd ? `, plus daily sleep and health data from Garmin Connect (${hd[0].d.slice(0, 4)} onwards)` : ''}. What you did each month, how fitness markers moved, and where you went.`;
|
||||||
|
const fmtM = m => new Date(m + '-15').toLocaleString('en', { month: 'long', year: 'numeric' });
|
||||||
|
$('headNote').textContent = 'When several sources recorded the same outing, one copy is kept (watch first). Car, plane, train and boat trips and very short tracks are left out; tracks without an activity type were classified by speed, so a few may be mislabelled.' +
|
||||||
|
(gaps.length ? ` There are no recordings ${gaps.map(([a, b]) => `from ${fmtM(a)} to ${fmtM(b)}`).join(', ')}.` : '');
|
||||||
|
|
||||||
|
// tiles
|
||||||
|
$('tiles').innerHTML = [[ACTS.length, 'activities'], [Math.round(sum(ACTS, 'dist_km')).toLocaleString(), 'km covered'], [Math.round(sum(ACTS, 'moving_min') / 60).toLocaleString(), 'hours of activity'],
|
||||||
|
[Math.round(sum(ACTS, 'ascent_m')).toLocaleString(), 'm climbed'], [ACTS.filter(a => TRACKS[a.file]).length, 'GPS tracks']].map(([v, l]) => `<div class="tile"><b>${v}</b><span>${l}</span></div>`).join('');
|
||||||
|
|
||||||
|
Chart.defaults.font.family = css('--body').split(',')[0].replace(/"/g, '');
|
||||||
|
Chart.defaults.color = css('--muted');
|
||||||
|
Chart.defaults.borderColor = css('--rule');
|
||||||
|
const grid = { color: css('--rule') };
|
||||||
|
const tip = { backgroundColor: css('--surface'), titleColor: css('--fg'), bodyColor: css('--fg'), borderColor: css('--rule'), borderWidth: 1, padding: 10 };
|
||||||
|
const gapTicks = { maxRotation: 0, maxTicksLimit: 8, callback(v) { const l = this.getLabelForValue(v); return l.startsWith('no data') ? '⋯' : l } };
|
||||||
|
|
||||||
|
// VO2max ratings (Cooper Institute norms, as Garmin uses): [superior, excellent, good, fair] lower bounds per age band
|
||||||
|
const VO2N = { M: [[29, 55.4, 51.1, 45.4, 41.7], [39, 54.0, 48.3, 44.0, 40.5], [49, 52.5, 46.4, 42.4, 38.5], [59, 48.9, 43.4, 39.2, 35.6], [69, 45.7, 39.5, 35.5, 32.3], [200, 42.1, 36.7, 32.3, 29.4]],
|
||||||
|
F: [[29, 49.6, 43.9, 39.5, 36.1], [39, 47.4, 42.4, 37.8, 34.4], [49, 45.3, 39.7, 36.3, 33.0], [59, 41.1, 36.7, 33.0, 30.1], [69, 37.8, 33.0, 30.0, 27.5], [200, 36.7, 30.9, 28.1, 25.9]] };
|
||||||
|
const nowAge = ageIn(new Date().getFullYear());
|
||||||
|
const vo2Norm = P.sex && nowAge ? VO2N[P.sex].find(r => nowAge <= r[0]) : null;
|
||||||
|
const vo2Band = (age, sex) => sex && age ? VO2N[sex].find(r => age <= r[0]) : null;
|
||||||
|
const vo2Label = v => { if (!vo2Norm) return ''; const i = vo2Norm.slice(1).findIndex(b => v >= b); return ['Superior', 'Excellent', 'Good', 'Fair'][i] || 'Poor' };
|
||||||
|
const sexWord = { M: 'men', F: 'women' }[P.sex];
|
||||||
|
const ageBand = vo2Norm ? (() => { const i = VO2N[P.sex].indexOf(vo2Norm); return i === VO2N[P.sex].length - 1 ? '70+' : `${20 + 10 * i}–${29 + 10 * i}` })() : null;
|
||||||
|
|
||||||
|
// monthly volume
|
||||||
|
const usedGroups = GROUPS.map((g, i) => i).filter(i => ACTS.some(a => a.g === i));
|
||||||
|
$('legendVol').innerHTML = usedGroups.map(i => `<span><i style="background:${color(i)}"></i>${GROUPS[i][0]}</span>`).join('');
|
||||||
|
const volVal = { hours: a => a.moving_min / 60, km: a => a.dist_km, count: () => 1 };
|
||||||
|
const volData = mode => usedGroups.map(i => ({ label: GROUPS[i][0], backgroundColor: color(i), borderColor: css('--surface'), borderWidth: { top: 2 }, borderRadius: 2, borderSkipped: 'bottom',
|
||||||
|
data: months.map(m => +ACTS.filter(a => a.month === m && a.g === i).reduce((s, a) => s + volVal[mode](a), 0).toFixed(1)) }));
|
||||||
|
const cVol = new Chart($('cVol'), { type: 'bar', data: { labels: months, datasets: volData('hours') },
|
||||||
|
options: { maintainAspectRatio: false, interaction: { mode: 'index', intersect: false },
|
||||||
|
plugins: { legend: { display: false }, tooltip: { ...tip, filter: i => i.raw > 0, footer: items => 'Total ' + items.reduce((s, i) => s + i.raw, 0).toFixed(1) } },
|
||||||
|
scales: { x: { stacked: true, grid: { display: false }, ticks: { ...gapTicks, maxTicksLimit: 12 } }, y: { stacked: true, grid } } } });
|
||||||
|
$('volMode').addEventListener('click', e => { const b = e.target.closest('button'); if (!b) return;
|
||||||
|
document.querySelectorAll('#volMode .chip').forEach(c => c.setAttribute('aria-pressed', c === b)); cVol.data.datasets = volData(b.dataset.m); cVol.update(); });
|
||||||
|
|
||||||
|
// activity markers
|
||||||
|
function series(id, pts, col, { yfmt = v => v, tfmt = v => v, line = true, reverse = false, step = false, bands = [] } = {}) {
|
||||||
|
if (!pts.length) { $(id).closest('.card').hidden = true; return }
|
||||||
|
const x0 = pts[0].x, x1 = pts.at(-1).x;
|
||||||
|
const bandSets = bands.map(v => ({ data: [{ x: x0, y: v }, { x: x1, y: v }], borderColor: css('--muted'), borderDash: [5, 4], borderWidth: 1.5, pointRadius: 0, pointHoverRadius: 0 }));
|
||||||
|
new Chart($(id), { type: 'line',
|
||||||
|
data: { datasets: [{ data: pts, borderColor: col, backgroundColor: col, borderWidth: line ? 2 : 0, pointRadius: line ? 0 : 3, pointHoverRadius: 5, stepped: step, showLine: line, tension: 0 }, ...bandSets] },
|
||||||
|
options: { maintainAspectRatio: false, parsing: false, interaction: { mode: 'nearest', intersect: false },
|
||||||
|
plugins: { legend: { display: false }, tooltip: { ...tip, filter: i => i.datasetIndex === 0, callbacks: { title: i => fmtD(i[0].raw.x) + (i[0].raw.n ? ' · ' + i[0].raw.n : ''), label: i => tfmt(i.raw.y) } } },
|
||||||
|
scales: { x: { type: 'linear', grid, ticks: { callback: v => new Date(v).toISOString().slice(0, 7), maxTicksLimit: 7 } }, y: { grid, reverse, ticks: { callback: yfmt } } } } });
|
||||||
|
}
|
||||||
|
const pts = (f, v) => ACTS.filter(f).map(a => ({ x: a.t, y: v(a), n: a.sport })).filter(p => p.y != null && isFinite(p.y));
|
||||||
|
if (vo2Norm) $('vo2Bands').innerHTML = `<i></i>Rating for ${sexWord} aged ${ageBand}: Superior from ${vo2Norm[1]}, Excellent from ${vo2Norm[2]}`;
|
||||||
|
series('cVo2', pts(a => a.sport === 'running' && a.vo2max, a => a.vo2max), color(0), { step: true, tfmt: v => v + ' ml/kg/min', bands: vo2Norm ? [vo2Norm[1], vo2Norm[2]] : [] });
|
||||||
|
series('cEff', pts(a => a.sport === 'running' && a.avg_hr && a.dist_km > 1, a => +(a.dist_km * 1000 / (a.avg_hr * a.moving_min)).toFixed(2)), color(6), { line: false, tfmt: v => v + ' m/beat' });
|
||||||
|
series('cPace', pts(goodRun, a => a.moving_min / a.dist_km), color(1), { line: false, reverse: true, yfmt: pace, tfmt: v => pace(v) + ' /km' });
|
||||||
|
series('cRunHr', pts(a => a.sport === 'running' && a.avg_hr, a => a.avg_hr), color(4), { line: false, tfmt: v => v + ' bpm' });
|
||||||
|
const barChart = (id, data, col, o = {}) => { if (!data.some(v => v)) { $(id).closest('.card').hidden = true; return }
|
||||||
|
new Chart($(id), { type: 'bar', data: { labels: months, datasets: [{ data, backgroundColor: col, borderRadius: 2 }] },
|
||||||
|
options: { maintainAspectRatio: false, plugins: { legend: { display: false }, tooltip: { ...tip, ...(o.tip || {}) } }, scales: { x: { grid: { display: false }, ticks: gapTicks }, y: { grid, ...(o.y || {}) } } } }) };
|
||||||
|
barChart('cAsc', months.map(m => Math.round(sum(ACTS.filter(a => a.month === m), 'ascent_m'))), color(5), { tip: { callbacks: { label: i => i.raw.toLocaleString() + ' m' } } });
|
||||||
|
barChart('cTe', months.map(m => { const x = ACTS.filter(a => a.month === m && a.te_aerobic); return x.length ? +(sum(x, 'te_aerobic') / x.length).toFixed(2) : null }), color(2), { y: { min: 0, max: 5 } });
|
||||||
|
|
||||||
|
// year by year
|
||||||
|
const Y = {}; years.forEach(y => {
|
||||||
|
const A = ACTS.filter(a => a.start_local.startsWith(y)), R = A.filter(goodRun);
|
||||||
|
Y[y] = { A, R, hours: sum(A, 'moving_min') / 60, km: sum(A, 'dist_km'), asc: sum(A, 'ascent_m'),
|
||||||
|
pace: med(R.map(a => a.moving_min / a.dist_km)), best: R.filter(a => a.dist_km >= 4.5).map(a => a.moving_min / a.dist_km).sort((a, b) => a - b)[0] ?? null,
|
||||||
|
vo2: A.filter(a => a.sport === 'running' && a.vo2max).map(a => a.vo2max), eff: med(R.filter(a => a.avg_hr && a.dist_km > 2).map(a => a.dist_km * 1000 / (a.avg_hr * a.moving_min))),
|
||||||
|
maxhr: Math.max(0, ...A.map(a => a.max_hr || 0)) || null };
|
||||||
|
});
|
||||||
|
$('tYear').innerHTML = `<thead><tr><th class="l">Year</th>${P.birth_year ? '<th>Age</th>' : ''}<th>Sessions</th><th>Hours</th><th>km</th><th>Ascent m</th><th>Runs</th><th>Median pace</th><th>Best pace (4.5 km+)</th><th>VO2max</th><th>m per beat</th><th class="l">Sources</th></tr></thead><tbody>` +
|
||||||
|
[...years].reverse().map(y => { const v = Y[y]; return `<tr><td>${y}</td>${P.birth_year ? `<td>${ageIn(+y)}</td>` : ''}<td>${v.A.length}</td><td>${Math.round(v.hours)}</td><td>${Math.round(v.km)}</td><td>${Math.round(v.asc).toLocaleString()}</td>` +
|
||||||
|
`<td>${v.R.length || ''}</td><td>${v.pace ? pace(v.pace) : ''}</td><td>${v.best ? pace(v.best) : ''}</td><td>${v.vo2.length ? range(v.vo2) : ''}</td><td>${v.eff ? v.eff.toFixed(2) : ''}</td><td class="l dim">${[...new Set(v.A.map(a => a.srcl))].join(', ')}</td></tr>` }).join('') + '</tbody>';
|
||||||
|
|
||||||
|
// findings: every number and direction comes from the data
|
||||||
|
(function () {
|
||||||
|
const F = [], yrs = years.filter(y => Y[y].A.length);
|
||||||
|
if (P.birth_year && yrs.length) $('ageNote').textContent = `Born ${P.birth_year}: aged ${ageIn(+yrs[0])} in ${yrs[0]} and ${ageIn(+yrs.at(-1))} in ${yrs.at(-1)}.`;
|
||||||
|
const thisYear = String(new Date().getFullYear()), full = yrs.filter(y => y !== thisYear);
|
||||||
|
const big = [...full].sort((a, b) => Y[b].hours - Y[a].hours);
|
||||||
|
if (big.length >= 2) { const b = Y[big[0]], typ = med(full.map(y => Y[y].hours));
|
||||||
|
F.push(['Busiest year: ' + big[0], `<b>${Math.round(b.hours)} hours</b>, ${b.A.length} sessions, ${Math.round(b.km).toLocaleString()} km and ${Math.round(b.asc).toLocaleString()} m of climbing. A typical year has about ${Math.round(typ)} hours.` +
|
||||||
|
(b.hours > 2 * typ ? ' That is more than twice the usual.' : '')]) }
|
||||||
|
const py = yrs.filter(y => Y[y].R.length >= 8 && Y[y].pace);
|
||||||
|
if (py.length >= 2) {
|
||||||
|
const fast = [...py].sort((a, b) => Y[a].pace - Y[b].pace)[0], last = py.at(-1), bestEver = Math.min(...py.map(y => Y[y].best ?? 99));
|
||||||
|
const bestY = py.find(y => Y[y].best === bestEver);
|
||||||
|
if (fast === last) F.push(['Running faster than ever', `Your median running pace in ${last} is <b>${pace(Y[last].pace)} /km</b>, the fastest of any year on record${P.birth_year ? `, at age ${ageIn(+last)}` : ''}. The slowest year was ${[...py].sort((a, b) => Y[b].pace - Y[a].pace)[0]} (${pace(Math.max(...py.map(y => Y[y].pace)))} /km).`]);
|
||||||
|
else { const since = py.filter(y => y > fast).sort((a, b) => Y[a].pace - Y[b].pace)[0];
|
||||||
|
F.push([since === last ? 'Back towards your best' : 'Fastest running in ' + fast, `Your fastest year was <b>${fast}</b>, with a median pace of <b>${pace(Y[fast].pace)} /km</b>${P.birth_year ? ` (age ${ageIn(+fast)})` : ''}. ` +
|
||||||
|
`In ${last} the median is ${pace(Y[last].pace)} /km${since === last ? `, your quickest since ${fast}` : ''}. Best run of 4.5 km or more: ${pace(bestEver)} /km in ${bestY}.`]) }
|
||||||
|
}
|
||||||
|
const vo = ACTS.filter(a => a.sport === 'running' && a.vo2max);
|
||||||
|
if (vo.length) { const now = vo.at(-1).vo2max, hi = Math.max(...vo.map(a => a.vo2max)), lab = vo2Label(now);
|
||||||
|
F.push([`VO2max ${now}` + (lab ? `: ${lab} for your age` : ''), `Garmin's running estimate ranges ${range(vo.map(a => a.vo2max))} (peak ${hi} on ${vo.find(a => a.vo2max === hi).start_local.slice(0, 10)}) and is <b>${now}</b> now.` +
|
||||||
|
(vo2Norm ? ` For ${sexWord} aged ${ageBand}, ${vo2Norm[2]}+ is Excellent and ${vo2Norm[1]}+ Superior (top 5%).` : ' Add sex and birth year in settings to see how this rates for your age.')]) }
|
||||||
|
const ey = yrs.filter(y => Y[y].eff);
|
||||||
|
if (ey.length >= 2) { const a = Y[ey[0]].eff, b = Y[ey.at(-1)].eff, ch = (b / a - 1) * 100;
|
||||||
|
F.push([ch > 3 ? 'A more efficient heart' : ch < -3 ? 'Less distance per heartbeat' : 'Steady running efficiency', `Distance per heartbeat on runs went from ${a.toFixed(2)} m (${ey[0]}) to <b>${b.toFixed(2)} m</b> (${ey.at(-1)}), ${ch >= 0 ? 'up' : 'down'} ${Math.abs(ch).toFixed(0)}%. More metres per beat at a similar effort is a sign of aerobic fitness.`]) }
|
||||||
|
const hy = yrs.filter(y => Y[y].maxhr && Y[y].A.filter(a => a.max_hr).length >= 10);
|
||||||
|
if (hy.length >= 2 && P.birth_year) F.push(['Maximum heart rate', `Highest recorded heart rate per year: ${hy.map(y => `${y}: ${Y[y].maxhr}`).join(', ')}. The common estimate 220 minus age gives ${220 - nowAge} for you now; it usually falls about 1 bpm a year. Single wrist-sensor peaks can be glitches.`]);
|
||||||
|
const notes = [];
|
||||||
|
if (ACTS.some(a => a.sub_sport === 'suspect GPS')) notes.push(`${ACTS.filter(a => a.sub_sport === 'suspect GPS').length} runs with GPS errors are left out of pace figures`);
|
||||||
|
const noHr = Object.keys(SRC).filter(s => ACTS.some(a => a.src === s) && !ACTS.some(a => a.src === s && a.avg_hr));
|
||||||
|
const list = xs => xs.length > 1 ? xs.slice(0, -1).join(', ') + ' and ' + xs.at(-1) : xs[0];
|
||||||
|
if (noHr.length) notes.push(`${list(noHr.map(s => SRC[s]))} recordings have no heart rate`);
|
||||||
|
F.push(['Read with care', 'Pace depends on route, heat and hills, and some years have few runs. Garmin\'s estimates (VO2max, training effect) can jump after firmware or settings changes. ' + (notes.length ? notes.join('; ') + '.' : '')]);
|
||||||
|
$('find').innerHTML = F.map(([t, p]) => `<article><h3>${t}</h3><p>${p}</p></article>`).join('');
|
||||||
|
})();
|
||||||
|
|
||||||
|
// sleep and health (Garmin Connect)
|
||||||
|
if (hd) (function () {
|
||||||
|
$('health').hidden = false;
|
||||||
|
const D = hd; D.forEach(r => r.t = Date.parse(r.d));
|
||||||
|
const has = k => D.filter(r => r[k] != null);
|
||||||
|
const roll = (k, n = 30) => { const out = []; const xs = has(k); let j = 0, s = 0;
|
||||||
|
xs.forEach((r, i) => { s += r[k]; while (xs[j].t < r.t - n * 864e5) { s -= xs[j][k]; j++ } out.push({ x: r.t, y: +(s / (i - j + 1)).toFixed(1) }) }); return out };
|
||||||
|
const clock = h => { h = (h + 24) % 24; return `${Math.floor(h)}:${String(Math.round(h % 1 * 60)).padStart(2, '0')}` };
|
||||||
|
const hm = v => `${Math.floor(v)} h ${String(Math.round(v % 1 * 60)).padStart(2, '0')}`;
|
||||||
|
const leg = (id, items) => $(id).innerHTML = items.map(([l, c, dash]) => `<span><i style="background:${c}${dash ? ';height:2px' : ''}"></i>${l}</span>`).join('');
|
||||||
|
const xAxis = { type: 'linear', min: D[0].t, grid, ticks: { callback: v => new Date(v).toISOString().slice(0, 7), maxTicksLimit: 7 } };
|
||||||
|
const line = (data, col, o = {}) => ({ data, borderColor: col, backgroundColor: col, borderWidth: 2, pointRadius: 0, pointHoverRadius: 4, tension: 0, ...o });
|
||||||
|
const dots = (data, col, o = {}) => ({ data, borderColor: col, backgroundColor: col, showLine: false, pointRadius: 1.5, pointHoverRadius: 4, ...o });
|
||||||
|
const tchart = (id, datasets, { yfmt = v => v, tfmt = v => v, y = {} } = {}) => new Chart($(id), { type: 'line', data: { datasets },
|
||||||
|
options: { maintainAspectRatio: false, parsing: false, interaction: { mode: 'nearest', intersect: false },
|
||||||
|
plugins: { legend: { display: false }, tooltip: { ...tip, callbacks: { title: i => fmtD(i[0].raw.x), label: i => (i.dataset.label ? i.dataset.label + ': ' : '') + tfmt(i.raw.y) } } },
|
||||||
|
scales: { x: xAxis, y: { grid, ticks: { callback: yfmt }, ...y } } } });
|
||||||
|
const series = k => has(k).map(r => ({ x: r.t, y: r[k] }));
|
||||||
|
document.querySelectorAll('#health .card[data-k]').forEach(c => c.hidden = c.dataset.k === 'fage' ? !HEALTH.fage.length : has(c.dataset.k).length < 7);
|
||||||
|
$('hNote').textContent = `Daily values from Garmin Connect, ${D[0].d} to ${D.at(-1).d}. Sleep stages, HRV, Body Battery, stress, fitness age and training readiness are Garmin's own estimates from the wrist sensor: good for trends, not medical measurements.`;
|
||||||
|
|
||||||
|
const last = D.at(-1).t, recent = (k, days) => has(k).filter(r => r.t > last - days * 864e5).map(r => r[k]);
|
||||||
|
const fa = HEALTH.fage.at(-1);
|
||||||
|
const T = [];
|
||||||
|
if (recent('sleep', 90).length) T.push([clock(med(recent('sleep', 90))).replace(':', 'h'), 'median sleep, last 90 nights']);
|
||||||
|
if (recent('sleep', 365).length > 30) T.push([Math.round(100 * recent('sleep', 365).filter(v => v < 6).length / recent('sleep', 365).length) + '%', 'nights under 6 hours, last year']);
|
||||||
|
if (recent('rhr', 30).length) T.push([med(recent('rhr', 30)), 'resting heart rate, last 30 days (bpm)']);
|
||||||
|
if (has('hrvW').length) T.push([has('hrvW').at(-1).hrvW, 'HRV 7-day average, latest (ms)']);
|
||||||
|
if (recent('ready', 30).length) T.push([Math.round(med(recent('ready', 30))), 'training readiness, last 30 days (of 100)']);
|
||||||
|
if (fa) T.push([fa.bio.toFixed(1), `fitness age (real age ${fa.age})`]);
|
||||||
|
$('hTiles').innerHTML = T.map(([v, l]) => `<div class="tile"><b>${v}</b><span>${l}</span></div>`).join('');
|
||||||
|
|
||||||
|
// findings: first full year of data against the last 12 months
|
||||||
|
const firstY = D.find(r => r.d.endsWith('-01-01') || r.d.slice(5) <= '01-15')?.d.slice(0, 4) ?? String(+D[0].d.slice(0, 4) + 1);
|
||||||
|
const yr = k => med(has(k).filter(r => r.d.startsWith(firstY)).map(r => r[k]));
|
||||||
|
const yearAgo = new Date(last - 365 * 864e5).toISOString().slice(0, 10), compare = firstY < yearAgo.slice(0, 4);
|
||||||
|
const dow = r => new Date(r.t).getUTCDay();
|
||||||
|
const corr = (a, b) => { const p = D.filter(r => r[a] != null && r[b] != null); if (p.length < 30) return null; const ma = avg(p.map(r => r[a])), mb = avg(p.map(r => r[b]));
|
||||||
|
const c = p.reduce((s, r) => s + (r[a] - ma) * (r[b] - mb), 0), va = p.reduce((s, r) => s + (r[a] - ma) ** 2, 0), vb = p.reduce((s, r) => s + (r[b] - mb) ** 2, 0); return c / Math.sqrt(va * vb) };
|
||||||
|
const F = [];
|
||||||
|
if (recent('sleep', 365).length > 60) {
|
||||||
|
const now = med(recent('sleep', 365));
|
||||||
|
if (compare && yr('sleep')) { const then = yr('sleep'), d = now - then;
|
||||||
|
F.push([Math.abs(d) < 0.15 ? 'Sleep is steady' : d < 0 ? 'Sleep is getting shorter' : 'Sleeping longer', `Median sleep was <b>${hm(then)}</b> a night in ${firstY} and <b>${hm(now)}</b> over the last year` +
|
||||||
|
(yr('rem') && recent('rem', 365).length ? `; REM ${hm(yr('rem'))} → ${hm(med(recent('rem', 365)))}, deep ${hm(yr('deep'))} → ${hm(med(recent('deep', 365)))}.` : '.') + ' Garmin\'s sleep-stage estimates change with firmware, so compare stages with care.']) }
|
||||||
|
const wk = has('sleep').filter(r => r.d >= yearAgo), work = med(wk.filter(r => dow(r) >= 1 && dow(r) <= 5).map(r => r.sleep)), wkend = med(wk.filter(r => dow(r) === 0 || dow(r) === 6).map(r => r.sleep));
|
||||||
|
if (work && wkend) F.push([wkend - work > 0.75 ? 'Weekday sleep debt' : 'Sleep through the week', `Over the last year you slept a median <b>${hm(work)}</b> on nights before a weekday and <b>${hm(wkend)}</b> on Friday and Saturday nights. Typical wake-up ${clock(med(recent('wake', 365)))}, bedtime ${clock(med(recent('bed', 365)))}.`]);
|
||||||
|
}
|
||||||
|
const c = corr('sscore', 'ready');
|
||||||
|
if (c != null) F.push([c > 0.5 ? 'Sleep drives readiness' : 'Sleep and readiness', `Sleep score and training readiness ${c > 0.5 ? 'move together closely' : 'are only loosely related'} (correlation ${c.toFixed(2)}).` +
|
||||||
|
(compare && yr('ready') ? ` Readiness was a median ${Math.round(yr('ready'))} in ${firstY} and ${Math.round(med(recent('ready', 90)))} over the last 3 months.` : '')]);
|
||||||
|
if (has('rhr').length > 30) F.push(['Resting heart rate', `Median <b>${med(recent('rhr', 365))} bpm</b> over the last year (lowest ${Math.min(...series('rhr').map(p => p.y))}).` +
|
||||||
|
(has('hrvW').length ? ` HRV 7-day average has ranged ${range(series('hrvW').map(p => p.y))} ms and is ${has('hrvW').at(-1).hrvW} ms now.` : '') + ' Below 60 bpm is typical of regular endurance training.']);
|
||||||
|
if (fa) { const ages = HEALTH.fage.map(f => f.bio), gap = fa.age - fa.bio;
|
||||||
|
F.push([gap >= 1 ? `Fitness age ${Math.round(gap)} years below your age` : 'Fitness age', `Garmin's fitness age (from VO2max, resting heart rate, activity and BMI) has ranged <b>${Math.min(...ages).toFixed(1)}–${Math.max(...ages).toFixed(1)}</b>; it is ${fa.bio.toFixed(1)} now, against a real age of ${fa.age}.`]) }
|
||||||
|
if (HEALTH.bp.length) { const s = HEALTH.bp.map(b => b.sys), d = HEALTH.bp.map(b => b.dia), hb = HEALTH.bp.filter(b => b.hb).map(b => b.hb);
|
||||||
|
F.push(['Blood pressure' + (hb.length ? ' and haemoglobin' : ''), `${HEALTH.bp.length} readings since ${HEALTH.bp[0].d.slice(0, 7)}: ${range(s)} / ${range(d)} mmHg (median ${med(s)}/${med(d)}).` +
|
||||||
|
(hb.length ? ` Haemoglobin ${range(hb)} g/dL.` : '') + ' These are your own entries; discuss them with a doctor rather than relying on this summary.']) }
|
||||||
|
$('hFind').innerHTML = F.map(([t, p]) => `<article><h3>${t}</h3><p>${p}</p></article>`).join('');
|
||||||
|
|
||||||
|
const hm_ = [...new Set(has('sleep').map(r => r.d.slice(0, 7)))];
|
||||||
|
if (hm_.length) {
|
||||||
|
const stages = [['Deep', 'deep', 6], ['Light', 'light', 0], ['REM', 'rem', 4], ['Awake', 'awake', 7]];
|
||||||
|
leg('hSleepLeg', stages.map(([l, , c]) => [l, color(c)]));
|
||||||
|
new Chart($('cSleep'), { type: 'bar', data: { labels: hm_, datasets: stages.map(([l, k, c]) => ({ label: l, backgroundColor: color(c), borderColor: css('--surface'), borderWidth: { top: 1 }, borderRadius: 2, borderSkipped: 'bottom',
|
||||||
|
data: hm_.map(m => +(avg(D.filter(r => r.sleep != null && r.d.startsWith(m)).map(r => r[k] || 0)) || 0).toFixed(2)) })) },
|
||||||
|
options: { maintainAspectRatio: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { display: false }, tooltip: { ...tip, callbacks: { label: i => `${i.dataset.label}: ${hm(i.raw)}` }, footer: it => 'Asleep ' + hm(it.filter(i => i.dataset.label !== 'Awake').reduce((s, i) => s + i.raw, 0)) } },
|
||||||
|
scales: { x: { stacked: true, grid: { display: false }, ticks: { maxRotation: 0, maxTicksLimit: 8 } }, y: { stacked: true, grid } } } });
|
||||||
|
const monthMed = k => hm_.map(m => ({ x: Date.parse(m + '-15'), y: med(D.filter(r => r[k] != null && r.d.startsWith(m)).map(r => r[k])) }));
|
||||||
|
leg('hBedLeg', [['Bedtime', color(6)], ['Wake-up', color(3)]]);
|
||||||
|
tchart('cBed', [line(monthMed('bed'), color(6), { label: 'Bedtime', pointRadius: 2 }), line(monthMed('wake'), color(3), { label: 'Wake-up', pointRadius: 2 })], { yfmt: clock, tfmt: clock, y: { reverse: true } });
|
||||||
|
const names = ['Sat → Sun', 'Sun → Mon', 'Mon → Tue', 'Tue → Wed', 'Wed → Thu', 'Thu → Fri', 'Fri → Sat'], order = [1, 2, 3, 4, 5, 6, 0];
|
||||||
|
const wk = order.map(d => avg(has('sleep').filter(r => dow(r) === d).map(r => r.sleep)) || 0);
|
||||||
|
new Chart($('cWeek'), { type: 'bar', data: { labels: order.map(d => names[d]), datasets: [{ data: wk.map(v => +v.toFixed(2)), backgroundColor: order.map(d => color(d === 6 || d === 0 ? 3 : 6)), borderRadius: 2 }] },
|
||||||
|
options: { maintainAspectRatio: false, plugins: { legend: { display: false }, tooltip: { ...tip, callbacks: { label: i => hm(i.raw) } } }, scales: { x: { grid: { display: false } }, y: { grid, suggestedMin: 5 } } } });
|
||||||
|
}
|
||||||
|
leg('hScoreLeg', [['Sleep score', color(6)], ['Training readiness', color(2)]]);
|
||||||
|
tchart('cScore', [line(roll('sscore'), color(6), { label: 'Sleep score' }), line(roll('ready'), color(2), { label: 'Readiness' })], { y: { suggestedMin: 40, suggestedMax: 100 } });
|
||||||
|
tchart('cRhr', [dots(series('rhr'), color(4), { label: 'Day' }), line(roll('rhr'), color(4), { label: '30-day' })], { tfmt: v => v + ' bpm' });
|
||||||
|
tchart('cHrv', [dots(series('hrv'), color(0), { label: 'Night' }), line(series('hrvW'), color(0), { label: '7-day avg' })], { tfmt: v => v + ' ms' });
|
||||||
|
leg('hStressLeg', [['All-day stress (0–100, lower is calmer)', color(1)], ['Body Battery peak of the day', color(2)]]);
|
||||||
|
tchart('cStress', [line(roll('stress'), color(1), { label: 'Stress' }), line(roll('bbHi'), color(2), { label: 'Body Battery peak' })], { y: { min: 0, max: 100 } });
|
||||||
|
if (HEALTH.fage.length) { leg('hAgeLeg', [['Fitness age', color(2)], ['Real age', css('--muted'), true]]);
|
||||||
|
tchart('cAge', [line(HEALTH.fage.map(f => ({ x: Date.parse(f.d), y: f.bio })), color(2), { label: 'Fitness age' }),
|
||||||
|
line(HEALTH.fage.map(f => ({ x: Date.parse(f.d), y: f.age })), css('--muted'), { label: 'Real age', stepped: true, borderDash: [5, 4], borderWidth: 1.5 })], { tfmt: v => (+v).toFixed(1) + ' years' }) }
|
||||||
|
const r5 = RACES.filter(r => Math.abs(r.km - 5) < 0.2 && r.date >= D[0].d);
|
||||||
|
leg('hPredLeg', [['Garmin 5 km prediction', color(0)], ...(r5.length ? [['5 km race finish time', color(1)]] : [])]);
|
||||||
|
tchart('cPred', [line(series('p5k'), color(0), { label: 'Predicted' }), dots(r5.map(r => ({ x: Date.parse(r.date), y: r.sec })), color(1), { label: 'Race', pointRadius: 5 })], { yfmt: mmss, tfmt: mmss, y: { reverse: true } });
|
||||||
|
leg('hLoadLeg', [['Acute load (7 days)', color(1)], ['Chronic load (4 weeks)', color(0)]]);
|
||||||
|
tchart('cLoad', [line(series('acute'), color(1), { label: 'Acute', borderWidth: 1.5 }), line(series('chronic'), color(0), { label: 'Chronic' })]);
|
||||||
|
if (HEALTH.bp.length) {
|
||||||
|
$('bpBlock').hidden = false;
|
||||||
|
const B = HEALTH.bp.map(b => ({ ...b, t: Date.parse(b.d) }));
|
||||||
|
leg('hBpLeg', [['Systolic', color(4)], ['Diastolic', color(0)], ...(B.some(b => b.hb) ? [['Haemoglobin (right axis)', color(2)]] : [])]);
|
||||||
|
new Chart($('cBp'), { type: 'line', data: { datasets: [
|
||||||
|
line(B.map(b => ({ x: b.t, y: b.sys })), color(4), { label: 'Systolic', pointRadius: 3 }), line(B.map(b => ({ x: b.t, y: b.dia })), color(0), { label: 'Diastolic', pointRadius: 3 }),
|
||||||
|
dots(B.filter(b => b.hb).map(b => ({ x: b.t, y: b.hb })), color(2), { label: 'Hb', pointRadius: 4, yAxisID: 'y2' })] },
|
||||||
|
options: { maintainAspectRatio: false, parsing: false, plugins: { legend: { display: false }, tooltip: { ...tip, callbacks: { title: i => fmtD(i[0].raw.x), label: i => `${i.dataset.label}: ${i.raw.y}${i.dataset.label === 'Hb' ? ' g/dL' : ' mmHg'}` } } },
|
||||||
|
scales: { x: { ...xAxis, min: undefined }, y: { grid, suggestedMin: 50, suggestedMax: 140 }, y2: { display: B.some(b => b.hb), position: 'right', grid: { display: false }, suggestedMin: 12, suggestedMax: 17 } } } });
|
||||||
|
$('tBp').innerHTML = '<thead><tr><th class="l">Date</th><th>Blood pressure</th><th>Pulse</th><th>Hb g/dL</th><th class="l">Note</th></tr></thead><tbody>' +
|
||||||
|
[...B].reverse().map(b => `<tr><td>${b.d}</td><td>${b.sys}/${b.dia}</td><td>${b.pulse ?? ''}</td><td>${b.hb ?? ''}</td><td class="l dim">${(b.note || '').replace(/[<>&]/g, '')}</td></tr>`).join('') + '</tbody>';
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
// races (races.csv)
|
||||||
|
if (RACES.length) (function () {
|
||||||
|
$('races').hidden = false;
|
||||||
|
const ev = [...new Set(RACES.map(r => r.event))], evCol = e => color([1, 3, 6, 4, 0, 2][ev.indexOf(e) % 6]);
|
||||||
|
const byDay = {}; ACTS.forEach(a => (byDay[a.start_local.slice(0, 10)] ??= []).push(a)); // any sport: a race is sometimes logged as a walk
|
||||||
|
RACES.forEach(r => { r.t = Date.parse(r.date); r.a = (byDay[r.date] || []).filter(a => Math.abs(a.dist_km - r.km) < 0.3 * r.km).sort((x, y) => Math.abs(x.dist_km - r.km) - Math.abs(y.dist_km - r.km))[0] });
|
||||||
|
const dists = [...new Set(RACES.map(r => r.km))];
|
||||||
|
const T = [[RACES.length, `races (${ev.map(e => RACES.filter(r => r.event === e).length + ' ' + e).join(', ')})`]];
|
||||||
|
dists.forEach(k => { const b = RACES.filter(r => r.km === k).reduce((b, r) => r.sec < b.sec ? r : b); T.push([b.time, `fastest ${k} km, ${b.event} ${b.date}`]) });
|
||||||
|
const ag = RACES.filter(r => r.ag); if (ag.length) { const b = ag.reduce((b, r) => r.ag > b.ag ? r : b); T.push([b.ag.toFixed(1) + '%', `best age grade, ${b.date}`]) } else $('prAgCard').hidden = true;
|
||||||
|
$('prTiles').innerHTML = T.map(([v, l]) => `<div class="tile"><b>${v}</b><span>${l}</span></div>`).join('');
|
||||||
|
$('prLegend').innerHTML = ev.map(e => `<span><i style="background:${evCol(e)}"></i>${e}</span>`).join('') + (RACES.some(r => r.pb) ? '<span>larger dot = PB</span>' : '');
|
||||||
|
const chart = (id, y, yfmt, reverse) => new Chart($(id), { type: 'scatter',
|
||||||
|
data: { datasets: [{ data: RACES.filter(r => y(r) != null).map(r => ({ x: r.t, y: y(r), run: r })), pointBackgroundColor: RACES.map(r => evCol(r.event)), pointBorderColor: RACES.map(r => evCol(r.event)),
|
||||||
|
pointRadius: RACES.map(r => r.pb ? 6 : 4), pointHoverRadius: 7 }] },
|
||||||
|
options: { maintainAspectRatio: false, parsing: false, plugins: { legend: { display: false }, tooltip: { ...tip, callbacks: {
|
||||||
|
title: i => `${i[0].raw.run.date} · ${i[0].raw.run.event}`, label: i => `${i.raw.run.time}${i.raw.run.ag ? ' · ' + i.raw.run.ag.toFixed(2) + '%' : ''}${i.raw.run.pos ? ' · position ' + i.raw.run.pos : ''}${i.raw.run.pb ? ' · PB' : ''}` } } },
|
||||||
|
scales: { x: { type: 'linear', grid, ticks: { callback: v => new Date(v).toISOString().slice(0, 7), maxTicksLimit: 7 } }, y: { grid, reverse, ticks: { callback: yfmt } } } } });
|
||||||
|
chart('cPrTime', r => r.sec, mmss, true);
|
||||||
|
if (ag.length) chart('cPrAg', r => r.ag, v => v + '%', false);
|
||||||
|
$('tPr').innerHTML = '<thead><tr><th class="l">Date</th><th class="l">Event</th><th>km</th><th>Position</th><th>Time</th><th>Pace /km</th><th>Age grade</th><th class="l">PB</th><th>Avg HR</th><th>Max HR</th><th class="l">Recorded by</th></tr></thead><tbody>' +
|
||||||
|
[...RACES].reverse().map(r => `<tr><td>${r.date}</td><td class="l"><span class="dot" style="background:${evCol(r.event)}"></span>${r.event}</td><td>${r.km}</td><td>${r.pos ?? ''}</td><td>${r.time}</td><td>${mmss(r.sec / r.km)}</td><td>${r.ag ? r.ag.toFixed(2) + '%' : ''}</td><td class="l">${r.pb ? 'PB' : ''}</td>` +
|
||||||
|
`<td>${r.a?.avg_hr ?? ''}</td><td>${r.a?.max_hr ?? ''}</td><td class="l dim">${r.a ? r.a.srcl : '—'}</td></tr>`).join('') + '</tbody>';
|
||||||
|
})();
|
||||||
|
|
||||||
|
// map
|
||||||
|
const map = L.map('map', { preferCanvas: true });
|
||||||
|
// tile.openstreetmap.org refuses pages opened from disk (403), so use providers that serve file:// pages
|
||||||
|
const osmAttr = '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors';
|
||||||
|
const bases = {
|
||||||
|
'Street map': L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', { maxZoom: 19, attribution: 'Tiles © Esri, HERE, Garmin, © OpenStreetMap contributors' }),
|
||||||
|
'Topographic': L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', { maxZoom: 17, attribution: osmAttr + ', SRTM | style © <a href="https://opentopomap.org">OpenTopoMap</a> (CC-BY-SA)' }),
|
||||||
|
'Satellite': L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { maxZoom: 19, attribution: 'Imagery © Esri, Maxar, Earthstar Geographics' }),
|
||||||
|
};
|
||||||
|
bases['Street map'].addTo(map);
|
||||||
|
L.control.layers(bases, null, { position: 'topright' }).addTo(map);
|
||||||
|
const esc = s => String(s ?? '').replace(/[<>&"]/g, c => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[c]);
|
||||||
|
const lines = ACTS.filter(a => TRACKS[a.file]).map(a => {
|
||||||
|
const pl = L.polyline(TRACKS[a.file], { color: color(a.g), weight: 2.5, opacity: .8 });
|
||||||
|
pl.bindPopup(`<b>${a.start_local}</b>${a.name ? '<br>' + esc(a.name) : ''}<br>${a.grp}<br>${a.dist_km} km · ${Math.round(a.moving_min)} min${a.ascent_m ? ' · ' + a.ascent_m + ' m up' : ''}${a.avg_hr ? '<br>avg HR ' + a.avg_hr + ' bpm' : ''}<br><span style="color:#888">${a.srcl}</span>`);
|
||||||
|
pl.on('mouseover', () => pl.setStyle({ weight: 5, opacity: 1 })); pl.on('mouseout', () => pl.setStyle({ weight: 2.5, opacity: .8 }));
|
||||||
|
return { a, pl };
|
||||||
|
});
|
||||||
|
const mapOn = new Set(usedGroups);
|
||||||
|
$('mapSports').innerHTML = usedGroups.filter(i => lines.some(l => l.a.g === i)).map(i => `<button class="chip" aria-pressed="true" data-g="${i}"><i style="background:${color(i)}"></i>${GROUPS[i][0]}</button>`).join('');
|
||||||
|
$('mapYear').innerHTML = '<option value="">All years</option>' + years.map(y => `<option>${y}</option>`).join('');
|
||||||
|
let firstFit = true;
|
||||||
|
function drawMap() {
|
||||||
|
const y = $('mapYear').value; const shown = [];
|
||||||
|
lines.forEach(({ a, pl }) => { const on = mapOn.has(a.g) && (!y || a.start_local.startsWith(y)); if (on) { pl.addTo(map); shown.push(pl) } else pl.remove() });
|
||||||
|
$('mapCount').textContent = shown.length + ' tracks';
|
||||||
|
if (!shown.length) { if (firstFit) map.setView([0, 0], 2); return }
|
||||||
|
if (firstFit) { // open on the home area: densest 0.5° cell
|
||||||
|
const c = {}; shown.forEach(p => { const ll = p.getLatLngs()[0]; const k = Math.round(ll.lat * 2) / 2 + ',' + Math.round(ll.lng * 2) / 2; (c[k] = c[k] || []).push(p) });
|
||||||
|
const best = Object.values(c).sort((a, b) => b.length - a.length)[0]; map.fitBounds(L.featureGroup(best).getBounds(), { padding: [20, 20] }); firstFit = false;
|
||||||
|
} else map.fitBounds(L.featureGroup(shown).getBounds(), { padding: [20, 20] });
|
||||||
|
}
|
||||||
|
$('mapSports').addEventListener('click', e => { const b = e.target.closest('button'); if (!b) return; const g = +b.dataset.g;
|
||||||
|
mapOn.has(g) ? mapOn.delete(g) : mapOn.add(g); b.setAttribute('aria-pressed', mapOn.has(g)); drawMap(); });
|
||||||
|
$('mapYear').addEventListener('change', drawMap);
|
||||||
|
drawMap();
|
||||||
|
|
||||||
|
// month table
|
||||||
|
(function () {
|
||||||
|
const head = `<thead><tr><th class="l">Month</th>${usedGroups.map(i => `<th><span class="dot" style="background:${color(i)}"></span>${GROUPS[i][0]}</th>`).join('')}<th>Sessions</th><th>Hours</th><th>km</th><th>Ascent m</th><th>Avg HR</th></tr></thead>`;
|
||||||
|
const row = (label, xs, cls = '') => {
|
||||||
|
const cell = i => { const s = xs.filter(a => a.g === i); if (!s.length) return '<td class="dim">·</td>';
|
||||||
|
const km = sum(s, 'dist_km'); return `<td>${s.length}${km >= 1 ? ` <span class="dim">/ ${Math.round(km)} km</span>` : ''}</td>` };
|
||||||
|
const hr = xs.filter(a => a.avg_hr);
|
||||||
|
return `<tr class="${cls}"><td>${label}</td>${usedGroups.map(cell).join('')}<td>${xs.length || '<span class="dim">0</span>'}</td><td>${(sum(xs, 'moving_min') / 60).toFixed(1)}</td><td>${Math.round(sum(xs, 'dist_km'))}</td><td>${Math.round(sum(xs, 'ascent_m'))}</td><td>${hr.length ? Math.round(sum(hr, 'avg_hr') / hr.length) : ''}</td></tr>`;
|
||||||
|
};
|
||||||
|
let body = ''; [...years].reverse().forEach(y => {
|
||||||
|
body += row(y + ' total', ACTS.filter(a => a.month.startsWith(y)), 'year');
|
||||||
|
months.filter(m => m.startsWith(y) && active.has(m)).reverse().forEach(m => body += row(m, ACTS.filter(a => a.month === m)));
|
||||||
|
});
|
||||||
|
$('tMonth').innerHTML = head + '<tbody>' + body + '</tbody>';
|
||||||
|
})();
|
||||||
|
|
||||||
|
// activity log
|
||||||
|
const cols = [['start_local', 'Start (local)', 'l'], ['grp', 'Sport', 'l'], ['name', 'Name', 'l'], ['srcl', 'Source', 'l'], ['dist_km', 'km'], ['moving_min', 'Min'], ['ascent_m', 'Ascent m'], ['avg_hr', 'Avg HR'], ['max_hr', 'Max HR'],
|
||||||
|
['te_aerobic', 'Aerobic TE'], ['kcal', 'kcal'], ['vo2max', 'VO2max']];
|
||||||
|
let sortK = 'start_local', sortDir = -1;
|
||||||
|
function drawLog() {
|
||||||
|
const q = $('q').value.toLowerCase().trim();
|
||||||
|
const xs = ACTS.filter(a => !q || (a.start_local + ' ' + a.grp + ' ' + a.srcl + ' ' + (a.name || '')).toLowerCase().includes(q))
|
||||||
|
.sort((x, y) => ((x[sortK] ?? -1e9) > (y[sortK] ?? -1e9) ? 1 : -1) * sortDir);
|
||||||
|
$('qCount').textContent = xs.length + ' activities';
|
||||||
|
$('tAct').innerHTML = `<thead><tr>${cols.map(([k, l, c]) => `<th class="${c || ''}" data-k="${k}">${l}${k === sortK ? (sortDir > 0 ? ' ▲' : ' ▼') : ''}</th>`).join('')}</tr></thead><tbody>` +
|
||||||
|
xs.map(a => `<tr>${cols.map(([k, , c]) => `<td class="${c || ''}">${k === 'grp' ? `<span class="dot" style="background:${color(a.g)}"></span>` : ''}${esc(a[k])}</td>`).join('')}</tr>`).join('') + '</tbody>';
|
||||||
|
}
|
||||||
|
$('tAct').addEventListener('click', e => { const th = e.target.closest('th'); if (!th) return; const k = th.dataset.k; sortDir = k === sortK ? -sortDir : -1; sortK = k; drawLog(); });
|
||||||
|
$('q').addEventListener('input', drawLog);
|
||||||
|
drawLog();
|
||||||
|
$('foot').textContent = `Built ${DATA.built} with myGarmin ${DATA.version}.`;
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -94,7 +94,7 @@ def health(lib, items):
|
|||||||
return len(D)
|
return len(D)
|
||||||
|
|
||||||
def bp_entry(p):
|
def bp_entry(p):
|
||||||
"""Blood pressure record; a haemoglobin value written in the notes ('Hb 14.7', 'Hgb 14 1', 'Himoglobien 14.2') is picked up."""
|
"""Blood pressure record; a haemoglobin value written in the notes ('Hb 15.0', 'Hgb 15 0', 'Haemoglobin 15.0') is picked up."""
|
||||||
hb = re.search(r'(?<!\d)(1\d)(?:[ .,](\d))?(?!\d)', p.get('notes') or '') # first number 10-19, optionally with one decimal
|
hb = re.search(r'(?<!\d)(1\d)(?:[ .,](\d))?(?!\d)', p.get('notes') or '') # first number 10-19, optionally with one decimal
|
||||||
return {'sys': p['systolic'], 'dia': p['diastolic'], 'pulse': p.get('pulse'),
|
return {'sys': p['systolic'], 'dia': p['diastolic'], 'pulse': p.get('pulse'),
|
||||||
'hb': float(hb.group(1) + '.' + (hb.group(2) or '0')) if hb else None, 'note': p.get('notes') or ''}
|
'hb': float(hb.group(1) + '.' + (hb.group(2) or '0')) if hb else None, 'note': p.get('notes') or ''}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ def inbox(tmp_path):
|
|||||||
buf = io.StringIO(); csv.writer(buf).writerows(rows)
|
buf = io.StringIO(); csv.writer(buf).writerows(rows)
|
||||||
(st / 'activities.csv').write_text(buf.getvalue() + '\x00' * 20) # Strava pads its files with NULs
|
(st / 'activities.csv').write_text(buf.getvalue() + '\x00' * 20) # Strava pads its files with NULs
|
||||||
# Garmin Connect export, zipped, with two days of health data
|
# Garmin Connect export, zipped, with two days of health data
|
||||||
days = [{'calendarDate': f'2024-03-0{i}', 'restingHeartRate': 50 + i, 'totalSteps': 9000, 'bodyBattery': {'bodyBatteryStatList': [
|
days = [{'calendarDate': f'2024-03-0{i}', 'restingHeartRate': 60 + i, 'totalSteps': 9000, 'bodyBattery': {'bodyBatteryStatList': [
|
||||||
{'bodyBatteryStatType': 'HIGHEST', 'statsValue': 90}, {'bodyBatteryStatType': 'LOWEST', 'statsValue': 20}]}} for i in (2, 3)]
|
{'bodyBatteryStatType': 'HIGHEST', 'statsValue': 90}, {'bodyBatteryStatType': 'LOWEST', 'statsValue': 20}]}} for i in (2, 3)]
|
||||||
sleep = [{'calendarDate': '2024-03-03', 'sleepStartTimestampGMT': '2024-03-02T20:30:00.0', 'sleepEndTimestampGMT': '2024-03-03T04:45:00.0',
|
sleep = [{'calendarDate': '2024-03-03', 'sleepStartTimestampGMT': '2024-03-02T20:30:00.0', 'sleepEndTimestampGMT': '2024-03-03T04:45:00.0',
|
||||||
'deepSleepSeconds': 4000, 'lightSleepSeconds': 16000, 'remSleepSeconds': 6000, 'awakeSleepSeconds': 600, 'sleepScores': {'overallScore': 81}}]
|
'deepSleepSeconds': 4000, 'lightSleepSeconds': 16000, 'remSleepSeconds': 6000, 'awakeSleepSeconds': 600, 'sleepScores': {'overallScore': 81}}]
|
||||||
@@ -70,7 +70,7 @@ def test_pipeline(tmp_path, inbox):
|
|||||||
assert a['car.trk']['flag'] == 'transport'
|
assert a['car.trk']['flag'] == 'transport'
|
||||||
assert a['2.gpx']['dup_of'] is None and a['2.gpx']['name'] == 'Morning Ride'
|
assert a['2.gpx']['dup_of'] is None and a['2.gpx']['name'] == 'Morning Ride'
|
||||||
days = {d['d']: d for d in lib.days()}
|
days = {d['d']: d for d in lib.days()}
|
||||||
assert days['2024-03-03']['rhr'] == 53 and days['2024-03-03']['sleep'] == round(26000 / 3600, 2)
|
assert days['2024-03-03']['rhr'] == 63 and days['2024-03-03']['sleep'] == round(26000 / 3600, 2)
|
||||||
assert days['2024-03-03']['bed'] == -1.5 # 22:30 local
|
assert days['2024-03-03']['bed'] == -1.5 # 22:30 local
|
||||||
assert lib.series('bp')[0]['hb'] == 14.6
|
assert lib.series('bp')[0]['hb'] == 14.6
|
||||||
out = report.build(lib, log=lambda *_: None)
|
out = report.build(lib, log=lambda *_: None)
|
||||||
|
|||||||
Reference in New Issue
Block a user