YannisTevissen commited on
Commit
24c3f28
·
verified ·
1 Parent(s): 796c184

Publish reproducible Kinect build and baseline scripts

Browse files
scripts/build_dataset.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build a reach-intent benchmark from PLOS ONE supplementary archive S3.
2
+
3
+ The builder reads the source archive without extracting it, joins event logs to
4
+ the approximately 16 Hz skeleton stream, and writes viewer-friendly CSV files.
5
+ It intentionally excludes the clinical table and fine-grained demographics.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import csv
12
+ import gzip
13
+ import hashlib
14
+ import io
15
+ import json
16
+ import re
17
+ import urllib.request
18
+ import zipfile
19
+ from collections import Counter, defaultdict
20
+ from datetime import date, datetime
21
+ from pathlib import Path
22
+ from typing import Iterable, Iterator
23
+
24
+ SOURCE_URL = (
25
+ "https://journals.plos.org/plosone/article/file?type=supplementary&"
26
+ "id=info:doi/10.1371/journal.pone.0170472.s003"
27
+ )
28
+ SOURCE_SHA256 = "21fc2ae8d8bce10b3cecd6416fdda390ba98476c9b9abe95be91857aea07d008"
29
+
30
+ TARGET_NAMES = {
31
+ 0: "right_low_45",
32
+ 1: "right_lateral",
33
+ 2: "right_up_30",
34
+ 3: "right_up_60",
35
+ 4: "right_top",
36
+ 5: "left_low_45",
37
+ 6: "left_lateral",
38
+ 7: "left_up_30",
39
+ 8: "left_up_60",
40
+ 9: "left_top",
41
+ }
42
+
43
+ # The two session-level PCA outliers removed in the public analysis workflow.
44
+ QC_OUTLIER_FEATURE_KEYS = {
45
+ "1024_2015.03.19_19.19",
46
+ "1038_2014.12.11_17.45",
47
+ }
48
+
49
+ EVENT_RE = re.compile(
50
+ r"\t(?P<timestamp>\d+)\tObject (?P<object>\d+) "
51
+ r"(?P<event>appeared|timed out|reached by (?P<hand>right|left) hand)!"
52
+ )
53
+ SESSION_RE = re.compile(
54
+ r"(?P<participant>\d+)_(?P<date>\d{4}\.\d{2}\.\d{2})_"
55
+ r"(?P<time>\d{2}\.\d{2}\.\d{2})\.txt$"
56
+ )
57
+
58
+
59
+ def _open_text(data: bytes) -> io.TextIOWrapper:
60
+ return io.TextIOWrapper(io.BytesIO(data), encoding="utf-8-sig", newline="")
61
+
62
+
63
+ def _write_csv(path: Path, fieldnames: list[str], rows: Iterable[dict]) -> None:
64
+ path.parent.mkdir(parents=True, exist_ok=True)
65
+ if path.suffix == ".gz":
66
+ raw = path.open("wb")
67
+ binary = gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0)
68
+ handle = io.TextIOWrapper(binary, encoding="utf-8", newline="")
69
+ else:
70
+ handle = path.open("w", encoding="utf-8", newline="")
71
+ try:
72
+ writer = csv.DictWriter(handle, fieldnames=fieldnames, extrasaction="ignore")
73
+ writer.writeheader()
74
+ writer.writerows(rows)
75
+ finally:
76
+ handle.close()
77
+
78
+
79
+ def download_source(destination: Path) -> Path:
80
+ """Download and checksum the canonical PLOS supplementary archive."""
81
+ destination.parent.mkdir(parents=True, exist_ok=True)
82
+ request = urllib.request.Request(SOURCE_URL, headers={"User-Agent": "open-sma-hub/0.1"})
83
+ with urllib.request.urlopen(request) as response, destination.open("wb") as output:
84
+ while block := response.read(1024 * 1024):
85
+ output.write(block)
86
+ digest = hashlib.sha256(destination.read_bytes()).hexdigest()
87
+ if digest != SOURCE_SHA256:
88
+ destination.unlink(missing_ok=True)
89
+ raise ValueError(f"Source checksum mismatch: expected {SOURCE_SHA256}, got {digest}")
90
+ return destination
91
+
92
+
93
+ def _read_features(outer: zipfile.ZipFile) -> dict[str, str]:
94
+ data = outer.read("S1_Dataset/full_features_class.txt")
95
+ rows = csv.DictReader(_open_text(data), delimiter="\t")
96
+ return {
97
+ row["name"]: "sma" if row["class"].strip().lower() == "sma" else "control"
98
+ for row in rows
99
+ }
100
+
101
+
102
+ def _read_clinical_context(
103
+ outer: zipfile.ZipFile,
104
+ ) -> tuple[set[str], dict[tuple[str, date], int]]:
105
+ """Read only IDs, dates, and visit numbers needed for source-study filtering."""
106
+ rows = csv.DictReader(_open_text(outer.read("S1_Dataset/clinical_data.csv")))
107
+ participants: set[str] = set()
108
+ visits: dict[tuple[str, date], int] = {}
109
+ for row in rows:
110
+ participant_id = row["ID"]
111
+ participants.add(participant_id)
112
+ visits[(participant_id, datetime.strptime(row["DATE"], "%d.%m.%Y").date())] = int(
113
+ row["VISIT"]
114
+ )
115
+ return participants, visits
116
+
117
+
118
+ def _parse_raw(data: bytes) -> list[dict[str, str]]:
119
+ reader = csv.DictReader(_open_text(data), delimiter="\t")
120
+ rows = []
121
+ for row in reader:
122
+ if not row.get("currentTimeMillis"):
123
+ continue
124
+ cleaned = {key.strip(): value.strip() for key, value in row.items() if key is not None}
125
+ cleaned["currentTimeMillis"] = str(int(float(cleaned["currentTimeMillis"])))
126
+ rows.append(cleaned)
127
+ return rows
128
+
129
+
130
+ def _parse_events(data: bytes, raw_start_ms: int | None = None) -> list[dict]:
131
+ active: dict[int, int] = {}
132
+ trials: list[dict] = []
133
+ inferred_first_object_closed = False
134
+ for line in data.decode("utf-8-sig", errors="replace").splitlines():
135
+ match = EVENT_RE.search(line)
136
+ if not match:
137
+ continue
138
+ timestamp = int(match.group("timestamp"))
139
+ object_index = int(match.group("object"))
140
+ event = match.group("event")
141
+ if event == "appeared":
142
+ active[object_index] = timestamp
143
+ elif object_index in active:
144
+ trials.append(
145
+ {
146
+ "object_index": object_index,
147
+ "target_label": object_index % 10,
148
+ "target_name": TARGET_NAMES[object_index % 10],
149
+ "repeat_index": object_index // 10,
150
+ "start_ms": active.pop(object_index),
151
+ "end_ms": timestamp,
152
+ "status": "reached" if event.startswith("reached") else "timed_out",
153
+ "hand": match.group("hand") or "",
154
+ "start_inferred": False,
155
+ }
156
+ )
157
+ elif (
158
+ raw_start_ms is not None
159
+ and object_index == 0
160
+ and timestamp >= raw_start_ms
161
+ and not inferred_first_object_closed
162
+ ):
163
+ # The game source starts object 0 without logging an "appeared" event.
164
+ # Raw recording begins after game initialization, so raw_start_ms is
165
+ # the earliest observable bound for its first presentation.
166
+ trials.append(
167
+ {
168
+ "object_index": 0,
169
+ "target_label": 0,
170
+ "target_name": TARGET_NAMES[0],
171
+ "repeat_index": 0,
172
+ "start_ms": raw_start_ms,
173
+ "end_ms": timestamp,
174
+ "status": "reached" if event.startswith("reached") else "timed_out",
175
+ "hand": match.group("hand") or "",
176
+ "start_inferred": True,
177
+ }
178
+ )
179
+ inferred_first_object_closed = True
180
+ return trials
181
+
182
+
183
+ def _nested_archive(outer: zipfile.ZipFile, name: str) -> zipfile.ZipFile:
184
+ return zipfile.ZipFile(io.BytesIO(outer.read(name)))
185
+
186
+
187
+ def build(source_zip: Path, output_dir: Path) -> dict:
188
+ digest = hashlib.sha256(source_zip.read_bytes()).hexdigest()
189
+ if digest != SOURCE_SHA256:
190
+ raise ValueError(f"Source checksum mismatch: expected {SOURCE_SHA256}, got {digest}")
191
+
192
+ trials_out: list[dict] = []
193
+ frames_out: list[dict] = []
194
+ sessions: list[dict] = []
195
+
196
+ with zipfile.ZipFile(source_zip) as outer:
197
+ groups = _read_features(outer)
198
+ clinical_participants, clinical_visits = _read_clinical_context(outer)
199
+ with _nested_archive(outer, "S1_Dataset/Full_RawData.zip") as raw_zip, _nested_archive(
200
+ outer, "S1_Dataset/Full_LogFile.zip"
201
+ ) as log_zip:
202
+ raw_names = sorted(name for name in raw_zip.namelist() if name.endswith(".txt"))
203
+ log_by_session = {
204
+ Path(name).name.removeprefix("log_").removesuffix(".txt"): name
205
+ for name in log_zip.namelist()
206
+ if name.endswith(".txt")
207
+ }
208
+ raw_session_ids = {Path(name).name.removesuffix(".txt") for name in raw_names}
209
+ unmatched_raw_sessions = sorted(raw_session_ids - set(log_by_session))
210
+ unmatched_log_sessions = sorted(set(log_by_session) - raw_session_ids)
211
+ invalid_date_sessions: list[str] = []
212
+ for raw_name in raw_names:
213
+ filename = Path(raw_name).name
214
+ match = SESSION_RE.match(filename)
215
+ if not match:
216
+ continue
217
+ session_id = filename.removesuffix(".txt")
218
+ participant_id = match.group("participant")
219
+ # Reproduce the public R preprocessing rules from the study.
220
+ if participant_id == "1018": # Marked "not SMA" in StatisticalAnalysis.Rmd.
221
+ continue
222
+ if participant_id not in clinical_participants:
223
+ continue
224
+ if session_id.startswith("1027_2014.07.10_"): # Marked "no real game".
225
+ continue
226
+ session_date = datetime.strptime(match.group("date"), "%Y.%m.%d").date()
227
+ visit_number = clinical_visits.get((participant_id, session_date))
228
+ # These fallbacks exactly reproduce 1_dataPreprocessing.R.
229
+ if visit_number is None and session_date > date(2015, 1, 1):
230
+ visit_number = 4
231
+ if participant_id in {"1035", "1039"} and session_date == date(2014, 12, 18):
232
+ visit_number = 3
233
+ if visit_number is None:
234
+ invalid_date_sessions.append(session_id)
235
+ continue
236
+ feature_key = session_id.rsplit(".", 1)[0]
237
+ group = groups.get(feature_key)
238
+ if group is None:
239
+ raise KeyError(f"No group label for {session_id}")
240
+ qc_outlier = feature_key in QC_OUTLIER_FEATURE_KEYS
241
+ log_name = log_by_session.get(session_id)
242
+ if log_name is None:
243
+ continue
244
+ raw_rows = _parse_raw(raw_zip.read(raw_name))
245
+ if not raw_rows:
246
+ continue
247
+ raw_min = int(raw_rows[0]["currentTimeMillis"])
248
+ raw_max = int(raw_rows[-1]["currentTimeMillis"])
249
+ events = _parse_events(log_zip.read(log_name), raw_start_ms=raw_min)
250
+ kept = 0
251
+ reached = 0
252
+ for sequence, trial in enumerate(events):
253
+ start = max(trial["start_ms"], raw_min)
254
+ end = min(trial["end_ms"], raw_max)
255
+ selected = [
256
+ row for row in raw_rows if start <= int(row["currentTimeMillis"]) <= end
257
+ ]
258
+ if end <= start or len(selected) < 2:
259
+ continue
260
+ trial_id = f"{session_id}__{sequence:02d}_o{trial['object_index']:02d}"
261
+ duration = end - start
262
+ trial_row = {
263
+ "trial_id": trial_id,
264
+ "session_id": session_id,
265
+ "participant_id": participant_id,
266
+ "group": group,
267
+ "qc_outlier": qc_outlier,
268
+ **trial,
269
+ "start_ms": start,
270
+ "end_ms": end,
271
+ "duration_ms": duration,
272
+ "n_frames": len(selected),
273
+ }
274
+ trials_out.append(trial_row)
275
+ kept += 1
276
+ reached += trial["status"] == "reached"
277
+ for frame_index, row in enumerate(selected):
278
+ timestamp = int(row["currentTimeMillis"])
279
+ frames_out.append(
280
+ {
281
+ "trial_id": trial_id,
282
+ "session_id": session_id,
283
+ "participant_id": participant_id,
284
+ "group": group,
285
+ "qc_outlier": qc_outlier,
286
+ "target_label": trial["target_label"],
287
+ "target_name": trial["target_name"],
288
+ "repeat_index": trial["repeat_index"],
289
+ "status": trial["status"],
290
+ "hand": trial["hand"],
291
+ "start_inferred": trial["start_inferred"],
292
+ "frame_index": frame_index,
293
+ "timestamp_ms": timestamp,
294
+ "elapsed_ms": timestamp - start,
295
+ "progress": round((timestamp - start) / duration, 6),
296
+ **{
297
+ key: value
298
+ for key, value in row.items()
299
+ if key not in {"Time", "currentTimeMillis"}
300
+ },
301
+ }
302
+ )
303
+ sessions.append(
304
+ {
305
+ "session_id": session_id,
306
+ "participant_id": participant_id,
307
+ "group": group,
308
+ "qc_outlier": qc_outlier,
309
+ "session_datetime": f"{match.group('date').replace('.', '-') }T{match.group('time').replace('.', ':')}",
310
+ "visit_index": visit_number - 1,
311
+ "n_trials": kept,
312
+ "n_reached_trials": reached,
313
+ }
314
+ )
315
+
316
+ by_participant: dict[str, list[dict]] = defaultdict(list)
317
+ for session in sessions:
318
+ by_participant[session["participant_id"]].append(session)
319
+ participants_by_group: dict[str, list[str]] = defaultdict(list)
320
+ for participant_id, participant_sessions in by_participant.items():
321
+ participants_by_group[participant_sessions[0]["group"]].append(participant_id)
322
+ folds: dict[str, int] = {}
323
+ for group, participant_ids in participants_by_group.items():
324
+ for index, participant_id in enumerate(sorted(participant_ids)):
325
+ folds[participant_id] = index % 5
326
+
327
+ session_lookup = {session["session_id"]: session for session in sessions}
328
+ for session in sessions:
329
+ session["fold"] = folds[session["participant_id"]]
330
+ for row in trials_out:
331
+ row["visit_index"] = session_lookup[row["session_id"]]["visit_index"]
332
+ row["fold"] = folds[row["participant_id"]]
333
+ for row in frames_out:
334
+ row["visit_index"] = session_lookup[row["session_id"]]["visit_index"]
335
+ row["fold"] = folds[row["participant_id"]]
336
+
337
+ coordinate_columns = [
338
+ key
339
+ for key in frames_out[0]
340
+ if key.endswith("-X") or key.endswith("-Y") or key.endswith("-Z")
341
+ ]
342
+ trial_fields = [
343
+ "trial_id", "session_id", "participant_id", "group", "qc_outlier", "visit_index", "fold",
344
+ "object_index", "target_label", "target_name", "repeat_index", "status", "hand", "start_inferred",
345
+ "start_ms", "end_ms", "duration_ms", "n_frames",
346
+ ]
347
+ frame_fields = [
348
+ "trial_id", "session_id", "participant_id", "group", "qc_outlier", "visit_index", "fold",
349
+ "target_label", "target_name", "repeat_index", "status", "hand", "start_inferred", "frame_index",
350
+ "timestamp_ms", "elapsed_ms", "progress", *coordinate_columns,
351
+ ]
352
+ session_fields = [
353
+ "session_id", "participant_id", "group", "qc_outlier", "session_datetime", "visit_index", "fold",
354
+ "n_trials", "n_reached_trials",
355
+ ]
356
+ split_rows = [
357
+ {
358
+ "participant_id": participant_id,
359
+ "group": participant_sessions[0]["group"],
360
+ "fold": folds[participant_id],
361
+ }
362
+ for participant_id, participant_sessions in sorted(by_participant.items())
363
+ ]
364
+
365
+ _write_csv(output_dir / "reach_trials.csv.gz", trial_fields, trials_out)
366
+ _write_csv(output_dir / "reach_frames.csv.gz", frame_fields, frames_out)
367
+ _write_csv(output_dir / "sessions.csv", session_fields, sessions)
368
+ _write_csv(output_dir / "participant_folds.csv", ["participant_id", "group", "fold"], split_rows)
369
+
370
+ summary = {
371
+ "source_sha256": digest,
372
+ "participants": len(by_participant),
373
+ "sessions": len(sessions),
374
+ "trials": len(trials_out),
375
+ "frames": len(frames_out),
376
+ "groups": Counter(session["group"] for session in sessions),
377
+ "participant_groups": Counter(row["group"] for row in split_rows),
378
+ "trial_status": Counter(row["status"] for row in trials_out),
379
+ "targets": Counter(row["target_name"] for row in trials_out),
380
+ "inferred_start_trials": sum(bool(row["start_inferred"]) for row in trials_out),
381
+ "qc_outlier_sessions": sorted(
382
+ session["session_id"] for session in sessions if session["qc_outlier"]
383
+ ),
384
+ "unmatched_raw_sessions": unmatched_raw_sessions,
385
+ "unmatched_log_sessions": unmatched_log_sessions,
386
+ "study_preprocessing_exclusions": {
387
+ "participant_not_sma": ["1018"],
388
+ "participant_without_clinical_record": ["1036"],
389
+ "invalid_game": ["1027_2014.07.10"],
390
+ "invalid_or_nonstudy_session_dates": invalid_date_sessions,
391
+ },
392
+ }
393
+ summary = {key: dict(value) if isinstance(value, Counter) else value for key, value in summary.items()}
394
+ (output_dir / "build_summary.json").write_text(
395
+ json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
396
+ )
397
+ return summary
398
+
399
+
400
+ def main(argv: list[str] | None = None) -> None:
401
+ parser = argparse.ArgumentParser(description=__doc__)
402
+ parser.add_argument("--source-zip", type=Path, help="Downloaded PLOS supplementary S3 archive")
403
+ parser.add_argument("--output-dir", type=Path, default=Path("kinect/data"))
404
+ parser.add_argument(
405
+ "--download",
406
+ type=Path,
407
+ metavar="PATH",
408
+ help="Download the canonical source archive to PATH before building",
409
+ )
410
+ args = parser.parse_args(argv)
411
+ source = download_source(args.download) if args.download else args.source_zip
412
+ if source is None:
413
+ parser.error("provide --source-zip or --download")
414
+ print(json.dumps(build(source, args.output_dir), indent=2, sort_keys=True))
415
+
416
+
417
+ if __name__ == "__main__":
418
+ main()
scripts/download_original.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Download the canonical PLOS supplementary archive and verify its checksum."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import urllib.request
8
+ from pathlib import Path
9
+
10
+ URL = "https://journals.plos.org/plosone/article/file?type=supplementary&id=info:doi/10.1371/journal.pone.0170472.s003"
11
+ SHA256 = "21fc2ae8d8bce10b3cecd6416fdda390ba98476c9b9abe95be91857aea07d008"
12
+
13
+
14
+ def main() -> None:
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument("output", type=Path, nargs="?", default=Path("plos_s3_dataset.zip"))
17
+ args = parser.parse_args()
18
+ request = urllib.request.Request(URL, headers={"User-Agent": "open-sma-hub/0.1"})
19
+ with urllib.request.urlopen(request) as response, args.output.open("wb") as output:
20
+ while block := response.read(1024 * 1024):
21
+ output.write(block)
22
+ digest = hashlib.sha256(args.output.read_bytes()).hexdigest()
23
+ if digest != SHA256:
24
+ args.output.unlink(missing_ok=True)
25
+ raise SystemExit(f"Checksum mismatch: expected {SHA256}, got {digest}")
26
+ print(f"Verified {args.output} ({digest})")
27
+
28
+
29
+ if __name__ == "__main__":
30
+ main()
31
+
scripts/evaluate_baseline.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dependency-free nearest-centroid baselines for the reach-intent benchmark."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import gzip
8
+ import json
9
+ import math
10
+ from collections import defaultdict
11
+ from pathlib import Path
12
+
13
+ CHECKPOINTS = (0.25, 0.50, 1.00)
14
+
15
+
16
+ def read_rows(path: Path):
17
+ opener = gzip.open if path.suffix == ".gz" else open
18
+ with opener(path, "rt", encoding="utf-8", newline="") as handle:
19
+ yield from csv.DictReader(handle)
20
+
21
+
22
+ def vector(row, initial):
23
+ values = []
24
+ for side in ("Right", "Left"):
25
+ for axis in ("X", "Y", "Z"):
26
+ hand = float(row[f"{side}Hand-{axis}"])
27
+ shoulder = float(row[f"{side}Shoulder-{axis}"])
28
+ start_hand = float(initial[f"{side}Hand-{axis}"])
29
+ values.extend((hand - shoulder, hand - start_hand))
30
+ shoulder_width = math.sqrt(
31
+ sum(
32
+ (float(row[f"RightShoulder-{axis}"]) - float(row[f"LeftShoulder-{axis}"])) ** 2
33
+ for axis in ("X", "Y", "Z")
34
+ )
35
+ )
36
+ scale = max(shoulder_width, 1.0)
37
+ return tuple(value / scale for value in values)
38
+
39
+
40
+ def load_examples(
41
+ data_dir: Path,
42
+ checkpoint: float,
43
+ exclude_inferred: bool = False,
44
+ exclude_qc_outliers: bool = True,
45
+ ):
46
+ trials = {
47
+ row["trial_id"]: row
48
+ for row in read_rows(data_dir / "reach_trials.csv.gz")
49
+ if row["status"] == "reached"
50
+ and not (exclude_inferred and row["start_inferred"].lower() == "true")
51
+ and not (exclude_qc_outliers and row["qc_outlier"].lower() == "true")
52
+ }
53
+ first, selected = {}, {}
54
+ for row in read_rows(data_dir / "reach_frames.csv.gz"):
55
+ trial_id = row["trial_id"]
56
+ if trial_id not in trials:
57
+ continue
58
+ first.setdefault(trial_id, row)
59
+ progress = float(row["progress"])
60
+ if progress <= checkpoint:
61
+ selected[trial_id] = row
62
+ examples = []
63
+ for trial_id, row in selected.items():
64
+ metadata = trials[trial_id]
65
+ examples.append(
66
+ {
67
+ **metadata,
68
+ "label": int(metadata["target_label"]),
69
+ "fold": int(metadata["fold"]),
70
+ "visit": int(metadata["visit_index"]),
71
+ "x": vector(row, first[trial_id]),
72
+ }
73
+ )
74
+ return examples
75
+
76
+
77
+ def centroid(rows):
78
+ return tuple(sum(row["x"][i] for row in rows) / len(rows) for i in range(len(rows[0]["x"])))
79
+
80
+
81
+ def prototypes(rows):
82
+ by_label = defaultdict(list)
83
+ for row in rows:
84
+ by_label[row["label"]].append(row)
85
+ return {label: centroid(items) for label, items in by_label.items()}
86
+
87
+
88
+ def predict(x, centers):
89
+ return min(centers, key=lambda label: sum((a - b) ** 2 for a, b in zip(x, centers[label])))
90
+
91
+
92
+ def metrics(pairs):
93
+ if not pairs:
94
+ return {"n": 0, "accuracy": None, "macro_recall": None, "by_group": {}}
95
+ recalls, by_group = [], defaultdict(list)
96
+ for label in range(10):
97
+ subset = [(truth, pred) for truth, pred, _ in pairs if truth == label]
98
+ if subset:
99
+ recalls.append(sum(truth == pred for truth, pred in subset) / len(subset))
100
+ for truth, pred, group in pairs:
101
+ by_group[group].append(truth == pred)
102
+ return {
103
+ "n": len(pairs),
104
+ "accuracy": round(sum(truth == pred for truth, pred, _ in pairs) / len(pairs), 4),
105
+ "macro_recall": round(sum(recalls) / len(recalls), 4),
106
+ "by_group": {
107
+ group: round(sum(values) / len(values), 4) for group, values in sorted(by_group.items())
108
+ },
109
+ }
110
+
111
+
112
+ def generic(examples):
113
+ pairs = []
114
+ for fold in range(5):
115
+ train = [row for row in examples if row["fold"] != fold]
116
+ test = [row for row in examples if row["fold"] == fold]
117
+ centers = prototypes(train)
118
+ pairs.extend((row["label"], predict(row["x"], centers), row["group"]) for row in test)
119
+ return metrics(pairs)
120
+
121
+
122
+ def personalized(examples, shots, prior_weight=5):
123
+ """Compare generic, personal-only, and prior-weighted adaptation fairly."""
124
+ generic_pairs, personal_pairs, adapted_pairs = [], [], []
125
+ for fold in range(5):
126
+ generic_centers = prototypes([row for row in examples if row["fold"] != fold])
127
+ people = defaultdict(list)
128
+ for row in examples:
129
+ if row["fold"] == fold:
130
+ people[row["participant_id"]].append(row)
131
+ for rows in people.values():
132
+ ordered = sorted(
133
+ rows, key=lambda row: (row["visit"], row["session_id"], row["trial_id"])
134
+ )
135
+ by_label = defaultdict(list)
136
+ for row in ordered:
137
+ by_label[row["label"]].append(row)
138
+ calibration_by_label = {
139
+ label: items[:shots] for label, items in by_label.items() if items[:shots]
140
+ }
141
+ test = [row for items in by_label.values() for row in items[shots:]]
142
+ personal_centers = {
143
+ label: centroid(items) for label, items in calibration_by_label.items()
144
+ }
145
+ adapted_centers = dict(generic_centers)
146
+ for label, personal_center in personal_centers.items():
147
+ n_personal = len(calibration_by_label[label])
148
+ adapted_centers[label] = tuple(
149
+ (prior_weight * generic_value + n_personal * personal_value)
150
+ / (prior_weight + n_personal)
151
+ for generic_value, personal_value in zip(
152
+ generic_centers[label], personal_center
153
+ )
154
+ )
155
+ for row in test:
156
+ item = (row["label"], row["group"])
157
+ generic_pairs.append((item[0], predict(row["x"], generic_centers), item[1]))
158
+ personal_pairs.append((item[0], predict(row["x"], personal_centers), item[1]))
159
+ adapted_pairs.append((item[0], predict(row["x"], adapted_centers), item[1]))
160
+ generic_metrics = metrics(generic_pairs)
161
+ personal_metrics = metrics(personal_pairs)
162
+ adapted_metrics = metrics(adapted_pairs)
163
+ gain = None
164
+ if adapted_metrics["accuracy"] is not None and generic_metrics["accuracy"] is not None:
165
+ gain = round(adapted_metrics["accuracy"] - generic_metrics["accuracy"], 4)
166
+ return {
167
+ "generic_on_same_test": generic_metrics,
168
+ "personal_only": personal_metrics,
169
+ "adapted": adapted_metrics,
170
+ "adapted_accuracy_gain": gain,
171
+ "generic_prior_weight": prior_weight,
172
+ }
173
+
174
+
175
+ def cross_visit(examples):
176
+ pairs = []
177
+ people = defaultdict(list)
178
+ for row in examples:
179
+ people[row["participant_id"]].append(row)
180
+ for rows in people.values():
181
+ calibration = [row for row in rows if row["visit"] == 0]
182
+ test = [row for row in rows if row["visit"] > 0]
183
+ centers = prototypes(calibration)
184
+ pairs.extend((row["label"], predict(row["x"], centers), row["group"]) for row in test)
185
+ return metrics(pairs)
186
+
187
+
188
+ def main():
189
+ parser = argparse.ArgumentParser()
190
+ parser.add_argument("--data-dir", type=Path, default=Path("data"))
191
+ parser.add_argument("--output", type=Path)
192
+ args = parser.parse_args()
193
+ result = {}
194
+ for checkpoint in CHECKPOINTS:
195
+ result[str(checkpoint)] = {}
196
+ for slice_name, exclude_inferred, exclude_qc_outliers in (
197
+ ("paper_qc", False, True),
198
+ ("paper_qc_explicit_start_only", True, True),
199
+ ("all_exact_pairs", False, False),
200
+ ):
201
+ examples = load_examples(
202
+ args.data_dir,
203
+ checkpoint,
204
+ exclude_inferred=exclude_inferred,
205
+ exclude_qc_outliers=exclude_qc_outliers,
206
+ )
207
+ result[str(checkpoint)][slice_name] = {
208
+ "generic_5_fold": generic(examples),
209
+ "personalized_1_shot": personalized(examples, 1),
210
+ "personalized_5_shot": personalized(examples, 5),
211
+ "cross_visit": cross_visit(examples),
212
+ }
213
+ rendered = json.dumps(result, indent=2, sort_keys=True) + "\n"
214
+ if args.output:
215
+ args.output.write_text(rendered, encoding="utf-8")
216
+ print(rendered, end="")
217
+
218
+
219
+ if __name__ == "__main__":
220
+ main()