jfslin commited on
Commit
dbd774a
·
verified ·
1 Parent(s): 0061fa4

Add run 26; sensor button presses (button.csv) (part 3)

Browse files
LICENSE CHANGED
@@ -1,32 +1,32 @@
1
- LEVEL Running Dataset
2
- Copyright (c) 2026 Level Health Innovations Corp.
3
-
4
- This work (the dataset, its figures, its documentation, and the accompanying reports) is licensed
5
- under the Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0).
6
- The Python code under scripts/ is licensed separately under the MIT License (scripts/LICENSE).
7
-
8
- Human-readable summary : https://creativecommons.org/licenses/by-nc/4.0/
9
- Full legal code : https://creativecommons.org/licenses/by-nc/4.0/legalcode
10
-
11
- You are free to:
12
- - Share -- copy and redistribute the material in any medium or format.
13
- - Adapt -- remix, transform, and build upon the material.
14
- The licensor cannot revoke these freedoms as long as you follow the license terms.
15
-
16
- Under the following terms:
17
- - Attribution -- You must give appropriate credit, provide a link to the license, and indicate
18
- if changes were made. You may do so in any reasonable manner, but not in any way
19
- that suggests the licensor endorses you or your use.
20
- - NonCommercial -- You may not use the material for commercial purposes.
21
- - No additional restrictions -- You may not apply legal terms or technological measures that legally
22
- restrict others from doing anything the license permits.
23
-
24
- The full CC BY-NC 4.0 legal code (linked above) governs. This notice applies the license; it does not
25
- replace or modify it. Commercial use, including any use primarily intended for or directed toward
26
- commercial advantage or monetary compensation, requires separate permission from the copyright holder.
27
-
28
- Attribution / how to cite:
29
- Lin, J. (2026). LEVEL Running Dataset. Level Health Innovations Corp.
30
- https://huggingface.co/datasets/lvlmotion/running
31
-
32
- For commercial licensing enquiries: jlin@lvlmotion.com
 
1
+ LEVEL Running Dataset
2
+ Copyright (c) 2026 Level Health Innovations Corp.
3
+
4
+ This work (the dataset, its figures, its documentation, and the accompanying reports) is licensed
5
+ under the Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0).
6
+ The Python code under scripts/ is licensed separately under the MIT License (scripts/LICENSE).
7
+
8
+ Human-readable summary : https://creativecommons.org/licenses/by-nc/4.0/
9
+ Full legal code : https://creativecommons.org/licenses/by-nc/4.0/legalcode
10
+
11
+ You are free to:
12
+ - Share -- copy and redistribute the material in any medium or format.
13
+ - Adapt -- remix, transform, and build upon the material.
14
+ The licensor cannot revoke these freedoms as long as you follow the license terms.
15
+
16
+ Under the following terms:
17
+ - Attribution -- You must give appropriate credit, provide a link to the license, and indicate
18
+ if changes were made. You may do so in any reasonable manner, but not in any way
19
+ that suggests the licensor endorses you or your use.
20
+ - NonCommercial -- You may not use the material for commercial purposes.
21
+ - No additional restrictions -- You may not apply legal terms or technological measures that legally
22
+ restrict others from doing anything the license permits.
23
+
24
+ The full CC BY-NC 4.0 legal code (linked above) governs. This notice applies the license; it does not
25
+ replace or modify it. Commercial use, including any use primarily intended for or directed toward
26
+ commercial advantage or monetary compensation, requires separate permission from the copyright holder.
27
+
28
+ Attribution / how to cite:
29
+ Lin, J. (2026). LEVEL Running Dataset. Level Health Innovations Corp.
30
+ https://huggingface.co/datasets/lvlmotion/running
31
+
32
+ For commercial licensing enquiries: jlin@lvlmotion.com
README.md CHANGED
@@ -75,7 +75,7 @@ private context, with their sign-off). Per-session figures are in `figures/` her
75
  ## The sessions
76
 
77
  <!-- glance:start (generated by scripts/make_catalog.py) -->
78
- **25 sessions, 1 participant, 11.9 h of recording.**
79
  <!-- glance:end -->
80
 
81
  Every run's results, one row each (duration, distance, pace, cadence, contact time, asymmetry, heart
 
75
  ## The sessions
76
 
77
  <!-- glance:start (generated by scripts/make_catalog.py) -->
78
+ **26 sessions, 1 participant, 12.5 h of recording.**
79
  <!-- glance:end -->
80
 
81
  Every run's results, one row each (duration, distance, pace, cadence, contact time, asymmetry, heart
figures/S01/R26/analysis-foottilt.png ADDED

Git LFS Details

  • SHA256: 7e3488c5080cd53f94118911dfc4d8e3e5f97b97d3f20839476fd592ff80f630
  • Pointer size: 131 Bytes
  • Size of remote file: 105 kB
figures/S01/R26/analysis-gait.png ADDED

Git LFS Details

  • SHA256: b700695b2e30206fbfc6b26981e62d50a5a96c0e26b7122ad255553d63b1d97c
  • Pointer size: 131 Bytes
  • Size of remote file: 188 kB
figures/S01/R26/analysis-groundtruth.png ADDED

Git LFS Details

  • SHA256: 152b84084d734808599b27bc6be876714003a2d209b8e1cba1e7ad253e7fd379
  • Pointer size: 131 Bytes
  • Size of remote file: 186 kB
figures/S01/R26/analysis-pace.png ADDED

Git LFS Details

  • SHA256: 807998713950ecffe0dc3cb01e35e3ee11a85e8e98527e2fcfbc5c1f07bd2f59
  • Pointer size: 131 Bytes
  • Size of remote file: 115 kB
figures/S01/R26/data-fit3.png ADDED

Git LFS Details

  • SHA256: ce3eb48e469663e8448e399d002d9b18931c43b5daaf604cd2a03f06883c4e9f
  • Pointer size: 130 Bytes
  • Size of remote file: 78.7 kB
figures/S01/R26/data-imu.png ADDED

Git LFS Details

  • SHA256: a4fdbb45bf9aefa814203c2044a97ef7568ddcba4f2fa0c37bfe9f4b662c4be0
  • Pointer size: 131 Bytes
  • Size of remote file: 756 kB
figures/S01/R26/data-phone.png ADDED

Git LFS Details

  • SHA256: a0a97f11e0d3b6581139be3031445dc22060aabd9b3b14e70571244cb8ceedc7
  • Pointer size: 131 Bytes
  • Size of remote file: 155 kB
figures/S01/R26/derived-spectrum.png ADDED

Git LFS Details

  • SHA256: 9355c7d6cc248b2b00cd63e607a68f3743bcca4da4f6df7b0d1470abc1cd4deb
  • Pointer size: 131 Bytes
  • Size of remote file: 109 kB
figures/S01/R26/overview.png ADDED

Git LFS Details

  • SHA256: 48ee61675b411a6d3dcdb890d782c77db5d41aa434912d2038afe080cd64a0cc
  • Pointer size: 131 Bytes
  • Size of remote file: 328 kB
measurements.csv CHANGED
@@ -24,3 +24,4 @@ S01,R22,44.9,,5.06,,8.88,,6622.0,,152.0,,,,,
24
  S01,R23,40.9,39.9,7.94,7.16,5.15,5.57,6275.0,,158.0,,,,,
25
  S01,R24,4.7,,6.64,,0.71,,654.0,,146.0,,,,,
26
  S01,R25,39.0,,5.15,,7.57,,6131.0,,158.0,,,,,
 
 
24
  S01,R23,40.9,39.9,7.94,7.16,5.15,5.57,6275.0,,158.0,,,,,
25
  S01,R24,4.7,,6.64,,0.71,,654.0,,146.0,,,,,
26
  S01,R25,39.0,,5.15,,7.57,,6131.0,,158.0,,,,,
27
+ S01,R26,38.3,40.2,4.99,5.61,7.68,7.16,6002.0,6228.0,157.0,155.0,,,156.0,169.0
running.csv CHANGED
@@ -24,3 +24,4 @@ S01,R22,outdoor,grass;dirt;pavement,,,,152.0,phone_steps
24
  S01,R23,outdoor,pavement,,,,158.0,phone_steps
25
  S01,R24,indoor,track,,,,146.0,phone_steps
26
  S01,R25,outdoor,pavement,,,,158.0,phone_steps
 
 
24
  S01,R23,outdoor,pavement,,,,158.0,phone_steps
25
  S01,R24,indoor,track,,,,146.0,phone_steps
26
  S01,R25,outdoor,pavement,,,,158.0,phone_steps
27
+ S01,R26,outdoor,pavement,156.0,169.0,fit3_watch,157.0,phone_steps
scripts/LICENSE CHANGED
@@ -1,24 +1,24 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Level Health Innovations Corp.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
22
-
23
- This license covers the Python code under scripts/ only. The dataset, figures and reports are
24
- licensed separately under CC BY-NC 4.0 (see ../LICENSE).
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Level Health Innovations Corp.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ This license covers the Python code under scripts/ only. The dataset, figures and reports are
24
+ licensed separately under CC BY-NC 4.0 (see ../LICENSE).
scripts/lvl_running/__init__.py CHANGED
@@ -1,15 +1,15 @@
1
- """lvl_running -- iterate, load and plot the LEVEL running dataset.
2
-
3
- from lvl_running import iter_sessions, load_session, load_fit3, plot_session
4
-
5
- for run_dir in iter_sessions("data"): # every run session, all subjects and days
6
- run = load_session(run_dir) # IMUs (per placement) + phone streams + meta
7
- print(run.name, sorted(run.imus), run.duration_s)
8
- """
9
- from .catalog import load_context
10
- from .fit3 import Fit3, load_fit3
11
- from .plots import plot_session
12
- from .session import ImuStream, Session, find_sessions, iter_sessions, load_session, unwrap_time_sensor
13
-
14
- __all__ = ["iter_sessions", "find_sessions", "load_session", "Session", "ImuStream",
15
- "load_fit3", "Fit3", "plot_session", "unwrap_time_sensor", "load_context"]
 
1
+ """lvl_running -- iterate, load and plot the LEVEL running dataset.
2
+
3
+ from lvl_running import iter_sessions, load_session, load_fit3, plot_session
4
+
5
+ for run_dir in iter_sessions("data"): # every run session, all subjects and days
6
+ run = load_session(run_dir) # IMUs (per placement) + phone streams + meta
7
+ print(run.name, sorted(run.imus), run.duration_s)
8
+ """
9
+ from .catalog import load_context
10
+ from .fit3 import Fit3, load_fit3
11
+ from .plots import plot_session
12
+ from .session import ImuStream, Session, find_sessions, iter_sessions, load_session, unwrap_time_sensor
13
+
14
+ __all__ = ["iter_sessions", "find_sessions", "load_session", "Session", "ImuStream",
15
+ "load_fit3", "Fit3", "plot_session", "unwrap_time_sensor", "load_context"]
scripts/lvl_running/catalog.py CHANGED
@@ -1,331 +1,331 @@
1
- """The dataset's table of contents: one row per session (its run), split into three files that share the
2
- session key (subject, session) --
3
-
4
- running.csv the run: conditions (setting, surface) and heart rate + cadence, each with its source
5
- capture.csv the recording: setup (sensors, placements, channels, rate, packet size, transport,
6
- firmware, app, phone, time-sync mode, reference streams) and capture analysis
7
- (recording length, loss, effective rate, gaps, time-sync verdict, data-quality flags,
8
- phone battery / temperature, files, size)
9
- measurements.csv what each connected device measured, side by side (duration, distance, pace,
10
- steps, cadence, heart rate from phone GPS, watch, phone step counter, chest strap)
11
-
12
- Only what the connected devices recorded, summed or counted: no calendar date, no free text, no
13
- participant-reported values (an official finish time), no event or place, and nothing from our IMU
14
- analysis -- those live in the reports. `run_truth` picks a run's duration / distance for a reader who has a reported value too.
15
-
16
- from lvl_running.catalog import build_catalog, split_catalog
17
- running, capture, measurements = split_catalog(build_catalog("data")) # written by make_catalog.py
18
- """
19
- from __future__ import annotations
20
-
21
- import glob
22
- import json
23
- import os
24
-
25
- import numpy as np
26
- import pandas as pd
27
-
28
- from .session import iter_sessions
29
-
30
- # LEVEL sensors' battery voltage + temperature, lowest / highest across the sensors at start / end
31
- SENSOR_TELEMETRY_COLS = ("sensor_voltage_start_min_v", "sensor_voltage_start_max_v", "sensor_voltage_end_min_v",
32
- "sensor_voltage_end_max_v", "sensor_temp_start_min_c", "sensor_temp_start_max_c",
33
- "sensor_temp_end_min_c", "sensor_temp_end_max_c")
34
- # what a user must know before trusting the session: a sensor came loose / off, cross-sensor timing is
35
- # not reliable, the radio link could not carry the stream (capture.csv; set per run by the data owner)
36
- QUALITY_FLAGS = ("sensor_detached", "clock_unreliable", "link_saturated")
37
- HR_MIN_COVERAGE = 0.8 # fraction of the run a HR source must span to be reported
38
- CHANNELS = {"accel": "accel_x", "gyro": "gyro_x", "mag": "mag_x"} # channel -> a column that marks it
39
-
40
-
41
- def _json(path: str) -> dict:
42
- try:
43
- return json.load(open(path, encoding="utf-8"))
44
- except (OSError, ValueError):
45
- return {}
46
-
47
-
48
- def _csv(path: str) -> pd.DataFrame | None:
49
- try:
50
- return pd.read_csv(path)
51
- except (OSError, ValueError):
52
- return None
53
-
54
-
55
- _CONTEXT: dict[str, dict] = {}
56
-
57
-
58
- def load_context(data_root: str) -> dict[tuple[str, str], dict]:
59
- """context/session_context.csv as {(subject, session): row} -- the facts a recording cannot carry
60
- (setting, surface, setup, data-quality flags, policy). Blank cells become None. Cached per root."""
61
- key = os.path.abspath(data_root)
62
- if key not in _CONTEXT:
63
- df = _csv(os.path.join(data_root, "context", "session_context.csv"))
64
- _CONTEXT[key] = {} if df is None else {
65
- (r["subject"], r["session"]): {k: (None if (isinstance(v, float) and pd.isna(v)) else v) for k, v in r.items()}
66
- for r in df.to_dict("records")}
67
- return _CONTEXT[key]
68
-
69
-
70
- def _join(values) -> str:
71
- return ";".join(sorted({str(v) for v in values if v not in (None, "")}))
72
-
73
-
74
- def _channels(run_dir: str) -> str:
75
- """Sensor channels actually recorded, read from the IMU files' headers (e.g. accel+gyro)."""
76
- cols = set()
77
- for f in glob.glob(os.path.join(run_dir, "imu-*.csv")):
78
- with open(f, encoding="utf-8") as fh:
79
- cols |= set(fh.readline().strip().split(","))
80
- return "+".join(ch for ch, col in CHANNELS.items() if col in cols)
81
-
82
-
83
- def _num(v):
84
- """A context cell as a number (int when whole); None when blank."""
85
- if v is None or (isinstance(v, float) and pd.isna(v)) or str(v).strip() == "":
86
- return None
87
- f = float(v)
88
- return int(f) if f.is_integer() else f
89
-
90
-
91
- LONG_GAP_S = 0.15 # a gap longer than this counts toward long_gaps_per_hour (3+ packets at 5 samples/packet)
92
-
93
-
94
- def _capture_stats(run_dir: str, nominal_hz: float | None, session_end_us: int | None) -> dict:
95
- """Per LEVEL sensor (rotation files combined): effective_rate_hz and loss_pct averaged over sensors;
96
- max_gap_s, long_gaps_per_hour and data_ends_early_s for the worst sensor.
97
-
98
- effective rate = samples received / recording span.
99
- loss = samples missing between each sensor's first and last sample, from gaps in `frame_sensor`
100
- (a sample counter, wraps 0-255). A gap longer than 2 s could hide a full counter wrap, so its size is
101
- taken from `time` and the nominal rate instead. A sensor that stops for good is not counted as loss
102
- (nothing after it is missing from the counter) -- a short duration shows that.
103
- max gap = the longest interval between two consecutive samples of any sensor, in seconds: loss says
104
- how much went missing, this says whether it went in one piece (a dropout) or as scattered packets.
105
- long gaps per hour = gaps longer than LONG_GAP_S per hour of that sensor's recording.
106
- data ends early = seconds between a sensor's last sample and the end of the session (a stalled or
107
- stopped sensor; ~0-2 s is normal)."""
108
- streams: dict[str, list[pd.DataFrame]] = {}
109
- for f in glob.glob(os.path.join(run_dir, "imu-*.csv")):
110
- key = os.path.basename(f).split(".")[0] # imu-<placement>-<id> (drops .NNN rotation)
111
- df = pd.read_csv(f)
112
- df = df.rename(columns={"frame_number": "frame_sensor"})
113
- streams.setdefault(key, []).append(df[[c for c in ("time", "frame_sensor") if c in df]])
114
- rates, losses, gaps, long_rate, early = [], [], [], [], []
115
- for parts in streams.values():
116
- df = pd.concat(parts).sort_values("time")
117
- t = df["time"].to_numpy(dtype="int64")
118
- if len(t) < 2 or t[-1] <= t[0]:
119
- continue
120
- rates.append(len(t) / ((t[-1] - t[0]) / 1e6))
121
- dt = np.diff(t)
122
- gaps.append(dt.max() / 1e6)
123
- long_rate.append((dt > LONG_GAP_S * 1e6).sum() / ((t[-1] - t[0]) / 3.6e9))
124
- if session_end_us:
125
- early.append(max(0.0, (session_end_us - t[-1]) / 1e6))
126
- if "frame_sensor" in df and nominal_hz:
127
- step = np.diff(df["frame_sensor"].to_numpy(dtype="int64")) % 256
128
- long_gap = dt > 2_000_000
129
- missing = np.where(long_gap, np.rint(dt * nominal_hz / 1e6) - 1, np.maximum(step - 1, 0))
130
- missing = np.clip(missing, 0, None).sum()
131
- losses.append(100.0 * missing / (missing + len(t)))
132
- avg = lambda v, n: round(sum(v) / len(v), n) if v else None
133
- worst = lambda v, n: round(max(v), n) if v else None
134
- return {"effective_rate_hz": avg(rates, 2), "loss_pct": avg(losses, 2), "max_gap_s": worst(gaps, 2),
135
- "long_gaps_per_hour": worst(long_rate, 1), "data_ends_early_s": worst(early, 1)}
136
-
137
-
138
- # which data files a session carries: column -> file patterns in the run folder (fit3/ is beside it)
139
- AVAILABLE = {
140
- "gps": ("pace_profile.csv", "gps.csv"), # the coordinate-free profile (the raw route only where published)
141
- "barometer": ("barometer.csv",),
142
- "steps": ("steps.csv",),
143
- "h10_hr": ("polar_*_hr.csv",),
144
- "h10_ecg": ("polar_*_ecg.csv",),
145
- "h10_acc": ("polar_*_acc.csv",),
146
- "watch": ("../fit3/fit3_live.csv",),
147
- }
148
-
149
-
150
- def _available(run_dir: str) -> dict:
151
- """{column: True/False} -- whether each optional data file exists for the session."""
152
- return {col: any(glob.glob(os.path.join(run_dir, pat)) for pat in pats) for col, pats in AVAILABLE.items()}
153
-
154
-
155
- def session_row(run_dir: str, data_root: str) -> dict:
156
- """One session's catalog row (every column of running.csv + capture.csv + measurements.csv)."""
157
- parts = os.path.relpath(run_dir, data_root).replace(os.sep, "/").split("/")
158
- day_dir = os.path.dirname(run_dir)
159
- ms = _json(os.path.join(run_dir, "meta-summary.json"))
160
- info = load_context(data_root).get((parts[0], parts[1]), {})
161
- sess, settings, app = ms.get("session") or {}, ms.get("settings") or {}, ms.get("app") or {}
162
- sensors, transports = ms.get("sensors", []), ms.get("transports", [])
163
- files = [f for f in os.listdir(run_dir) if os.path.isfile(os.path.join(run_dir, f))]
164
- pace = _csv(os.path.join(run_dir, "pace_profile.csv"))
165
- fit3 = _csv(os.path.join(day_dir, "fit3", "fit3_summary.csv"))
166
- fit3 = fit3.iloc[0] if fit3 is not None and len(fit3) else None
167
- h10 = next(iter(sorted(glob.glob(os.path.join(run_dir, "polar_*_hr.csv")))), None)
168
- duration_min = sess["durationMs"] / 60000 if sess.get("durationMs") else None
169
- cap = _capture_stats(run_dir, float(settings["sampling_rate_hz"]) if settings.get("sampling_rate_hz") else None,
170
- int(sess["endedAtMs"]) * 1000 if sess.get("endedAtMs") else None)
171
-
172
- def fit3_val(key):
173
- return None if fit3 is None or pd.isna(fit3.get(key)) else float(fit3[key])
174
-
175
- # what each device measured over the recording (phone GPS: last - first; the public cum_km is zeroed
176
- # at a hidden mid-run moment). Which one is the RUN's length is run_truth's call, not the catalog's.
177
- gps_km = gps_min = None
178
- span = pace.iloc[[0, -1]] if pace is not None and len(pace) else None
179
- if span is not None and span["cum_km"].diff().iloc[-1] > 0:
180
- gps_km, gps_min = span["cum_km"].diff().iloc[-1], span["time_us"].diff().iloc[-1] / 6e7
181
- fit3_km = fit3_val("distance_m") / 1000 if fit3_val("distance_m") else None
182
- fit3_min = fit3_val("duration_s") / 60 if fit3_val("duration_s") else None
183
-
184
- # HR: chest strap preferred, then watch -- only if it covers most of the run (a strap that drops
185
- # out early leaves a warm-up segment that is not representative)
186
- hr_src = hr_mean = hr_max = None
187
- hr = _csv(h10) if h10 else None
188
- if hr is not None and len(hr) and duration_min:
189
- hr = hr[hr["HEART_RATE"] > 0]
190
- span_min = (hr["RECEIVED_TIMESTAMP"].iloc[-1] - hr["RECEIVED_TIMESTAMP"].iloc[0]) / 6e7 if len(hr) else 0
191
- if span_min >= HR_MIN_COVERAGE * duration_min:
192
- hr_src, hr_mean, hr_max = "polar_h10", hr["HEART_RATE"].mean(), hr["HEART_RATE"].max()
193
- if hr_src is None and fit3_val("hr_mean") is not None:
194
- hr_src, hr_mean, hr_max = "fit3_watch", fit3_val("hr_mean"), fit3_val("hr_max")
195
- # every source of each quantity is reported in measurements.csv; running.csv carries the pick
196
- hr_h10 = (hr["HEART_RATE"].mean(), hr["HEART_RATE"].max()) if hr_src == "polar_h10" else (None, None)
197
- # cadence: the phone's step counter only (every participant has the phone; the watch is not a reference)
198
- steps = _csv(os.path.join(run_dir, "steps.csv"))
199
- phone_steps = phone_cadence = None
200
- if steps is not None and len(steps) > 1 and "step_count" in steps:
201
- span_min = (steps["timestamp"].iloc[-1] - steps["timestamp"].iloc[0]) / 6e7
202
- phone_steps = steps["step_count"].iloc[-1] - steps["step_count"].iloc[0]
203
- if span_min > 1:
204
- phone_cadence = phone_steps / span_min
205
- cadence, cadence_src = phone_cadence, "phone_steps" if phone_cadence is not None else None
206
- fit3_steps = fit3_val("cadence_mean") * fit3_min if fit3_val("cadence_mean") and fit3_min else None
207
- r = lambda v, n=1: None if v is None else round(float(v), n)
208
- pace = lambda mins, km: r(mins / km, 2) if mins and km else None
209
-
210
- return {
211
- # session
212
- "subject": parts[0], "session": parts[1],
213
- # conditions
214
- "setting": info.get("setting"), "surface": info.get("surface"),
215
- # setup
216
- "sensor_count": len(sensors) or settings.get("sensor_count"),
217
- # app labels vary: "Left Foot" (schema 1) / "left_foot" (schema 2, normalized)
218
- "placements": _join((s.get("sensorLabel") or "").strip().replace("_", " ").title() for s in sensors),
219
- "channels": _channels(run_dir),
220
- "sampling_rate_hz": settings.get("sampling_rate_hz"),
221
- # meta-summary schema 2 moved it to the app's debug file (carried in context/session_context.csv)
222
- "samples_per_packet": settings.get("samples_per_packet") or _num(info.get("samples_per_packet")),
223
- "transport": _join(t.get("type") for t in transports),
224
- # recorded by the app where its build did so; else the version reported for that session (context)
225
- "dongle_firmware": (_join(t.get("firmwareVersion") for t in transports if t.get("type") == "DONGLE")
226
- or info.get("dongle_firmware_reported") or None),
227
- "sensor_firmware": _join(s.get("firmwareVersion") for s in sensors) or info.get("sensor_firmware_reported") or None,
228
- "app_version": app.get("versionName"),
229
- "recorder_app": info.get("recorder_app"), # collector = LEVEL Collector; qa = the LEVEL QA test app
230
- "phone_model": info.get("phone_model") or info.get("phone_model_reported"), # app record, else reported
231
- # blank = not recorded (app builds before 2026-09-16 did not log it), not "off"
232
- "time_sync": info.get("time_sync_mode") or ({True: "on", False: "off"}.get(settings.get("time_sync"))),
233
- # how it was carried / calibrated (from context)
234
- "phone_carry": info.get("phone_carry"),
235
- "calibration": info.get("calibration"),
236
- # data available: one column per optional file type (the LEVEL sensors are sensor_count)
237
- **_available(run_dir),
238
- # the LEVEL recording's length (the run's own length, where known, is in the reports)
239
- "recording_min": r(duration_min),
240
- "hr_mean_bpm": r(hr_mean, 0), "hr_max_bpm": r(hr_max, 0), "hr_source": hr_src,
241
- "cadence_mean_spm": r(cadence, 0), "cadence_source": cadence_src,
242
- # capture analysis
243
- "loss_pct": cap["loss_pct"],
244
- "effective_rate_hz": cap["effective_rate_hz"],
245
- "max_gap_s": cap["max_gap_s"],
246
- "long_gaps_per_hour": cap["long_gaps_per_hour"],
247
- "data_ends_early_s": cap["data_ends_early_s"],
248
- "terminated_early": info.get("terminated_early"),
249
- "time_sync_verdict": info.get("time_sync_verdict"),
250
- "unreliable_sensors": info.get("unreliable_sensors"),
251
- **{k: info.get(k) for k in QUALITY_FLAGS},
252
- **{k: _num(info.get(k)) for k in ("phone_battery_start_pct", "phone_battery_end_pct", "phone_temp_start_c",
253
- "phone_temp_end_c", *SENSOR_TELEMETRY_COLS)},
254
- "n_files": len(files),
255
- "size_mb": round(sum(os.path.getsize(os.path.join(run_dir, f)) for f in files) / 1e6, 1),
256
- # measurements: what each connected device measured, one column per source
257
- "duration_min_gps": r(gps_min), "duration_min_fit3": r(fit3_min),
258
- "distance_km_gps": r(gps_km, 2), "distance_km_fit3": r(fit3_km, 2),
259
- "pace_min_km_gps": pace(gps_min, gps_km), "pace_min_km_fit3": pace(fit3_min, fit3_km),
260
- "steps_phone": r(phone_steps, 0), "steps_fit3": r(fit3_steps, 0),
261
- "cadence_spm_phone": r(phone_cadence, 0), "cadence_spm_fit3": r(fit3_val("cadence_mean"), 0),
262
- "hr_mean_bpm_h10": r(hr_h10[0], 0), "hr_max_bpm_h10": r(hr_h10[1], 0),
263
- "hr_mean_bpm_fit3": r(fit3_val("hr_mean"), 0), "hr_max_bpm_fit3": r(fit3_val("hr_max"), 0),
264
- }
265
-
266
-
267
- def run_truth(row: dict, duration_min_reported: float | None = None,
268
- distance_km_reported: float | None = None) -> dict:
269
- """The RUN's duration / distance / pace (as distinct from how much was recorded), first source that
270
- has it: 1) a value the participant reported (an official finish time, a 5.00 km course), 2) phone
271
- GPS (outdoors, and only when the recording covered the whole run), 3) duration only: the LEVEL
272
- recording's length, unless it stopped before the run ended. The watch is not used: its distance comes
273
- from steps (no GPS of its own) and its clock is not synced to the app. `row` = a catalog row (running +
274
- capture + measurements columns). Also the share of the run the recording covers."""
275
- def v(k):
276
- x = row.get(k)
277
- return None if x is None or (isinstance(x, float) and pd.isna(x)) else float(x)
278
- stopped_early = str(row.get("terminated_early")).lower() in ("true", "yes", "1")
279
- gps_ok = not stopped_early and row.get("setting") != "indoor"
280
-
281
- def first(*cands):
282
- return next(((x, src) for x, src in cands if x is not None), (None, None))
283
- km, km_src = first((distance_km_reported, "user_reported"),
284
- (v("distance_km_gps") if gps_ok else None, "phone_gps"))
285
- mins, min_src = first((duration_min_reported, "user_reported"),
286
- (v("duration_min_gps") if gps_ok else None, "phone_gps"),
287
- (None if stopped_early else v("recording_min"), "imu_recording_length"))
288
- rec = v("recording_min")
289
- return {"run_duration_min": mins, "run_duration_source": min_src, "distance_km": km, "distance_source": km_src,
290
- "pace_min_km": mins / km if mins and km else None,
291
- # how much of the run the recording covers (R09 stopped at 44 %); None when the run length is unknown
292
- "coverage_pct": round(100.0 * rec / mins) if rec and mins else None}
293
-
294
-
295
- def build_catalog(data_root: str) -> pd.DataFrame:
296
- """Every session under data_root, one row each (its run), all columns."""
297
- return pd.DataFrame([session_row(d, data_root) for d in iter_sessions(data_root, kind="run")])
298
-
299
-
300
- KEY_COLS = ["subject", "session"]
301
- RUNNING_COLS = KEY_COLS + [
302
- "setting", "surface",
303
- "hr_mean_bpm", "hr_max_bpm", "hr_source", "cadence_mean_spm", "cadence_source",
304
- ]
305
- CAPTURE_COLS = KEY_COLS + [
306
- "sensor_count", "placements", "channels", "sampling_rate_hz", "samples_per_packet", "transport",
307
- "dongle_firmware", "sensor_firmware", "app_version", "recorder_app", "phone_model", "time_sync",
308
- "phone_carry", "calibration",
309
- "gps", "barometer", "steps", "h10_hr", "h10_ecg", "h10_acc", "watch",
310
- "recording_min", "terminated_early", "data_ends_early_s",
311
- "loss_pct", "effective_rate_hz", "max_gap_s", "long_gaps_per_hour",
312
- "time_sync_verdict", "unreliable_sensors", *QUALITY_FLAGS,
313
- "phone_battery_start_pct", "phone_battery_end_pct", "phone_temp_start_c", "phone_temp_end_c",
314
- *SENSOR_TELEMETRY_COLS,
315
- "n_files", "size_mb",
316
- ]
317
- MEASUREMENT_COLS = KEY_COLS + [
318
- "duration_min_gps", "duration_min_fit3", "distance_km_gps", "distance_km_fit3",
319
- "pace_min_km_gps", "pace_min_km_fit3", "steps_phone", "steps_fit3", "cadence_spm_phone", "cadence_spm_fit3",
320
- "hr_mean_bpm_h10", "hr_max_bpm_h10", "hr_mean_bpm_fit3", "hr_max_bpm_fit3",
321
- ]
322
-
323
-
324
- def split_catalog(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
325
- """The full catalog -> (running.csv, capture.csv, measurements.csv) frames. Every column of the full
326
- row must land in exactly one file (plus the shared key), so a new column added to session_row fails
327
- loudly here."""
328
- missing = set(df.columns) - set(RUNNING_COLS) - set(CAPTURE_COLS) - set(MEASUREMENT_COLS)
329
- if missing:
330
- raise KeyError(f"catalog columns not assigned to running.csv, capture.csv or measurements.csv: {sorted(missing)}")
331
- return tuple(df[[c for c in cols if c in df]] for cols in (RUNNING_COLS, CAPTURE_COLS, MEASUREMENT_COLS))
 
1
+ """The dataset's table of contents: one row per session (its run), split into three files that share the
2
+ session key (subject, session) --
3
+
4
+ running.csv the run: conditions (setting, surface) and heart rate + cadence, each with its source
5
+ capture.csv the recording: setup (sensors, placements, channels, rate, packet size, transport,
6
+ firmware, app, phone, time-sync mode, reference streams) and capture analysis
7
+ (recording length, loss, effective rate, gaps, time-sync verdict, data-quality flags,
8
+ phone battery / temperature, files, size)
9
+ measurements.csv what each connected device measured, side by side (duration, distance, pace,
10
+ steps, cadence, heart rate from phone GPS, watch, phone step counter, chest strap)
11
+
12
+ Only what the connected devices recorded, summed or counted: no calendar date, no free text, no
13
+ participant-reported values (an official finish time), no event or place, and nothing from our IMU
14
+ analysis -- those live in the reports. `run_truth` picks a run's duration / distance for a reader who has a reported value too.
15
+
16
+ from lvl_running.catalog import build_catalog, split_catalog
17
+ running, capture, measurements = split_catalog(build_catalog("data")) # written by make_catalog.py
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import glob
22
+ import json
23
+ import os
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+
28
+ from .session import iter_sessions
29
+
30
+ # LEVEL sensors' battery voltage + temperature, lowest / highest across the sensors at start / end
31
+ SENSOR_TELEMETRY_COLS = ("sensor_voltage_start_min_v", "sensor_voltage_start_max_v", "sensor_voltage_end_min_v",
32
+ "sensor_voltage_end_max_v", "sensor_temp_start_min_c", "sensor_temp_start_max_c",
33
+ "sensor_temp_end_min_c", "sensor_temp_end_max_c")
34
+ # what a user must know before trusting the session: a sensor came loose / off, cross-sensor timing is
35
+ # not reliable, the radio link could not carry the stream (capture.csv; set per run by the data owner)
36
+ QUALITY_FLAGS = ("sensor_detached", "clock_unreliable", "link_saturated")
37
+ HR_MIN_COVERAGE = 0.8 # fraction of the run a HR source must span to be reported
38
+ CHANNELS = {"accel": "accel_x", "gyro": "gyro_x", "mag": "mag_x"} # channel -> a column that marks it
39
+
40
+
41
+ def _json(path: str) -> dict:
42
+ try:
43
+ return json.load(open(path, encoding="utf-8"))
44
+ except (OSError, ValueError):
45
+ return {}
46
+
47
+
48
+ def _csv(path: str) -> pd.DataFrame | None:
49
+ try:
50
+ return pd.read_csv(path)
51
+ except (OSError, ValueError):
52
+ return None
53
+
54
+
55
+ _CONTEXT: dict[str, dict] = {}
56
+
57
+
58
+ def load_context(data_root: str) -> dict[tuple[str, str], dict]:
59
+ """context/session_context.csv as {(subject, session): row} -- the facts a recording cannot carry
60
+ (setting, surface, setup, data-quality flags, policy). Blank cells become None. Cached per root."""
61
+ key = os.path.abspath(data_root)
62
+ if key not in _CONTEXT:
63
+ df = _csv(os.path.join(data_root, "context", "session_context.csv"))
64
+ _CONTEXT[key] = {} if df is None else {
65
+ (r["subject"], r["session"]): {k: (None if (isinstance(v, float) and pd.isna(v)) else v) for k, v in r.items()}
66
+ for r in df.to_dict("records")}
67
+ return _CONTEXT[key]
68
+
69
+
70
+ def _join(values) -> str:
71
+ return ";".join(sorted({str(v) for v in values if v not in (None, "")}))
72
+
73
+
74
+ def _channels(run_dir: str) -> str:
75
+ """Sensor channels actually recorded, read from the IMU files' headers (e.g. accel+gyro)."""
76
+ cols = set()
77
+ for f in glob.glob(os.path.join(run_dir, "imu-*.csv")):
78
+ with open(f, encoding="utf-8") as fh:
79
+ cols |= set(fh.readline().strip().split(","))
80
+ return "+".join(ch for ch, col in CHANNELS.items() if col in cols)
81
+
82
+
83
+ def _num(v):
84
+ """A context cell as a number (int when whole); None when blank."""
85
+ if v is None or (isinstance(v, float) and pd.isna(v)) or str(v).strip() == "":
86
+ return None
87
+ f = float(v)
88
+ return int(f) if f.is_integer() else f
89
+
90
+
91
+ LONG_GAP_S = 0.15 # a gap longer than this counts toward long_gaps_per_hour (3+ packets at 5 samples/packet)
92
+
93
+
94
+ def _capture_stats(run_dir: str, nominal_hz: float | None, session_end_us: int | None) -> dict:
95
+ """Per LEVEL sensor (rotation files combined): effective_rate_hz and loss_pct averaged over sensors;
96
+ max_gap_s, long_gaps_per_hour and data_ends_early_s for the worst sensor.
97
+
98
+ effective rate = samples received / recording span.
99
+ loss = samples missing between each sensor's first and last sample, from gaps in `frame_sensor`
100
+ (a sample counter, wraps 0-255). A gap longer than 2 s could hide a full counter wrap, so its size is
101
+ taken from `time` and the nominal rate instead. A sensor that stops for good is not counted as loss
102
+ (nothing after it is missing from the counter) -- a short duration shows that.
103
+ max gap = the longest interval between two consecutive samples of any sensor, in seconds: loss says
104
+ how much went missing, this says whether it went in one piece (a dropout) or as scattered packets.
105
+ long gaps per hour = gaps longer than LONG_GAP_S per hour of that sensor's recording.
106
+ data ends early = seconds between a sensor's last sample and the end of the session (a stalled or
107
+ stopped sensor; ~0-2 s is normal)."""
108
+ streams: dict[str, list[pd.DataFrame]] = {}
109
+ for f in glob.glob(os.path.join(run_dir, "imu-*.csv")):
110
+ key = os.path.basename(f).split(".")[0] # imu-<placement>-<id> (drops .NNN rotation)
111
+ df = pd.read_csv(f)
112
+ df = df.rename(columns={"frame_number": "frame_sensor"})
113
+ streams.setdefault(key, []).append(df[[c for c in ("time", "frame_sensor") if c in df]])
114
+ rates, losses, gaps, long_rate, early = [], [], [], [], []
115
+ for parts in streams.values():
116
+ df = pd.concat(parts).sort_values("time")
117
+ t = df["time"].to_numpy(dtype="int64")
118
+ if len(t) < 2 or t[-1] <= t[0]:
119
+ continue
120
+ rates.append(len(t) / ((t[-1] - t[0]) / 1e6))
121
+ dt = np.diff(t)
122
+ gaps.append(dt.max() / 1e6)
123
+ long_rate.append((dt > LONG_GAP_S * 1e6).sum() / ((t[-1] - t[0]) / 3.6e9))
124
+ if session_end_us:
125
+ early.append(max(0.0, (session_end_us - t[-1]) / 1e6))
126
+ if "frame_sensor" in df and nominal_hz:
127
+ step = np.diff(df["frame_sensor"].to_numpy(dtype="int64")) % 256
128
+ long_gap = dt > 2_000_000
129
+ missing = np.where(long_gap, np.rint(dt * nominal_hz / 1e6) - 1, np.maximum(step - 1, 0))
130
+ missing = np.clip(missing, 0, None).sum()
131
+ losses.append(100.0 * missing / (missing + len(t)))
132
+ avg = lambda v, n: round(sum(v) / len(v), n) if v else None
133
+ worst = lambda v, n: round(max(v), n) if v else None
134
+ return {"effective_rate_hz": avg(rates, 2), "loss_pct": avg(losses, 2), "max_gap_s": worst(gaps, 2),
135
+ "long_gaps_per_hour": worst(long_rate, 1), "data_ends_early_s": worst(early, 1)}
136
+
137
+
138
+ # which data files a session carries: column -> file patterns in the run folder (fit3/ is beside it)
139
+ AVAILABLE = {
140
+ "gps": ("pace_profile.csv", "gps.csv"), # the coordinate-free profile (the raw route only where published)
141
+ "barometer": ("barometer.csv",),
142
+ "steps": ("steps.csv",),
143
+ "h10_hr": ("polar_*_hr.csv",),
144
+ "h10_ecg": ("polar_*_ecg.csv",),
145
+ "h10_acc": ("polar_*_acc.csv",),
146
+ "watch": ("../fit3/fit3_live.csv",),
147
+ }
148
+
149
+
150
+ def _available(run_dir: str) -> dict:
151
+ """{column: True/False} -- whether each optional data file exists for the session."""
152
+ return {col: any(glob.glob(os.path.join(run_dir, pat)) for pat in pats) for col, pats in AVAILABLE.items()}
153
+
154
+
155
+ def session_row(run_dir: str, data_root: str) -> dict:
156
+ """One session's catalog row (every column of running.csv + capture.csv + measurements.csv)."""
157
+ parts = os.path.relpath(run_dir, data_root).replace(os.sep, "/").split("/")
158
+ day_dir = os.path.dirname(run_dir)
159
+ ms = _json(os.path.join(run_dir, "meta-summary.json"))
160
+ info = load_context(data_root).get((parts[0], parts[1]), {})
161
+ sess, settings, app = ms.get("session") or {}, ms.get("settings") or {}, ms.get("app") or {}
162
+ sensors, transports = ms.get("sensors", []), ms.get("transports", [])
163
+ files = [f for f in os.listdir(run_dir) if os.path.isfile(os.path.join(run_dir, f))]
164
+ pace = _csv(os.path.join(run_dir, "pace_profile.csv"))
165
+ fit3 = _csv(os.path.join(day_dir, "fit3", "fit3_summary.csv"))
166
+ fit3 = fit3.iloc[0] if fit3 is not None and len(fit3) else None
167
+ h10 = next(iter(sorted(glob.glob(os.path.join(run_dir, "polar_*_hr.csv")))), None)
168
+ duration_min = sess["durationMs"] / 60000 if sess.get("durationMs") else None
169
+ cap = _capture_stats(run_dir, float(settings["sampling_rate_hz"]) if settings.get("sampling_rate_hz") else None,
170
+ int(sess["endedAtMs"]) * 1000 if sess.get("endedAtMs") else None)
171
+
172
+ def fit3_val(key):
173
+ return None if fit3 is None or pd.isna(fit3.get(key)) else float(fit3[key])
174
+
175
+ # what each device measured over the recording (phone GPS: last - first; the public cum_km is zeroed
176
+ # at a hidden mid-run moment). Which one is the RUN's length is run_truth's call, not the catalog's.
177
+ gps_km = gps_min = None
178
+ span = pace.iloc[[0, -1]] if pace is not None and len(pace) else None
179
+ if span is not None and span["cum_km"].diff().iloc[-1] > 0:
180
+ gps_km, gps_min = span["cum_km"].diff().iloc[-1], span["time_us"].diff().iloc[-1] / 6e7
181
+ fit3_km = fit3_val("distance_m") / 1000 if fit3_val("distance_m") else None
182
+ fit3_min = fit3_val("duration_s") / 60 if fit3_val("duration_s") else None
183
+
184
+ # HR: chest strap preferred, then watch -- only if it covers most of the run (a strap that drops
185
+ # out early leaves a warm-up segment that is not representative)
186
+ hr_src = hr_mean = hr_max = None
187
+ hr = _csv(h10) if h10 else None
188
+ if hr is not None and len(hr) and duration_min:
189
+ hr = hr[hr["HEART_RATE"] > 0]
190
+ span_min = (hr["RECEIVED_TIMESTAMP"].iloc[-1] - hr["RECEIVED_TIMESTAMP"].iloc[0]) / 6e7 if len(hr) else 0
191
+ if span_min >= HR_MIN_COVERAGE * duration_min:
192
+ hr_src, hr_mean, hr_max = "polar_h10", hr["HEART_RATE"].mean(), hr["HEART_RATE"].max()
193
+ if hr_src is None and fit3_val("hr_mean") is not None:
194
+ hr_src, hr_mean, hr_max = "fit3_watch", fit3_val("hr_mean"), fit3_val("hr_max")
195
+ # every source of each quantity is reported in measurements.csv; running.csv carries the pick
196
+ hr_h10 = (hr["HEART_RATE"].mean(), hr["HEART_RATE"].max()) if hr_src == "polar_h10" else (None, None)
197
+ # cadence: the phone's step counter only (every participant has the phone; the watch is not a reference)
198
+ steps = _csv(os.path.join(run_dir, "steps.csv"))
199
+ phone_steps = phone_cadence = None
200
+ if steps is not None and len(steps) > 1 and "step_count" in steps:
201
+ span_min = (steps["timestamp"].iloc[-1] - steps["timestamp"].iloc[0]) / 6e7
202
+ phone_steps = steps["step_count"].iloc[-1] - steps["step_count"].iloc[0]
203
+ if span_min > 1:
204
+ phone_cadence = phone_steps / span_min
205
+ cadence, cadence_src = phone_cadence, "phone_steps" if phone_cadence is not None else None
206
+ fit3_steps = fit3_val("cadence_mean") * fit3_min if fit3_val("cadence_mean") and fit3_min else None
207
+ r = lambda v, n=1: None if v is None else round(float(v), n)
208
+ pace = lambda mins, km: r(mins / km, 2) if mins and km else None
209
+
210
+ return {
211
+ # session
212
+ "subject": parts[0], "session": parts[1],
213
+ # conditions
214
+ "setting": info.get("setting"), "surface": info.get("surface"),
215
+ # setup
216
+ "sensor_count": len(sensors) or settings.get("sensor_count"),
217
+ # app labels vary: "Left Foot" (schema 1) / "left_foot" (schema 2, normalized)
218
+ "placements": _join((s.get("sensorLabel") or "").strip().replace("_", " ").title() for s in sensors),
219
+ "channels": _channels(run_dir),
220
+ "sampling_rate_hz": settings.get("sampling_rate_hz"),
221
+ # meta-summary schema 2 moved it to the app's debug file (carried in context/session_context.csv)
222
+ "samples_per_packet": settings.get("samples_per_packet") or _num(info.get("samples_per_packet")),
223
+ "transport": _join(t.get("type") for t in transports),
224
+ # recorded by the app where its build did so; else the version reported for that session (context)
225
+ "dongle_firmware": (_join(t.get("firmwareVersion") for t in transports if t.get("type") == "DONGLE")
226
+ or info.get("dongle_firmware_reported") or None),
227
+ "sensor_firmware": _join(s.get("firmwareVersion") for s in sensors) or info.get("sensor_firmware_reported") or None,
228
+ "app_version": app.get("versionName"),
229
+ "recorder_app": info.get("recorder_app"), # collector = LEVEL Collector; qa = the LEVEL QA test app
230
+ "phone_model": info.get("phone_model") or info.get("phone_model_reported"), # app record, else reported
231
+ # blank = not recorded (app builds before 2026-09-16 did not log it), not "off"
232
+ "time_sync": info.get("time_sync_mode") or ({True: "on", False: "off"}.get(settings.get("time_sync"))),
233
+ # how it was carried / calibrated (from context)
234
+ "phone_carry": info.get("phone_carry"),
235
+ "calibration": info.get("calibration"),
236
+ # data available: one column per optional file type (the LEVEL sensors are sensor_count)
237
+ **_available(run_dir),
238
+ # the LEVEL recording's length (the run's own length, where known, is in the reports)
239
+ "recording_min": r(duration_min),
240
+ "hr_mean_bpm": r(hr_mean, 0), "hr_max_bpm": r(hr_max, 0), "hr_source": hr_src,
241
+ "cadence_mean_spm": r(cadence, 0), "cadence_source": cadence_src,
242
+ # capture analysis
243
+ "loss_pct": cap["loss_pct"],
244
+ "effective_rate_hz": cap["effective_rate_hz"],
245
+ "max_gap_s": cap["max_gap_s"],
246
+ "long_gaps_per_hour": cap["long_gaps_per_hour"],
247
+ "data_ends_early_s": cap["data_ends_early_s"],
248
+ "terminated_early": info.get("terminated_early"),
249
+ "time_sync_verdict": info.get("time_sync_verdict"),
250
+ "unreliable_sensors": info.get("unreliable_sensors"),
251
+ **{k: info.get(k) for k in QUALITY_FLAGS},
252
+ **{k: _num(info.get(k)) for k in ("phone_battery_start_pct", "phone_battery_end_pct", "phone_temp_start_c",
253
+ "phone_temp_end_c", *SENSOR_TELEMETRY_COLS)},
254
+ "n_files": len(files),
255
+ "size_mb": round(sum(os.path.getsize(os.path.join(run_dir, f)) for f in files) / 1e6, 1),
256
+ # measurements: what each connected device measured, one column per source
257
+ "duration_min_gps": r(gps_min), "duration_min_fit3": r(fit3_min),
258
+ "distance_km_gps": r(gps_km, 2), "distance_km_fit3": r(fit3_km, 2),
259
+ "pace_min_km_gps": pace(gps_min, gps_km), "pace_min_km_fit3": pace(fit3_min, fit3_km),
260
+ "steps_phone": r(phone_steps, 0), "steps_fit3": r(fit3_steps, 0),
261
+ "cadence_spm_phone": r(phone_cadence, 0), "cadence_spm_fit3": r(fit3_val("cadence_mean"), 0),
262
+ "hr_mean_bpm_h10": r(hr_h10[0], 0), "hr_max_bpm_h10": r(hr_h10[1], 0),
263
+ "hr_mean_bpm_fit3": r(fit3_val("hr_mean"), 0), "hr_max_bpm_fit3": r(fit3_val("hr_max"), 0),
264
+ }
265
+
266
+
267
+ def run_truth(row: dict, duration_min_reported: float | None = None,
268
+ distance_km_reported: float | None = None) -> dict:
269
+ """The RUN's duration / distance / pace (as distinct from how much was recorded), first source that
270
+ has it: 1) a value the participant reported (an official finish time, a 5.00 km course), 2) phone
271
+ GPS (outdoors, and only when the recording covered the whole run), 3) duration only: the LEVEL
272
+ recording's length, unless it stopped before the run ended. The watch is not used: its distance comes
273
+ from steps (no GPS of its own) and its clock is not synced to the app. `row` = a catalog row (running +
274
+ capture + measurements columns). Also the share of the run the recording covers."""
275
+ def v(k):
276
+ x = row.get(k)
277
+ return None if x is None or (isinstance(x, float) and pd.isna(x)) else float(x)
278
+ stopped_early = str(row.get("terminated_early")).lower() in ("true", "yes", "1")
279
+ gps_ok = not stopped_early and row.get("setting") != "indoor"
280
+
281
+ def first(*cands):
282
+ return next(((x, src) for x, src in cands if x is not None), (None, None))
283
+ km, km_src = first((distance_km_reported, "user_reported"),
284
+ (v("distance_km_gps") if gps_ok else None, "phone_gps"))
285
+ mins, min_src = first((duration_min_reported, "user_reported"),
286
+ (v("duration_min_gps") if gps_ok else None, "phone_gps"),
287
+ (None if stopped_early else v("recording_min"), "imu_recording_length"))
288
+ rec = v("recording_min")
289
+ return {"run_duration_min": mins, "run_duration_source": min_src, "distance_km": km, "distance_source": km_src,
290
+ "pace_min_km": mins / km if mins and km else None,
291
+ # how much of the run the recording covers (R09 stopped at 44 %); None when the run length is unknown
292
+ "coverage_pct": round(100.0 * rec / mins) if rec and mins else None}
293
+
294
+
295
+ def build_catalog(data_root: str) -> pd.DataFrame:
296
+ """Every session under data_root, one row each (its run), all columns."""
297
+ return pd.DataFrame([session_row(d, data_root) for d in iter_sessions(data_root, kind="run")])
298
+
299
+
300
+ KEY_COLS = ["subject", "session"]
301
+ RUNNING_COLS = KEY_COLS + [
302
+ "setting", "surface",
303
+ "hr_mean_bpm", "hr_max_bpm", "hr_source", "cadence_mean_spm", "cadence_source",
304
+ ]
305
+ CAPTURE_COLS = KEY_COLS + [
306
+ "sensor_count", "placements", "channels", "sampling_rate_hz", "samples_per_packet", "transport",
307
+ "dongle_firmware", "sensor_firmware", "app_version", "recorder_app", "phone_model", "time_sync",
308
+ "phone_carry", "calibration",
309
+ "gps", "barometer", "steps", "h10_hr", "h10_ecg", "h10_acc", "watch",
310
+ "recording_min", "terminated_early", "data_ends_early_s",
311
+ "loss_pct", "effective_rate_hz", "max_gap_s", "long_gaps_per_hour",
312
+ "time_sync_verdict", "unreliable_sensors", *QUALITY_FLAGS,
313
+ "phone_battery_start_pct", "phone_battery_end_pct", "phone_temp_start_c", "phone_temp_end_c",
314
+ *SENSOR_TELEMETRY_COLS,
315
+ "n_files", "size_mb",
316
+ ]
317
+ MEASUREMENT_COLS = KEY_COLS + [
318
+ "duration_min_gps", "duration_min_fit3", "distance_km_gps", "distance_km_fit3",
319
+ "pace_min_km_gps", "pace_min_km_fit3", "steps_phone", "steps_fit3", "cadence_spm_phone", "cadence_spm_fit3",
320
+ "hr_mean_bpm_h10", "hr_max_bpm_h10", "hr_mean_bpm_fit3", "hr_max_bpm_fit3",
321
+ ]
322
+
323
+
324
+ def split_catalog(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
325
+ """The full catalog -> (running.csv, capture.csv, measurements.csv) frames. Every column of the full
326
+ row must land in exactly one file (plus the shared key), so a new column added to session_row fails
327
+ loudly here."""
328
+ missing = set(df.columns) - set(RUNNING_COLS) - set(CAPTURE_COLS) - set(MEASUREMENT_COLS)
329
+ if missing:
330
+ raise KeyError(f"catalog columns not assigned to running.csv, capture.csv or measurements.csv: {sorted(missing)}")
331
+ return tuple(df[[c for c in cols if c in df]] for cols in (RUNNING_COLS, CAPTURE_COLS, MEASUREMENT_COLS))
scripts/lvl_running/fit3.py CHANGED
@@ -1,131 +1,131 @@
1
- """Samsung Galaxy Fit3 watch loader -- the non-LEVEL reference (heart rate, cadence, speed).
2
-
3
- Fit3 data is day-level: data/<subject>/<day>/fit3/. Two on-disk layouts, same Fit3 object out:
4
- released dataset (our own schema):
5
- fit3_live.csv 10 s samples: time(us), heart_rate, cadence, speed
6
- fit3_summary.csv one row: start_time(us), duration_s, hr_mean/max/min, cadence_mean/max, ...
7
- Samsung Health export ("Download personal data"), staged into fit3/:
8
- live_data.json 10 s samples: heart_rate, cadence, distance, power, speed, start_time(ms)
9
- location_data.json 1 s samples: latitude, longitude, altitude, accuracy, start_time(ms)
10
- exercise_summary.csv the summary CSV -- avg/max HR etc.
11
-
12
- Times are epoch-us, on the same clock as the IMU and phone streams.
13
- """
14
- from __future__ import annotations
15
-
16
- import csv
17
- import json
18
- import os
19
- from dataclasses import dataclass
20
-
21
- import pandas as pd
22
-
23
- LIVE_COLS = ["time", "heart_rate", "cadence", "speed"] # Samsung's `power` is always 0 on the Fit3
24
-
25
-
26
- @dataclass
27
- class Fit3:
28
- live: pd.DataFrame # time(us), heart_rate, cadence, speed (10 s)
29
- loc: pd.DataFrame # time(us), lat, lon, altitude, accuracy (1 s; Samsung export only)
30
- summary: dict # hr_mean/max/min, cadence_mean/max, mean_speed, duration_min, calorie
31
-
32
-
33
- def _load_series(fit3_dir: str) -> tuple[pd.DataFrame, pd.DataFrame]:
34
- public = os.path.join(fit3_dir, "fit3_live.csv")
35
- if os.path.exists(public):
36
- live = pd.read_csv(public)
37
- return live[[c for c in LIVE_COLS if c in live]].sort_values("time").reset_index(drop=True), pd.DataFrame()
38
-
39
- def js(name):
40
- p = os.path.join(fit3_dir, name)
41
- return json.load(open(p)) if os.path.exists(p) else []
42
-
43
- live = pd.DataFrame(js("live_data.json"))
44
- if not live.empty:
45
- live["time"] = live["start_time"].astype("int64") * 1000
46
- live = live[[c for c in LIVE_COLS if c in live]].sort_values("time").reset_index(drop=True)
47
-
48
- loc = pd.DataFrame(js("location_data.json"))
49
- if not loc.empty:
50
- loc["time"] = loc["start_time"].astype("int64") * 1000
51
- loc = loc.rename(columns={"latitude": "lat", "longitude": "lon"})
52
- loc = loc[["time", "lat", "lon", "altitude", "accuracy"]].sort_values("time").reset_index(drop=True)
53
- return live, loc
54
-
55
-
56
- def _parse_summary(fit3_dir: str, start_us: int | None) -> dict:
57
- """The run's summary: fit3_summary.csv, else the matching row of Samsung's exercise_summary.csv.
58
-
59
- Samsung header (line 2) is prefix-labelled (com.samsung.health.exercise.<field>); rows carry one extra
60
- trailing field, but zip(header, row) aligns the leading columns we need. We pick the running
61
- workout (exercise_type 1002) nearest the session start, else the longest running workout.
62
- """
63
- pub = os.path.join(fit3_dir, "fit3_summary.csv")
64
- if os.path.exists(pub):
65
- rows = pd.read_csv(pub).to_dict("records")
66
- if not rows:
67
- return {}
68
- r = {k: (None if pd.isna(v) else v) for k, v in rows[0].items()}
69
- return {"start_time": r.get("start_time"), "duration_min": (r.get("duration_s") or 0) / 60.0,
70
- "hr_mean": r.get("hr_mean"), "hr_max": r.get("hr_max"), "hr_min": r.get("hr_min"),
71
- "cadence_mean": r.get("cadence_mean"), "cadence_max": r.get("cadence_max"),
72
- "mean_speed": r.get("speed_mean_mps"), "calorie": r.get("calorie_kcal")}
73
- p = os.path.join(fit3_dir, "exercise_summary.csv")
74
- if not os.path.exists(p):
75
- return {}
76
- lines = open(p, encoding="utf-8-sig").read().splitlines()
77
- if len(lines) < 3:
78
- return {}
79
- hdr = next(csv.reader([lines[1]]))
80
- idx = {h.split(".")[-1]: i for i, h in enumerate(hdr)} # last segment: start_time, duration, ...
81
-
82
- def g(row, key, cast=str):
83
- j = idx.get(key)
84
- if j is None or j >= len(row) or row[j] == "":
85
- return None
86
- try:
87
- return cast(row[j])
88
- except ValueError:
89
- return row[j]
90
-
91
- best, best_key = None, None
92
- for ln in lines[2:]:
93
- row = next(csv.reader([ln]))
94
- if g(row, "exercise_type") != "1002": # running only
95
- continue
96
- dur = g(row, "duration", float) or 0.0
97
- st = g(row, "start_time") # "YYYY-MM-DD HH:MM:SS.000" (UTC)
98
- key = dur
99
- if start_us is not None and st:
100
- try:
101
- t = pd.Timestamp(st, tz="UTC").value // 1000 # -> epoch us
102
- key = -abs(t - start_us) # nearest start wins
103
- except Exception:
104
- pass
105
- if best_key is None or key > best_key:
106
- best, best_key = row, key
107
- if best is None:
108
- return {}
109
- return {
110
- "start_time": g(best, "start_time"),
111
- "duration_min": (g(best, "duration", float) or 0) / 60000.0,
112
- "hr_mean": g(best, "mean_heart_rate", float),
113
- "hr_max": g(best, "max_heart_rate", float),
114
- "hr_min": g(best, "min_heart_rate", float),
115
- "cadence_mean": g(best, "mean_cadence", float),
116
- "cadence_max": g(best, "max_cadence", float),
117
- "mean_speed": g(best, "mean_speed", float),
118
- "calorie": g(best, "calorie", float),
119
- }
120
-
121
-
122
- def load_fit3(day_path: str) -> Fit3 | None:
123
- """Fit3 for one day folder (data/<subject>/<day>), or None if that day has no watch data."""
124
- fit3_dir = os.path.join(day_path, "fit3")
125
- if not os.path.isdir(fit3_dir):
126
- return None
127
- live, loc = _load_series(fit3_dir)
128
- if live.empty and loc.empty:
129
- return None
130
- start_us = int(live["time"].iloc[0]) if not live.empty else int(loc["time"].iloc[0])
131
- return Fit3(live=live, loc=loc, summary=_parse_summary(fit3_dir, start_us))
 
1
+ """Samsung Galaxy Fit3 watch loader -- the non-LEVEL reference (heart rate, cadence, speed).
2
+
3
+ Fit3 data is day-level: data/<subject>/<day>/fit3/. Two on-disk layouts, same Fit3 object out:
4
+ released dataset (our own schema):
5
+ fit3_live.csv 10 s samples: time(us), heart_rate, cadence, speed
6
+ fit3_summary.csv one row: start_time(us), duration_s, hr_mean/max/min, cadence_mean/max, ...
7
+ Samsung Health export ("Download personal data"), staged into fit3/:
8
+ live_data.json 10 s samples: heart_rate, cadence, distance, power, speed, start_time(ms)
9
+ location_data.json 1 s samples: latitude, longitude, altitude, accuracy, start_time(ms)
10
+ exercise_summary.csv the summary CSV -- avg/max HR etc.
11
+
12
+ Times are epoch-us, on the same clock as the IMU and phone streams.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import csv
17
+ import json
18
+ import os
19
+ from dataclasses import dataclass
20
+
21
+ import pandas as pd
22
+
23
+ LIVE_COLS = ["time", "heart_rate", "cadence", "speed"] # Samsung's `power` is always 0 on the Fit3
24
+
25
+
26
+ @dataclass
27
+ class Fit3:
28
+ live: pd.DataFrame # time(us), heart_rate, cadence, speed (10 s)
29
+ loc: pd.DataFrame # time(us), lat, lon, altitude, accuracy (1 s; Samsung export only)
30
+ summary: dict # hr_mean/max/min, cadence_mean/max, mean_speed, duration_min, calorie
31
+
32
+
33
+ def _load_series(fit3_dir: str) -> tuple[pd.DataFrame, pd.DataFrame]:
34
+ public = os.path.join(fit3_dir, "fit3_live.csv")
35
+ if os.path.exists(public):
36
+ live = pd.read_csv(public)
37
+ return live[[c for c in LIVE_COLS if c in live]].sort_values("time").reset_index(drop=True), pd.DataFrame()
38
+
39
+ def js(name):
40
+ p = os.path.join(fit3_dir, name)
41
+ return json.load(open(p)) if os.path.exists(p) else []
42
+
43
+ live = pd.DataFrame(js("live_data.json"))
44
+ if not live.empty:
45
+ live["time"] = live["start_time"].astype("int64") * 1000
46
+ live = live[[c for c in LIVE_COLS if c in live]].sort_values("time").reset_index(drop=True)
47
+
48
+ loc = pd.DataFrame(js("location_data.json"))
49
+ if not loc.empty:
50
+ loc["time"] = loc["start_time"].astype("int64") * 1000
51
+ loc = loc.rename(columns={"latitude": "lat", "longitude": "lon"})
52
+ loc = loc[["time", "lat", "lon", "altitude", "accuracy"]].sort_values("time").reset_index(drop=True)
53
+ return live, loc
54
+
55
+
56
+ def _parse_summary(fit3_dir: str, start_us: int | None) -> dict:
57
+ """The run's summary: fit3_summary.csv, else the matching row of Samsung's exercise_summary.csv.
58
+
59
+ Samsung header (line 2) is prefix-labelled (com.samsung.health.exercise.<field>); rows carry one extra
60
+ trailing field, but zip(header, row) aligns the leading columns we need. We pick the running
61
+ workout (exercise_type 1002) nearest the session start, else the longest running workout.
62
+ """
63
+ pub = os.path.join(fit3_dir, "fit3_summary.csv")
64
+ if os.path.exists(pub):
65
+ rows = pd.read_csv(pub).to_dict("records")
66
+ if not rows:
67
+ return {}
68
+ r = {k: (None if pd.isna(v) else v) for k, v in rows[0].items()}
69
+ return {"start_time": r.get("start_time"), "duration_min": (r.get("duration_s") or 0) / 60.0,
70
+ "hr_mean": r.get("hr_mean"), "hr_max": r.get("hr_max"), "hr_min": r.get("hr_min"),
71
+ "cadence_mean": r.get("cadence_mean"), "cadence_max": r.get("cadence_max"),
72
+ "mean_speed": r.get("speed_mean_mps"), "calorie": r.get("calorie_kcal")}
73
+ p = os.path.join(fit3_dir, "exercise_summary.csv")
74
+ if not os.path.exists(p):
75
+ return {}
76
+ lines = open(p, encoding="utf-8-sig").read().splitlines()
77
+ if len(lines) < 3:
78
+ return {}
79
+ hdr = next(csv.reader([lines[1]]))
80
+ idx = {h.split(".")[-1]: i for i, h in enumerate(hdr)} # last segment: start_time, duration, ...
81
+
82
+ def g(row, key, cast=str):
83
+ j = idx.get(key)
84
+ if j is None or j >= len(row) or row[j] == "":
85
+ return None
86
+ try:
87
+ return cast(row[j])
88
+ except ValueError:
89
+ return row[j]
90
+
91
+ best, best_key = None, None
92
+ for ln in lines[2:]:
93
+ row = next(csv.reader([ln]))
94
+ if g(row, "exercise_type") != "1002": # running only
95
+ continue
96
+ dur = g(row, "duration", float) or 0.0
97
+ st = g(row, "start_time") # "YYYY-MM-DD HH:MM:SS.000" (UTC)
98
+ key = dur
99
+ if start_us is not None and st:
100
+ try:
101
+ t = pd.Timestamp(st, tz="UTC").value // 1000 # -> epoch us
102
+ key = -abs(t - start_us) # nearest start wins
103
+ except Exception:
104
+ pass
105
+ if best_key is None or key > best_key:
106
+ best, best_key = row, key
107
+ if best is None:
108
+ return {}
109
+ return {
110
+ "start_time": g(best, "start_time"),
111
+ "duration_min": (g(best, "duration", float) or 0) / 60000.0,
112
+ "hr_mean": g(best, "mean_heart_rate", float),
113
+ "hr_max": g(best, "max_heart_rate", float),
114
+ "hr_min": g(best, "min_heart_rate", float),
115
+ "cadence_mean": g(best, "mean_cadence", float),
116
+ "cadence_max": g(best, "max_cadence", float),
117
+ "mean_speed": g(best, "mean_speed", float),
118
+ "calorie": g(best, "calorie", float),
119
+ }
120
+
121
+
122
+ def load_fit3(day_path: str) -> Fit3 | None:
123
+ """Fit3 for one day folder (data/<subject>/<day>), or None if that day has no watch data."""
124
+ fit3_dir = os.path.join(day_path, "fit3")
125
+ if not os.path.isdir(fit3_dir):
126
+ return None
127
+ live, loc = _load_series(fit3_dir)
128
+ if live.empty and loc.empty:
129
+ return None
130
+ start_us = int(live["time"].iloc[0]) if not live.empty else int(loc["time"].iloc[0])
131
+ return Fit3(live=live, loc=loc, summary=_parse_summary(fit3_dir, start_us))
scripts/lvl_running/session.py CHANGED
@@ -1,166 +1,166 @@
1
- """Load a LEVEL running-dataset session folder into typed frames.
2
-
3
- A session folder (data/<subject>/<day>/<session>/) contains:
4
- imu-{placement}-{shortmac}[.NNN].csv per-sensor raw (time-us, accel xyz, gyro xyz, frame_sensor,
5
- time_sensor[, time_host]; older recordings are renamed on load);
6
- .NNN are rotation segments -- concatenated + time-sorted here.
7
- gps.csv, barometer.csv, steps.csv phone-native streams (epoch-us); gps.csv only on public-event days
8
- pace_profile.csv coordinate-free distance / pace / elevation derived from GPS
9
- polar_<4hex>_{hr,acc,ecg}.csv Polar H10 chest strap, when worn
10
- meta-summary.json manifest (session window, sensors, settings, transport)
11
- meta-debug.json diagnostics (phone battery, time-sync result, phone); older
12
- app builds call it meta-device.json -- either is loaded.
13
- Not in the release: its values are in sessions.csv
14
- meta-telemetry.csv per-sensor telemetry snapshots (voltage/rssi/loss) -- internal
15
- recordings only, not in the release (loaded when present)
16
- The day folder also holds fit3/ (Samsung Galaxy Fit3 watch reference) -- see fit3.py.
17
- """
18
- from __future__ import annotations
19
-
20
- import glob
21
- import json
22
- import os
23
- import re
24
- from dataclasses import dataclass, field
25
- from typing import Iterator
26
-
27
- import pandas as pd
28
-
29
- # LEVEL Collector's 2026-09 column rename (header-only): older recordings load under the current names
30
- IMU_RENAME = {"frame_number": "frame_sensor", "raw_counter": "time_sensor"}
31
- TIME_SENSOR_WRAP_MS = 1 << 16 # time_sensor is the sensor's 16-bit ms clock
32
-
33
-
34
- def unwrap_time_sensor(df: pd.DataFrame) -> pd.Series:
35
- """time_sensor (16-bit ms, wraps every 65.5 s) as a continuous ms count from the first sample.
36
- Wraps are counted from `time` (host timeline), so a dropout longer than one wrap cannot fool it."""
37
- raw = df["time_sensor"].astype("int64")
38
- elapsed_ms = (df["time"] - df["time"].iloc[0]) // 1000
39
- wraps = ((elapsed_ms - (raw - raw.iloc[0])) / TIME_SENSOR_WRAP_MS).round().astype("int64")
40
- return raw - raw.iloc[0] + wraps * TIME_SENSOR_WRAP_MS
41
-
42
-
43
- # imu-<placement>-<4hex>[.NNN].csv (placement may contain hyphens/underscores, e.g. left_foot)
44
- _IMU_RE = re.compile(r"^imu-(?P<placement>.+)-(?P<mac>[0-9a-fA-F]{4})(?:\.(?P<seg>\d+))?\.csv$")
45
-
46
-
47
- @dataclass
48
- class ImuStream:
49
- placement: str
50
- mac: str
51
- df: pd.DataFrame # time, accel_x..gyro_z, frame_sensor, time_sensor[, time_host] -- concatenated + time-sorted
52
- n_segments: int # how many rotation files were stitched
53
-
54
-
55
- @dataclass
56
- class Session:
57
- path: str
58
- name: str
59
- imus: dict[str, ImuStream] = field(default_factory=dict) # keyed by placement
60
- gps: pd.DataFrame | None = None
61
- barometer: pd.DataFrame | None = None
62
- steps: pd.DataFrame | None = None
63
- meta_summary: dict | None = None
64
- meta_telemetry: pd.DataFrame | None = None
65
- meta_debug: dict | None = None # diagnostics (meta-debug.json): battery, time sync, phone
66
-
67
- @property
68
- def settings(self) -> dict:
69
- """Stream settings from both meta files. meta-summary schema 2 keeps only sampling_rate_hz /
70
- sensor_count / time_sync; the rest (samples_per_packet, ...) moved to meta-debug.json."""
71
- return {**((self.meta_debug or {}).get("settings") or {}),
72
- **((self.meta_summary or {}).get("settings") or {})}
73
-
74
- @property
75
- def session_ms(self) -> tuple[int | None, int | None]:
76
- """(startedAtMs, endedAtMs) from meta-summary, if present."""
77
- s = (self.meta_summary or {}).get("session", {})
78
- return s.get("startedAtMs"), s.get("endedAtMs")
79
-
80
- @property
81
- def duration_s(self) -> float | None:
82
- s = (self.meta_summary or {}).get("session", {})
83
- d = s.get("durationMs")
84
- return d / 1000.0 if d is not None else None
85
-
86
-
87
- def _read_csv(path: str) -> pd.DataFrame | None:
88
- try:
89
- return pd.read_csv(path)
90
- except Exception:
91
- return None
92
-
93
-
94
- def load_session(path: str) -> Session:
95
- name = os.path.basename(os.path.normpath(path))
96
- if name in ("level", "calib"): # role-named recording: say which session it belongs to
97
- name = f"{os.path.basename(os.path.dirname(os.path.normpath(path)))}/{name}"
98
- sess = Session(path=path, name=name)
99
-
100
- # --- IMU: group rotation segments by (placement, mac), concat, sort by time ---
101
- segs: dict[tuple[str, str], list[pd.DataFrame]] = {}
102
- for fn in sorted(os.listdir(path)):
103
- m = _IMU_RE.match(fn)
104
- if not m:
105
- continue
106
- df = _read_csv(os.path.join(path, fn))
107
- if df is None or "time" not in df.columns:
108
- continue
109
- df = df.rename(columns=IMU_RENAME)
110
- segs.setdefault((m["placement"], m["mac"]), []).append(df)
111
-
112
- for (placement, mac), parts in segs.items():
113
- parts.sort(key=lambda d: int(d["time"].iloc[0])) # order by first timestamp
114
- df = pd.concat(parts, ignore_index=True).sort_values("time").reset_index(drop=True)
115
- sess.imus[placement] = ImuStream(placement, mac, df, n_segments=len(parts))
116
-
117
- # --- phone-native streams + meta ---
118
- sess.gps = _read_csv(os.path.join(path, "gps.csv"))
119
- sess.barometer = _read_csv(os.path.join(path, "barometer.csv"))
120
- sess.steps = _read_csv(os.path.join(path, "steps.csv"))
121
- sess.meta_telemetry = _read_csv(os.path.join(path, "meta-telemetry.csv"))
122
-
123
- ms = os.path.join(path, "meta-summary.json")
124
- if os.path.exists(ms):
125
- try:
126
- sess.meta_summary = json.load(open(ms))
127
- except Exception:
128
- sess.meta_summary = None
129
-
130
- md = os.path.join(path, "meta-debug.json")
131
- if not os.path.exists(md): # app builds before meta-summary schema 2
132
- md = os.path.join(path, "meta-device.json")
133
- if os.path.exists(md):
134
- try:
135
- sess.meta_debug = json.load(open(md))
136
- except Exception:
137
- sess.meta_debug = None
138
-
139
- return sess
140
-
141
-
142
- def find_sessions(root: str) -> list[str]:
143
- """Session subfolders directly under root (those containing a meta-summary.json)."""
144
- out = []
145
- for d in sorted(glob.glob(os.path.join(root, "*"))):
146
- if os.path.isdir(d) and os.path.exists(os.path.join(d, "meta-summary.json")):
147
- out.append(d)
148
- return out
149
-
150
-
151
- PUBLIC_ROLE = {"run": "level"} # the run's public folder is level/ (beside fit3/); raw ones end in -run
152
-
153
-
154
- def iter_sessions(root: str, kind: str | None = "run") -> Iterator[str]:
155
- """Every session folder anywhere under root (data/, a subject, or a day), in sorted order.
156
-
157
- kind="run" (default) yields only the runs (`level/`); kind="calib" the calibrations (`calib/`);
158
- kind=None everything. Raw-style names (`<timestamp>-run`) match too.
159
- """
160
- for dirpath, dirs, files in os.walk(root):
161
- dirs.sort()
162
- if "meta-summary.json" in files:
163
- name = os.path.basename(dirpath)
164
- if kind is None or name == PUBLIC_ROLE.get(kind, kind) or name.endswith(f"-{kind}"):
165
- yield dirpath
166
- dirs.clear() # a session folder has no nested sessions
 
1
+ """Load a LEVEL running-dataset session folder into typed frames.
2
+
3
+ A session folder (data/<subject>/<day>/<session>/) contains:
4
+ imu-{placement}-{shortmac}[.NNN].csv per-sensor raw (time-us, accel xyz, gyro xyz, frame_sensor,
5
+ time_sensor[, time_host]; older recordings are renamed on load);
6
+ .NNN are rotation segments -- concatenated + time-sorted here.
7
+ gps.csv, barometer.csv, steps.csv phone-native streams (epoch-us); gps.csv only on public-event days
8
+ pace_profile.csv coordinate-free distance / pace / elevation derived from GPS
9
+ polar_<4hex>_{hr,acc,ecg}.csv Polar H10 chest strap, when worn
10
+ meta-summary.json manifest (session window, sensors, settings, transport)
11
+ meta-debug.json diagnostics (phone battery, time-sync result, phone); older
12
+ app builds call it meta-device.json -- either is loaded.
13
+ Not in the release: its values are in sessions.csv
14
+ meta-telemetry.csv per-sensor telemetry snapshots (voltage/rssi/loss) -- internal
15
+ recordings only, not in the release (loaded when present)
16
+ The day folder also holds fit3/ (Samsung Galaxy Fit3 watch reference) -- see fit3.py.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import glob
21
+ import json
22
+ import os
23
+ import re
24
+ from dataclasses import dataclass, field
25
+ from typing import Iterator
26
+
27
+ import pandas as pd
28
+
29
+ # LEVEL Collector's 2026-09 column rename (header-only): older recordings load under the current names
30
+ IMU_RENAME = {"frame_number": "frame_sensor", "raw_counter": "time_sensor"}
31
+ TIME_SENSOR_WRAP_MS = 1 << 16 # time_sensor is the sensor's 16-bit ms clock
32
+
33
+
34
+ def unwrap_time_sensor(df: pd.DataFrame) -> pd.Series:
35
+ """time_sensor (16-bit ms, wraps every 65.5 s) as a continuous ms count from the first sample.
36
+ Wraps are counted from `time` (host timeline), so a dropout longer than one wrap cannot fool it."""
37
+ raw = df["time_sensor"].astype("int64")
38
+ elapsed_ms = (df["time"] - df["time"].iloc[0]) // 1000
39
+ wraps = ((elapsed_ms - (raw - raw.iloc[0])) / TIME_SENSOR_WRAP_MS).round().astype("int64")
40
+ return raw - raw.iloc[0] + wraps * TIME_SENSOR_WRAP_MS
41
+
42
+
43
+ # imu-<placement>-<4hex>[.NNN].csv (placement may contain hyphens/underscores, e.g. left_foot)
44
+ _IMU_RE = re.compile(r"^imu-(?P<placement>.+)-(?P<mac>[0-9a-fA-F]{4})(?:\.(?P<seg>\d+))?\.csv$")
45
+
46
+
47
+ @dataclass
48
+ class ImuStream:
49
+ placement: str
50
+ mac: str
51
+ df: pd.DataFrame # time, accel_x..gyro_z, frame_sensor, time_sensor[, time_host] -- concatenated + time-sorted
52
+ n_segments: int # how many rotation files were stitched
53
+
54
+
55
+ @dataclass
56
+ class Session:
57
+ path: str
58
+ name: str
59
+ imus: dict[str, ImuStream] = field(default_factory=dict) # keyed by placement
60
+ gps: pd.DataFrame | None = None
61
+ barometer: pd.DataFrame | None = None
62
+ steps: pd.DataFrame | None = None
63
+ meta_summary: dict | None = None
64
+ meta_telemetry: pd.DataFrame | None = None
65
+ meta_debug: dict | None = None # diagnostics (meta-debug.json): battery, time sync, phone
66
+
67
+ @property
68
+ def settings(self) -> dict:
69
+ """Stream settings from both meta files. meta-summary schema 2 keeps only sampling_rate_hz /
70
+ sensor_count / time_sync; the rest (samples_per_packet, ...) moved to meta-debug.json."""
71
+ return {**((self.meta_debug or {}).get("settings") or {}),
72
+ **((self.meta_summary or {}).get("settings") or {})}
73
+
74
+ @property
75
+ def session_ms(self) -> tuple[int | None, int | None]:
76
+ """(startedAtMs, endedAtMs) from meta-summary, if present."""
77
+ s = (self.meta_summary or {}).get("session", {})
78
+ return s.get("startedAtMs"), s.get("endedAtMs")
79
+
80
+ @property
81
+ def duration_s(self) -> float | None:
82
+ s = (self.meta_summary or {}).get("session", {})
83
+ d = s.get("durationMs")
84
+ return d / 1000.0 if d is not None else None
85
+
86
+
87
+ def _read_csv(path: str) -> pd.DataFrame | None:
88
+ try:
89
+ return pd.read_csv(path)
90
+ except Exception:
91
+ return None
92
+
93
+
94
+ def load_session(path: str) -> Session:
95
+ name = os.path.basename(os.path.normpath(path))
96
+ if name in ("level", "calib"): # role-named recording: say which session it belongs to
97
+ name = f"{os.path.basename(os.path.dirname(os.path.normpath(path)))}/{name}"
98
+ sess = Session(path=path, name=name)
99
+
100
+ # --- IMU: group rotation segments by (placement, mac), concat, sort by time ---
101
+ segs: dict[tuple[str, str], list[pd.DataFrame]] = {}
102
+ for fn in sorted(os.listdir(path)):
103
+ m = _IMU_RE.match(fn)
104
+ if not m:
105
+ continue
106
+ df = _read_csv(os.path.join(path, fn))
107
+ if df is None or "time" not in df.columns:
108
+ continue
109
+ df = df.rename(columns=IMU_RENAME)
110
+ segs.setdefault((m["placement"], m["mac"]), []).append(df)
111
+
112
+ for (placement, mac), parts in segs.items():
113
+ parts.sort(key=lambda d: int(d["time"].iloc[0])) # order by first timestamp
114
+ df = pd.concat(parts, ignore_index=True).sort_values("time").reset_index(drop=True)
115
+ sess.imus[placement] = ImuStream(placement, mac, df, n_segments=len(parts))
116
+
117
+ # --- phone-native streams + meta ---
118
+ sess.gps = _read_csv(os.path.join(path, "gps.csv"))
119
+ sess.barometer = _read_csv(os.path.join(path, "barometer.csv"))
120
+ sess.steps = _read_csv(os.path.join(path, "steps.csv"))
121
+ sess.meta_telemetry = _read_csv(os.path.join(path, "meta-telemetry.csv"))
122
+
123
+ ms = os.path.join(path, "meta-summary.json")
124
+ if os.path.exists(ms):
125
+ try:
126
+ sess.meta_summary = json.load(open(ms))
127
+ except Exception:
128
+ sess.meta_summary = None
129
+
130
+ md = os.path.join(path, "meta-debug.json")
131
+ if not os.path.exists(md): # app builds before meta-summary schema 2
132
+ md = os.path.join(path, "meta-device.json")
133
+ if os.path.exists(md):
134
+ try:
135
+ sess.meta_debug = json.load(open(md))
136
+ except Exception:
137
+ sess.meta_debug = None
138
+
139
+ return sess
140
+
141
+
142
+ def find_sessions(root: str) -> list[str]:
143
+ """Session subfolders directly under root (those containing a meta-summary.json)."""
144
+ out = []
145
+ for d in sorted(glob.glob(os.path.join(root, "*"))):
146
+ if os.path.isdir(d) and os.path.exists(os.path.join(d, "meta-summary.json")):
147
+ out.append(d)
148
+ return out
149
+
150
+
151
+ PUBLIC_ROLE = {"run": "level"} # the run's public folder is level/ (beside fit3/); raw ones end in -run
152
+
153
+
154
+ def iter_sessions(root: str, kind: str | None = "run") -> Iterator[str]:
155
+ """Every session folder anywhere under root (data/, a subject, or a day), in sorted order.
156
+
157
+ kind="run" (default) yields only the runs (`level/`); kind="calib" the calibrations (`calib/`);
158
+ kind=None everything. Raw-style names (`<timestamp>-run`) match too.
159
+ """
160
+ for dirpath, dirs, files in os.walk(root):
161
+ dirs.sort()
162
+ if "meta-summary.json" in files:
163
+ name = os.path.basename(dirpath)
164
+ if kind is None or name == PUBLIC_ROLE.get(kind, kind) or name.endswith(f"-{kind}"):
165
+ yield dirpath
166
+ dirs.clear() # a session folder has no nested sessions
scripts/make_figures.py CHANGED
@@ -1,49 +1,49 @@
1
- """Render the figures for every run in data/ into figures/<subject>/<session>/ (flat: overview.png,
2
- data-*.png as recorded, derived-*.png computed).
3
-
4
- python scripts/make_figures.py # only runs that have no figures yet
5
- python scripts/make_figures.py --force # re-render everything (bloats the repo history -- rarely)
6
-
7
- Doubles as the dataset's smoke test: it loads and plots every run, so if it finishes clean the data and
8
- the lvl_running package agree. Exit code 1 if any run fails to load or plot.
9
- """
10
- from __future__ import annotations
11
-
12
- import argparse
13
- import os
14
- import sys
15
- import traceback
16
-
17
- from lvl_running import iter_sessions, plot_session
18
-
19
- HERE = os.path.dirname(os.path.abspath(__file__))
20
- ROOT = os.path.dirname(HERE) # the dataset folder (scripts/ lives inside it)
21
-
22
-
23
- def main(argv=None) -> int:
24
- ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
25
- ap.add_argument("--data", default=os.path.join(ROOT, "data"))
26
- ap.add_argument("--figures", default=os.path.join(ROOT, "figures"))
27
- ap.add_argument("--force", action="store_true", help="re-render runs that already have figures")
28
- a = ap.parse_args(argv)
29
-
30
- done = skipped = failed = 0
31
- for run_dir in iter_sessions(a.data):
32
- rel = os.path.dirname(os.path.relpath(run_dir, a.data)) # S01/R01 (the level/ folder is dropped)
33
- out = os.path.join(a.figures, rel)
34
- if not a.force and os.path.isdir(out) and os.listdir(out):
35
- skipped += 1
36
- continue
37
- try:
38
- made = [k for k, p in plot_session(run_dir, out).items() if p]
39
- print(f" {rel}: {', '.join(made) or 'no figures'}")
40
- done += 1
41
- except Exception:
42
- print(f" FAIL {rel}\n{traceback.format_exc()}", file=sys.stderr)
43
- failed += 1
44
- print(f"{done} rendered, {skipped} already had figures, {failed} failed -> {a.figures}")
45
- return 1 if failed else 0
46
-
47
-
48
- if __name__ == "__main__":
49
- raise SystemExit(main())
 
1
+ """Render the figures for every run in data/ into figures/<subject>/<session>/ (flat: overview.png,
2
+ data-*.png as recorded, derived-*.png computed).
3
+
4
+ python scripts/make_figures.py # only runs that have no figures yet
5
+ python scripts/make_figures.py --force # re-render everything (bloats the repo history -- rarely)
6
+
7
+ Doubles as the dataset's smoke test: it loads and plots every run, so if it finishes clean the data and
8
+ the lvl_running package agree. Exit code 1 if any run fails to load or plot.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import os
14
+ import sys
15
+ import traceback
16
+
17
+ from lvl_running import iter_sessions, plot_session
18
+
19
+ HERE = os.path.dirname(os.path.abspath(__file__))
20
+ ROOT = os.path.dirname(HERE) # the dataset folder (scripts/ lives inside it)
21
+
22
+
23
+ def main(argv=None) -> int:
24
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
25
+ ap.add_argument("--data", default=os.path.join(ROOT, "data"))
26
+ ap.add_argument("--figures", default=os.path.join(ROOT, "figures"))
27
+ ap.add_argument("--force", action="store_true", help="re-render runs that already have figures")
28
+ a = ap.parse_args(argv)
29
+
30
+ done = skipped = failed = 0
31
+ for run_dir in iter_sessions(a.data):
32
+ rel = os.path.dirname(os.path.relpath(run_dir, a.data)) # S01/R01 (the level/ folder is dropped)
33
+ out = os.path.join(a.figures, rel)
34
+ if not a.force and os.path.isdir(out) and os.listdir(out):
35
+ skipped += 1
36
+ continue
37
+ try:
38
+ made = [k for k, p in plot_session(run_dir, out).items() if p]
39
+ print(f" {rel}: {', '.join(made) or 'no figures'}")
40
+ done += 1
41
+ except Exception:
42
+ print(f" FAIL {rel}\n{traceback.format_exc()}", file=sys.stderr)
43
+ failed += 1
44
+ print(f"{done} rendered, {skipped} already had figures, {failed} failed -> {a.figures}")
45
+ return 1 if failed else 0
46
+
47
+
48
+ if __name__ == "__main__":
49
+ raise SystemExit(main())
scripts/requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
- numpy
2
- pandas
3
- scipy
4
- matplotlib
 
1
+ numpy
2
+ pandas
3
+ scipy
4
+ matplotlib