File size: 32,464 Bytes
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95345f5
 
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ae2bb
 
 
 
 
 
 
 
 
 
 
 
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
6cf57d6
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be24b6b
56b39b6
 
 
 
 
 
 
 
 
 
95345f5
56b39b6
 
 
 
be24b6b
 
 
 
 
 
95345f5
 
 
be24b6b
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be24b6b
 
 
 
052eb02
be24b6b
 
 
 
 
 
 
 
 
 
 
 
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cf57d6
 
 
 
 
95345f5
 
6cf57d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95345f5
6cf57d6
 
56b39b6
 
 
95345f5
56b39b6
95345f5
 
 
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ae2bb
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ae2bb
 
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ae2bb
 
 
 
56b39b6
 
 
 
 
 
 
 
 
 
 
 
95345f5
 
56b39b6
 
 
 
 
 
 
 
 
 
64f8454
 
 
 
 
 
 
 
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
64f8454
56b39b6
 
 
 
 
 
da6cba2
 
 
56b39b6
da6cba2
 
56b39b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95345f5
 
56b39b6
 
 
 
d5ae2bb
 
 
95345f5
d5ae2bb
 
 
56b39b6
 
 
 
 
 
 
 
 
0b19142
 
95345f5
0b19142
 
 
 
 
 
 
 
6cf57d6
 
 
 
 
 
 
95345f5
 
 
0b19142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ae2bb
 
0b19142
 
 
 
64f8454
0b19142
 
 
 
 
 
 
 
 
64f8454
0b19142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95345f5
0b19142
 
95345f5
 
0b19142
 
 
6cf57d6
 
 
95345f5
6cf57d6
 
 
 
 
95345f5
6cf57d6
 
0b19142
 
 
95345f5
0b19142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64f8454
0b19142
 
 
 
 
 
 
 
 
64f8454
0b19142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56b39b6
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
"""Generate the parameter-/model-recovery notebook.

Kept as a generator rather than a hand-edited .ipynb so the notebook can be
rebuilt and re-executed reproducibly, and so the source lives in a file that
diffs cleanly.

    python build_notebook.py && jupyter nbconvert --execute --inplace \
        --ExecutePreprocessor.timeout=-1 recovery.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"""
# Effort discounting: parameter and model recovery

Can this task's design actually recover the parameters it is meant to measure,
and can it tell the competing models apart? Both are asked with **simulated**
data, where the true values are known, so the answers are about the *design*.
No participant data enters them.

The model is the prosocial effort-discounting model (Lockwood et al.; Cutler's
`mod_ms_all.m`):

$$V_{\text{work}} = R - k\,E^{p} \qquad V_{\text{rest}} = c_{\text{rest}}
\qquad P(\text{work}) = \sigma\!\big(\beta\,(V_{\text{work}} - V_{\text{rest}})\big)$$

$E$ is the required effort as a fraction of the participant's own calibrated
maximum, so it is comparable across people of different strength. Fitting is
hierarchical Expectation-Maximisation via **pyEM** (Shawn Rhoads).

The family crosses three binary choices, giving eight models:

| | options |
|---|---|
| $k$ | one rate, or one each for SELF and OTHER |
| $\beta$ | one inverse temperature, or one each |
| $p$ | 2 (parabolic) or 1 (linear) |

The 1-$k$ models are the **null**: the SELF/OTHER difference in $k$ is the whole
point of the task, so if a 1-$k$ model wins, the design did not detect prosocial
discounting at all.

**What the task actually ships**, and therefore which row to read:

| block | trials | note |
|---|---|---|
| day task (SELF/OTHER) | **48** | the 24-cell grid runs once per block, and there are two blocks, so every cell appears twice |
| Night 1 (raid) | **24** | one pass through its 24 cells |
| Night 2 (whose pocket) | **24** | one pass through its 24 cells |

So the day-task row to read below is **48**, not 24. The 24-trial row is half
the shipped design and is kept only as the bottom of the sweep; 72 and 96 show
what additional blocks would buy. For the two night conditions the shipped
design *is* 24.
""")

code("""
import os, time, pickle, zlib
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

from pyem.api import EMModel
import effort_models as M

RNG_SEED = 20260827
N_SUBJECTS = 100
TRIAL_COUNTS = [24, 48, 72, 96]
PRIMARY = "2k1b_par"          # separate k for self/other, one beta, parabolic
CACHE = "recovery_cache.pkl"

# Readable defaults; colours below are picked to stay distinguishable in
# grayscale and under the common colour-vision deficiencies.
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",
})
INK, MUTED = "#1f2328", "#6e7280"
BLUE, ORANGE, GREEN, PURPLE = "#2b6cb0", "#c05621", "#2f855a", "#6b46c1"

print("models in the family:", list(M.MODELS))
print(f"{N_SUBJECTS} simulated participants; trial counts {TRIAL_COUNTS}")
""")

md(r"""
## 1. Is the design informative before any fitting?

Two things can make recovery fail for reasons that have nothing to do with the
model, and both are cheap to check first.

**The squash.** pyEM optimises on an unbounded scale and maps into range with
`norm2beta(x, max_val)`. If `max_val` is set far above the plausible values the
sigmoid saturates: every candidate maps to nearly the same number, the optimiser
sees no slope, and recovery collapses in a way that looks like a modelling
result. The gradient below is how much native movement one unit of fitting-space
movement buys. It must not be near zero.

**Choice balance.** Information in a binary choice is $p(1-p)$, maximal at
$p=0.5$ and vanishing at the extremes. A design that pins everyone at 0.02 or
0.98 cannot recover anything, however many trials it has.

**The assumed $k$ is anchored to the pilot, not guessed.** Every number below is
a statement about the assumed parameter range as much as about the design, so
the range is pinned to data: the nine complete pilot sessions chose work on 66%
of SELF and 58% of OTHER trials, and $k_{self}=6$, $k_{other}=9$, $\beta=0.6$
reproduces that. An earlier version of this notebook guessed $k \in [1,5]$,
which implies working on ~80% of trials, well above what the pilot shows. Under
that guess two-thirds of the design sits at ceiling and 24-trial recovery looks
hopeless. The per-cell information table below shows where the real
design actually stands.
""")

code("""
rng = np.random.default_rng(RNG_SEED)
spec = M.MODELS[PRIMARY]
true_demo = M.draw_true(spec, 400, rng)

g_k = M.check_gradients(true_demo[:, :2], M.K_MAX, "k")
g_b = M.check_gradients(true_demo[:, 2:], M.BETA_MAX, "beta")
for g in (g_k, g_b):
    lo, hi = g["gradient_range"]
    vlo, vhi = g["value_range"]
    flag = "OK" if lo > 0.05 else "SATURATED -- recovery will fail for this reason alone"
    print(f"{g['name']:>5s}  values {vlo:5.2f}..{vhi:5.2f}  "
          f"(max_val {g['max_val']:.0f})  gradient {lo:.2f}..{hi:.2f}   {flag}")

print()
for nt in TRIAL_COUNTS:
    b = M.choice_balance(spec, true_demo, nt, np.random.default_rng(1))
    print(f"{nt:3d} trials   mean P(work) {b['mean_p_work']:.2f}   "
          f"range {b['min']:.2f}-{b['max']:.2f}   saturated {b['frac_saturated']:.0%}")

# Where the information actually is, cell by cell. p(1-p) is the Fisher
# information of a binary choice, so a cell near 0 contributes nothing however
# many times it is repeated.
print("\\ninformation per trial, p(1-p), at the median simulated participant:")
ks, ko, bt = (float(np.median(true_demo[:, 0])), float(np.median(true_demo[:, 1])),
              float(np.median(true_demo[:, 2])))
info_tbl = []
for rew in M.REWARDS:
    for e in M.EFFORT_FRACS:
        for lbl, kk in (("SELF", ks), ("OTHER", ko)):
            p = 1 / (1 + np.exp(-bt * (rew - kk * e ** 2 - M.REST_CREDIT)))
            info_tbl.append({"reward": rew, "effort": e, "who": lbl,
                             "p_work": p, "info": p * (1 - p)})
info_df = pd.DataFrame(info_tbl)
print(info_df.pivot_table(index=["reward", "effort"], columns="who",
                          values="info").round(3).to_string())
""")

code("""
fig, axes = plt.subplots(1, 2, figsize=(9.5, 3.4))

# --- how P(work) depends on effort and reward, at the median k
ax = axes[0]
k_med = float(np.median(true_demo[:, 0]))
b_med = float(np.median(true_demo[:, 2]))
e_grid = np.linspace(0.2, 0.95, 100)
for rew, col in zip(M.REWARDS, (BLUE, ORANGE, GREEN)):
    v = rew - k_med * e_grid ** 2 - M.REST_CREDIT
    ax.plot(e_grid, 1 / (1 + np.exp(-b_med * v)), color=col, lw=2,
            label=f"{rew:.0f} credits")
for e in M.EFFORT_FRACS:
    ax.axvline(e, color=MUTED, lw=0.8, ls=":", zorder=0)
ax.axhline(0.5, color=MUTED, lw=0.8, ls="--", zorder=0)
ax.set_xlabel("effort required (fraction of own maximum)")
ax.set_ylabel("P(work)")
ax.set_title("Where the design sits\\n(dotted = the four effort levels used)")
ax.set_ylim(0, 1)
ax.legend(title="reward", frameon=False, fontsize=8, title_fontsize=8)

# --- information per trial, p(1-p)
ax = axes[1]
p_all = []
for i in range(true_demo.shape[0]):
    ben, eff, rew = M.make_design(24, np.random.default_rng(100 + i))
    p_all.append(M.p_work(true_demo[i], spec, ben, eff, rew))
p_all = np.concatenate(p_all)
ax.hist(p_all, bins=40, color=BLUE, alpha=0.85, edgecolor="white", linewidth=0.4)
ax.axvline(0.5, color=ORANGE, lw=2, label="most informative")
ax.set_xlabel("P(work) on a trial")
ax.set_ylabel("trials")
ax.set_title(f"Trial-level choice probabilities\\n{np.mean((p_all<0.05)|(p_all>0.95)):.1%} saturated")
ax.legend(frameon=False, fontsize=8)

fig.tight_layout()
plt.show()
""")

md("""
## 1b. What the parameters are assumed to be

Recovery is measured against these draws, so the ranges decide what the results
mean. Both were corrected after checking them against the published work.

`k` runs 6 to 18, the range implied by Lockwood's design. This project's pilot
sits lower, at 3 to 9.
`beta` runs 0.7 to 2.2, matching the choice determinism in Jo Cutler's
simulation code, which bounds beta at 0 to 5 and tests recovery at 1, 3 and 5.
The comparison is on beta times the value difference, since that is what the
softmax sees and the two value scales differ.
""")

code("""
import night_models as N

N_DRAW = 20000
param_sets = {
    "day task": (M.draw_true(M.MODELS["2k1b_par"], N_DRAW, np.random.default_rng(11)),
                 ["k_self", "k_other", "beta"], True),
    "night 1": (N.n1_draw_true(N.NIGHT1_MODELS["h_par"], N_DRAW, np.random.default_rng(12)),
                ["h", "k", "beta"], False),
    "night 2": (N.n2_draw_true(N.NIGHT2_MODELS["w_dk_par"], N_DRAW, np.random.default_rng(13)),
                ["w", "dk", "beta"], False),
}
rows = []
for label, (arr, names, has_gap) in param_sets.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 has_gap:
        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, has_gap)) in enumerate(param_sets.items()):
    cols, vals = list(names), [arr[:, j] for j in range(arr.shape[1])]
    if has_gap:
        cols += ["gap = k_other - k_self"]
        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], [BLUE, ORANGE, GREEN, PURPLE][col % 4]
        ax.hist(v, bins=60, color=c, alpha=0.85, edgecolor="white", linewidth=0.3)
        ax.axvline(v.mean(), color=INK, 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, fontsize=9)
fig.suptitle(f"Assumed parameter distributions ({N_DRAW} draws)", y=1.01)
fig.tight_layout(); plt.show()
""")

md(r"""
## 2. 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)$$

$R$ is 3, 6 or 10 credits and resting always pays 2. $E$ is the required effort
as a fraction of that participant's own calibrated maximum, so it runs 0.35 to
0.80 and means the same thing for a strong and a weak participant.

| 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 when the partner is paid | the participant rests more on OTHER trials |
| $\beta$ | choice consistency | choices track value more closely |
| gap | $k_{other} - k_{self}$, computed by subtracting two fitted values | effort is spent less readily for the partner |

### Parameter recovery

Simulate participants from the primary model, fit that same model back, and
correlate the estimates with the truth. This is run at each trial count so the
cost of the 24-trial design is visible in the numbers.

A recovery correlation that does **not** improve as trials are added points at a
bug in the code. That is what caught a badly-chosen squash range in an earlier
run of this analysis.
""")

code("""
def fit_model(name, data, seed=1, verbose=0):
    spec = M.MODELS[name]
    m = EMModel(all_data=data, fit_func=M.make_objfunc(spec),
                param_names=M.param_names(spec))
    res = m.fit(verbose=verbose, seed=seed)
    est = np.asarray(res.m if hasattr(res, "m") else res["m"])   # params x subjects
    native = np.column_stack([M.to_native(est[:, i], spec)
                              for i in range(est.shape[1])]).T   # subjects x params
    return res, native


def load_cache():
    if os.path.exists(CACHE):
        with open(CACHE, "rb") as f:
            return pickle.load(f)
    return {}


def save_cache(c):
    with open(CACHE, "wb") as f:
        pickle.dump(c, f)


cache = load_cache()
key = ("param_recovery", PRIMARY, N_SUBJECTS, tuple(TRIAL_COUNTS), RNG_SEED)
if key in cache:
    pr = cache[key]
    print("loaded from cache")
else:
    pr = {}
    for nt in TRIAL_COUNTS:
        r = np.random.default_rng(RNG_SEED + nt)
        true = M.draw_true(spec, N_SUBJECTS, r)
        data = M.make_dataset(spec, true, nt, r)
        t0 = time.time()
        _, est = fit_model(PRIMARY, data)
        pr[nt] = {"true": true, "est": est}
        print(f"{nt:3d} trials fitted in {time.time()-t0:5.1f}s")
    cache[key] = pr
    save_cache(cache)

names = M.param_names(spec)
rows = []
for nt in TRIAL_COUNTS:
    t, e = pr[nt]["true"], pr[nt]["est"]
    row = {"trials": nt}
    for j, nm in enumerate(names):
        row[nm] = np.corrcoef(t[:, j], e[:, j])[0, 1]
    row["k_other - k_self"] = np.corrcoef(t[:, 1] - t[:, 0], e[:, 1] - e[:, 0])[0, 1]
    rows.append(row)
recov = pd.DataFrame(rows).set_index("trials")
recov.round(2)
""")

code("""
fig, axes = plt.subplots(1, len(names) + 1, figsize=(3.1 * (len(names) + 1), 3.2))
nt = 48                                   # the shipped day-task design
t, e = pr[nt]["true"], pr[nt]["est"]
cols = [BLUE, ORANGE, GREEN, PURPLE]

panels = [(nm, t[:, j], e[:, j]) for j, nm in enumerate(names)]
panels.append(("k_other - k_self", t[:, 1] - t[:, 0], e[:, 1] - e[:, 0]))

for ax, (nm, tv, ev), col in zip(axes, panels, cols):
    ax.scatter(tv, ev, s=26, color=col, alpha=0.75, edgecolor="white", linewidth=0.5)
    lo = min(tv.min(), ev.min()); hi = max(tv.max(), ev.max())
    pad = 0.05 * (hi - lo)
    ax.plot([lo - pad, hi + pad], [lo - pad, hi + pad], color=MUTED, lw=1, ls="--")
    ax.set_xlabel(f"true {nm}")
    ax.set_ylabel(f"estimated {nm}")
    ax.set_title(f"{nm}\\nr = {np.corrcoef(tv, ev)[0,1]:+.2f}")

fig.suptitle(f"Day task, parameter recovery at the shipped {nt} trials "
             f"({N_SUBJECTS} simulated participants)", y=1.04)
fig.tight_layout()
plt.show()
""")

code("""
fig, ax = plt.subplots(figsize=(6.2, 3.6))
for nm, col in zip(list(recov.columns), [BLUE, ORANGE, GREEN, PURPLE]):
    ax.plot(recov.index, recov[nm], marker="o", lw=2, color=col, label=nm)
    ax.annotate(nm, (recov.index[-1], recov[nm].iloc[-1]), xytext=(6, 0),
                textcoords="offset points", color=col, fontsize=8, va="center")
ax.axhline(0.7, color=MUTED, ls="--", lw=1)
ax.annotate("0.7, a common floor for usable recovery",
            (recov.index[0], 0.7), xytext=(0, -14), textcoords="offset points",
            color=MUTED, fontsize=8)
ax.set_xlabel("trials per participant")
ax.set_ylabel("recovery correlation (true vs estimated)")
ax.axvline(48, color=ORANGE, lw=1.5, ls=":", zorder=0)
ax.annotate("shipped design\\n(48 = 24 x 2 blocks)", (48, 0.06), xytext=(5, 0),
            textcoords="offset points", color=ORANGE, fontsize=8)
ax.set_title("What extra trials buy (day task)")
ax.set_xticks(TRIAL_COUNTS)
ax.set_ylim(0, 1)
ax.set_xlim(TRIAL_COUNTS[0] - 3, TRIAL_COUNTS[-1] + 22)
fig.tight_layout()
plt.show()
""")

md("""
## 3. Model recovery

Simulate from each of the eight models in turn and fit **all** eight back. The
confusion matrix reports how often each generating model is correctly picked out
by integrated BIC (lower is better). Read the diagonal. Off-diagonal
mass means the design cannot distinguish those two accounts, so a
model-comparison result on real data would not be trustworthy.

This is 8 x 8 fits per trial count and is the slow part of the notebook; results
are cached.
""")

code("""
from pyem.api import calc_BICint

MR_TRIALS = [24, 48]
#: Model recovery uses fewer participants than parameter recovery, deliberately.
#: It asks whether integrated BIC picks the generating model, and BIC
#: differences grow with participants, so more of them make the question EASIER
#: rather than sharper. At n = 100 the 8 x 8 sweep ran for over two hours
#: without finishing; at 40 it answers the same question in a fraction of that.
MR_SUBJECTS = 40
BIC_SAMPLES = 300       # integrated BIC Monte-Carlo draws per subject
mr_key = ("model_recovery", MR_SUBJECTS, tuple(MR_TRIALS), RNG_SEED)

if mr_key in cache:
    conf = cache[mr_key]
    print("loaded from cache")
else:
    conf = {}
    for nt in MR_TRIALS:
        mat = pd.DataFrame(index=list(M.MODELS), columns=list(M.MODELS), dtype=float)
        for gen in M.MODELS:
            gspec = M.MODELS[gen]
            # zlib.crc32, NOT hash(): hash() is salted per process, so the
            # notebook would draw different data on every run and stop being
            # reproducible -- the same bug this project just fixed in the task.
            r = np.random.default_rng(RNG_SEED + zlib.crc32(gen.encode()) % 10000 + nt)
            true = M.draw_true(gspec, MR_SUBJECTS, r)
            data = M.make_dataset(gspec, true, nt, r)
            for fit_name in M.MODELS:
                fspec = M.MODELS[fit_name]
                t0 = time.time()
                try:
                    res, _ = fit_model(fit_name, data)
                    # posterior_mu / posterior_sigma, not mu / sigma -- pyEM's
                    # FitResult has no mu, and the wrong name would make every
                    # cell of the matrix nan.
                    bic = calc_BICint(data, M.param_names(fspec),
                                      res.posterior_mu, res.posterior_sigma,
                                      M.make_objfunc(fspec), nsamples=BIC_SAMPLES)
                except Exception as exc:
                    print(f"    {gen} -> {fit_name} FAILED: {exc}")
                    bic = np.nan
                mat.loc[gen, fit_name] = bic
                print(f"  {nt:3d}tr  gen {gen:>10s} fit {fit_name:>10s}  "
                      f"BICint {bic:9.1f}  ({time.time()-t0:.0f}s)")
        conf[nt] = mat
    cache[mr_key] = conf
    save_cache(cache)

for nt, mat in conf.items():
    print(f"\\n--- {nt} trials: best-fitting model per generating model ---")
    print(mat.idxmin(axis=1).to_string())
""")

code("""
fig, axes = plt.subplots(1, len(conf), figsize=(6.4 * len(conf), 5.4))
axes = np.atleast_1d(axes)

for ax, (nt, mat) in zip(axes, sorted(conf.items())):
    # Row-normalise to "was this the winner", which is what the matrix is for;
    # raw BIC values are not comparable across generating models.
    win = pd.DataFrame(0.0, index=mat.index, columns=mat.columns)
    for g in mat.index:
        win.loc[g, mat.loc[g].idxmin()] = 1.0
    im = ax.imshow(win.values, cmap="Blues", vmin=0, vmax=1)
    ax.set_xticks(range(len(mat.columns)))
    ax.set_xticklabels(mat.columns, rotation=45, ha="right", fontsize=8)
    ax.set_yticks(range(len(mat.index)))
    ax.set_yticklabels(mat.index, fontsize=8)
    ax.set_xlabel("model fitted")
    ax.set_ylabel("model that generated the data")
    hits = int(np.trace(win.values))
    ax.set_title(f"{nt} trials — {hits}/{len(mat)} recovered")
    for i in range(len(mat.index)):
        for j in range(len(mat.columns)):
            if win.values[i, j] > 0:
                ax.text(j, i, "✓", ha="center", va="center",
                        color="white", fontsize=12, fontweight="bold")
    ax.grid(False)

fig.suptitle("Model recovery — does integrated BIC pick the generating model?", y=1.0)
fig.tight_layout()
plt.show()
""")

md("""
## 4. What this says about the design

The cells above are the evidence. If they and this summary ever disagree, the
cells are right.

- **Section 1** shows whether the design is informative at all, before any
  fitting. Saturated choice probabilities or a flattened squash would make
  everything below meaningless.
- **Section 2** gives the day-task recovery correlations. Read the **48-trial**
  row: that is what ships (24 cells x 2 blocks). `k_other - k_self` is the
  quantity the task exists to estimate, so it is the number to judge the design
  on, ahead of the individual $k$s. Note what that number does and does not
  license: a gap that recovers moderately per participant can still support a
  group comparison, because group means average away the per-person error,
  while a correlation against another per-person measure is attenuated by it.
- **Section 3** says whether a model comparison on real data could be trusted.
  Off-diagonal mass between a 1-$k$ and a 2-$k$ model would be the serious
  case: it would mean the design cannot tell "discounts more for others" from
  "discounts the same for everyone".

All of this is simulation. It bounds what the design *could* show with perfect
model specification; real data will do worse.
""")


md(r"""
## 5. Night 1: raid, or stay asleep

A separate decision with its own model. Raiding pays you $g$ and costs your
partner $l$; sleeping pays the night rest credit and costs them nothing. Gain
and loss are crossed orthogonally, so what a credit gained is worth is separable
from what taking one off someone else costs.

$$V_{raid} = g - h\,l - k\,E^{p} \qquad V_{sleep} = c_{rest}$$

| parameter | meaning | rises when |
|---|---|---|
| $h$ | harm aversion, how far a credit taken off the partner cancels one gained | the participant avoids raids that cost the partner a lot |
| $k$ | effort discounting, as in the day task | the participant avoids high-effort raids |
| $\beta$ | choice consistency | choices track value more closely |

$h = 0$ is pure self-interest and sits in the family as the null. Because gain
and loss are crossed orthogonally, $h$ is a main effect of its own regressor.
The day task's gap is a difference between two estimates, which is why it costs
far more trials.

**These ranges are assumptions, not anchored to data.** The day-task ranges could
be pinned to the pilot's observed choice rates; the night conditions have never
been run, so there is nothing to anchor to.
""")

code("""
import night_models as N

def fit_generic(data, objfunc, names, seed=1):
    m = EMModel(all_data=data, fit_func=objfunc, param_names=names)
    res = m.fit(verbose=0, seed=seed)
    return res, np.asarray(res.m if hasattr(res, "m") else res["m"])

n1_key = ("night1_param", N_SUBJECTS, tuple(TRIAL_COUNTS), RNG_SEED)
if n1_key in cache:
    n1 = cache[n1_key]; print("loaded from cache")
else:
    spec1 = N.NIGHT1_MODELS["h_par"]
    n1 = {}
    for nt in TRIAL_COUNTS:
        r = np.random.default_rng(RNG_SEED + 1000 + nt)
        true = N.n1_draw_true(spec1, N_SUBJECTS, r)
        data = N.n1_dataset(spec1, true, nt, r)
        t0 = time.time()
        _, est = fit_generic(data, N.n1_objfunc(spec1), N.n1_param_names(spec1))
        native = np.column_stack([N.n1_to_native(est[:, i], spec1)
                                  for i in range(est.shape[1])]).T
        n1[nt] = {"true": true, "est": native}
        print(f"{nt:3d} trials fitted in {time.time()-t0:5.1f}s")
    cache[n1_key] = n1; save_cache(cache)

n1_names = N.n1_param_names(N.NIGHT1_MODELS["h_par"])
n1_tbl = pd.DataFrame([
    {"trials": nt, **{nm: np.corrcoef(d["true"][:, j], d["est"][:, j])[0, 1]
                      for j, nm in enumerate(n1_names)}}
    for nt, d in sorted(n1.items())]).set_index("trials")
n1_tbl.round(2)
""")

code("""
fig, axes = plt.subplots(1, len(n1_names) + 1, figsize=(3.1 * (len(n1_names) + 1), 3.2))
nt0 = TRIAL_COUNTS[0]
d = n1[nt0]
for ax, (j, nm), col in zip(axes[:-1], enumerate(n1_names), [BLUE, ORANGE, GREEN]):
    tv, ev = d["true"][:, j], d["est"][:, j]
    ax.scatter(tv, ev, s=26, color=col, alpha=0.75, edgecolor="white", linewidth=0.5)
    lo, hi = min(tv.min(), ev.min()), max(tv.max(), ev.max())
    ax.plot([lo, hi], [lo, hi], color=MUTED, lw=1, ls="--")
    ax.set_xlabel(f"true {nm}"); ax.set_ylabel(f"estimated {nm}")
    ax.set_title(f"{nm}\\nr = {np.corrcoef(tv, ev)[0,1]:+.2f}")

ax = axes[-1]
for nm, col in zip(n1_names, [BLUE, ORANGE, GREEN]):
    ax.plot(n1_tbl.index, n1_tbl[nm], marker="o", lw=2, color=col, label=nm)
ax.axhline(0.7, color=MUTED, ls="--", lw=1)
ax.set_xlabel("trials"); ax.set_ylabel("recovery r")
ax.set_xticks(TRIAL_COUNTS); ax.set_ylim(0, 1)
ax.set_title("Night 1: what trials buy"); ax.legend(frameon=False, fontsize=8)

fig.suptitle(f"Night 1 parameter recovery at the shipped {nt0} trials "
             f"({N_SUBJECTS} participants)", y=1.04)
fig.tight_layout(); plt.show()
""")

code("""
n1m_key = ("night1_model", MR_SUBJECTS, tuple(MR_TRIALS), RNG_SEED)
if n1m_key in cache:
    n1_conf = cache[n1m_key]; print("loaded from cache")
else:
    n1_conf = {}
    for nt in MR_TRIALS:
        mat = pd.DataFrame(index=list(N.NIGHT1_MODELS), columns=list(N.NIGHT1_MODELS),
                           dtype=float)
        for gen, gspec in N.NIGHT1_MODELS.items():
            r = np.random.default_rng(RNG_SEED + zlib.crc32(gen.encode()) % 10000 + nt)
            true = N.n1_draw_true(gspec, MR_SUBJECTS, r)
            data = N.n1_dataset(gspec, true, nt, r)
            for fname, fspec in N.NIGHT1_MODELS.items():
                names = N.n1_param_names(fspec)
                try:
                    res, _ = fit_generic(data, N.n1_objfunc(fspec), names)
                    bic = calc_BICint(data, names, res.posterior_mu, res.posterior_sigma,
                                      N.n1_objfunc(fspec), nsamples=BIC_SAMPLES)
                except Exception as exc:
                    print(f"    {gen} -> {fname} FAILED: {exc}"); bic = np.nan
                mat.loc[gen, fname] = bic
        n1_conf[nt] = mat
        hits = sum(1 for g in mat.index if mat.loc[g].idxmin() == g)
        print(f"{nt:3d} trials: {hits}/{len(mat)} recovered")
    cache[n1m_key] = n1_conf; save_cache(cache)

for nt, mat in sorted(n1_conf.items()):
    print(f"\\n{nt} trials:")
    print(mat.idxmin(axis=1).to_string())
""")

md(r"""
## 6. Night 2: whose pocket

The harvest happens either way; the only question is where it lands. Effort is
**identical on both options**, so the two effort terms cancel and only their
difference is estimable.

$$V_{self} - V_{partner} = a - w\,b - \Delta k\,E^{p}$$

| 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 |
| $\beta$ | choice consistency | choices track value more closely |

Night 2 estimates $w$ and $\Delta k$, never $k_{self}$ and $k_{other}$
separately, because the effort terms cancel.

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.

**Coupled vs decoupled.** As shipped, the pairs sum to 12 on every trial, so what
you gain and what they gain correlate $-1$. Both versions are run below, so the
cost of that coupling is measured below.
""")

code("""
n2_key = ("night2_param", N_SUBJECTS, tuple(TRIAL_COUNTS), RNG_SEED)
if n2_key in cache:
    n2 = cache[n2_key]; print("loaded from cache")
else:
    spec2 = N.NIGHT2_MODELS["w_dk_par"]
    n2 = {}
    for label, pairs in (("coupled", N.NIGHT2_PAIRS_COUPLED),
                         ("decoupled", N.NIGHT2_PAIRS_DECOUPLED)):
        for nt in TRIAL_COUNTS:
            r = np.random.default_rng(RNG_SEED + 2000 + nt)
            true = N.n2_draw_true(spec2, N_SUBJECTS, r)
            data = N.n2_dataset(spec2, true, nt, r, pairs)
            t0 = time.time()
            _, est = fit_generic(data, N.n2_objfunc(spec2), N.n2_param_names(spec2))
            native = np.column_stack([N.n2_to_native(est[:, i], spec2)
                                      for i in range(est.shape[1])]).T
            n2[(label, nt)] = {"true": true, "est": native}
            print(f"{label:>10s} {nt:3d} trials fitted in {time.time()-t0:5.1f}s")
    cache[n2_key] = n2; save_cache(cache)

n2_names = N.n2_param_names(N.NIGHT2_MODELS["w_dk_par"])
n2_tbl = pd.DataFrame([
    {"design": lbl, "trials": nt,
     **{nm: np.corrcoef(d["true"][:, j], d["est"][:, j])[0, 1]
        for j, nm in enumerate(n2_names)}}
    for (lbl, nt), d in sorted(n2.items())]).set_index(["design", "trials"])
n2_tbl.round(2)
""")

code("""
fig, axes = plt.subplots(1, len(n2_names), figsize=(3.4 * len(n2_names), 3.4))
for ax, (j, nm) in zip(axes, enumerate(n2_names)):
    for lbl, col, mk in (("coupled", ORANGE, "o"), ("decoupled", BLUE, "s")):
        ys = [np.corrcoef(n2[(lbl, nt)]["true"][:, j], n2[(lbl, nt)]["est"][:, j])[0, 1]
              for nt in TRIAL_COUNTS]
        ax.plot(TRIAL_COUNTS, ys, marker=mk, lw=2, color=col, label=lbl)
    ax.axhline(0.7, color=MUTED, ls="--", lw=1)
    ax.set_xlabel("trials"); ax.set_ylabel("recovery r")
    ax.set_xticks(TRIAL_COUNTS); ax.set_ylim(0, 1)
    ax.set_title(nm)
    ax.legend(frameon=False, fontsize=8)
fig.suptitle("Night 2: does decoupling the pairs buy anything?", y=1.03)
fig.tight_layout(); plt.show()
""")

code("""
n2m_key = ("night2_model", MR_SUBJECTS, tuple(MR_TRIALS), RNG_SEED)
if n2m_key in cache:
    n2_conf = cache[n2m_key]; print("loaded from cache")
else:
    n2_conf = {}
    for nt in MR_TRIALS:
        mat = pd.DataFrame(index=list(N.NIGHT2_MODELS), columns=list(N.NIGHT2_MODELS),
                           dtype=float)
        for gen, gspec in N.NIGHT2_MODELS.items():
            r = np.random.default_rng(RNG_SEED + zlib.crc32(gen.encode()) % 10000 + nt)
            true = N.n2_draw_true(gspec, MR_SUBJECTS, r)
            data = N.n2_dataset(gspec, true, nt, r, N.NIGHT2_PAIRS_COUPLED)
            for fname, fspec in N.NIGHT2_MODELS.items():
                names = N.n2_param_names(fspec)
                try:
                    res, _ = fit_generic(data, N.n2_objfunc(fspec), names)
                    bic = calc_BICint(data, names, res.posterior_mu, res.posterior_sigma,
                                      N.n2_objfunc(fspec), nsamples=BIC_SAMPLES)
                except Exception as exc:
                    print(f"    {gen} -> {fname} FAILED: {exc}"); bic = np.nan
                mat.loc[gen, fname] = bic
        n2_conf[nt] = mat
        hits = sum(1 for g in mat.index if mat.loc[g].idxmin() == g)
        print(f"{nt:3d} trials: {hits}/{len(mat)} recovered")
    cache[n2m_key] = n2_conf; save_cache(cache)

for nt, mat in sorted(n2_conf.items()):
    print(f"\\n{nt} trials:")
    print(mat.idxmin(axis=1).to_string())
""")

code("""
fig, axes = plt.subplots(2, len(MR_TRIALS), figsize=(5.0 * len(MR_TRIALS), 8.4))
for row, (conf, title) in enumerate(((n1_conf, "Night 1"), (n2_conf, "Night 2"))):
    for col, (nt, mat) in enumerate(sorted(conf.items())):
        ax = axes[row, col]
        win = pd.DataFrame(0.0, index=mat.index, columns=mat.columns)
        for g in mat.index:
            win.loc[g, mat.loc[g].idxmin()] = 1.0
        ax.imshow(win.values, cmap="Blues", vmin=0, vmax=1)
        ax.set_xticks(range(len(mat.columns)))
        ax.set_xticklabels(mat.columns, rotation=45, ha="right", fontsize=8)
        ax.set_yticks(range(len(mat.index)))
        ax.set_yticklabels(mat.index, fontsize=8)
        ax.set_xlabel("model fitted"); ax.set_ylabel("generating model")
        hits = int(np.trace(win.values))
        ax.set_title(f"{title}, {nt} trials — {hits}/{len(mat)}")
        for i in range(len(mat.index)):
            for j in range(len(mat.columns)):
                if win.values[i, j] > 0:
                    ax.text(j, i, "✓", ha="center", va="center", color="white",
                            fontsize=12, fontweight="bold")
        ax.grid(False)
fig.suptitle("Night model recovery", y=1.0)
fig.tight_layout(); plt.show()
""")

nb["cells"] = C
nb.metadata.kernelspec = {"name": "python3", "display_name": "Python 3",
                          "language": "python"}
with open("recovery.ipynb", "w", encoding="utf-8") as f:
    nbf.write(nb, f)
print(f"wrote recovery.ipynb ({len(C)} cells)")