Spaces:
Running
Running
Download analysis/pe_analysis/models.py from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 9.31 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/analysis/pe_analysis/models.py
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/analysis/pe_analysis/models.py
-
curl -L -o models.py https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/analysis/pe_analysis/models.py
9.31 kB
| """The effort-discounting model family, fitted to real sessions with pyEM. | |
| V_work = R - k * E**p V_rest = rest_credit | |
| P(work) = sigmoid(beta * (V_work - V_rest)) | |
| `analysis/effort_models.py` carries the same family for the design | |
| simulations. This is deliberately a separate implementation rather than an | |
| import: that one builds its own balanced design and takes the rest credit from | |
| a module constant, which is right for simulation and wrong here, because the | |
| rest credit has already changed once and every real trial has to carry its | |
| own. Sharing the module would let a change made for one silently alter the | |
| other. | |
| Everything is fitted per SESSION, never per pid. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import numpy as np | |
| import pandas as pd | |
| from pyem.api import EMModel, calc_BICint | |
| from . import loader | |
| from pyem.utils.math import calc_fval, norm2beta | |
| #: Squash ceilings for the unbounded fitting space. k * E**p has to be able to | |
| #: both undercut and overtake the reward-minus-rest gap or choices carry no | |
| #: information about k at all; with E**2 around 0.12-0.64 that needs room well | |
| #: above 10. | |
| K_MAX = 30.0 | |
| BETA_MAX = 3.0 | |
| RHO_MAX = 3.0 | |
| MISSING = ("", None) | |
| class Spec: | |
| """One model. `p` is the effort exponent: 2 is the parabolic cost used by | |
| Lockwood et al., 1 the linear alternative the family tests against it.""" | |
| n_k: int = 1 | |
| n_beta: int = 1 | |
| p: int = 2 | |
| n_rho: int = 0 | |
| def name(self) -> str: | |
| base = f"{self.n_k}k{self.n_beta}b_{'par' if self.p == 2 else 'lin'}" | |
| return base + (f"_{self.n_rho}rho" if self.n_rho else "") | |
| def param_names(self) -> list[str]: | |
| ks = ["k_self", "k_other"] if self.n_k == 2 else ["k"] | |
| bs = ["beta_self", "beta_other"] if self.n_beta == 2 else ["beta"] | |
| rs = (["rho_self", "rho_other"] if self.n_rho == 2 | |
| else ["rho"] if self.n_rho == 1 else []) | |
| return ks + bs + rs | |
| def n_params(self) -> int: | |
| return len(self.param_names) | |
| #: The eight the published comparisons use: self/other k crossed with | |
| #: self/other beta, each under a parabolic and a linear effort cost. | |
| FAMILY = {s.name: s for s in ( | |
| Spec(n_k, n_beta, p) for n_k in (1, 2) for n_beta in (1, 2) for p in (2, 1) | |
| )} | |
| #: Two more, and the reason for them. The day task crosses reward against | |
| #: effort fully, so it can separate "values their partner's credits less" from | |
| #: "finds effort costlier for their partner" -- but only if reward sensitivity | |
| #: is in the model. Without rho, every self/other difference is attributed to | |
| #: effort by construction, which is the whole claim. Kept out of FAMILY so the | |
| #: headline comparison stays the published one, and available for the test. | |
| EXTENDED = dict(FAMILY, **{s.name: s for s in ( | |
| Spec(1, 1, 2, 2), Spec(2, 1, 2, 2), | |
| )}) | |
| def _split(params: np.ndarray, spec: Spec): | |
| """Native-space (k_self, k_other, beta_self, beta_other, rho_self, rho_other).""" | |
| i = 0 | |
| if spec.n_k == 2: | |
| k_self, k_other = params[0], params[1]; i = 2 | |
| else: | |
| k_self = k_other = params[0]; i = 1 | |
| if spec.n_beta == 2: | |
| b_self, b_other = params[i], params[i + 1]; i += 2 | |
| else: | |
| b_self = b_other = params[i]; i += 1 | |
| if spec.n_rho == 2: | |
| r_self, r_other = params[i], params[i + 1] | |
| elif spec.n_rho == 1: | |
| r_self = r_other = params[i] | |
| else: | |
| r_self = r_other = 1.0 | |
| return k_self, k_other, b_self, b_other, r_self, r_other | |
| def p_work(params, spec: Spec, ben, eff, rew, rest): | |
| """P(choose work) per trial, from NATIVE-space parameters. | |
| `rest` is per trial, not a constant: it was 1 for every pilot session and | |
| is 2 now, and night 1 has its own value again. | |
| """ | |
| k_s, k_o, b_s, b_o, r_s, r_o = _split(np.asarray(params, float), spec) | |
| other = np.asarray(ben) == 1 | |
| k = np.where(other, k_o, k_s) | |
| beta = np.where(other, b_o, b_s) | |
| rho = np.where(other, r_o, r_s) | |
| v = rho * np.asarray(rew, float) - k * np.asarray(eff, float) ** spec.p \ | |
| - np.asarray(rest, float) | |
| return 1.0 / (1.0 + np.exp(-beta * v)) | |
| def to_native(params, spec: Spec) -> np.ndarray: | |
| """Unbounded fitting space -> native space.""" | |
| x = np.asarray(params, float) | |
| i = spec.n_k | |
| out = [norm2beta(v, K_MAX) for v in x[:i]] | |
| out += [norm2beta(v, BETA_MAX) for v in x[i:i + spec.n_beta]] | |
| i += spec.n_beta | |
| out += [norm2beta(v, RHO_MAX) for v in x[i:i + spec.n_rho]] | |
| return np.array(out) | |
| def make_objfunc(spec: Spec): | |
| """pyEM's expected signature for one model. | |
| Two output modes, both required. EM fitting wants a scalar objective, and | |
| calc_BICint calls the same function with output="all" and subscripts the | |
| result for "nll" -- returning a bare float there raises "'float' object is | |
| not subscriptable" from inside a joblib worker, a long way from the cause. | |
| """ | |
| def objfunc(params, ben, eff, rew, rest, choice, prior=None, output="npl"): | |
| native = to_native(params, spec) | |
| p = np.clip(p_work(native, spec, ben, eff, rew, rest), 1e-10, 1 - 1e-10) | |
| choice = np.asarray(choice, float) | |
| negll = -float(np.sum(choice * np.log(p) + (1 - choice) * np.log(1 - p))) | |
| if output == "all": | |
| return {"nll": 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 | |
| def to_pyem(trials: pd.DataFrame, day_only: bool = True) -> tuple[list, list[str]]: | |
| """Tidy frame -> pyEM's all_data: one list of arrays per session. | |
| Missed trials are dropped before any likelihood, matching Cutler's | |
| mod_ms_all.m. Sessions, not pids, in the order they first appear. | |
| """ | |
| df = trials | |
| if day_only: | |
| # is_day where the loader provides it. A night-watch trial carries | |
| # night=None, so filtering on that alone fitted the day model to the | |
| # watch block as well: 96 trials instead of 48, half of them with | |
| # reward=0 and a partner loss the day model has no term for. | |
| df = df[loader.day_mask(df)] | |
| # astype(bool): after a concat across sessions the column is object dtype, | |
| # and pandas reads an object mask as a list of column labels rather than | |
| # as a selection, which fails with a KeyError full of -1s. | |
| df = df[~df["missed"].astype(bool)] | |
| keys, data = [], [] | |
| for key, g in df.groupby(["pid", "session"], sort=False): | |
| need = ("beneficiary", "effort_frac", "reward", "rest_credit", "chose_work") | |
| if g[list(need)].isna().any().any(): | |
| raise ValueError(f"{key} has missing design columns; check the loader") | |
| data.append([ | |
| (g["beneficiary"].to_numpy() == "other").astype(int), | |
| g["effort_frac"].to_numpy(float), | |
| g["reward"].to_numpy(float), | |
| g["rest_credit"].to_numpy(float), | |
| g["chose_work"].to_numpy(float), | |
| ]) | |
| keys.append(f"{key[0]}/{key[1]}") | |
| return data, keys | |
| def fit(data, spec: Spec, seed: int = 1, verbose: int = 0): | |
| """Hierarchical EM fit. Returns (FitResult, native params as subjects x params).""" | |
| m = EMModel(all_data=data, fit_func=make_objfunc(spec), param_names=spec.param_names) | |
| 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([to_native(est[:, i], spec) for i in range(est.shape[1])]).T | |
| return res, native | |
| def bic_int(data, spec: Spec, res, nsamples: int = 2000) -> float: | |
| """Integrated BIC, the model-comparison statistic the family is ranked on. | |
| posterior_mu / posterior_sigma, not mu / sigma: pyEM's FitResult has no | |
| `mu`, and the wrong name makes every cell of a comparison matrix nan | |
| without raising. | |
| """ | |
| return float(calc_BICint(data, spec.param_names, res.posterior_mu, | |
| res.posterior_sigma, make_objfunc(spec), | |
| nsamples=nsamples)) | |
| def fit_table(data, keys, spec: Spec, seed: int = 1) -> pd.DataFrame: | |
| """One row per session, one column per parameter, in native units.""" | |
| _, native = fit(data, spec, seed=seed) | |
| out = pd.DataFrame(native, columns=spec.param_names) | |
| out.insert(0, "session_key", keys) | |
| out.insert(1, "model", spec.name) | |
| return out | |
| def compare(data, keys, specs=None, seed: int = 1, nsamples: int = 2000) -> pd.DataFrame: | |
| """Integrated BIC for each model, best first.""" | |
| specs = list((specs or FAMILY).values()) if isinstance(specs, dict) else list(specs or FAMILY.values()) | |
| rows = [] | |
| for spec in specs: | |
| res, _ = fit(data, spec, seed=seed) | |
| rows.append(dict(model=spec.name, n_params=spec.n_params, | |
| bic_int=bic_int(data, spec, res, nsamples=nsamples))) | |
| return pd.DataFrame(rows).sort_values("bic_int").reset_index(drop=True) | |
| def simulate(params, spec: Spec, ben, eff, rew, rest, rng) -> np.ndarray: | |
| """Choices from native-space parameters, for recovery on a real design.""" | |
| return (rng.random(len(np.asarray(eff))) | |
| < p_work(params, spec, ben, eff, rew, rest)).astype(int) | |