Spaces:
Running
Running
Download docs/prereg/make_figures.py from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 8.02 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/docs/prereg/make_figures.py
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/docs/prereg/make_figures.py
-
curl -L -o make_figures.py https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/docs/prereg/make_figures.py
8.02 kB
| """Figures for the preregistration, built from the recovery runs in analysis/. | |
| Nothing here simulates anything new. The recovery panels read | |
| analysis/recovery_cache.pkl, written by recovery.ipynb; the design panels are | |
| drawn from the shipped task constants. Run with the py3_afni_mid interpreter. | |
| python docs/prereg/make_figures.py | |
| """ | |
| import os | |
| import pickle | |
| import sys | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| REPO = os.path.dirname(os.path.dirname(HERE)) | |
| sys.path.insert(0, REPO) | |
| sys.path.insert(0, os.path.join(REPO, "analysis")) | |
| import effort_design as D # noqa: E402 | |
| import effort_models as M # noqa: E402 | |
| plt.rcParams.update({ | |
| # 150, not higher: HuggingFace refuses binaries much over 100 KB in the | |
| # Space repo, and at 6.3 inches wide in the document this is already more | |
| # resolution than Word will show. | |
| "figure.dpi": 150, "savefig.dpi": 150, "font.family": "sans-serif", | |
| "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans"], "font.size": 8, | |
| "axes.titlesize": 9, "axes.labelsize": 8, | |
| "axes.spines.top": False, "axes.spines.right": False, | |
| "axes.grid": True, "grid.alpha": 0.25, "grid.linewidth": 0.5, | |
| "figure.facecolor": "white", | |
| }) | |
| BLUE, GREEN, GREY = "#2b6cb0", "#2f855a", "#6e7280" | |
| CACHE = os.path.join(REPO, "analysis", "recovery_cache.pkl") | |
| def _cache(): | |
| with open(CACHE, "rb") as f: | |
| return pickle.load(f) | |
| def fig_pe_design(path): | |
| """What the effort task offers, and what the model predicts about it.""" | |
| fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.9)) | |
| ax = axes[0] | |
| eff = np.array(D.EFFORT_FRACS) | |
| for r, style in zip(D.REWARDS, ["-o", "-s", "-^"]): | |
| ax.plot(eff, [r] * len(eff), style, color=BLUE, ms=4, lw=0.8, alpha=0.85) | |
| ax.set_xticks(eff); ax.set_xticklabels([f"{int(e*100)}%" for e in eff]) | |
| ax.set_yticks(list(D.REWARDS)) | |
| ax.axhline(D.REST_CREDIT, color=GREY, ls="--", lw=1) | |
| ax.text(eff[-1], D.REST_CREDIT + 0.3, "rest pays 2", ha="right", color=GREY, fontsize=7) | |
| ax.set_xlabel("effort required (% of own calibrated maximum)") | |
| ax.set_ylabel("credits offered for working") | |
| ax.set_title("The 12 offers, each run once per beneficiary per block") | |
| ax.set_ylim(0, 11) | |
| ax = axes[1] | |
| grid = np.linspace(0.3, 0.85, 120) | |
| for k, label, col in ((8.0, "k = 8", BLUE), (14.0, "k = 14", GREEN)): | |
| for r, ls in zip(D.REWARDS, ["-", "--", ":"]): | |
| v = r - k * grid ** 2 - D.REST_CREDIT | |
| ax.plot(grid, 1 / (1 + np.exp(-1.5 * v)), ls, color=col, lw=1.1) | |
| ax.set_xlabel("effort required (fraction of maximum)") | |
| ax.set_ylabel("P(choose work)") | |
| ax.set_title("Predicted choices, beta = 1.5\nblue k = 8, green k = 14; line style = 3, 6, 10 credits") | |
| ax.set_ylim(0, 1) | |
| fig.tight_layout(); fig.savefig(path); plt.close(fig) | |
| return path | |
| def fig_pe_param_recovery(path): | |
| c = _cache() | |
| pr = c[("param_recovery", "2k1b_par", 100, (24, 48, 72, 96), 20260827)] | |
| d = pr[48] | |
| names = M.param_names(M.MODELS["2k1b_par"]) | |
| fig, axes = plt.subplots(1, len(names) + 1, figsize=(9.2, 2.5)) | |
| for j, nm in enumerate(names): | |
| ax = axes[j] | |
| t, e = d["true"][:, j], d["est"][:, j] | |
| ax.scatter(t, e, s=7, color=BLUE, alpha=0.6, linewidths=0) | |
| lo, hi = min(t.min(), e.min()), max(t.max(), e.max()) | |
| ax.plot([lo, hi], [lo, hi], color=GREY, lw=0.8, ls="--") | |
| ax.set_title(f"{nm}\nr = {np.corrcoef(t, e)[0,1]:+.2f}") | |
| ax.set_xlabel("true"); ax.set_ylabel("recovered" if j == 0 else "") | |
| ax = axes[-1] | |
| gt = d["true"][:, 1] - d["true"][:, 0] | |
| ge = d["est"][:, 1] - d["est"][:, 0] | |
| ax.scatter(gt, ge, s=7, color=GREEN, alpha=0.6, linewidths=0) | |
| lo, hi = min(gt.min(), ge.min()), max(gt.max(), ge.max()) | |
| ax.plot([lo, hi], [lo, hi], color=GREY, lw=0.8, ls="--") | |
| ax.set_title(f"k_other - k_self\nr = {np.corrcoef(gt, ge)[0,1]:+.2f}") | |
| ax.set_xlabel("true"); ax.set_ylabel("") | |
| fig.tight_layout(); fig.savefig(path); plt.close(fig) | |
| return path | |
| def fig_pe_model_recovery(path): | |
| c = _cache() | |
| mat = c[("model_recovery", 40, (24, 48), 20260827)][48] | |
| m = mat.to_numpy(dtype=float) | |
| # one row per generating model: which fitted model won, by lowest iBIC | |
| win = np.zeros_like(m) | |
| win[np.arange(m.shape[0]), m.argmin(axis=1)] = 1 | |
| fig, ax = plt.subplots(figsize=(4.4, 3.8)) | |
| ax.imshow(win, cmap="Blues", vmin=0, vmax=1.4) | |
| ax.set_xticks(range(len(mat.columns))) | |
| ax.set_xticklabels(mat.columns, rotation=90, fontsize=7) | |
| ax.set_yticks(range(len(mat.index))) | |
| ax.set_yticklabels(mat.index, fontsize=7) | |
| for i in range(m.shape[0]): | |
| for j in range(m.shape[1]): | |
| if win[i, j]: | |
| ax.text(j, i, "x", ha="center", va="center", fontsize=9, color="white") | |
| ax.set_xlabel("fitted model (lowest integrated BIC)") | |
| ax.set_ylabel("generating model") | |
| ax.set_title("Model recovery, 48 trials") | |
| ax.grid(False) | |
| correct = int(np.trace(win)) | |
| fig.text(0.5, 0.005, f"{correct} of {m.shape[0]} recovered", ha="center", fontsize=8) | |
| fig.tight_layout(); fig.savefig(path); plt.close(fig) | |
| return path, correct, m.shape[0] | |
| def fig_pe_trials(path): | |
| c = _cache() | |
| pr = c[("param_recovery", "2k1b_par", 100, (24, 48, 72, 96), 20260827)] | |
| counts = sorted(pr) | |
| names = M.param_names(M.MODELS["2k1b_par"]) | |
| fig, ax = plt.subplots(figsize=(4.4, 2.9)) | |
| for j, nm in enumerate(names): | |
| rs = [np.corrcoef(pr[n]["true"][:, j], pr[n]["est"][:, j])[0, 1] for n in counts] | |
| ax.plot(counts, rs, "-o", ms=4, lw=1.2, label=nm) | |
| rs = [np.corrcoef(pr[n]["true"][:, 1] - pr[n]["true"][:, 0], | |
| pr[n]["est"][:, 1] - pr[n]["est"][:, 0])[0, 1] for n in counts] | |
| ax.plot(counts, rs, "-o", ms=4, lw=1.2, color=GREY, label="k_other - k_self") | |
| ax.axhline(0.7, color="#c0392b", ls="--", lw=1) | |
| ax.axvline(48, color="#333", ls=":", lw=1) | |
| ax.text(48.8, 0.02, "shipped", fontsize=7, color="#333") | |
| ax.set_xlabel("trials"); ax.set_ylabel("recovery (Pearson r)") | |
| ax.set_ylim(0, 1); ax.legend(fontsize=7, frameon=False) | |
| ax.set_title("Recovery against trial count, 100 participants") | |
| fig.tight_layout(); fig.savefig(path); plt.close(fig) | |
| return path | |
| def fig_sl_outcomes(path): | |
| """The learning task's outcome structure: exact counts, not a draw.""" | |
| kinds = [("A", "good", "good"), ("B", "good", "bad"), | |
| ("C", "bad", "good"), ("D", "bad", "bad")] | |
| fig, axes = plt.subplots(1, 4, figsize=(7.6, 2.4), sharey=True) | |
| for ax, (letter, s_, o_) in zip(axes, kinds): | |
| for i, (who, prof, col) in enumerate((("you", s_, BLUE), ("partner", o_, GREEN))): | |
| counts = [12, 2, 2] if prof == "good" else [2, 12, 2] | |
| ax.bar(np.arange(3) + (i - 0.5) * 0.36, counts, width=0.34, | |
| color=col, label=who if letter == "A" else None) | |
| ax.set_xticks(range(3)); ax.set_xticklabels(["+10", "-10", "0"], fontsize=7) | |
| ax.set_title(f"{letter} ({s_}/{o_})", fontsize=8) | |
| ax.set_ylim(0, 14) | |
| axes[0].set_ylabel("trials out of 16") | |
| axes[0].legend(fontsize=7, frameon=False, loc="upper right") | |
| fig.suptitle("Learning task: coin outcomes per chest kind, per 16-trial house", fontsize=9) | |
| fig.tight_layout(); fig.savefig(path); plt.close(fig) | |
| return path | |
| if __name__ == "__main__": | |
| out = [] | |
| out.append(fig_pe_design(os.path.join(HERE, "fig_pe_design.png"))) | |
| out.append(fig_pe_param_recovery(os.path.join(HERE, "fig_pe_param_recovery.png"))) | |
| p, correct, total = fig_pe_model_recovery(os.path.join(HERE, "fig_pe_model_recovery.png")) | |
| out.append(p) | |
| out.append(fig_pe_trials(os.path.join(HERE, "fig_pe_trials.png"))) | |
| out.append(fig_sl_outcomes(os.path.join(HERE, "fig_sl_outcomes.png"))) | |
| for o in out: | |
| print("wrote", os.path.basename(o)) | |
| print(f"model recovery at 48 trials: {correct}/{total}") | |