Download pyem_data.py from princessamygdala/TreasureHuntForTwo: direct link, hf CLI and curl.
- Browser
- Download file 4.4 kB
-
https://huggingface.co/spaces/princessamygdala/TreasureHuntForTwo/resolve/main/pyem_data.py
- Command line
-
hf download hf://spaces/princessamygdala/TreasureHuntForTwo/pyem_data.py
-
curl -L -o pyem_data.py https://huggingface.co/spaces/princessamygdala/TreasureHuntForTwo/resolve/main/pyem_data.py
4.4 kB
| """ | |
| Load TreasureHuntForTwo data (the GitLab `*_data.csv` from export_csv.py) into the exact | |
| array format the pyem RL models expect (rl_hp.py / rl_hp.ipynb). | |
| Each subject -> a dict with, per the fit-function signature | |
| `rw*_fit(params, choices, outcomes_self, outcomes_other, option_pairs, ...)`: | |
| choices (12, 16) chosen letter 'A'..'D' | |
| outcomes_self (12, 16) in {-1, 0, +1} (0 = the neutral trials; RW handles them fine) | |
| outcomes_other (12, 16) in {-1, 0, +1} | |
| option_pairs (12, 16, 2) the two shown letters, e.g. ['B','D'] | |
| Main-task trials only (practice dropped). Matches the OG task's block/trial structure exactly | |
| (12 blocks x 16 trials, 6 pairs x 2). | |
| Usage: | |
| from pyem_data import load_subjects, to_all_data | |
| subs = load_subjects("data/*_data.csv") # one dict per participant | |
| all_data = to_all_data(subs) # just the fit kwargs | |
| model = EMModel(all_data=all_data, fit_func=rw1q1a1b_fit, | |
| param_names=["beta", "alpha"], param_xform=[norm2beta, norm2alpha]) | |
| model.fit() | |
| """ | |
| import csv | |
| import glob | |
| import numpy as np | |
| NBLOCKS, NTRIALS = 12, 16 | |
| FIT_KEYS = ("choices", "outcomes_self", "outcomes_other", "option_pairs") | |
| def load_subject(csv_path, nblocks=NBLOCKS, ntrials=NTRIALS): | |
| """Build one subject's (nblocks, ntrials) arrays from an exported `*_data.csv`.""" | |
| rows = list(csv.DictReader(open(csv_path))) | |
| tr = [r for r in rows if r.get("row_type") == "trial" and r.get("practice") == "0"] | |
| if not tr: | |
| return None | |
| choices = np.empty((nblocks, ntrials), dtype=object) | |
| outcomes_self = np.zeros((nblocks, ntrials), dtype=int) | |
| outcomes_other = np.zeros((nblocks, ntrials), dtype=int) | |
| option_pairs = np.empty((nblocks, ntrials, 2), dtype=object) | |
| seen = np.zeros((nblocks, ntrials), dtype=bool) | |
| for r in tr: | |
| b, t = int(r["blockIndex"]), int(r["trialIndex"]) | |
| # chosen letter: prefer the direct column, else derive (side + which letter is there) | |
| ch = r.get("chosen_option") or ( | |
| r["option_left"] if r["chosen_side"] == "left" else r["option_right"]) | |
| choices[b, t] = ch | |
| outcomes_self[b, t] = int(r["self_outcome"]) | |
| outcomes_other[b, t] = int(r["other_outcome"]) | |
| pr = r["option_pairs"] # e.g. "BD" | |
| option_pairs[b, t, 0], option_pairs[b, t, 1] = pr[0], pr[1] | |
| seen[b, t] = True | |
| if not seen.all(): | |
| miss = np.argwhere(~seen).tolist() | |
| raise ValueError(f"{csv_path}: {len(miss)} missing (block,trial) cells, e.g. {miss[:5]}") | |
| return dict(pid=tr[0]["pid"], gid=tr[0]["gid"], | |
| choices=choices, outcomes_self=outcomes_self, | |
| outcomes_other=outcomes_other, option_pairs=option_pairs) | |
| def load_subjects(pattern="data/*_data.csv"): | |
| """Load every exported CSV matching `pattern` -> list of per-subject dicts.""" | |
| out = [] | |
| for p in sorted(glob.glob(pattern)): | |
| try: | |
| s = load_subject(p) | |
| except Exception as e: | |
| print(f" skipped {p}: {e}") | |
| continue | |
| if s: | |
| out.append(s) | |
| return out | |
| def to_all_data(subjects): | |
| """Strip to just the fit-function arguments (drop pid/gid) for `EMModel(all_data=...)`. | |
| A TUPLE per subject, in FIT_KEYS order, which is the fit functions' parameter order | |
| after `params`. pyEM documents all_data[i] as "args for objfunc for subject i" and | |
| calls `objfunc(x, *all_data[i])`, so a dict unpacks to its KEYS: every fit got the | |
| four strings "choices", "outcomes_self", ... in place of its arrays and died inside | |
| joblib with `int() argument must be ... not NoneType`, from vectorizing a letter | |
| lookup over the characters of the word "choices". This returned dicts until | |
| 2026-11-09 and nothing had run it against the installed pyem. | |
| """ | |
| return [tuple(s[k] for k in FIT_KEYS) for s in subjects] | |
| if __name__ == "__main__": | |
| subs = load_subjects() | |
| print(f"loaded {len(subs)} subject(s)") | |
| for s in subs: | |
| vals_s = sorted(set(int(x) for x in s["outcomes_self"].ravel())) | |
| letters = sorted(set(s["choices"].ravel().tolist())) | |
| print(f" pid={s['pid']} gid={s['gid']} choices{s['choices'].shape}={letters} " | |
| f"outcomes_self{s['outcomes_self'].shape} in {vals_s} " | |
| f"pairs{s['option_pairs'].shape}") | |