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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
"""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)")