File size: 3,967 Bytes
689b5c1 2d4c705 689b5c1 2d4c705 702c817 2d4c705 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 | """Write sessions.csv -- one row per session: its conditions, how it was captured, what was measured,
and the capture analysis (column groups in lvl_running/catalog.py) -- and mount a compact Markdown
version of it in README.md (between the sessions:start / sessions:end markers), so the dataset card
never goes stale.
python scripts/make_catalog.py
Always rebuilt in full: it is small, text, and diffs cleanly release to release.
"""
from __future__ import annotations
import os
import re
import pandas as pd
from lvl_running.catalog import build_catalog
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE) # the dataset folder (scripts/ lives inside it)
MARKERS = re.compile(r"(<!-- sessions:start[^>]*-->).*?(<!-- sessions:end -->)", re.S)
GLANCE = re.compile(r"(<!-- glance:start[^>]*-->).*?(<!-- glance:end -->)", re.S)
def _v(x) -> str:
return "" if x is None or (isinstance(x, float) and pd.isna(x)) else str(x)
def _num(x, fmt: str) -> str:
return "" if _v(x) == "" else fmt.format(float(x))
def sessions_markdown(df: pd.DataFrame) -> str:
"""The card's session table: what a visitor needs at a glance; sessions.csv has every column."""
head = ("| Date | Session | Conditions | Data (min) | Run (min) | Distance (km) | LEVEL sensors | Reference data | Packet loss (%) | Eff. rate (Hz) | Max gap (s) |\n"
"|---|---|---|---:|---:|---:|---:|---|---:|---:|---:|")
rows = []
for r in df.to_dict("records"):
overview = f"figures/{r['subject']}/{r['session']}/overview.png"
cond = _v(r.get("setting")) # indoor / outdoor; surface, event, location are in sessions.csv
sensors = _v(r.get("sensor_count")) # placements are in sessions.csv
refs = ", ".join(n for n, ok in (("chest strap", r.get("h10_hr")), ("watch", r.get("watch"))) if ok is True)
cells = [_v(r["date"]), f"[{r['session']}]({overview})", cond, _num(r.get("duration_min"), "{:.0f}"), _num(r.get("run_duration_min"), "{:.0f}"),
_num(r.get("distance_km"), "{:.2f}"), sensors, refs, _num(r.get("loss_pct"), "{:.1f}"),
_num(r.get("effective_rate_hz"), "{:.1f}"), _num(r.get("max_gap_s"), "{:.2f}")]
rows.append("| " + " | ".join(c.replace("|", "/") for c in cells) + " |")
return (f"{head}\n" + "\n".join(rows) + f"\n\n*{len(df)} sessions. Click a session for its overview figure; "
"every column (setup, versions, heart rate, capture quality) is in `sessions.csv`.*")
def glance(df: pd.DataFrame) -> str:
"""One line of totals: what the dataset is, at a glance."""
n, subs = len(df), df["subject"].nunique()
hours = df["duration_min"].fillna(0).sum() / 60
km = df["distance_km"].fillna(0).sum()
d0, d1 = df["date"].min(), df["date"].max()
return (f"**{n} session{'s' if n != 1 else ''}, {subs} participant{'s' if subs != 1 else ''}, "
f"{hours:.1f} h of recording, {km:.0f} km outdoors, {d0} to {d1}.**")
def mount(readme_path: str, table: str, glance_line: str) -> bool:
"""Replace the generated blocks between their markers in README.md; False if a marker is missing."""
text = open(readme_path, encoding="utf-8").read()
if not (MARKERS.search(text) and GLANCE.search(text)):
return False
new = MARKERS.sub(lambda m: f"{m.group(1)}\n{table}\n{m.group(2)}", text)
new = GLANCE.sub(lambda m: f"{m.group(1)}\n{glance_line}\n{m.group(2)}", new)
with open(readme_path, "w", encoding="utf-8", newline="\n") as f: # same bytes on every OS
f.write(new)
return True
if __name__ == "__main__":
df = build_catalog(os.path.join(ROOT, "data"))
df.to_csv(os.path.join(ROOT, "sessions.csv"), index=False)
ok = mount(os.path.join(ROOT, "README.md"), sessions_markdown(df), glance(df))
print(f"{len(df)} sessions -> sessions.csv" + ("; README.md table updated" if ok else "; README.md markers NOT found"))
|