running / scripts /lvl_running /catalog.py
jfslin's picture
R12 (2026-10-10 parkrun, 12 samples per packet); catalog split into running.csv + capture.csv (part 2)
af4a5b4 verified
Raw History Blame Contribute Delete
17 kB
"""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)
from lvl_running.catalog import build_catalog, split_catalog
running, capture = 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) -> dict:
parts = os.path.relpath(run_dir, data_root).replace(os.sep, "/").split("/")
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")
# cadence: the watch if worn, else the phone's step counter (every participant has the phone)
cadence, cadence_src = fit3_val("cadence_mean"), "fit3" if fit3_val("cadence_mean") is not None else None
steps = _csv(os.path.join(run_dir, "steps.csv"))
if cadence is None and steps is not None and len(steps) > 1 and "step_count" in steps:
span_min = (steps["timestamp"].iloc[-1] - steps["timestamp"].iloc[0]) / 6e7
if span_min > 1:
cadence, cadence_src = (steps["step_count"].iloc[-1] - steps["step_count"].iloc[0]) / span_min, "phone_steps"
r = lambda v, n=1: None if v is None else round(float(v), n)
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
}
def build_catalog(data_root: str) -> pd.DataFrame:
"""Every session under data_root, one row each (its run), all columns."""
return pd.DataFrame([session_row(d, data_root) for d in iter_sessions(data_root, kind="run")])
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",
]
def split_catalog(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
"""The full catalog -> (running.csv, capture.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)
if missing:
raise KeyError(f"catalog columns not assigned to running.csv or capture.csv: {sorted(missing)}")
return df[[c for c in RUNNING_COLS if c in df]], df[[c for c in CAPTURE_COLS if c in df]]