File size: 21,153 Bytes
af4a5b4 f995d75 af4a5b4 f995d75 689b5c1 702c817 689b5c1 702c817 689b5c1 702c817 689b5c1 702c817 689b5c1 702c817 689b5c1 702c817 689b5c1 702c817 689b5c1 702c817 689b5c1 702c817 689b5c1 f995d75 689b5c1 f995d75 689b5c1 702c817 689b5c1 2d4c705 689b5c1 f995d75 689b5c1 f995d75 689b5c1 f995d75 689b5c1 f995d75 689b5c1 f995d75 689b5c1 702c817 689b5c1 e66c47a 702c817 689b5c1 702c817 e66c47a 702c817 af4a5b4 2d4c705 689b5c1 702c817 689b5c1 f995d75 689b5c1 f995d75 af4a5b4 f995d75 af4a5b4 f995d75 af4a5b4 f995d75 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | """The dataset's table of contents: one row per session (its run), split into two files that share the
session key (subject, date, session) --
running.csv the run: conditions (setting, surface, event, location) and what was measured
(run duration, distance, pace, heart rate, cadence, each with its source)
capture.csv the recording: setup (sensors, placements, channels, rate, packet size, transport,
firmware, app, phone, time-sync mode, reference streams) and capture analysis
(recording length vs the run, loss, effective rate, gaps, time-sync verdict, phone
battery / temperature, files, size, notes -- the session's journal)
measurements.csv every source of each run quantity side by side (duration, distance, pace, steps,
cadence, heart rate from the participant's report, phone GPS, watch, phone step
counter, chest strap, and the LEVEL sensors where an analysis table is supplied) plus a
`<quantity>_use` column naming the source running.csv carries
from lvl_running.catalog import build_catalog, split_catalog
running, capture, measurements = split_catalog(build_catalog("data")) # written by make_catalog.py
"""
from __future__ import annotations
import glob
import json
import os
import numpy as np
import pandas as pd
from .session import iter_sessions
HR_MIN_COVERAGE = 0.8 # fraction of the run a HR source must span to be reported
CHANNELS = {"accel": "accel_x", "gyro": "gyro_x", "mag": "mag_x"} # channel -> a column that marks it
def _json(path: str) -> dict:
try:
return json.load(open(path, encoding="utf-8"))
except (OSError, ValueError):
return {}
def _csv(path: str) -> pd.DataFrame | None:
try:
return pd.read_csv(path)
except (OSError, ValueError):
return None
_CONTEXT: dict[str, dict] = {}
def load_context(data_root: str) -> dict[tuple[str, str], dict]:
"""context/session_context.csv as {(subject, session): row} -- the facts a recording cannot carry (date,
setting, surface, event, published location, policy). Blank cells become None. Cached per root."""
key = os.path.abspath(data_root)
if key not in _CONTEXT:
df = _csv(os.path.join(data_root, "context", "session_context.csv"))
_CONTEXT[key] = {} if df is None else {
(r["subject"], r["session"]): {k: (None if (isinstance(v, float) and pd.isna(v)) else v) for k, v in r.items()}
for r in df.to_dict("records")}
return _CONTEXT[key]
def _join(values) -> str:
return ";".join(sorted({str(v) for v in values if v not in (None, "")}))
def _channels(run_dir: str) -> str:
"""Sensor channels actually recorded, read from the IMU files' headers (e.g. accel+gyro)."""
cols = set()
for f in glob.glob(os.path.join(run_dir, "imu-*.csv")):
with open(f, encoding="utf-8") as fh:
cols |= set(fh.readline().strip().split(","))
return "+".join(ch for ch, col in CHANNELS.items() if col in cols)
BLUETOOTH_DEVICES = ("none", "headphones", "watch", "other")
def _num(v):
"""A context cell as a number (int when whole); None when blank."""
if v is None or (isinstance(v, float) and pd.isna(v)) or str(v).strip() == "":
return None
f = float(v)
return int(f) if f.is_integer() else f
LONG_GAP_S = 0.15 # a gap longer than this counts toward long_gaps_per_hour (3+ packets at 5 samples/packet)
def _capture_stats(run_dir: str, nominal_hz: float | None, session_end_us: int | None) -> dict:
"""Per LEVEL sensor (rotation files combined): effective_rate_hz and loss_pct averaged over sensors;
max_gap_s, long_gaps_per_hour and data_ends_early_s for the worst sensor.
effective rate = samples received / recording span.
loss = samples missing between each sensor's first and last sample, from gaps in `frame_sensor`
(a sample counter, wraps 0-255). A gap longer than 2 s could hide a full counter wrap, so its size is
taken from `time` and the nominal rate instead. A sensor that stops for good is not counted as loss
(nothing after it is missing from the counter) -- a short duration shows that.
max gap = the longest interval between two consecutive samples of any sensor, in seconds: loss says
how much went missing, this says whether it went in one piece (a dropout) or as scattered packets.
long gaps per hour = gaps longer than LONG_GAP_S per hour of that sensor's recording.
data ends early = seconds between a sensor's last sample and the end of the session (a stalled or
stopped sensor; ~0-2 s is normal)."""
streams: dict[str, list[pd.DataFrame]] = {}
for f in glob.glob(os.path.join(run_dir, "imu-*.csv")):
key = os.path.basename(f).split(".")[0] # imu-<placement>-<id> (drops .NNN rotation)
df = pd.read_csv(f)
df = df.rename(columns={"frame_number": "frame_sensor"})
streams.setdefault(key, []).append(df[[c for c in ("time", "frame_sensor") if c in df]])
rates, losses, gaps, long_rate, early = [], [], [], [], []
for parts in streams.values():
df = pd.concat(parts).sort_values("time")
t = df["time"].to_numpy(dtype="int64")
if len(t) < 2 or t[-1] <= t[0]:
continue
rates.append(len(t) / ((t[-1] - t[0]) / 1e6))
dt = np.diff(t)
gaps.append(dt.max() / 1e6)
long_rate.append((dt > LONG_GAP_S * 1e6).sum() / ((t[-1] - t[0]) / 3.6e9))
if session_end_us:
early.append(max(0.0, (session_end_us - t[-1]) / 1e6))
if "frame_sensor" in df and nominal_hz:
step = np.diff(df["frame_sensor"].to_numpy(dtype="int64")) % 256
long_gap = dt > 2_000_000
missing = np.where(long_gap, np.rint(dt * nominal_hz / 1e6) - 1, np.maximum(step - 1, 0))
missing = np.clip(missing, 0, None).sum()
losses.append(100.0 * missing / (missing + len(t)))
avg = lambda v, n: round(sum(v) / len(v), n) if v else None
worst = lambda v, n: round(max(v), n) if v else None
return {"effective_rate_hz": avg(rates, 2), "loss_pct": avg(losses, 2), "max_gap_s": worst(gaps, 2),
"long_gaps_per_hour": worst(long_rate, 1), "data_ends_early_s": worst(early, 1)}
# which data files a session carries: column -> file patterns in the run folder (fit3/ is beside it)
AVAILABLE = {
"gps": ("pace_profile.csv", "gps.csv"), # the coordinate-free profile (the raw route only where published)
"barometer": ("barometer.csv",),
"steps": ("steps.csv",),
"h10_hr": ("polar_*_hr.csv",),
"h10_ecg": ("polar_*_ecg.csv",),
"h10_acc": ("polar_*_acc.csv",),
"watch": ("../fit3/fit3_live.csv",),
}
def _available(run_dir: str) -> dict:
"""{column: True/False} -- whether each optional data file exists for the session."""
return {col: any(glob.glob(os.path.join(run_dir, pat)) for pat in pats) for col, pats in AVAILABLE.items()}
def session_row(run_dir: str, data_root: str, level: dict | None = None) -> dict:
"""`level` = the LEVEL-sensor analysis values for this session, when the caller has them (see
build_catalog): `cadence_spm`, `distance_km`. They are reported in measurements.csv only."""
parts = os.path.relpath(run_dir, data_root).replace(os.sep, "/").split("/")
level = level or {}
day_dir = os.path.dirname(run_dir)
ms = _json(os.path.join(run_dir, "meta-summary.json"))
info = load_context(data_root).get((parts[0], parts[1]), {})
sess, settings, app = ms.get("session", {}), ms.get("settings", {}), ms.get("app", {})
sensors, transports = ms.get("sensors", []), ms.get("transports", [])
files = [f for f in os.listdir(run_dir) if os.path.isfile(os.path.join(run_dir, f))]
pace = _csv(os.path.join(run_dir, "pace_profile.csv"))
fit3 = _csv(os.path.join(day_dir, "fit3", "fit3_summary.csv"))
fit3 = fit3.iloc[0] if fit3 is not None and len(fit3) else None
h10 = next(iter(sorted(glob.glob(os.path.join(run_dir, "polar_*_hr.csv")))), None)
duration_min = sess["durationMs"] / 60000 if sess.get("durationMs") else None
cap = _capture_stats(run_dir, float(settings["sampling_rate_hz"]) if settings.get("sampling_rate_hz") else None,
int(sess["endedAtMs"]) * 1000 if sess.get("endedAtMs") else None)
def fit3_val(key):
return None if fit3 is None or pd.isna(fit3.get(key)) else float(fit3[key])
# Ground truth for the RUN (as distinct from how much data was recorded), first source that has it:
# 1) hand-set (e.g. a parkrun is 5.00 km), 2) phone GPS (outdoors only; last - first, the public cum_km
# is zeroed at a hidden mid-run moment), 3) the watch (its clock is not synced to the app, so a few
# minutes' difference is expected), 4) duration only: the recording itself, unless the session's notes
# flag it as stopped before the run ended
# the phone's GPS is part of the recording: when the notes flag the recording as stopped early, it
# covers only part of the run and is not used as the run's ground truth
stopped_early = str(info.get("terminated_early")).lower() in ("true", "yes", "1")
gps_km = gps_min = None
span = pace.iloc[[0, -1]] if pace is not None and len(pace) else None
if (not stopped_early and info.get("setting") != "indoor" and span is not None
and span["cum_km"].diff().iloc[-1] > 0):
gps_km, gps_min = span["cum_km"].diff().iloc[-1], span["time_us"].diff().iloc[-1] / 6e7
fit3_km = fit3_val("distance_m") / 1000 if fit3_val("distance_m") else None
fit3_min = fit3_val("duration_s") / 60 if fit3_val("duration_s") else None
def first(*cands):
return next(((v, src) for v, src in cands if v is not None), (None, None))
distance_km, distance_src = first((_num(info.get("distance_km_reported")), "reported"),
(gps_km, "phone_gps"), (fit3_km, "fit3"))
run_duration_min, run_duration_src = first((_num(info.get("run_duration_min_reported")), "reported"),
(gps_min, "phone_gps"), (fit3_min, "fit3"),
(None if stopped_early else duration_min, "recording"))
pace_min_km = run_duration_min / distance_km if run_duration_min and distance_km else None
# HR: chest strap preferred, then watch -- only if it covers most of the run (a strap that drops
# out early leaves a warm-up segment that is not representative)
hr_src = hr_mean = hr_max = None
hr = _csv(h10) if h10 else None
if hr is not None and len(hr) and duration_min:
hr = hr[hr["HEART_RATE"] > 0]
span_min = (hr["RECEIVED_TIMESTAMP"].iloc[-1] - hr["RECEIVED_TIMESTAMP"].iloc[0]) / 6e7 if len(hr) else 0
if span_min >= HR_MIN_COVERAGE * duration_min:
hr_src, hr_mean, hr_max = "polar_h10", hr["HEART_RATE"].mean(), hr["HEART_RATE"].max()
if hr_src is None and fit3_val("hr_mean") is not None:
hr_src, hr_mean, hr_max = "fit3", fit3_val("hr_mean"), fit3_val("hr_max")
# every source of each quantity is reported in measurements.csv; running.csv carries the pick
hr_h10 = (hr["HEART_RATE"].mean(), hr["HEART_RATE"].max()) if hr_src == "polar_h10" else (None, None)
# cadence: the watch if worn, else the phone's step counter (every participant has the phone)
steps = _csv(os.path.join(run_dir, "steps.csv"))
phone_steps = phone_cadence = None
if steps is not None and len(steps) > 1 and "step_count" in steps:
span_min = (steps["timestamp"].iloc[-1] - steps["timestamp"].iloc[0]) / 6e7
phone_steps = steps["step_count"].iloc[-1] - steps["step_count"].iloc[0]
if span_min > 1:
phone_cadence = phone_steps / span_min
cadence, cadence_src = first((fit3_val("cadence_mean"), "fit3"), (phone_cadence, "phone_steps"))
fit3_steps = fit3_val("cadence_mean") * fit3_min if fit3_val("cadence_mean") and fit3_min else None
level_steps = level.get("cadence_spm") * duration_min if level.get("cadence_spm") and duration_min else None
r = lambda v, n=1: None if v is None else round(float(v), n)
pace = lambda mins, km: r(mins / km, 2) if mins and km else None
return {
# session
"subject": parts[0], "date": info.get("date"), "session": parts[1],
# conditions
"setting": info.get("setting"), "surface": info.get("surface"), "event": info.get("event"),
"location": info.get("location"),
# setup
"sensor_count": len(sensors) or settings.get("sensor_count"),
# app labels vary: "Left Foot" (schema 1) / "left_foot" (schema 2, normalized)
"placements": _join((s.get("sensorLabel") or "").strip().replace("_", " ").title() for s in sensors),
"channels": _channels(run_dir),
"sampling_rate_hz": settings.get("sampling_rate_hz"),
# meta-summary schema 2 moved it to the app's debug file (carried in context/session_context.csv)
"samples_per_packet": settings.get("samples_per_packet") or _num(info.get("samples_per_packet")),
"transport": _join(t.get("type") for t in transports),
# recorded by the app where its build did so; else the version reported for that session (context)
"dongle_firmware": (_join(t.get("firmwareVersion") for t in transports if t.get("type") == "DONGLE")
or info.get("dongle_firmware_reported") or None),
"sensor_firmware": _join(s.get("firmwareVersion") for s in sensors) or info.get("sensor_firmware_reported") or None,
"app_version": app.get("versionName"),
"phone_model": info.get("phone_model") or info.get("phone_model_reported"), # app record, else reported
# recorded by the app (builds from 2026-09-21), else the participant's report; blank = unknown
"bluetooth_devices": info.get("bluetooth_devices") or info.get("other_bluetooth_reported"),
# blank = not recorded (app builds before 2026-09-16 did not log it), not "off"
"time_sync": info.get("time_sync_mode") or ({True: "on", False: "off"}.get(settings.get("time_sync"))),
# how it was carried / calibrated (from context)
"phone_carry": info.get("phone_carry"),
"calibration": info.get("calibration"),
# data available: one column per optional file type (the LEVEL sensors are sensor_count)
**_available(run_dir),
# run (recording_min is the LEVEL recording's length; run_duration_min is the run itself)
"recording_min": r(duration_min), "run_duration_min": r(run_duration_min), "run_duration_source": run_duration_src,
# how much of the run the recording covers (R09 stopped at 44 %); None when the run length is unknown
"coverage_pct": (r(100.0 * duration_min / run_duration_min, 0)
if duration_min and run_duration_min else None),
"distance_source": distance_src, "distance_km": r(distance_km, 2), "pace_min_km": r(pace_min_km, 2),
"hr_mean_bpm": r(hr_mean, 0), "hr_max_bpm": r(hr_max, 0), "hr_source": hr_src,
"cadence_mean_spm": r(cadence, 0), "cadence_source": cadence_src,
# capture analysis
"loss_pct": cap["loss_pct"],
"effective_rate_hz": cap["effective_rate_hz"],
"max_gap_s": cap["max_gap_s"],
"long_gaps_per_hour": cap["long_gaps_per_hour"],
"data_ends_early_s": cap["data_ends_early_s"],
"terminated_early": info.get("terminated_early"),
"time_sync_verdict": info.get("time_sync_verdict"),
"unreliable_sensors": info.get("unreliable_sensors"),
**{k: _num(info.get(k)) for k in ("phone_battery_start_pct", "phone_battery_end_pct", "phone_temp_start_c",
"phone_temp_end_c", "sensor_voltage_start_v", "sensor_voltage_end_v",
"sensor_temp_start_c", "sensor_temp_end_c")},
"n_files": len(files),
"size_mb": round(sum(os.path.getsize(os.path.join(run_dir, f)) for f in files) / 1e6, 1),
"notes": info.get("notes"), # what a user must know before trusting the session
# measurements: one column per source of each run quantity, and which one running.csv uses
"duration_min_reported": r(_num(info.get("run_duration_min_reported"))), "duration_min_gps": r(gps_min),
"duration_min_fit3": r(fit3_min), "duration_min_recording": r(duration_min), "duration_use": run_duration_src,
"distance_km_reported": r(_num(info.get("distance_km_reported")), 2), "distance_km_gps": r(gps_km, 2),
"distance_km_fit3": r(fit3_km, 2), "distance_km_level": r(level.get("distance_km"), 2), "distance_use": distance_src,
"pace_min_km_gps": pace(gps_min, gps_km), "pace_min_km_fit3": pace(fit3_min, fit3_km),
"pace_use": f"{run_duration_src}/{distance_src}" if pace_min_km else None,
"steps_phone": r(phone_steps, 0), "steps_fit3": r(fit3_steps, 0), "steps_level": r(level_steps, 0),
"cadence_spm_level": r(level.get("cadence_spm"), 0), "cadence_spm_phone": r(phone_cadence, 0),
"cadence_spm_fit3": r(fit3_val("cadence_mean"), 0), "cadence_use": cadence_src,
"hr_mean_bpm_h10": r(hr_h10[0], 0), "hr_max_bpm_h10": r(hr_h10[1], 0),
"hr_mean_bpm_fit3": r(fit3_val("hr_mean"), 0), "hr_max_bpm_fit3": r(fit3_val("hr_max"), 0), "hr_use": hr_src,
}
def load_level_metrics(path: str | None) -> dict[tuple[str, str], dict]:
"""A LEVEL analysis table (one row per run: `date`, `session` = `R<NN>/level` or `S01/R<NN>`,
`imu_cadence_spm`, `zupt_km`) -> {(date, R<NN>): {cadence_spm, distance_km}}. Empty when no path."""
df = _csv(path) if path else None
if df is None:
return {}
out = {}
for row in df.to_dict("records"):
sess = next((p for p in str(row.get("session", "")).split("/") if p.startswith("R")), None)
if sess:
out[(str(row.get("date")), sess)] = {"cadence_spm": _num(row.get("imu_cadence_spm")),
"distance_km": _num(row.get("zupt_km"))}
return out
def build_catalog(data_root: str, level_metrics: str | None = None) -> pd.DataFrame:
"""Every session under data_root, one row each (its run), all columns. `level_metrics` = optional
path to the LEVEL analysis table (its values land in measurements.csv only)."""
level = load_level_metrics(level_metrics)
rows = []
for d in iter_sessions(data_root, kind="run"):
parts = os.path.relpath(d, data_root).replace(os.sep, "/").split("/")
info = load_context(data_root).get((parts[0], parts[1]), {})
rows.append(session_row(d, data_root, level.get((str(info.get("date")), parts[1]))))
return pd.DataFrame(rows)
KEY_COLS = ["subject", "date", "session"]
RUNNING_COLS = KEY_COLS + [
"setting", "surface", "event", "location",
"run_duration_min", "run_duration_source", "distance_km", "distance_source", "pace_min_km",
"hr_mean_bpm", "hr_max_bpm", "hr_source", "cadence_mean_spm", "cadence_source",
]
CAPTURE_COLS = KEY_COLS + [
"sensor_count", "placements", "channels", "sampling_rate_hz", "samples_per_packet", "transport",
"dongle_firmware", "sensor_firmware", "app_version", "phone_model", "bluetooth_devices", "time_sync",
"phone_carry", "calibration",
"gps", "barometer", "steps", "h10_hr", "h10_ecg", "h10_acc", "watch",
"recording_min", "coverage_pct", "terminated_early", "data_ends_early_s",
"loss_pct", "effective_rate_hz", "max_gap_s", "long_gaps_per_hour",
"time_sync_verdict", "unreliable_sensors",
"phone_battery_start_pct", "phone_battery_end_pct", "phone_temp_start_c", "phone_temp_end_c",
"sensor_voltage_start_v", "sensor_voltage_end_v", "sensor_temp_start_c", "sensor_temp_end_c",
"n_files", "size_mb", "notes",
]
MEASUREMENT_COLS = KEY_COLS + [
"duration_min_reported", "duration_min_gps", "duration_min_fit3", "duration_min_recording", "duration_use",
"distance_km_reported", "distance_km_gps", "distance_km_fit3", "distance_km_level", "distance_use",
"pace_min_km_gps", "pace_min_km_fit3", "pace_use",
"steps_phone", "steps_fit3", "steps_level",
"cadence_spm_level", "cadence_spm_phone", "cadence_spm_fit3", "cadence_use",
"hr_mean_bpm_h10", "hr_max_bpm_h10", "hr_mean_bpm_fit3", "hr_max_bpm_fit3", "hr_use",
]
def split_catalog(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
"""The full catalog -> (running.csv, capture.csv, measurements.csv) frames. Every column of the full
row must land in exactly one file (plus the shared key), so a new column added to session_row fails
loudly here."""
missing = set(df.columns) - set(RUNNING_COLS) - set(CAPTURE_COLS) - set(MEASUREMENT_COLS)
if missing:
raise KeyError(f"catalog columns not assigned to running.csv, capture.csv or measurements.csv: {sorted(missing)}")
return tuple(df[[c for c in cols if c in df]] for cols in (RUNNING_COLS, CAPTURE_COLS, MEASUREMENT_COLS))
|