Spaces:
Running
Running
Download analysis/effort_models.py from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/analysis/effort_models.py
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/analysis/effort_models.py
-
curl -L -o effort_models.py https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/analysis/effort_models.py
10.1 kB
| """The effort-discounting model family, for use with Shawn Rhoads' pyEM. | |
| The model is the one used for prosocial effort discounting (Lockwood et al., | |
| Cutler's mod_ms_all.m): | |
| V_work = R - k * E**p | |
| V_rest = rest credit | |
| P(work) = sigmoid( beta * (V_work - V_rest) ) | |
| with E the required effort as a fraction of the participant's own calibrated | |
| maximum, so E is on (0, 1] and comparable across people of different strength. | |
| The family crosses three binary choices, giving eight models: | |
| k one discount rate, or one each for SELF and OTHER | |
| beta one inverse temperature, or one each | |
| p 2 (parabolic) or 1 (linear) | |
| The whole point of fitting these is the SELF/OTHER difference in k, so 1k models | |
| are in the family as the null: if they win, this task did not detect prosocial | |
| discounting at all. | |
| PARAMETER RANGES ARE THE THING TO GET RIGHT HERE. pyEM fits on an unbounded | |
| scale and squashes into range with norm2beta(x, max_val), so max_val has to | |
| bracket the plausible values without flattening the gradient. Set it far too | |
| high and the sigmoid saturates: every candidate value maps to nearly the same | |
| number, the optimiser sees no slope, and recovery is garbage in a way that looks | |
| like a modelling result rather than a bug. K_MAX and BETA_MAX below are chosen | |
| against the actual design (rewards 3/6/10, rest 2, effort 0.35-0.80), and | |
| `check_gradients()` verifies the squash is still informative at those values. | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| from pyem.utils.math import calc_fval, norm2beta | |
| # --- the design, from effort_design.py -------------------------------------- | |
| EFFORT_FRACS = np.array([0.35, 0.50, 0.65, 0.80]) | |
| REWARDS = np.array([3.0, 6.0, 10.0]) | |
| REST_CREDIT = 2.0 | |
| BENEFICIARIES = (0, 1) # 0 = SELF, 1 = OTHER | |
| #: Squash ranges. k * E**2 must be able to both undercut and overtake the | |
| #: reward-minus-rest gap (1 to 8 credits) or choices carry no information about | |
| #: k. With E**2 in 0.12..0.64 that needs k well above 10, so the ceiling is 20. | |
| K_MAX = 30.0 | |
| BETA_MAX = 3.0 | |
| #: Default true-parameter ranges, taken from the published work rather than | |
| #: from this project's own pilot. | |
| #: | |
| #: k 6..18 follows Lockwood et al. (2017, 2021): a rest option of 1 credit at 0% | |
| #: MVC against work at 2-10 credits for 30-70% MVC puts indifference near k of | |
| #: 10-20 when effort is coded as a fraction of maximum, which is how this task | |
| #: codes it. An earlier version anchored k to the pilot (3..9), which was wrong | |
| #: twice over -- the pilot ran a different design, and its nine sessions were | |
| #: mostly the researcher's own trial runs. It also inverted a design conclusion: | |
| #: under the pilot anchor the 10-credit trials looked like dead weight, when at | |
| #: the published scale they are what measures participants who rarely work. | |
| #: | |
| #: beta 0.7..2.2 matches the choice determinism in Jo Cutler's simulation code, | |
| #: which bounds beta at 0-5 and tests recovery at 1, 3 and 5. Value scales | |
| #: differ, so the match is on beta * (value difference), which is what the | |
| #: softmax sees. The earlier 0.4..0.9 made simulated participants about half as | |
| #: decisive as hers and suppressed the self/other gap from +0.60 to +0.30 at 48 | |
| #: trials, without changing overall P(work) at all. | |
| K_LO, K_HI = 6.0, 18.0 | |
| K_GAP = 3.0 | |
| K_GAP_SD = 1.5 | |
| BETA_LO, BETA_HI = 0.7, 2.2 | |
| #: The eight models, as (n_k, n_beta, exponent). | |
| MODELS = { | |
| f"{nk}k{nb}b_{'par' if p == 2 else 'lin'}": (nk, nb, p) | |
| for nk in (1, 2) for nb in (1, 2) for p in (2, 1) | |
| } | |
| def param_names(spec): | |
| nk, nb, _ = spec | |
| ks = ["k_self", "k_other"] if nk == 2 else ["k"] | |
| bs = ["beta_self", "beta_other"] if nb == 2 else ["beta"] | |
| return ks + bs | |
| def n_params(spec): | |
| return len(param_names(spec)) | |
| # --- design ----------------------------------------------------------------- | |
| def make_design(n_trials, rng): | |
| """Beneficiary / effort / reward arrays for one simulated participant. | |
| Built by repeating the full 24-cell grid and truncating, so every trial | |
| count is as close to balanced as it can be, then shuffled. A 24-trial run is | |
| exactly one pass through the grid -- the same structure the task uses. | |
| """ | |
| cells = [(b, e, r) for b in BENEFICIARIES for e in EFFORT_FRACS for r in REWARDS] | |
| reps = int(np.ceil(n_trials / len(cells))) | |
| d = np.array(cells * reps, dtype=float) | |
| rng.shuffle(d) | |
| d = d[:n_trials] | |
| return d[:, 0].astype(int), d[:, 1], d[:, 2] | |
| # --- native-space model ------------------------------------------------------ | |
| def _split(params, spec): | |
| """Native-space (k_self, k_other, beta_self, beta_other) for any model.""" | |
| nk, nb, _ = spec | |
| if nk == 2: | |
| k_self, k_other = params[0], params[1] | |
| rest = params[2:] | |
| else: | |
| k_self = k_other = params[0] | |
| rest = params[1:] | |
| if nb == 2: | |
| b_self, b_other = rest[0], rest[1] | |
| else: | |
| b_self = b_other = rest[0] | |
| return k_self, k_other, b_self, b_other | |
| def p_work(params, spec, ben, eff, rew): | |
| """P(choose work) per trial, from NATIVE-space parameters.""" | |
| _, _, p = spec | |
| k_self, k_other, b_self, b_other = _split(params, spec) | |
| k = np.where(ben == 0, k_self, k_other) | |
| beta = np.where(ben == 0, b_self, b_other) | |
| v = rew - k * eff ** p - REST_CREDIT | |
| return 1.0 / (1.0 + np.exp(-beta * v)) | |
| def simulate(params, spec, ben, eff, rew, rng): | |
| return (rng.random(len(eff)) < p_work(params, spec, ben, eff, rew)).astype(int) | |
| # --- fitting ----------------------------------------------------------------- | |
| def to_native(params, spec): | |
| """Unbounded fitting space -> native space.""" | |
| nk, nb, _ = spec | |
| ks = [norm2beta(x, K_MAX) for x in params[:nk]] | |
| bs = [norm2beta(x, BETA_MAX) for x in params[nk:nk + nb]] | |
| return np.array(ks + bs) | |
| def make_objfunc(spec): | |
| """An objfunc with pyEM's expected signature for one model. | |
| Two output modes, both required. EM fitting wants a scalar objective, but | |
| calc_BICint calls the same function with output="all" and subscripts the | |
| result for its "nll" key -- returning a bare float there raises | |
| "'float' object is not subscriptable" from inside a joblib worker, which is | |
| a long way from the actual cause. | |
| """ | |
| def objfunc(params, ben, eff, rew, choice, prior=None, output="npl"): | |
| native = to_native(np.asarray(params, dtype=float), spec) | |
| p = np.clip(p_work(native, spec, ben, eff, rew), 1e-10, 1 - 1e-10) | |
| negll = -np.sum(choice * np.log(p) + (1 - choice) * np.log(1 - p)) | |
| if output == "all": | |
| return {"nll": float(negll), | |
| "npl": float(calc_fval(negll, params, prior=prior, output="npl")), | |
| "params": native, "p_work": p} | |
| return calc_fval(negll, params, prior=prior, output=output) | |
| return objfunc | |
| # --- true parameters for simulation ----------------------------------------- | |
| def draw_true(spec, n_subjects, rng, k_lo=None, k_hi=None, b_lo=None, b_hi=None, | |
| k_gap=None): | |
| """Plausible true parameters. | |
| SELF and OTHER k are drawn with OTHER shifted up by `k_gap` on average -- | |
| people discount effort more steeply when the reward goes to someone else, | |
| which is the effect the task exists to measure. Simulating with no gap at | |
| all would make the 2k models unidentifiable by construction and the model | |
| recovery meaningless. | |
| """ | |
| k_lo = K_LO if k_lo is None else k_lo | |
| k_hi = K_HI if k_hi is None else k_hi | |
| b_lo = BETA_LO if b_lo is None else b_lo | |
| b_hi = BETA_HI if b_hi is None else b_hi | |
| k_gap = K_GAP if k_gap is None else k_gap | |
| nk, nb, _ = spec | |
| cols = [] | |
| k_self = rng.uniform(k_lo, k_hi, n_subjects) | |
| if nk == 2: | |
| cols += [k_self, np.clip(k_self + rng.normal(k_gap, K_GAP_SD, n_subjects), | |
| 0.2, K_MAX - 0.2)] | |
| else: | |
| cols += [k_self] | |
| b_self = rng.uniform(b_lo, b_hi, n_subjects) | |
| if nb == 2: | |
| cols += [b_self, np.clip(b_self + rng.normal(0.0, 0.3, n_subjects), | |
| 0.1, BETA_MAX - 0.1)] | |
| else: | |
| cols += [b_self] | |
| return np.column_stack(cols) | |
| def make_dataset(spec, true_params, n_trials, rng): | |
| """[[ben, eff, rew, choice], ...] -- pyEM's per-subject argument lists.""" | |
| data = [] | |
| for i in range(true_params.shape[0]): | |
| ben, eff, rew = make_design(n_trials, rng) | |
| choice = simulate(true_params[i], spec, ben, eff, rew, rng) | |
| data.append([ben, eff, rew, choice]) | |
| return data | |
| # --- sanity checks on the squash -------------------------------------------- | |
| def check_gradients(values, max_val, name=""): | |
| """How much native movement one unit of fitting-space movement buys. | |
| A near-zero gradient means the squash has saturated at these values: the | |
| optimiser cannot tell candidate parameters apart, and recovery collapses | |
| for a reason that has nothing to do with the design. This is the check that | |
| catches a badly chosen max_val before it is mistaken for a result. | |
| """ | |
| values = np.asarray(values, dtype=float) | |
| frac = values / max_val | |
| grad = max_val * frac * (1 - frac) # d(norm2beta)/dx at that value | |
| return {"name": name, "max_val": max_val, | |
| "value_range": (float(values.min()), float(values.max())), | |
| "gradient_range": (float(grad.min()), float(grad.max()))} | |
| def choice_balance(spec, true_params, n_trials, rng, n_rep=200): | |
| """P(work) across simulated participants. | |
| Binary-choice information is p(1-p), maximised at 0.5 and vanishing at the | |
| extremes, so a design that pins everyone at 0.02 or 0.98 cannot recover | |
| anything however many trials it has. This reports where the design actually | |
| sits. | |
| """ | |
| ps = [] | |
| for i in range(min(n_rep, true_params.shape[0])): | |
| ben, eff, rew = make_design(n_trials, rng) | |
| ps.append(p_work(true_params[i], spec, ben, eff, rew).mean()) | |
| ps = np.array(ps) | |
| return {"mean_p_work": float(ps.mean()), | |
| "min": float(ps.min()), "max": float(ps.max()), | |
| "frac_saturated": float(np.mean((ps < 0.05) | (ps > 0.95)))} | |