File size: 8,367 Bytes
dffba6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
670ca7d
 
 
 
 
 
 
 
dffba6e
590551b
670ca7d
 
dffba6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The likelihood, and that it survives contact with real sessions.

The model is V_work = R - k*E**p, V_rest = rest_credit,
P(work) = sigmoid(beta * (V_work - V_rest)).

The one thing worth restating: `rest_credit` is per trial. It was 1 in every
pilot session and is 2 in the current build, and night 1 has its own value
again. A likelihood that takes it from a constant fits the pilot data to the
wrong indifference point.
"""
import numpy as np
import pandas as pd
import pytest

from pe_analysis import inclusion, loader, models as M


def test_the_family_is_the_eight_published_comparisons():
    assert len(M.FAMILY) == 8
    assert set(M.FAMILY) == {
        f"{k}k{b}b_{p}" for k in (1, 2) for b in (1, 2) for p in ("par", "lin")}
    assert M.FAMILY["2k2b_par"].n_params == 4
    assert M.FAMILY["1k1b_lin"].n_params == 2


def test_p_work_matches_the_formula_by_hand():
    spec = M.Spec(n_k=1, n_beta=1, p=2)
    k, beta, rew, eff, rest = 10.0, 1.5, 6.0, 0.5, 2.0
    v = rew - k * eff ** 2 - rest          # 6 - 2.5 - 2 = 1.5
    expected = 1.0 / (1.0 + np.exp(-beta * v))
    got = M.p_work([k, beta], spec, [0], [eff], [rew], [rest])
    assert got[0] == pytest.approx(expected)
    assert v == pytest.approx(1.5)


def test_the_rest_credit_comes_from_the_trial():
    """Same parameters, same offer, different rest option -> different choice
    probability. A constant here would fit the pilot's rest-1 sessions to the
    current rest-2 indifference point."""
    spec = M.Spec()
    p1, p2 = M.p_work([10.0, 1.5], spec, [0, 0], [0.5, 0.5], [6.0, 6.0], [1.0, 2.0])
    assert p1 > p2
    assert p1 == pytest.approx(1 / (1 + np.exp(-1.5 * (6 - 2.5 - 1))))


def test_the_exponent_is_what_separates_the_two_cost_shapes():
    par, lin = M.FAMILY["1k1b_par"], M.FAMILY["1k1b_lin"]
    args = ([10.0, 1.5], None, [0], [0.5], [6.0], [2.0])
    assert M.p_work(args[0], par, *args[2:])[0] != \
        pytest.approx(M.p_work(args[0], lin, *args[2:])[0])


def test_rho_defaults_to_one_so_the_base_family_is_unchanged():
    """The extended models must nest the published ones exactly, or a BIC
    comparison between them is measuring the reparameterisation."""
    base = M.Spec(1, 1, 2, 0)
    withrho = M.Spec(1, 1, 2, 2)
    a = M.p_work([9.0, 1.2], base, [0, 1], [0.5, 0.8], [6.0, 10.0], [2.0, 2.0])
    b = M.p_work([9.0, 1.2, 1.0, 1.0], withrho, [0, 1], [0.5, 0.8], [6.0, 10.0], [2.0, 2.0])
    assert np.allclose(a, b)


def test_the_objfunc_returns_a_hand_computed_nll():
    spec = M.Spec()
    f = M.make_objfunc(spec)
    native = np.array([10.0, 1.5])
    # work the unbounded space back from the native one via the same squash
    from scipy.optimize import brentq
    from pyem.utils.math import norm2beta
    x = [brentq(lambda z, t=t, mx=mx: norm2beta(z, mx) - t, -8, 8)
         for t, mx in ((10.0, M.K_MAX), (1.5, M.BETA_MAX))]
    ben, eff, rew, rest = [0, 1], [0.5, 0.8], [6.0, 10.0], [2.0, 2.0]
    choice = [1.0, 0.0]
    p = M.p_work(native, spec, ben, eff, rew, rest)
    expected = -(np.log(p[0]) + np.log(1 - p[1]))
    out = f(x, ben, eff, rew, rest, choice, output="all")
    assert out["nll"] == pytest.approx(expected, rel=1e-6)
    assert np.allclose(out["params"], native, rtol=1e-6)


def test_to_native_stays_inside_the_squash():
    """The bound is the point: the optimiser works unbounded and the squash is
    what keeps k and beta positive and finite. It saturates exactly at the
    ceiling for extreme inputs, which is fine -- what must never happen is a
    parameter at or below zero, or above the ceiling."""
    spec = M.FAMILY["2k2b_par"]
    for x in (-50, -3, 0, 3, 50):
        nat = M.to_native([x] * spec.n_params, spec)
        assert (nat > 0).all()
        assert (nat[:2] <= M.K_MAX).all() and (nat[2:] <= M.BETA_MAX).all()
    inside = M.to_native([2.5] * spec.n_params, spec)
    assert (inside[:2] < M.K_MAX).all() and (inside[2:] < M.BETA_MAX).all()


def _frame(rows):
    cols = list(loader._EMPTY_COLS)
    return pd.DataFrame(rows, columns=cols)


def test_to_pyem_splits_by_session_not_pid_and_drops_missed():
    rows = []
    for sess in ("a", "b"):
        for i in range(3):
            rows.append(dict(pid="0004", session=sess, night=np.nan, trial_index=i,
                             beneficiary="self" if i else "other", effort_frac=0.5,
                             reward=6, rest_credit=1, choice="work", chose_work=1.0,
                             missed=False))
    rows.append(dict(pid="0004", session="a", night=np.nan, trial_index=9,
                     beneficiary="self", effort_frac=0.5, reward=6, rest_credit=1,
                     choice=None, chose_work=np.nan, missed=True))
    data, keys = M.to_pyem(_frame(rows))
    assert keys == ["0004/a", "0004/b"]
    assert [len(d[0]) for d in data] == [3, 3]          # the missed trial is gone
    assert list(data[0][0]) == [1, 0, 0]                # other, self, self
    assert list(data[0][3]) == [1.0, 1.0, 1.0]          # rest_credit from the trial


def test_night_trials_are_left_out_of_the_day_fit_by_default():
    rows = [dict(pid="p", session="s", night=np.nan, beneficiary="self", effort_frac=0.5,
                 reward=6, rest_credit=2, choice="work", chose_work=1.0, missed=False),
            dict(pid="p", session="s", night=1, beneficiary="self_take", effort_frac=0.5,
                 reward=6, rest_credit=2, choice="work", chose_work=1.0, missed=False)]
    data, _ = M.to_pyem(_frame(rows))
    assert len(data[0][0]) == 1


# --- against the real pilot sessions ---------------------------------------

@pytest.fixture(scope="module")
def pilot_data(sessions):
    """The PILOT generation only.

    Rewards, effort fractions and the rest credit all changed in September, so
    a later session is a different experiment and the assertions below (48
    trials, rest credit 1) are statements about the pilot design. Selecting on
    the design rather than taking whatever is in the mirror also means a new
    SONA session arriving does not change what these tests measure.
    """
    trials, sess = loader.build(sessions)
    kept, _ = inclusion.apply(inclusion.audit(sess))
    pilot = kept[kept["rest_credits"].apply(lambda x: tuple(x) == (1,))]
    sel = trials.merge(pilot[["pid", "session"]], on=["pid", "session"])
    return M.to_pyem(sel)


def test_the_real_pool_reaches_pyem_intact(pilot_data):
    data, keys = pilot_data
    assert len(keys) == 8, keys          # 10 sessions, 2 always-work excluded
    for arrays in data:
        assert all(len(a) == 48 for a in arrays)
        assert set(np.unique(arrays[4])) <= {0.0, 1.0}
        assert set(np.unique(arrays[3])) == {1.0}     # the pilot rest credit


@pytest.mark.slow
def test_a_real_fit_returns_usable_parameters(pilot_data):
    data, keys = pilot_data
    spec = M.FAMILY["2k1b_par"]
    _, native = M.fit(data, spec, seed=1)
    assert native.shape == (len(keys), 3)
    assert np.isfinite(native).all()
    assert (native > 0).all()
    assert (native[:, :2] < M.K_MAX).all()


@pytest.mark.slow
def test_recovery_on_the_real_design_is_the_positive_control(pilot_data):
    """The pilot fits return almost the same k_self for every session, which
    is either the prior filling in for uninformative data or a broken
    likelihood. Simulating spread-out true parameters on the SAME design and
    refitting separates the two: if k_self recovers here, the flatness is the
    participants, not the code.

    It does recover, at about +0.98. The self trials in the pilot really are
    close to flat across effort (0.69/0.69/0.69/0.42) where the partner trials
    show a clean gradient, so there is little for k_self to be estimated from.
    """
    data, keys = pilot_data
    spec = M.FAMILY["2k1b_par"]
    rng = np.random.default_rng(0)
    true = np.column_stack([rng.uniform(4, 16, len(data)),
                            rng.uniform(4, 16, len(data)),
                            rng.uniform(0.7, 2.2, len(data))])
    sim = [[ben, eff, rew, rest,
            M.simulate(true[i], spec, ben, eff, rew, rest, rng).astype(float)]
           for i, (ben, eff, rew, rest, _) in enumerate(data)]
    _, est = M.fit(sim, spec, seed=1)
    for j, name in enumerate(spec.param_names[:2]):
        r = np.corrcoef(true[:, j], est[:, j])[0, 1]
        assert r > 0.8, f"{name} recovered at {r:+.2f} on the real design"