Download scripts/lvl_running/session.py from lvlmotion/running: direct link, hf CLI and curl.
- Browser
- Download file 7.39 kB
-
https://huggingface.co/datasets/lvlmotion/running/resolve/main/scripts/lvl_running/session.py
- Command line
-
hf download hf://datasets/lvlmotion/running/scripts/lvl_running/session.py
-
curl -L -o session.py https://huggingface.co/datasets/lvlmotion/running/resolve/main/scripts/lvl_running/session.py
7.39 kB
| """Load a LEVEL running-dataset session folder into typed frames. | |
| A session folder (data/<subject>/<day>/<session>/) contains: | |
| imu-{placement}-{shortmac}[.NNN].csv per-sensor raw (time-us, accel xyz, gyro xyz, frame_sensor, | |
| time_sensor[, time_host]; older recordings are renamed on load); | |
| .NNN are rotation segments -- concatenated + time-sorted here. | |
| gps.csv, barometer.csv, steps.csv phone-native streams (epoch-us); gps.csv only on public-event days | |
| pace_profile.csv coordinate-free distance / pace / elevation derived from GPS | |
| polar_<4hex>_{hr,acc,ecg}.csv Polar H10 chest strap, when worn | |
| meta-summary.json manifest (session window, sensors, settings, transport) | |
| meta-debug.json diagnostics (phone battery, time-sync result, phone); older | |
| app builds call it meta-device.json -- either is loaded. | |
| Not in the release: its values are in sessions.csv | |
| meta-telemetry.csv per-sensor telemetry snapshots (voltage/rssi/loss) -- internal | |
| recordings only, not in the release (loaded when present) | |
| The day folder also holds fit3/ (Samsung Galaxy Fit3 watch reference) -- see fit3.py. | |
| """ | |
| from __future__ import annotations | |
| import glob | |
| import json | |
| import os | |
| import re | |
| from dataclasses import dataclass, field | |
| from typing import Iterator | |
| import pandas as pd | |
| # LEVEL Collector's 2026-09 column rename (header-only): older recordings load under the current names | |
| IMU_RENAME = {"frame_number": "frame_sensor", "raw_counter": "time_sensor"} | |
| TIME_SENSOR_WRAP_MS = 1 << 16 # time_sensor is the sensor's 16-bit ms clock | |
| def unwrap_time_sensor(df: pd.DataFrame) -> pd.Series: | |
| """time_sensor (16-bit ms, wraps every 65.5 s) as a continuous ms count from the first sample. | |
| Wraps are counted from `time` (host timeline), so a dropout longer than one wrap cannot fool it.""" | |
| raw = df["time_sensor"].astype("int64") | |
| elapsed_ms = (df["time"] - df["time"].iloc[0]) // 1000 | |
| wraps = ((elapsed_ms - (raw - raw.iloc[0])) / TIME_SENSOR_WRAP_MS).round().astype("int64") | |
| return raw - raw.iloc[0] + wraps * TIME_SENSOR_WRAP_MS | |
| # imu-<placement>-<4hex>[.NNN].csv (placement may contain hyphens/underscores, e.g. left_foot) | |
| _IMU_RE = re.compile(r"^imu-(?P<placement>.+)-(?P<mac>[0-9a-fA-F]{4})(?:\.(?P<seg>\d+))?\.csv$") | |
| class ImuStream: | |
| placement: str | |
| mac: str | |
| df: pd.DataFrame # time, accel_x..gyro_z, frame_sensor, time_sensor[, time_host] -- concatenated + time-sorted | |
| n_segments: int # how many rotation files were stitched | |
| class Session: | |
| path: str | |
| name: str | |
| imus: dict[str, ImuStream] = field(default_factory=dict) # keyed by placement | |
| gps: pd.DataFrame | None = None | |
| barometer: pd.DataFrame | None = None | |
| steps: pd.DataFrame | None = None | |
| meta_summary: dict | None = None | |
| meta_telemetry: pd.DataFrame | None = None | |
| meta_debug: dict | None = None # diagnostics (meta-debug.json): battery, time sync, phone | |
| def settings(self) -> dict: | |
| """Stream settings from both meta files. meta-summary schema 2 keeps only sampling_rate_hz / | |
| sensor_count / time_sync; the rest (samples_per_packet, ...) moved to meta-debug.json.""" | |
| return {**((self.meta_debug or {}).get("settings") or {}), | |
| **((self.meta_summary or {}).get("settings") or {})} | |
| def session_ms(self) -> tuple[int | None, int | None]: | |
| """(startedAtMs, endedAtMs) from meta-summary, if present.""" | |
| s = (self.meta_summary or {}).get("session", {}) | |
| return s.get("startedAtMs"), s.get("endedAtMs") | |
| def duration_s(self) -> float | None: | |
| s = (self.meta_summary or {}).get("session", {}) | |
| d = s.get("durationMs") | |
| return d / 1000.0 if d is not None else None | |
| def _read_csv(path: str) -> pd.DataFrame | None: | |
| try: | |
| return pd.read_csv(path) | |
| except Exception: | |
| return None | |
| def load_session(path: str) -> Session: | |
| name = os.path.basename(os.path.normpath(path)) | |
| if name in ("level", "calib"): # role-named recording: say which session it belongs to | |
| name = f"{os.path.basename(os.path.dirname(os.path.normpath(path)))}/{name}" | |
| sess = Session(path=path, name=name) | |
| # --- IMU: group rotation segments by (placement, mac), concat, sort by time --- | |
| segs: dict[tuple[str, str], list[pd.DataFrame]] = {} | |
| for fn in sorted(os.listdir(path)): | |
| m = _IMU_RE.match(fn) | |
| if not m: | |
| continue | |
| df = _read_csv(os.path.join(path, fn)) | |
| if df is None or "time" not in df.columns: | |
| continue | |
| df = df.rename(columns=IMU_RENAME) | |
| segs.setdefault((m["placement"], m["mac"]), []).append(df) | |
| for (placement, mac), parts in segs.items(): | |
| parts.sort(key=lambda d: int(d["time"].iloc[0])) # order by first timestamp | |
| df = pd.concat(parts, ignore_index=True).sort_values("time").reset_index(drop=True) | |
| sess.imus[placement] = ImuStream(placement, mac, df, n_segments=len(parts)) | |
| # --- phone-native streams + meta --- | |
| sess.gps = _read_csv(os.path.join(path, "gps.csv")) | |
| sess.barometer = _read_csv(os.path.join(path, "barometer.csv")) | |
| sess.steps = _read_csv(os.path.join(path, "steps.csv")) | |
| sess.meta_telemetry = _read_csv(os.path.join(path, "meta-telemetry.csv")) | |
| ms = os.path.join(path, "meta-summary.json") | |
| if os.path.exists(ms): | |
| try: | |
| sess.meta_summary = json.load(open(ms)) | |
| except Exception: | |
| sess.meta_summary = None | |
| md = os.path.join(path, "meta-debug.json") | |
| if not os.path.exists(md): # app builds before meta-summary schema 2 | |
| md = os.path.join(path, "meta-device.json") | |
| if os.path.exists(md): | |
| try: | |
| sess.meta_debug = json.load(open(md)) | |
| except Exception: | |
| sess.meta_debug = None | |
| return sess | |
| def find_sessions(root: str) -> list[str]: | |
| """Session subfolders directly under root (those containing a meta-summary.json).""" | |
| out = [] | |
| for d in sorted(glob.glob(os.path.join(root, "*"))): | |
| if os.path.isdir(d) and os.path.exists(os.path.join(d, "meta-summary.json")): | |
| out.append(d) | |
| return out | |
| PUBLIC_ROLE = {"run": "level"} # the run's public folder is level/ (beside fit3/); raw ones end in -run | |
| def iter_sessions(root: str, kind: str | None = "run") -> Iterator[str]: | |
| """Every session folder anywhere under root (data/, a subject, or a day), in sorted order. | |
| kind="run" (default) yields only the runs (`level/`); kind="calib" the calibrations (`calib/`); | |
| kind=None everything. Raw-style names (`<timestamp>-run`) match too. | |
| """ | |
| for dirpath, dirs, files in os.walk(root): | |
| dirs.sort() | |
| if "meta-summary.json" in files: | |
| name = os.path.basename(dirpath) | |
| if kind is None or name == PUBLIC_ROLE.get(kind, kind) or name.endswith(f"-{kind}"): | |
| yield dirpath | |
| dirs.clear() # a session folder has no nested sessions | |