sma-upper-limb-kinect / scripts /build_dataset.py
YannisTevissen's picture
Publish reproducible Kinect build and baseline scripts
24c3f28 verified
Raw
History Blame Contribute Delete
18.1 kB
"""Build a reach-intent benchmark from PLOS ONE supplementary archive S3.
The builder reads the source archive without extracting it, joins event logs to
the approximately 16 Hz skeleton stream, and writes viewer-friendly CSV files.
It intentionally excludes the clinical table and fine-grained demographics.
"""
from __future__ import annotations
import argparse
import csv
import gzip
import hashlib
import io
import json
import re
import urllib.request
import zipfile
from collections import Counter, defaultdict
from datetime import date, datetime
from pathlib import Path
from typing import Iterable, Iterator
SOURCE_URL = (
"https://journals.plos.org/plosone/article/file?type=supplementary&"
"id=info:doi/10.1371/journal.pone.0170472.s003"
)
SOURCE_SHA256 = "21fc2ae8d8bce10b3cecd6416fdda390ba98476c9b9abe95be91857aea07d008"
TARGET_NAMES = {
0: "right_low_45",
1: "right_lateral",
2: "right_up_30",
3: "right_up_60",
4: "right_top",
5: "left_low_45",
6: "left_lateral",
7: "left_up_30",
8: "left_up_60",
9: "left_top",
}
# The two session-level PCA outliers removed in the public analysis workflow.
QC_OUTLIER_FEATURE_KEYS = {
"1024_2015.03.19_19.19",
"1038_2014.12.11_17.45",
}
EVENT_RE = re.compile(
r"\t(?P<timestamp>\d+)\tObject (?P<object>\d+) "
r"(?P<event>appeared|timed out|reached by (?P<hand>right|left) hand)!"
)
SESSION_RE = re.compile(
r"(?P<participant>\d+)_(?P<date>\d{4}\.\d{2}\.\d{2})_"
r"(?P<time>\d{2}\.\d{2}\.\d{2})\.txt$"
)
def _open_text(data: bytes) -> io.TextIOWrapper:
return io.TextIOWrapper(io.BytesIO(data), encoding="utf-8-sig", newline="")
def _write_csv(path: Path, fieldnames: list[str], rows: Iterable[dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
if path.suffix == ".gz":
raw = path.open("wb")
binary = gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0)
handle = io.TextIOWrapper(binary, encoding="utf-8", newline="")
else:
handle = path.open("w", encoding="utf-8", newline="")
try:
writer = csv.DictWriter(handle, fieldnames=fieldnames, extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
finally:
handle.close()
def download_source(destination: Path) -> Path:
"""Download and checksum the canonical PLOS supplementary archive."""
destination.parent.mkdir(parents=True, exist_ok=True)
request = urllib.request.Request(SOURCE_URL, headers={"User-Agent": "open-sma-hub/0.1"})
with urllib.request.urlopen(request) as response, destination.open("wb") as output:
while block := response.read(1024 * 1024):
output.write(block)
digest = hashlib.sha256(destination.read_bytes()).hexdigest()
if digest != SOURCE_SHA256:
destination.unlink(missing_ok=True)
raise ValueError(f"Source checksum mismatch: expected {SOURCE_SHA256}, got {digest}")
return destination
def _read_features(outer: zipfile.ZipFile) -> dict[str, str]:
data = outer.read("S1_Dataset/full_features_class.txt")
rows = csv.DictReader(_open_text(data), delimiter="\t")
return {
row["name"]: "sma" if row["class"].strip().lower() == "sma" else "control"
for row in rows
}
def _read_clinical_context(
outer: zipfile.ZipFile,
) -> tuple[set[str], dict[tuple[str, date], int]]:
"""Read only IDs, dates, and visit numbers needed for source-study filtering."""
rows = csv.DictReader(_open_text(outer.read("S1_Dataset/clinical_data.csv")))
participants: set[str] = set()
visits: dict[tuple[str, date], int] = {}
for row in rows:
participant_id = row["ID"]
participants.add(participant_id)
visits[(participant_id, datetime.strptime(row["DATE"], "%d.%m.%Y").date())] = int(
row["VISIT"]
)
return participants, visits
def _parse_raw(data: bytes) -> list[dict[str, str]]:
reader = csv.DictReader(_open_text(data), delimiter="\t")
rows = []
for row in reader:
if not row.get("currentTimeMillis"):
continue
cleaned = {key.strip(): value.strip() for key, value in row.items() if key is not None}
cleaned["currentTimeMillis"] = str(int(float(cleaned["currentTimeMillis"])))
rows.append(cleaned)
return rows
def _parse_events(data: bytes, raw_start_ms: int | None = None) -> list[dict]:
active: dict[int, int] = {}
trials: list[dict] = []
inferred_first_object_closed = False
for line in data.decode("utf-8-sig", errors="replace").splitlines():
match = EVENT_RE.search(line)
if not match:
continue
timestamp = int(match.group("timestamp"))
object_index = int(match.group("object"))
event = match.group("event")
if event == "appeared":
active[object_index] = timestamp
elif object_index in active:
trials.append(
{
"object_index": object_index,
"target_label": object_index % 10,
"target_name": TARGET_NAMES[object_index % 10],
"repeat_index": object_index // 10,
"start_ms": active.pop(object_index),
"end_ms": timestamp,
"status": "reached" if event.startswith("reached") else "timed_out",
"hand": match.group("hand") or "",
"start_inferred": False,
}
)
elif (
raw_start_ms is not None
and object_index == 0
and timestamp >= raw_start_ms
and not inferred_first_object_closed
):
# The game source starts object 0 without logging an "appeared" event.
# Raw recording begins after game initialization, so raw_start_ms is
# the earliest observable bound for its first presentation.
trials.append(
{
"object_index": 0,
"target_label": 0,
"target_name": TARGET_NAMES[0],
"repeat_index": 0,
"start_ms": raw_start_ms,
"end_ms": timestamp,
"status": "reached" if event.startswith("reached") else "timed_out",
"hand": match.group("hand") or "",
"start_inferred": True,
}
)
inferred_first_object_closed = True
return trials
def _nested_archive(outer: zipfile.ZipFile, name: str) -> zipfile.ZipFile:
return zipfile.ZipFile(io.BytesIO(outer.read(name)))
def build(source_zip: Path, output_dir: Path) -> dict:
digest = hashlib.sha256(source_zip.read_bytes()).hexdigest()
if digest != SOURCE_SHA256:
raise ValueError(f"Source checksum mismatch: expected {SOURCE_SHA256}, got {digest}")
trials_out: list[dict] = []
frames_out: list[dict] = []
sessions: list[dict] = []
with zipfile.ZipFile(source_zip) as outer:
groups = _read_features(outer)
clinical_participants, clinical_visits = _read_clinical_context(outer)
with _nested_archive(outer, "S1_Dataset/Full_RawData.zip") as raw_zip, _nested_archive(
outer, "S1_Dataset/Full_LogFile.zip"
) as log_zip:
raw_names = sorted(name for name in raw_zip.namelist() if name.endswith(".txt"))
log_by_session = {
Path(name).name.removeprefix("log_").removesuffix(".txt"): name
for name in log_zip.namelist()
if name.endswith(".txt")
}
raw_session_ids = {Path(name).name.removesuffix(".txt") for name in raw_names}
unmatched_raw_sessions = sorted(raw_session_ids - set(log_by_session))
unmatched_log_sessions = sorted(set(log_by_session) - raw_session_ids)
invalid_date_sessions: list[str] = []
for raw_name in raw_names:
filename = Path(raw_name).name
match = SESSION_RE.match(filename)
if not match:
continue
session_id = filename.removesuffix(".txt")
participant_id = match.group("participant")
# Reproduce the public R preprocessing rules from the study.
if participant_id == "1018": # Marked "not SMA" in StatisticalAnalysis.Rmd.
continue
if participant_id not in clinical_participants:
continue
if session_id.startswith("1027_2014.07.10_"): # Marked "no real game".
continue
session_date = datetime.strptime(match.group("date"), "%Y.%m.%d").date()
visit_number = clinical_visits.get((participant_id, session_date))
# These fallbacks exactly reproduce 1_dataPreprocessing.R.
if visit_number is None and session_date > date(2015, 1, 1):
visit_number = 4
if participant_id in {"1035", "1039"} and session_date == date(2014, 12, 18):
visit_number = 3
if visit_number is None:
invalid_date_sessions.append(session_id)
continue
feature_key = session_id.rsplit(".", 1)[0]
group = groups.get(feature_key)
if group is None:
raise KeyError(f"No group label for {session_id}")
qc_outlier = feature_key in QC_OUTLIER_FEATURE_KEYS
log_name = log_by_session.get(session_id)
if log_name is None:
continue
raw_rows = _parse_raw(raw_zip.read(raw_name))
if not raw_rows:
continue
raw_min = int(raw_rows[0]["currentTimeMillis"])
raw_max = int(raw_rows[-1]["currentTimeMillis"])
events = _parse_events(log_zip.read(log_name), raw_start_ms=raw_min)
kept = 0
reached = 0
for sequence, trial in enumerate(events):
start = max(trial["start_ms"], raw_min)
end = min(trial["end_ms"], raw_max)
selected = [
row for row in raw_rows if start <= int(row["currentTimeMillis"]) <= end
]
if end <= start or len(selected) < 2:
continue
trial_id = f"{session_id}__{sequence:02d}_o{trial['object_index']:02d}"
duration = end - start
trial_row = {
"trial_id": trial_id,
"session_id": session_id,
"participant_id": participant_id,
"group": group,
"qc_outlier": qc_outlier,
**trial,
"start_ms": start,
"end_ms": end,
"duration_ms": duration,
"n_frames": len(selected),
}
trials_out.append(trial_row)
kept += 1
reached += trial["status"] == "reached"
for frame_index, row in enumerate(selected):
timestamp = int(row["currentTimeMillis"])
frames_out.append(
{
"trial_id": trial_id,
"session_id": session_id,
"participant_id": participant_id,
"group": group,
"qc_outlier": qc_outlier,
"target_label": trial["target_label"],
"target_name": trial["target_name"],
"repeat_index": trial["repeat_index"],
"status": trial["status"],
"hand": trial["hand"],
"start_inferred": trial["start_inferred"],
"frame_index": frame_index,
"timestamp_ms": timestamp,
"elapsed_ms": timestamp - start,
"progress": round((timestamp - start) / duration, 6),
**{
key: value
for key, value in row.items()
if key not in {"Time", "currentTimeMillis"}
},
}
)
sessions.append(
{
"session_id": session_id,
"participant_id": participant_id,
"group": group,
"qc_outlier": qc_outlier,
"session_datetime": f"{match.group('date').replace('.', '-') }T{match.group('time').replace('.', ':')}",
"visit_index": visit_number - 1,
"n_trials": kept,
"n_reached_trials": reached,
}
)
by_participant: dict[str, list[dict]] = defaultdict(list)
for session in sessions:
by_participant[session["participant_id"]].append(session)
participants_by_group: dict[str, list[str]] = defaultdict(list)
for participant_id, participant_sessions in by_participant.items():
participants_by_group[participant_sessions[0]["group"]].append(participant_id)
folds: dict[str, int] = {}
for group, participant_ids in participants_by_group.items():
for index, participant_id in enumerate(sorted(participant_ids)):
folds[participant_id] = index % 5
session_lookup = {session["session_id"]: session for session in sessions}
for session in sessions:
session["fold"] = folds[session["participant_id"]]
for row in trials_out:
row["visit_index"] = session_lookup[row["session_id"]]["visit_index"]
row["fold"] = folds[row["participant_id"]]
for row in frames_out:
row["visit_index"] = session_lookup[row["session_id"]]["visit_index"]
row["fold"] = folds[row["participant_id"]]
coordinate_columns = [
key
for key in frames_out[0]
if key.endswith("-X") or key.endswith("-Y") or key.endswith("-Z")
]
trial_fields = [
"trial_id", "session_id", "participant_id", "group", "qc_outlier", "visit_index", "fold",
"object_index", "target_label", "target_name", "repeat_index", "status", "hand", "start_inferred",
"start_ms", "end_ms", "duration_ms", "n_frames",
]
frame_fields = [
"trial_id", "session_id", "participant_id", "group", "qc_outlier", "visit_index", "fold",
"target_label", "target_name", "repeat_index", "status", "hand", "start_inferred", "frame_index",
"timestamp_ms", "elapsed_ms", "progress", *coordinate_columns,
]
session_fields = [
"session_id", "participant_id", "group", "qc_outlier", "session_datetime", "visit_index", "fold",
"n_trials", "n_reached_trials",
]
split_rows = [
{
"participant_id": participant_id,
"group": participant_sessions[0]["group"],
"fold": folds[participant_id],
}
for participant_id, participant_sessions in sorted(by_participant.items())
]
_write_csv(output_dir / "reach_trials.csv.gz", trial_fields, trials_out)
_write_csv(output_dir / "reach_frames.csv.gz", frame_fields, frames_out)
_write_csv(output_dir / "sessions.csv", session_fields, sessions)
_write_csv(output_dir / "participant_folds.csv", ["participant_id", "group", "fold"], split_rows)
summary = {
"source_sha256": digest,
"participants": len(by_participant),
"sessions": len(sessions),
"trials": len(trials_out),
"frames": len(frames_out),
"groups": Counter(session["group"] for session in sessions),
"participant_groups": Counter(row["group"] for row in split_rows),
"trial_status": Counter(row["status"] for row in trials_out),
"targets": Counter(row["target_name"] for row in trials_out),
"inferred_start_trials": sum(bool(row["start_inferred"]) for row in trials_out),
"qc_outlier_sessions": sorted(
session["session_id"] for session in sessions if session["qc_outlier"]
),
"unmatched_raw_sessions": unmatched_raw_sessions,
"unmatched_log_sessions": unmatched_log_sessions,
"study_preprocessing_exclusions": {
"participant_not_sma": ["1018"],
"participant_without_clinical_record": ["1036"],
"invalid_game": ["1027_2014.07.10"],
"invalid_or_nonstudy_session_dates": invalid_date_sessions,
},
}
summary = {key: dict(value) if isinstance(value, Counter) else value for key, value in summary.items()}
(output_dir / "build_summary.json").write_text(
json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
return summary
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-zip", type=Path, help="Downloaded PLOS supplementary S3 archive")
parser.add_argument("--output-dir", type=Path, default=Path("kinect/data"))
parser.add_argument(
"--download",
type=Path,
metavar="PATH",
help="Download the canonical source archive to PATH before building",
)
args = parser.parse_args(argv)
source = download_source(args.download) if args.download else args.source_zip
if source is None:
parser.error("provide --source-zip or --download")
print(json.dumps(build(source, args.output_dir), indent=2, sort_keys=True))
if __name__ == "__main__":
main()