Spaces:
Running
Running
Download analysis/build_trials_notebook.py from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/analysis/build_trials_notebook.py
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/analysis/build_trials_notebook.py
-
curl -L -o build_trials_notebook.py https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/analysis/build_trials_notebook.py
19 kB
| """Generate trials_needed.ipynb from the results in trials_needed.json. | |
| Separate from build_notebook.py because it answers a different question. That | |
| one asks whether the design works; this one asks how many trials each parameter | |
| costs, and why the self/other gap costs so much more than the parameters it is | |
| built from. | |
| python build_trials_notebook.py | |
| jupyter nbconvert --execute --inplace --ExecutePreprocessor.timeout=-1 \ | |
| trials_needed.ipynb | |
| """ | |
| import nbformat as nbf | |
| nb = nbf.v4.new_notebook() | |
| C = [] | |
| def md(s): | |
| C.append(nbf.v4.new_markdown_cell(s.strip())) | |
| def code(s): | |
| C.append(nbf.v4.new_code_cell(s.strip())) | |
| md(r""" | |
| # How many trials does each parameter need? | |
| One question, asked for every parameter of every model: with 100 participants, | |
| at what trial count does its recovery correlation reach 0.7? | |
| Recovery is measured on simulated data, where the true parameter values are | |
| known, so the answers describe the design. | |
| No participant data enters them. | |
| ## What the task runs now | |
| | block | trials | | |
| |---|---| | |
| | day task, SELF and OTHER interleaved | 48, the 24-cell grid twice | | |
| | Night 1, raid or sleep | 24 | | |
| | Night 2, whose pocket | 24 | | |
| ## Where the assumed parameter values come from | |
| Recovery numbers depend on what the parameters are assumed to be. | |
| $k$ is drawn from 6 to 18. Lockwood et al. (2017, 2021) offered a rest option of | |
| 1 credit at 0% MVC against work options of 2 to 10 credits at 30 to 70% MVC. | |
| Setting $R - kE^2 = 1$ at the middle of that design gives $k$ near 10 to 20. | |
| An earlier version of this analysis drew $k$ from 3 to 9, anchored to this | |
| project's own pilot. That was wrong on two counts. The pilot ran a different | |
| design, with rewards of 2, 6 and 10 and an effort level set at 95% of measured | |
| capacity, and its nine sessions were mostly the researcher's own trial runs. | |
| The choice of range decides which reward levels look informative: under the | |
| pilot anchor the 10-credit trials appeared to carry almost no information, when | |
| at the published scale they are what measures participants who rarely work. | |
| The self/other difference is drawn with a standard deviation of 1.5. An earlier | |
| version used 0.8, which handicapped it before the design was considered, since | |
| recovery tracks true variance against measurement error. Both numbers are | |
| assumptions and the difference score results below are conditional on this one. | |
| """) | |
| code(""" | |
| import json | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib as mpl | |
| import matplotlib.pyplot as plt | |
| R = json.load(open("trials_needed.json")) | |
| results, thresholds = R["results"], R["threshold"] | |
| N_SUBJECTS, TARGET = R["n_subjects"], R["target"] | |
| mpl.rcParams.update({ | |
| "figure.dpi": 120, "savefig.dpi": 120, "font.size": 10, | |
| "axes.titlesize": 11, "axes.labelsize": 10, | |
| "axes.spines.top": False, "axes.spines.right": False, | |
| "axes.grid": True, "grid.alpha": 0.25, "grid.linewidth": 0.6, | |
| "figure.facecolor": "white", "axes.facecolor": "white", | |
| }) | |
| MUTED = "#6e7280" | |
| BLUE, ORANGE, GREEN, PURPLE = "#2b6cb0", "#c05621", "#2f855a", "#6b46c1" | |
| COLORS = [BLUE, ORANGE, GREEN, PURPLE] | |
| SHIPPED = {"day task (SELF/OTHER)": 48, "night 1 (raid)": 24, | |
| "night 2 (whose pocket)": 24} | |
| print(f"{N_SUBJECTS} participants per point, one fit per point, target r = {TARGET}") | |
| print(f"trial counts tested: {sorted(int(k) for k in next(iter(results.values())))}") | |
| """) | |
| md(r""" | |
| ## The three models in the figure | |
| Each panel fits a different decision, so the parameters are not comparable | |
| across panels. All three use the same softmax: the probability of choosing an | |
| option rises with how much more it is worth, and $\beta$ sets how sharply. | |
| $E$ is the required effort as a fraction of that participant's own calibrated | |
| maximum, so it runs from 0.35 to 0.80 and means the same thing for a strong and | |
| a weak participant. Rewards are in credits. The squared term is the parabolic | |
| discounting that won the model comparison in Lockwood et al. (2017). | |
| ### Day task, SELF and OTHER | |
| $$V_{work} = R - k_{agent}E^{2}, \qquad V_{rest} = 2$$ | |
| $$P(\text{work}) = \sigma\!\big(\beta(R - k_{agent}E^{2} - 2)\big)$$ | |
| $k_{agent}$ is $k_{self}$ on trials paying the participant and $k_{other}$ on | |
| trials paying the partner. $R$ is 3, 6 or 10 credits; resting always pays 2. | |
| | parameter | meaning | rises when | | |
| |---|---|---| | |
| | $k_{self}$ | how steeply effort devalues a reward for oneself | the participant rests more on SELF trials | | |
| | $k_{other}$ | the same for the partner | the participant rests more on OTHER trials | | |
| | $\beta$ | choice consistency | choices follow value more closely | | |
| | gap | $k_{other} - k_{self}$, derived by subtracting two fitted values | effort is spent less readily for the partner | | |
| ### Night 1, raid or stay asleep | |
| $$V_{raid} = g - h\,l - kE^{2}, \qquad V_{sleep} = 2$$ | |
| $$P(\text{raid}) = \sigma\!\big(\beta(g - h\,l - kE^{2} - 2)\big)$$ | |
| $g$ is what the raid pays the participant and $l$ is what it costs the sleeping | |
| partner. The design crosses them orthogonally, so what a credit gained is worth | |
| is estimated separately from what taking one costs. | |
| | parameter | meaning | rises when | | |
| |---|---|---| | |
| | $h$ | harm aversion, how much a credit taken off the partner cancels a credit gained | the participant avoids raids that cost the partner a lot | | |
| | $k$ | effort discounting, as above | the participant avoids high-effort raids | | |
| | $\beta$ | choice consistency | | | |
| $h = 0$ is pure self-interest and sits in the model family as the null. | |
| ### Night 2, whose pocket | |
| The harvest happens either way and the effort is identical on both options, so | |
| the two effort terms cancel and only their difference survives: | |
| $$V_{self} = a - k_{self}E^{2}, \qquad V_{partner} = w\,b - k_{other}E^{2}$$ | |
| $$V_{self} - V_{partner} = a - w\,b + \Delta k\,E^{2}, | |
| \qquad \Delta k \equiv k_{other} - k_{self}$$ | |
| $$P(\text{keep it}) = \sigma\!\big(\beta(a - w\,b + \Delta k\,E^{2})\big)$$ | |
| $a$ is what the harvest pays the participant if pocketed, $b$ what it pays the | |
| partner if left. | |
| | parameter | meaning | rises when | | |
| |---|---|---| | |
| | $w$ | social weight, what a credit in the partner's pocket is worth relative to one in the participant's | the participant leaves more of the harvest | | |
| | $\Delta k$ | $k_{other} - k_{self}$, fitted directly here as one parameter | effort feels costlier when it benefits the partner, so keeping becomes more attractive at high effort | | |
| | $\beta$ | choice consistency | | | |
| Because effort is matched across the two options, Night 2 cannot estimate | |
| $k_{self}$ and $k_{other}$ separately. It sees only $\Delta k$. | |
| With $k_{other} > k_{self}$, helping costs more as effort rises, | |
| so keeping the harvest becomes more attractive on harder trials, and $\Delta k$ | |
| enters with a plus. An earlier version of this code carried a minus while | |
| drawing $\Delta k$ positive, which simulated the opposite behaviour. Recovery | |
| magnitudes were unaffected, since the model was fitted to data it had generated | |
| itself, but the simulated direction was wrong. | |
| """) | |
| md(r""" | |
| ## What the parameters are assumed to be | |
| Recovery is measured against these draws, so the ranges below set what the | |
| results mean. They are assumptions, and the two that carry the most weight are | |
| called out under the histograms. | |
| """) | |
| code(""" | |
| import trials_needed as T | |
| N_DRAW = 20000 | |
| draws = { | |
| "day task (SELF/OTHER)": (T.day_true(N_DRAW, np.random.default_rng(1)), | |
| ["k_self", "k_other", "beta"]), | |
| "night 1 (raid)": (T.n1_true(N_DRAW, np.random.default_rng(2)), | |
| ["h", "k", "beta"]), | |
| "night 2 (whose pocket)": (T.n2_true(N_DRAW, np.random.default_rng(3)), | |
| ["w", "dk", "beta"]), | |
| } | |
| rows = [] | |
| for label, (arr, names) in draws.items(): | |
| for j, nm in enumerate(names): | |
| v = arr[:, j] | |
| rows.append({"model": label, "parameter": nm, "min": v.min(), | |
| "mean": v.mean(), "max": v.max(), "sd": v.std()}) | |
| if label.startswith("day"): | |
| g = arr[:, 1] - arr[:, 0] | |
| rows.append({"model": label, "parameter": "gap (derived)", "min": g.min(), | |
| "mean": g.mean(), "max": g.max(), "sd": g.std()}) | |
| pd.DataFrame(rows).set_index(["model", "parameter"]).round(2) | |
| """) | |
| code(""" | |
| fig, axes = plt.subplots(3, 4, figsize=(14, 8)) | |
| for row, (label, (arr, names)) in enumerate(draws.items()): | |
| cols = list(names) | |
| vals = [arr[:, j] for j in range(arr.shape[1])] | |
| if label.startswith("day"): | |
| cols = cols + ["gap = k_other - k_self"] | |
| vals = vals + [arr[:, 1] - arr[:, 0]] | |
| for col in range(4): | |
| ax = axes[row, col] | |
| if col >= len(cols): | |
| ax.axis("off") | |
| continue | |
| v, c = vals[col], COLORS[col % len(COLORS)] | |
| ax.hist(v, bins=60, color=c, alpha=0.85, edgecolor="white", linewidth=0.3) | |
| ax.axvline(v.mean(), color="#1f2328", lw=1.5, ls="--") | |
| ax.set_title(f"{cols[col]}\\nmean {v.mean():.2f}, sd {v.std():.2f}", fontsize=9) | |
| ax.set_yticks([]) | |
| if col == 0: | |
| ax.set_ylabel(label.split(" (")[0], fontsize=9) | |
| fig.suptitle("Assumed parameter distributions, 20000 draws", y=1.01) | |
| fig.tight_layout() | |
| plt.show() | |
| """) | |
| md(r""" | |
| Two of these drive the conclusions. | |
| **$k$ from 6 to 18** comes from the published design. Under the pilot anchor of 3 to 9 the 10-credit trials looked | |
| uninformative; at this scale they are what measures participants who rarely | |
| work. | |
| **The gap with sd 1.5** is a guess. It is the standard deviation of the | |
| between-person difference in discounting, and nothing in the literature pinned | |
| it. Because $k_{other}$ is drawn as $k_{self}$ plus that difference, the two | |
| correlate at about 0.92, which is what makes their difference so expensive to | |
| measure. If people's two discount rates are less alike than assumed, the gap | |
| recovers better than reported here. | |
| """) | |
| code(""" | |
| # What the assumed parameters imply for behaviour: P(work) across the design, | |
| # at the 10th, 50th and 90th percentile participant. | |
| arr, _ = draws["day task (SELF/OTHER)"] | |
| qs = [10, 50, 90] | |
| fig, axes = plt.subplots(1, len(qs), figsize=(4.4 * len(qs), 3.4), sharey=True) | |
| e_grid = np.linspace(0.25, 0.95, 100) | |
| for ax, q in zip(axes, qs): | |
| ks, ko, bt = [np.percentile(arr[:, j], q) for j in range(3)] | |
| for R_, col in zip(T.REW, COLORS): | |
| for k_, who, lw, style in ((ks, "self", 2.2, "-"), (ko, "other", 1.6, "--")): | |
| y = 1 / (1 + np.exp(-bt * (R_ - k_ * e_grid ** 2 - T.REST))) | |
| ax.plot(e_grid, y, color=col, lw=lw, ls=style, | |
| label=f"{R_:.0f} credits, {who}") | |
| for e in T.EFF: | |
| ax.axvline(e, color=MUTED, lw=0.7, ls=":", zorder=0) | |
| ax.axhline(0.5, color=MUTED, lw=0.8, ls="--", zorder=0) | |
| ax.set_ylim(0, 1) | |
| ax.set_xlabel("effort (fraction of own maximum)") | |
| ax.set_title(f"{q}th percentile participant\\nk_self {ks:.1f}, k_other {ko:.1f}, beta {bt:.2f}") | |
| axes[0].set_ylabel("P(work)") | |
| axes[-1].legend(frameon=False, fontsize=7, ncol=2) | |
| fig.suptitle("What those parameters mean for choices (solid = SELF, dashed = OTHER)", y=1.03) | |
| fig.tight_layout() | |
| plt.show() | |
| """) | |
| md(""" | |
| ## Trials needed | |
| The table reports the smallest trial count reaching r = 0.7, interpolated | |
| between the two counts that bracket it. | |
| """) | |
| code(""" | |
| rows = [] | |
| for label, per_n in results.items(): | |
| for param in per_n[next(iter(per_n))]: | |
| th = thresholds.get(f"{label}::{param}") | |
| rows.append({"model": label, "parameter": param, | |
| "trials for r>=0.7": th if th else "not reached by 150", | |
| "shipped": SHIPPED[label], | |
| "clears at shipped": "" if th is None else ("yes" if th <= SHIPPED[label] else "no")}) | |
| pd.DataFrame(rows).set_index(["model", "parameter"]) | |
| """) | |
| code(""" | |
| # Each panel carries its own model, so the equation sits on the panel rather | |
| # than in prose elsewhere: the parameters plotted are the ones in it. | |
| FORMULA = { | |
| "day task (SELF/OTHER)": | |
| r"$P(\\mathrm{work})=\\sigma\\!\\left(\\beta\\,(R-k_{\\mathrm{agent}}E^{2}-2)\\right)$", | |
| "night 1 (raid)": | |
| r"$P(\\mathrm{raid})=\\sigma\\!\\left(\\beta\\,(g-h\\,l-kE^{2}-2)\\right)$", | |
| "night 2 (whose pocket)": | |
| r"$P(\\mathrm{keep})=\\sigma\\!\\left(\\beta\\,(a-w\\,b+\\Delta k\\,E^{2})\\right)$", | |
| } | |
| PARAMS_NOTE = { | |
| "day task (SELF/OTHER)": "k per beneficiary, one beta; gap is k_other - k_self, subtracted", | |
| "night 1 (raid)": "h = harm aversion, k = effort cost, one beta", | |
| "night 2 (whose pocket)": "w = social weight, dk = k_other - k_self, fitted directly", | |
| } | |
| fig, axes = plt.subplots(1, len(results), figsize=(5.6 * len(results), 4.6), sharey=True) | |
| for ax, (label, per_n) in zip(np.atleast_1d(axes), results.items()): | |
| steps = sorted(int(k) for k in per_n) | |
| for (param, col) in zip(per_n[str(steps[0])], COLORS): | |
| ys = [per_n[str(n)][param] for n in steps] | |
| ax.plot(steps, ys, marker="o", lw=2, color=col, label=param) | |
| ax.axhline(TARGET, color=MUTED, ls="--", lw=1.2) | |
| ax.annotate(f"r = {TARGET}", (steps[0], TARGET), xytext=(2, 4), | |
| textcoords="offset points", color=MUTED, fontsize=8) | |
| ship = SHIPPED[label] | |
| ax.axvline(ship, color=ORANGE, ls=":", lw=1.5, zorder=0) | |
| ax.annotate(f"ships {ship}", (ship, 0.03), xytext=(4, 0), | |
| textcoords="offset points", color=ORANGE, fontsize=8) | |
| ax.set_xlabel("trials per participant") | |
| ax.set_title(f"{label}\\n{FORMULA[label]}", fontsize=10, pad=10) | |
| ax.text(0.5, -0.30, PARAMS_NOTE[label], transform=ax.transAxes, | |
| ha="center", va="top", fontsize=8, color=MUTED) | |
| ax.set_ylim(0, 1) | |
| ax.legend(frameon=False, fontsize=8, loc="lower right") | |
| np.atleast_1d(axes)[0].set_ylabel("recovery correlation") | |
| fig.suptitle(f"Recovery against trial count ({N_SUBJECTS} participants)", y=1.04) | |
| fig.tight_layout(rect=(0, 0.06, 1, 1)) | |
| plt.show() | |
| """) | |
| md(r""" | |
| ## Why the self/other difference costs so much more than the two $k$s | |
| Every model here has one parameter that needs far more trials than its | |
| neighbours, and in both cases it is a difference: the day task's | |
| $k_{other} - k_{self}$, and Night 2's $\Delta k$. | |
| Both are differences between quantities that are themselves strongly related | |
| across people. Someone who discounts effort steeply does so whoever benefits, | |
| so $k_{self}$ and $k_{other}$ correlate at about 0.92 under the assumptions | |
| above. Subtracting removes the shared component, which is most of the | |
| between-person variance, while the two measurement errors add. | |
| Classical test theory gives the reliability of a difference score: | |
| $$\rho_D = \frac{\sigma_1^2\rho_{11} + \sigma_2^2\rho_{22} | |
| - 2\sigma_1\sigma_2\rho_{12}} | |
| {\sigma_1^2 + \sigma_2^2 - 2\sigma_1\sigma_2\rho_{12}}$$ | |
| The cell below evaluates it across component reliabilities and component | |
| correlations. | |
| """) | |
| code(""" | |
| s1, s2 = 3.46, 3.77 # sd of k_self and k_other under the assumed draws | |
| grid = [] | |
| for rel in (0.7, 0.8, 0.9, 0.95): | |
| for r12 in (0.92, 0.8, 0.7, 0.5, 0.2): | |
| num = s1**2 * rel + s2**2 * rel - 2 * s1 * s2 * r12 | |
| den = s1**2 + s2**2 - 2 * s1 * s2 * r12 | |
| grid.append({"component reliability": rel, "corr(k_self, k_other)": r12, | |
| "difference reliability": max(0.0, num / den)}) | |
| g = pd.DataFrame(grid).pivot(index="component reliability", | |
| columns="corr(k_self, k_other)", | |
| values="difference reliability") | |
| g.round(2) | |
| """) | |
| code(""" | |
| fig, ax = plt.subplots(figsize=(6.4, 3.8)) | |
| for rel, col in zip(sorted(g.index), COLORS): | |
| xs = sorted(g.columns) | |
| ax.plot(xs, [g.loc[rel, x] for x in xs], marker="o", lw=2, color=col, | |
| label=f"each k measured at r = {rel}") | |
| ax.axvline(0.92, color=ORANGE, lw=1.5, ls=":") | |
| ax.annotate("where the two k's actually sit", (0.92, 0.82), xytext=(-6, 0), | |
| textcoords="offset points", ha="right", color=ORANGE, fontsize=8) | |
| ax.axhline(TARGET, color=MUTED, ls="--", lw=1.2) | |
| ax.set_xlabel("correlation between k_self and k_other across people") | |
| ax.set_ylabel("reliability of their difference") | |
| ax.set_ylim(0, 1) | |
| ax.invert_xaxis() | |
| ax.legend(frameon=False, fontsize=8) | |
| ax.set_title("A difference between two correlated measures\\nloses the shared variance and keeps both errors") | |
| fig.tight_layout() | |
| plt.show() | |
| """) | |
| md(""" | |
| ## What the published studies do instead | |
| Lockwood et al. report the two discount parameters separately and never a | |
| difference score. Two analyses carry the self versus other claim, and both are | |
| group level. | |
| The parameters are compared with a paired Wilcoxon signed-rank test across | |
| participants. Lockwood et al. (2017) report Study 1 $K_{other} > K_{self}$, | |
| Z = 5. | |
| The trial-level choices are analyzed with a generalized linear mixed-effects | |
| model, `glmer` in lme4, with choice coded binary and effort and reward entered | |
| as separate predictors. In their words this "enabled us to test separately for | |
| the influences of effort and reward on choices, which were combined in the | |
| computational k-parameter analysis." The self versus other claim comes from the | |
| agent by effort interaction. | |
| Neither analysis requires a reliable per-participant difference. A group | |
| comparison averages the per-person measurement error away; a correlation | |
| against another per-person measure does not. | |
| The `.qsf` computes none of this. It records choices, and the analysis happens | |
| afterwards. | |
| ## Recovery reported in the published work | |
| Lockwood et al. (2021) ran parameter recovery on their own schedule of 150 | |
| trials and report self k = 93%, other k = 93% and beta = 77%. The sweep here | |
| gives +0.92, +0.94 and +0.86 at the same trial count, so the harness reproduces | |
| a published result. They report no recovery figure for a difference parameter. | |
| """) | |
| code(""" | |
| lit = pd.DataFrame({ | |
| "Lockwood 2021, 150 trials": [0.93, 0.93, 0.77, np.nan], | |
| "this sweep, 150 trials": [ | |
| results["day task (SELF/OTHER)"]["150"]["k_self"], | |
| results["day task (SELF/OTHER)"]["150"]["k_other"], | |
| results["day task (SELF/OTHER)"]["150"]["beta"], | |
| results["day task (SELF/OTHER)"]["150"]["gap"]], | |
| }, index=["k_self", "k_other", "beta", "gap (not reported in the paper)"]) | |
| lit.round(2) | |
| """) | |
| md(""" | |
| ## Reading these numbers | |
| One fit per point, so single cells move by roughly the standard error of a | |
| correlation at n = 100, near 0.05. Read the trend and treat thresholds | |
| within a few trials of each other as the same. | |
| The difference score results are conditional on the assumed correlation between | |
| $k_{self}$ and $k_{other}$, which the simulation assumes. If people's two discount rates are less alike than assumed, the | |
| difference recovers better than shown here. Estimating that correlation is a | |
| question the collected data can answer. | |
| """) | |
| nb["cells"] = C | |
| nb.metadata.kernelspec = {"name": "python3", "display_name": "Python 3", | |
| "language": "python"} | |
| with open("trials_needed.ipynb", "w", encoding="utf-8") as f: | |
| nbf.write(nb, f) | |
| print(f"wrote trials_needed.ipynb ({len(C)} cells)") | |