"""Figures for one run session, one flat folder per session (figures///): overview.png every source on one time axis -- start here data-.png the published data as recorded, one figure per source: imu (a mid-run window of every sensor, accel + gyro), phone (GPS speed, pace vs distance, elevation, steps), h10 (Polar ECG + accel), fit3 (Samsung watch HR / cadence / speed) derived-.png anything computed from the data: spectrum (foot-accel PSD vs Nyquist) today; the running metrics (cadence, symmetry, ...) join once validated Uniform units: acceleration in g, angular velocity in deg/s. from lvl_running import plot_session plot_session("data/S01/R01/level", "figures/S01/R01") """ from __future__ import annotations import glob import os import numpy as np import pandas as pd from scipy.signal import welch from .fit3 import load_fit3 from .session import load_session G = 9.80665 DPS = 180.0 / np.pi ACC_RAIL_G = 16.0 # +/-16 g accelerometer range # house palette (matches lvl_toolkit.graphing): axes x/y/z = red/green/blue; bilateral feet blue/green AXIS_COLORS = ("#d62728", "#2ca02c", "#1f77b4") # x = red, y = green, z = blue FOOT_COLORS = {"left_foot": "#1f77b4", "right_foot": "#228B22"} DPI = 110 # fixed so a re-render of unchanged data is byte-stable in intent def _plt(): try: import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt return plt except ImportError: return None def _save(fig, plt, out_dir: str, name: str) -> str: os.makedirs(out_dir, exist_ok=True) p = os.path.join(out_dir, name) fig.savefig(p, dpi=DPI) plt.close(fig) return p def _mid_window(ts: np.ndarray, window_s: float, frac: float = 0.4) -> slice: dur = (ts[-1] - ts[0]) / 1e6 if dur <= window_s: return slice(0, len(ts)) i0 = int(np.searchsorted(ts, ts[0] + int(dur * frac * 1e6))) fs = 1e6 / np.median(np.diff(ts)) return slice(i0, i0 + int(window_s * fs)) def plot_imu(run, out_dir: str, window_s: float = 6.0) -> str | None: sensors = sorted(run.imus.values(), key=lambda s: s.placement) plt = _plt() if not sensors or plt is None: return None n = len(sensors) fig, ax = plt.subplots(n, 2, figsize=(12, 2.3 * n), sharex="col", squeeze=False) for r, s in enumerate(sensors): ts = s.df["time"].to_numpy(np.int64); w = _mid_window(ts, window_s) t = (ts[w] - ts[w][0]) / 1e6 acc = s.df[["accel_x", "accel_y", "accel_z"]].to_numpy() / G # g gyr = s.df[["gyro_x", "gyro_y", "gyro_z"]].to_numpy() * DPS # deg/s peak_g = float(np.linalg.norm(acc, axis=1).max()); peak_dps = float(np.abs(gyr).max()) for c, (d, lab, u, peak) in enumerate([(acc[w], "accel", "g", peak_g), (gyr[w], "gyro", "deg/s", peak_dps)]): a = ax[r][c] for k, axis in enumerate("xyz"): a.plot(t, d[:, k], lw=0.7, color=AXIS_COLORS[k], label=axis) if c == 0: # impact highlight: accel samples reaching the +/-16 g rail (under-resolved impacts) mag_w = np.linalg.norm(acc[w], axis=1) hit = mag_w >= 0.95 * ACC_RAIL_G if hit.any(): a.plot(t[hit], mag_w[hit], "k.", ms=4) a.axhline(ACC_RAIL_G, color="k", ls=":", lw=0.7) a.axhline(-ACC_RAIL_G, color="k", ls=":", lw=0.7) a.set_ylabel(f"{s.placement}\n{lab} ({u})", fontsize=8); a.grid(alpha=.3) a.text(0.99, 0.03, f"max |{lab}| = {peak:.0f} {u}" if u == "deg/s" else f"max |{lab}| = {peak:.1f} {u}", transform=a.transAxes, ha="right", va="bottom", fontsize=7, color="0.3") if r == 0: a.legend(ncol=3, fontsize=7, loc="upper right") a.set_title({0: "Accelerometer (g)", 1: "Gyroscope (deg/s)"}[c]) # same y-limits on both feet per channel so left vs right is directly comparable foot_rows = [r for r, s in enumerate(sensors) if s.placement in ("left_foot", "right_foot")] for c in (0, 1): lims = [ax[r][c].get_ylim() for r in foot_rows] if len(lims) > 1: lo = min(l[0] for l in lims); hi = max(l[1] for l in lims) for r in foot_rows: ax[r][c].set_ylim(lo, hi) ax[-1][0].set_xlabel("time (s)"); ax[-1][1].set_xlabel("time (s)") fig.suptitle(f"Raw IMU -- {window_s:.0f}s mid-run window -- black = accel at the +/-16 g rail " f"(under-resolved impacts)\n{run.name}", y=0.998, fontsize=10) fig.tight_layout() return _save(fig, plt, out_dir, "data-imu.png") def plot_spectrum(run, out_dir: str) -> str | None: """Foot-accel power spectrum vs Nyquist -- shows where the 100 Hz rate is too low (aliasing).""" feet = [f for f in ("left_foot", "right_foot") if f in run.imus] plt = _plt() if not feet or plt is None: return None fig, ax = plt.subplots(figsize=(12, 4)) nyq = None for foot in feet: s = run.imus[foot].df ts = s["time"].to_numpy(np.int64) fs = 1e6 / np.median(np.diff(ts)); nyq = fs / 2 mag = np.linalg.norm(s[["accel_x", "accel_y", "accel_z"]].to_numpy() / G, axis=1) f, pxx = welch(mag - mag.mean(), fs=fs, nperseg=min(2048, len(mag))) ax.semilogy(f, pxx, lw=1.0, color=FOOT_COLORS.get(foot, "0.5"), label=foot.replace("_", " ")) if nyq: ax.axvline(nyq, color="r", ls="--", lw=1.0, label=f"Nyquist ({nyq:.0f} Hz)") ax.set_xlabel("frequency (Hz)"); ax.set_ylabel("foot accel PSD (g^2/Hz)") ax.set_title(f"Foot-accel spectrum -- most energy < 30 Hz (100 Hz OK for timing); the tail still at " f"the {nyq:.0f} Hz Nyquist = impact transient under-sampled\n{run.name}", fontsize=9) ax.grid(alpha=.3, which="both"); ax.legend() fig.tight_layout() return _save(fig, plt, out_dir, "derived-spectrum.png") def plot_phone(run_dir: str, out_dir: str) -> str | None: """Phone streams: GPS-derived speed (coordinate-free pace_profile), barometric relative altitude and cumulative steps on one session-relative time axis, plus pace vs distance from the same profile.""" pp, baro, stp = (os.path.join(run_dir, f) for f in ("pace_profile.csv", "barometer.csv", "steps.csv")) plt = _plt() if not any(os.path.exists(f) for f in (pp, baro, stp)) or plt is None: return None starts, dfs = [], {} if os.path.exists(pp): dfs["pp"] = pd.read_csv(pp); starts.append(int(dfs["pp"]["time_us"].iloc[0])) if os.path.exists(baro): dfs["baro"] = pd.read_csv(baro); starts.append(int(dfs["baro"]["timestamp"].iloc[0])) if os.path.exists(stp): dfs["stp"] = pd.read_csv(stp); starts.append(int(dfs["stp"]["timestamp"].iloc[0])) t0 = min(starts) fig = plt.figure(figsize=(12, 8)) gs = fig.add_gridspec(4, 1) ax = [fig.add_subplot(gs[0])] ax += [fig.add_subplot(gs[i], sharex=ax[0]) for i in (1, 2)] # three panels vs time ... ax.append(fig.add_subplot(gs[3])) # ... and pace vs distance if "pp" in dfs: d = dfs["pp"]; t = (d["time_us"].to_numpy(np.int64) - t0) / 1e6 / 60.0 ax[0].plot(t, d["speed_mps"], lw=0.8, color="#1f77b4") if "baro_alt_rel_m" in d: ax[1].plot(t, d["baro_alt_rel_m"], lw=0.8, color="#8c564b", label="baro (pace_profile)") if "gps_alt_rel_m" in d: ax[1].plot(t, d["gps_alt_rel_m"], lw=0.6, color="#bbbbbb", label="GPS") if "baro" in dfs and "pp" not in dfs: d = dfs["baro"]; t = (d["timestamp"].to_numpy(np.int64) - t0) / 1e6 / 60.0 ax[1].plot(t, d["altitude_m"] - d["altitude_m"].iloc[0], lw=0.8, color="#8c564b", label="baro") ax[0].set_ylabel("speed (m/s)"); ax[0].set_title("Phone GPS -- ground speed (coordinate-free pace_profile)"); ax[0].grid(alpha=.3) ax[1].set_ylabel("rel. altitude (m)"); ax[1].set_title("Barometer -- relative altitude"); ax[1].grid(alpha=.3) if ax[1].get_legend_handles_labels()[0]: ax[1].legend(fontsize=7) if "stp" in dfs: d = dfs["stp"]; t = (d["timestamp"].to_numpy(np.int64) - t0) / 1e6 / 60.0 ax[2].plot(t, d["step_count"], lw=0.9, color="#2ca02c") ax[2].set_ylabel("cumulative steps"); ax[2].set_title("Phone step counter"); ax[2].set_xlabel("time (min)"); ax[2].grid(alpha=.3) if "pp" in dfs and len(dfs["pp"]) > 1: # the same profile against distance prof = dfs["pp"] d = prof["cum_km"].to_numpy() - float(prof["cum_km"].iloc[0]) ax[3].plot(d, prof["pace_min_km"].to_numpy(), lw=0.5, color="0.75", label="pace per GPS fix") ax[3].plot(d, prof["pace_min_km"].rolling(15, center=True, min_periods=1).median().to_numpy(), lw=1.5, color="#377eb8", label="rolling median") ax[3].set_ylim(3, 12); ax[3].invert_yaxis(); ax[3].legend(fontsize=8, loc="lower right") ax[3].set_ylabel("pace (min/km)"); ax[3].set_title("Phone GPS -- pace vs distance"); ax[3].set_xlabel("distance (km)"); ax[3].grid(alpha=.3) d = os.path.normpath(run_dir) # same label as Session.name: R01/level fig.suptitle(f"Phone streams -- {os.path.basename(os.path.dirname(d))}/{os.path.basename(d)}", y=0.999, fontsize=10) fig.tight_layout() return _save(fig, plt, out_dir, "data-phone.png") def plot_h10(run_dir: str, out_dir: str, ecg_s: float = 4.0, acc_s: float = 6.0) -> str | None: """Polar H10 chest strap: a mid-run window of the ECG waveform and the strap accelerometer.""" ecgf = glob.glob(os.path.join(run_dir, "polar_*_ecg.csv")) accf = glob.glob(os.path.join(run_dir, "polar_*_acc.csv")) plt = _plt() if (not ecgf and not accf) or plt is None: return None def mid(rx, span_s): t0 = rx[0] + (rx[-1] - rx[0]) * 0.4 m = (rx >= t0) & (rx <= t0 + span_s * 1e6) return m, (rx[m] - (rx[m][0] if m.any() else rx[0])) / 1e6 fig, ax = plt.subplots(2, 1, figsize=(12, 5)) if ecgf: e = pd.read_csv(ecgf[0]); rx = e["RECEIVED_TIMESTAMP"].to_numpy(float) m, t = mid(rx, ecg_s) ax[0].plot(t, e["ECG"].to_numpy()[m], lw=0.6, color="#c00") ax[0].set_ylabel("ECG (uV)"); ax[0].set_title("Polar H10 -- ECG"); ax[0].grid(alpha=.3) if accf: a = pd.read_csv(accf[0]); rx = a["RECEIVED_TIMESTAMP"].to_numpy(float) m, t = mid(rx, acc_s) cols = [c for c in ("ACCEL_X", "ACCEL_Y", "ACCEL_Z") if c in a] colors = {"x": AXIS_COLORS[0], "y": AXIS_COLORS[1], "z": AXIS_COLORS[2]} for c in cols: ax[1].plot(t, a[c].to_numpy()[m] / 1000.0, lw=0.6, color=colors.get(c[-1].lower()), label=c[-1].lower()) if cols: ax[1].legend(fontsize=7) ax[1].set_ylabel("ACC (g)"); ax[1].set_xlabel("time (s)") ax[1].set_title("Polar H10 -- accelerometer (g)"); ax[1].grid(alpha=.3) fig.tight_layout() return _save(fig, plt, out_dir, "data-h10.png") def plot_fit3(run_dir: str, out_dir: str) -> str | None: """Samsung Fit3 watch (non-LEVEL reference): heart rate, cadence and speed over the workout.""" f = load_fit3(os.path.dirname(os.path.normpath(run_dir))) # fit3/ is at the day level plt = _plt() if f is None or f.live.empty or plt is None: return None live = f.live t = (live["time"].to_numpy(float) - float(live["time"].iloc[0])) / 60e6 # us -> min col = lambda c: live[c].to_numpy(float) if c in live else np.full(len(live), np.nan) fig, ax = plt.subplots(3, 1, figsize=(12, 6), sharex=True) ax[0].plot(t, col("heart_rate"), lw=0.9, color="#c00"); ax[0].set_ylabel("HR (bpm)") ax[0].set_title("Fit3 -- heart rate"); ax[0].grid(alpha=.3) ax[1].plot(t, col("cadence"), lw=0.9, color="#ff7f0e"); ax[1].set_ylabel("cadence (spm)") ax[1].set_title("Fit3 -- cadence"); ax[1].grid(alpha=.3) ax[2].plot(t, col("speed"), lw=0.9, color="#1f77b4"); ax[2].set_ylabel("speed (m/s)") ax[2].set_title("Fit3 -- speed"); ax[2].set_xlabel("time (min)"); ax[2].grid(alpha=.3) fig.suptitle("Non-LEVEL reference -- Samsung Galaxy Fit3 watch", y=0.999, fontsize=10) fig.tight_layout() return _save(fig, plt, out_dir, "data-fit3.png") PLACEMENT_COLORS = {**FOOT_COLORS, "back": "#9467bd", "left_wrist": "#ff7f0e", "right_wrist": "#d62728", "wrist": "#ff7f0e", "arm": "#8c564b"} def _binned_std(t_us: np.ndarray, x: np.ndarray, t0: int, bin_s: float) -> tuple[np.ndarray, np.ndarray]: """Per-bin standard deviation of x (NaN where a bin has no samples -> dropouts show as gaps).""" i = ((t_us - t0) // int(bin_s * 1e6)).astype(np.int64) keep = i >= 0 i, x = i[keep], x[keep] n = np.bincount(i).astype(float) s1, s2 = np.bincount(i, x), np.bincount(i, x * x) with np.errstate(invalid="ignore", divide="ignore"): sd = np.sqrt(np.maximum(s2 / n - (s1 / n) ** 2, 0)) sd[n == 0] = np.nan return np.arange(len(n)) * bin_s / 60.0, sd def plot_overview(run_dir: str, out_dir: str) -> str | None: """The one-look summary of a run: every source on one time axis -- LEVEL sensor movement, heart rate (chest strap + watch), speed (phone GPS + watch), cadence (phone steps + watch), relative elevation -- titled with the setup. Dropouts show as gaps.""" from .catalog import session_row plt = _plt() run = load_session(run_dir) if plt is None or not run.imus: return None root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.normpath(run_dir)))) rr = sr = session_row(run_dir, root) t0 = min(int(s.df["time"].iloc[0]) for s in run.imus.values()) t_end = max(int(s.df["time"].iloc[-1]) for s in run.imus.values()) tmin = lambda us: (np.asarray(us, dtype=float) - t0) / 60e6 read = lambda name: pd.read_csv(p) if (p := next(iter(sorted(glob.glob(os.path.join(run_dir, name)))), None)) else None fit3 = load_fit3(os.path.dirname(os.path.normpath(run_dir))) live = fit3.live if fit3 is not None and not fit3.live.empty else None pace, steps, hr = read("pace_profile.csv"), read("steps.csv"), read("polar_*_hr.csv") fig, ax = plt.subplots(5, 1, figsize=(12, 11), sharex=True) none = lambda a: a.text(0.5, 0.5, "not recorded", transform=a.transAxes, ha="center", va="center", color="0.5") # 1 movement: 1 s variability of |accel| per sensor for pl, s in sorted(run.imus.items()): mag = np.linalg.norm(s.df[["accel_x", "accel_y", "accel_z"]].to_numpy() / G, axis=1) x, sd = _binned_std(s.df["time"].to_numpy(np.int64), mag, t0, 1.0) ax[0].plot(x, sd, lw=0.7, color=PLACEMENT_COLORS.get(pl, "0.4"), label=pl.replace("_", " ")) ax[0].set_ylabel("movement\n(1 s SD of |accel|, g)"); ax[0].legend(ncol=len(run.imus), fontsize=8, loc="upper right") ax[0].set_title("LEVEL sensors -- movement intensity (gaps = no data)") # 2 heart rate if hr is not None and len(hr): h = hr[hr["HEART_RATE"] > 0] ax[1].plot(tmin(h["RECEIVED_TIMESTAMP"]), h["HEART_RATE"], lw=0.9, color="#c00", label="Polar H10 (chest)") if live is not None and "heart_rate" in live: ax[1].plot(tmin(live["time"]), live["heart_rate"], lw=1.2, ls="--", color="#ff7f0e", label="Fit3 (wrist)") ax[1].set_ylabel("heart rate\n(bpm)"); ax[1].set_title("Heart rate") ax[1].legend(fontsize=8, loc="lower right") if ax[1].lines else none(ax[1]) # 3 speed if pace is not None and "speed_mps" in pace: ax[2].plot(tmin(pace["time_us"]), pace["speed_mps"].rolling(15, center=True, min_periods=1).median(), lw=0.9, color="#1f77b4", label="phone GPS") if live is not None and "speed" in live: ax[2].plot(tmin(live["time"]), live["speed"], lw=1.2, ls="--", color="#ff7f0e", label="Fit3") ax[2].set_ylabel("speed\n(m/s)"); ax[2].set_title("Speed") ax[2].legend(fontsize=8, loc="lower right") if ax[2].lines else none(ax[2]) # 4 cadence: phone step events per 30 s (x2 -> steps/min) + watch if steps is not None and len(steps): ts = steps["timestamp"].to_numpy(np.int64) i = (ts - t0) // int(30e6); i = i[i >= 0] if len(i): n = np.bincount(i).astype(float); n[n == 0] = np.nan ax[3].step(np.arange(len(n)) * 0.5, n * 2, where="post", lw=0.9, color="#2ca02c", label="phone step counter") if live is not None and "cadence" in live: ax[3].plot(tmin(live["time"]), live["cadence"], lw=1.2, ls="--", color="#ff7f0e", label="Fit3") ax[3].set_ylabel("cadence\n(steps/min)"); ax[3].set_title("Cadence") ax[3].legend(fontsize=8, loc="lower right") if ax[3].lines else none(ax[3]) # 5 relative elevation if pace is not None and "baro_alt_rel_m" in pace: ax[4].plot(tmin(pace["time_us"]), pace["baro_alt_rel_m"], lw=0.9, color="#8c564b", label="phone barometer") if pace is not None and "gps_alt_rel_m" in pace: ax[4].plot(tmin(pace["time_us"]), pace["gps_alt_rel_m"], lw=0.6, color="#bbbbbb", label="phone GPS") ax[4].set_ylabel("relative\nelevation (m)"); ax[4].set_title("Elevation (relative)") ax[4].legend(fontsize=8, loc="lower right") if ax[4].lines else none(ax[4]) for a in ax: a.grid(alpha=.3) ax[-1].set_xlabel("time since the first LEVEL sample (min)") # whole session, not just the LEVEL span: sensors that stop early show as lines ending early ax[-1].set_xlim(-0.5, max((t_end - t0) / 60e6, rr.get("duration_min") or 0) + 0.5) fmt = lambda v, f: "?" if v is None or (isinstance(v, float) and np.isnan(v)) else f.format(v) refs = ", ".join(k for k, ok in (("Polar H10", sr.get("polar_h10")), ("Fit3 watch", sr.get("fit3_watch"))) if ok) where = " ".join(v for v in (sr.get("setting"), sr.get("surface")) if v) or "?" # no event / place: figures stay anonymous fig.suptitle(f"{run.name} -- {where}, {fmt(rr.get('duration_min'), '{:.0f}')} min, " f"{fmt(rr.get('distance_km'), '{:.2f}')} km\n" f"{sr.get('sensor_count')} LEVEL sensors ({sr.get('placements', '').replace(';', ', ')}) via " f"{sr.get('transport') or '?'} at {sr.get('sampling_rate_hz') or '?'} Hz | references: {refs or 'none'}", fontsize=11) fig.tight_layout() return _save(fig, plt, out_dir, "overview.png") def plot_session(run_dir: str, out_dir: str) -> dict[str, str | None]: """Every figure for one run session into out_dir (flat: overview.png, data-*.png, derived-*.png). Returns {figure: path or None}.""" run = load_session(run_dir) return {"overview": plot_overview(run_dir, out_dir), "data-imu": plot_imu(run, out_dir), "data-phone": plot_phone(run_dir, out_dir), "data-h10": plot_h10(run_dir, out_dir), "data-fit3": plot_fit3(run_dir, out_dir), "derived-spectrum": plot_spectrum(run, out_dir)}