"""Dependency-free nearest-centroid baselines for the reach-intent benchmark.""" from __future__ import annotations import argparse import csv import gzip import json import math from collections import defaultdict from pathlib import Path CHECKPOINTS = (0.25, 0.50, 1.00) def read_rows(path: Path): opener = gzip.open if path.suffix == ".gz" else open with opener(path, "rt", encoding="utf-8", newline="") as handle: yield from csv.DictReader(handle) def vector(row, initial): values = [] for side in ("Right", "Left"): for axis in ("X", "Y", "Z"): hand = float(row[f"{side}Hand-{axis}"]) shoulder = float(row[f"{side}Shoulder-{axis}"]) start_hand = float(initial[f"{side}Hand-{axis}"]) values.extend((hand - shoulder, hand - start_hand)) shoulder_width = math.sqrt( sum( (float(row[f"RightShoulder-{axis}"]) - float(row[f"LeftShoulder-{axis}"])) ** 2 for axis in ("X", "Y", "Z") ) ) scale = max(shoulder_width, 1.0) return tuple(value / scale for value in values) def load_examples( data_dir: Path, checkpoint: float, exclude_inferred: bool = False, exclude_qc_outliers: bool = True, ): trials = { row["trial_id"]: row for row in read_rows(data_dir / "reach_trials.csv.gz") if row["status"] == "reached" and not (exclude_inferred and row["start_inferred"].lower() == "true") and not (exclude_qc_outliers and row["qc_outlier"].lower() == "true") } first, selected = {}, {} for row in read_rows(data_dir / "reach_frames.csv.gz"): trial_id = row["trial_id"] if trial_id not in trials: continue first.setdefault(trial_id, row) progress = float(row["progress"]) if progress <= checkpoint: selected[trial_id] = row examples = [] for trial_id, row in selected.items(): metadata = trials[trial_id] examples.append( { **metadata, "label": int(metadata["target_label"]), "fold": int(metadata["fold"]), "visit": int(metadata["visit_index"]), "x": vector(row, first[trial_id]), } ) return examples def centroid(rows): return tuple(sum(row["x"][i] for row in rows) / len(rows) for i in range(len(rows[0]["x"]))) def prototypes(rows): by_label = defaultdict(list) for row in rows: by_label[row["label"]].append(row) return {label: centroid(items) for label, items in by_label.items()} def predict(x, centers): return min(centers, key=lambda label: sum((a - b) ** 2 for a, b in zip(x, centers[label]))) def metrics(pairs): if not pairs: return {"n": 0, "accuracy": None, "macro_recall": None, "by_group": {}} recalls, by_group = [], defaultdict(list) for label in range(10): subset = [(truth, pred) for truth, pred, _ in pairs if truth == label] if subset: recalls.append(sum(truth == pred for truth, pred in subset) / len(subset)) for truth, pred, group in pairs: by_group[group].append(truth == pred) return { "n": len(pairs), "accuracy": round(sum(truth == pred for truth, pred, _ in pairs) / len(pairs), 4), "macro_recall": round(sum(recalls) / len(recalls), 4), "by_group": { group: round(sum(values) / len(values), 4) for group, values in sorted(by_group.items()) }, } def generic(examples): pairs = [] for fold in range(5): train = [row for row in examples if row["fold"] != fold] test = [row for row in examples if row["fold"] == fold] centers = prototypes(train) pairs.extend((row["label"], predict(row["x"], centers), row["group"]) for row in test) return metrics(pairs) def personalized(examples, shots, prior_weight=5): """Compare generic, personal-only, and prior-weighted adaptation fairly.""" generic_pairs, personal_pairs, adapted_pairs = [], [], [] for fold in range(5): generic_centers = prototypes([row for row in examples if row["fold"] != fold]) people = defaultdict(list) for row in examples: if row["fold"] == fold: people[row["participant_id"]].append(row) for rows in people.values(): ordered = sorted( rows, key=lambda row: (row["visit"], row["session_id"], row["trial_id"]) ) by_label = defaultdict(list) for row in ordered: by_label[row["label"]].append(row) calibration_by_label = { label: items[:shots] for label, items in by_label.items() if items[:shots] } test = [row for items in by_label.values() for row in items[shots:]] personal_centers = { label: centroid(items) for label, items in calibration_by_label.items() } adapted_centers = dict(generic_centers) for label, personal_center in personal_centers.items(): n_personal = len(calibration_by_label[label]) adapted_centers[label] = tuple( (prior_weight * generic_value + n_personal * personal_value) / (prior_weight + n_personal) for generic_value, personal_value in zip( generic_centers[label], personal_center ) ) for row in test: item = (row["label"], row["group"]) generic_pairs.append((item[0], predict(row["x"], generic_centers), item[1])) personal_pairs.append((item[0], predict(row["x"], personal_centers), item[1])) adapted_pairs.append((item[0], predict(row["x"], adapted_centers), item[1])) generic_metrics = metrics(generic_pairs) personal_metrics = metrics(personal_pairs) adapted_metrics = metrics(adapted_pairs) gain = None if adapted_metrics["accuracy"] is not None and generic_metrics["accuracy"] is not None: gain = round(adapted_metrics["accuracy"] - generic_metrics["accuracy"], 4) return { "generic_on_same_test": generic_metrics, "personal_only": personal_metrics, "adapted": adapted_metrics, "adapted_accuracy_gain": gain, "generic_prior_weight": prior_weight, } def cross_visit(examples): pairs = [] people = defaultdict(list) for row in examples: people[row["participant_id"]].append(row) for rows in people.values(): calibration = [row for row in rows if row["visit"] == 0] test = [row for row in rows if row["visit"] > 0] centers = prototypes(calibration) pairs.extend((row["label"], predict(row["x"], centers), row["group"]) for row in test) return metrics(pairs) def main(): parser = argparse.ArgumentParser() parser.add_argument("--data-dir", type=Path, default=Path("data")) parser.add_argument("--output", type=Path) args = parser.parse_args() result = {} for checkpoint in CHECKPOINTS: result[str(checkpoint)] = {} for slice_name, exclude_inferred, exclude_qc_outliers in ( ("paper_qc", False, True), ("paper_qc_explicit_start_only", True, True), ("all_exact_pairs", False, False), ): examples = load_examples( args.data_dir, checkpoint, exclude_inferred=exclude_inferred, exclude_qc_outliers=exclude_qc_outliers, ) result[str(checkpoint)][slice_name] = { "generic_5_fold": generic(examples), "personalized_1_shot": personalized(examples, 1), "personalized_5_shot": personalized(examples, 5), "cross_visit": cross_visit(examples), } rendered = json.dumps(result, indent=2, sort_keys=True) + "\n" if args.output: args.output.write_text(rendered, encoding="utf-8") print(rendered, end="") if __name__ == "__main__": main()