File size: 7,390 Bytes
689b5c1
 
 
 
 
 
 
 
 
 
 
702c817
 
689b5c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702c817
689b5c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702c817
 
 
689b5c1
 
 
702c817
689b5c1
 
 
 
 
 
702c817
689b5c1
 
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
"""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$")


@dataclass
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


@dataclass
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

    @property
    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 {})}

    @property
    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")

    @property
    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