Download rl_hp.py from princessamygdala/TreasureHuntForTwo: direct link, hf CLI and curl.
- Browser
- Download file 182 kB
-
https://huggingface.co/spaces/princessamygdala/TreasureHuntForTwo/resolve/main/rl_hp.py
- Command line
-
hf download hf://spaces/princessamygdala/TreasureHuntForTwo/rl_hp.py
-
curl -L -o rl_hp.py https://huggingface.co/spaces/princessamygdala/TreasureHuntForTwo/resolve/main/rl_hp.py
182 kB
import numpy as np, random
from itertools import permutations, chain
# Absolute, not `from ..utils.math`. This file is written to sit inside the pyem package
# as pyem/models/rl_hp.py, and the relative form only resolves there. It is not installed
# there: the copy that exists is this one, in the repo, so `import rl_hp` was an
# ImportError and nothing here could be run without first copying the file into
# site-packages. Absolute works from both places.
from pyem.utils.math import softmax, norm2alpha, norm2beta, calc_fval
LETTER_TO_IDX = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ALL_PAIRS = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
# A:+/+ B:+/− C:−/+ D:−/− (self, other)
OPT_TYPES = {
'A': ('+', '+'),
'B': ('+', '-'),
'C': ('-', '+'),
'D': ('-', '-'),
}
def gen_rnd_blocks(items, nblocks=2, nsubjects=100):
perms = list(permutations(items))
for _ in range(nsubjects):
blocks = random.choices(perms, k=nblocks)
combined = tuple(chain.from_iterable(blocks))
yield combined
# ----------------------------------------
# 1Q–1α–1β SIMULATE (1q1a1b)
# ----------------------------------------
def rw1q1a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
"""
1Q, 1α, 1β model.
- One value per option (EV)
- One inverse temperature beta
- One learning rate alpha applied to the sum of self & other PEs.
Outcomes_self/other in {-1,+1} via '+'/'-' templates:
A: +/+
B: +/-
C: -/+
D: -/-
Each trial: choose between a fixed pair of options in that block.
"""
assert nblocks % 6 == 0, "nblocks should be multiple of 6 for full counterbalancing"
# --- bounds / unpack ---
(beta_all,
alpha_all) = (params[:, i].astype(float) for i in range(2))
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
if not ((0.0 <= alpha_all) & (alpha_all <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure: each subject sees each pair exactly nblocks/6 times ---
reps_per_pair = nblocks // 6
block_orders = []
for _ in range(nsubjects):
pairs_for_subject = ALL_PAIRS * reps_per_pair # list of length nblocks
rng.shuffle(pairs_for_subject)
block_orders.append(pairs_for_subject)
# outcome templates for valence types: no zeros, non-deterministic
opt_templates = {
'+': rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int),
'-': rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
}
# --- outputs ---
choices = np.zeros((nsubjects, nblocks, ntrials), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
option_pairs = np.zeros((nsubjects, nblocks, ntrials, 2), dtype=object)
EV = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta = beta_all[s]
alpha = alpha_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = LETTER_TO_IDX[opt1], LETTER_TO_IDX[opt2]
# pre-generate outcomes for this block (only for shown options)
all_outcomes = {
f'{opt1}_self': rng.permutation(opt_templates[OPT_TYPES[opt1][0]]),
f'{opt1}_other': rng.permutation(opt_templates[OPT_TYPES[opt1][1]]),
f'{opt2}_self': rng.permutation(opt_templates[OPT_TYPES[opt2][0]]),
f'{opt2}_other': rng.permutation(opt_templates[OPT_TYPES[opt2][1]]),
}
EV[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t] = [opt1, opt2]
ch_prob[s, b, t, [o1, o2]] = softmax(EV[s, b, t, [o1, o2]], beta)
chosen = rng.choice([opt1, opt2], p=ch_prob[s, b, t, [o1, o2]])
choices[s, b, t] = chosen
c = LETTER_TO_IDX[chosen]
outcomes_self[s, b, t] = int(all_outcomes[f'{chosen}_self'][t])
outcomes_other[s, b, t] = int(all_outcomes[f'{chosen}_other'][t])
pe_self[s, b, t] = outcomes_self[s, b, t] - EV[s, b, t, c]
pe_other[s, b, t] = outcomes_other[s, b, t] - EV[s, b, t, c]
EV[s, b, t + 1] = EV[s, b, t]
EV[s, b, t + 1, c] += alpha * (pe_self[s, b, t] + pe_other[s, b, t])
return {
"params": np.column_stack((beta_all, alpha_all)),
"choices": choices,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"option_pairs": option_pairs,
"EV": EV,
"ch_prob": ch_prob,
"pe_self": pe_self,
"pe_other": pe_other
}
# ----------------------------------------
# 1Q–1α–1β FIT (1q1a1b)
# ----------------------------------------
def rw1q1a1b_fit(params: np.ndarray,
choices: np.ndarray,
outcomes_self: np.ndarray,
outcomes_other: np.ndarray,
option_pairs: np.ndarray,
prior=None,
output: str = "npl"):
"""
Fit 1Q, 1α, 1β model.
params (unconstrained):
params[0] -> beta via norm2beta
params[1] -> alpha via norm2alpha
choices: (nblocks, ntrials) letters ('A'..'D') or indices 0..3
outcomes_*: (nblocks, ntrials) in {-1, +1}
option_pairs: (nblocks, ntrials, 2) letters ('A'..'D')
"""
# ---- transforms / bounds ----
beta = norm2beta(params[0])
alpha = norm2alpha(params[1])
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
if not (0.0 <= float(alpha) <= 1.0):
return 1e7
# ---- choices to indices ----
choice_array = np.asarray(choices)
if not np.issubdtype(choice_array.dtype, np.number):
choice_array = np.vectorize(LETTER_TO_IDX.get)(choice_array)
choice_array = choice_array.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
# ---- storage ----
EV = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
nll = 0.0
for b in range(nblocks):
# start each block with zero values (matching SIM)
EV[b, 0, :] = 0.0
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = LETTER_TO_IDX[opt1], LETTER_TO_IDX[opt2]
c_idx = int(choice_array[b, t])
# choice probabilities for the two shown options
probs_2 = softmax(EV[b, t, [o1, o2]], beta)
ch_prob[b, t, [o1, o2]] = probs_2
# probability of the actually chosen option
if c_idx == o1:
p_chosen = probs_2[0]
elif c_idx == o2:
p_chosen = probs_2[1]
else:
# chosen option not among the two shown → impossible under design
return 1e7
nll += -np.log(p_chosen + 1e-12)
# outcomes
outcome_self_value = outcomes_self[b, t]
outcome_other_value = outcomes_other[b, t]
# prediction errors
pe_self[b, t] = outcome_self_value - EV[b, t, c_idx]
pe_other[b, t] = outcome_other_value - EV[b, t, c_idx]
# value update
EV[b, t + 1, :] = EV[b, t, :]
EV[b, t + 1, c_idx] = EV[b, t, c_idx] + alpha * (pe_self[b, t] + pe_other[b, t])
# 2 free parameters: beta, alpha
BIC = 2 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta, alpha],
"choices": choice_array,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"option_pairs": option_pairs,
"EV": EV,
"ch_prob": ch_prob,
"pe_self": pe_self,
"pe_other": pe_other,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ----------------------------------------
# 1Q–2α–1β (target) SIMULATE
# ----------------------------------------
def rw1q2a1b_target_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
"""
1Q, 2α (alpha_self, alpha_other), 1β.
Outcomes_self/other in {-1,+1}; choice between 2 of 4 options (A-D).
EV update uses separate alphas for self vs other PEs.
"""
assert nblocks % 6 == 0, "nblocks should be multiple of 6 for full counterbalancing"
# --- bounds / unpack ---
(beta_all,
alpha_self_all,
alpha_other_all) = (params[:, i].astype(float) for i in range(3))
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
for arr, name in [(alpha_self_all, "alpha_self"), (alpha_other_all, "alpha_other")]:
if not ((0.0 <= arr) & (arr <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# task structure: each subject sees each pair exactly nblocks/6 times
reps_per_pair = nblocks // 6
block_orders = []
for _ in range(nsubjects):
pairs_for_subject = ALL_PAIRS * reps_per_pair
rng.shuffle(pairs_for_subject)
block_orders.append(pairs_for_subject)
# same outcome schedule as 1q1a1b: no zeros
opt_templates = {
'+': rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int),
'-': rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
}
# --- outputs ---
choices = np.zeros((nsubjects, nblocks, ntrials), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
option_pairs = np.zeros((nsubjects, nblocks, ntrials, 2), dtype=object)
EV = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta = beta_all[s]
alpha_self = alpha_self_all[s]
alpha_other = alpha_other_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = LETTER_TO_IDX[opt1], LETTER_TO_IDX[opt2]
all_outcomes = {
f'{opt1}_self': rng.permutation(opt_templates[OPT_TYPES[opt1][0]]),
f'{opt1}_other': rng.permutation(opt_templates[OPT_TYPES[opt1][1]]),
f'{opt2}_self': rng.permutation(opt_templates[OPT_TYPES[opt2][0]]),
f'{opt2}_other': rng.permutation(opt_templates[OPT_TYPES[opt2][1]]),
}
EV[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t] = [opt1, opt2]
ch_prob[s, b, t, [o1, o2]] = softmax(EV[s, b, t, [o1, o2]], beta)
chosen = rng.choice([opt1, opt2], p=ch_prob[s, b, t, [o1, o2]])
choices[s, b, t] = chosen
c = LETTER_TO_IDX[chosen]
outcomes_self[s, b, t] = int(all_outcomes[f'{chosen}_self'][t])
outcomes_other[s, b, t] = int(all_outcomes[f'{chosen}_other'][t])
pe_self[s, b, t] = outcomes_self[s, b, t] - EV[s, b, t, c]
pe_other[s, b, t] = outcomes_other[s, b, t] - EV[s, b, t, c]
EV[s, b, t + 1] = EV[s, b, t]
EV[s, b, t + 1, c] = EV[s, b, t, c] + (
alpha_self * pe_self[s, b, t] +
alpha_other * pe_other[s, b, t]
)
return {
"params": np.column_stack((beta_all, alpha_self_all, alpha_other_all)),
"choices": choices,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"option_pairs": option_pairs,
"EV": EV,
"ch_prob": ch_prob,
"pe_self": pe_self,
"pe_other": pe_other
}
# ----------------------------------
# 1Q–2α–1β (target) FIT
# ----------------------------------
def rw1q2a1b_target_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters or indices
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha_self = norm2alpha(params[1])
alpha_other = norm2alpha(params[2])
# bounds
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
for a in (alpha_self, alpha_other):
if not (0.0 <= float(a) <= 1.0):
return 1e7
# choices -> indices
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(LETTER_TO_IDX.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
# option_pairs -> indices
op_arr = np.asarray(option_pairs)
if np.issubdtype(op_arr.dtype, np.number):
op_idx = op_arr.astype(int, copy=False)
else:
op_idx = np.vectorize(LETTER_TO_IDX.get)(op_arr)
nblocks, ntrials = outcomes_self.shape
EV = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
nll = 0.0
for b in range(nblocks):
EV[b, 0, :] = 0.0
for t in range(ntrials):
o1, o2 = int(op_idx[b, t, 0]), int(op_idx[b, t, 1])
c = int(ch_arr[b, t])
ch_prob[b, t, [o1, o2]] = softmax(EV[b, t, [o1, o2]], beta)
p_ch = ch_prob[b, t, c]
nll += -np.log(p_ch + 1e-12)
pe_self[b, t] = outcomes_self[b, t] - EV[b, t, c]
pe_other[b, t] = outcomes_other[b, t] - EV[b, t, c]
EV[b, t + 1] = EV[b, t]
EV[b, t + 1, c] = EV[b, t, c] + (
alpha_self * pe_self[b, t] +
alpha_other * pe_other[b, t]
)
# k = 3 free parameters
BIC = 3 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta, alpha_self, alpha_other],
"choices": ch_arr,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"option_pairs": option_pairs,
"EV": EV,
"ch_prob": ch_prob,
"pe_self": pe_self,
"pe_other": pe_other,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ----------------------------------------
# 1Q–2α–1β (valence) SIMULATE
# ----------------------------------------
def rw1q2a1b_valence_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
"""
1Q, 2α (alpha_pos, alpha_neg), 1β.
PEs from self and other are pooled by sign at the level of the
combined PE (pe_self + pe_other). Only pe_self and pe_other are stored.
"""
assert nblocks % 6 == 0, "nblocks should be multiple of 6 for full counterbalancing"
# --- bounds / unpack ---
(beta_all,
alpha_pos_all,
alpha_neg_all) = (params[:, i].astype(float) for i in range(3))
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
for arr, name in [(alpha_pos_all, "alpha_pos"), (alpha_neg_all, "alpha_neg")]:
if not ((0.0 <= arr) & (arr <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# task structure: each subject sees each pair exactly nblocks/6 times
reps_per_pair = nblocks // 6
block_orders = []
for _ in range(nsubjects):
pairs_for_subject = ALL_PAIRS * reps_per_pair
rng.shuffle(pairs_for_subject)
block_orders.append(pairs_for_subject)
# same outcome schedule as 1q1a1b: no zeros
opt_templates = {
'+': rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int),
'-': rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
}
# --- outputs ---
choices = np.zeros((nsubjects, nblocks, ntrials), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
option_pairs = np.zeros((nsubjects, nblocks, ntrials, 2), dtype=object)
EV = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta = beta_all[s]
alpha_pos = alpha_pos_all[s]
alpha_neg = alpha_neg_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = LETTER_TO_IDX[opt1], LETTER_TO_IDX[opt2]
all_outcomes = {
f'{opt1}_self': rng.permutation(opt_templates[OPT_TYPES[opt1][0]]),
f'{opt1}_other': rng.permutation(opt_templates[OPT_TYPES[opt1][1]]),
f'{opt2}_self': rng.permutation(opt_templates[OPT_TYPES[opt2][0]]),
f'{opt2}_other': rng.permutation(opt_templates[OPT_TYPES[opt2][1]]),
}
EV[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t] = [opt1, opt2]
ch_prob[s, b, t, [o1, o2]] = softmax(EV[s, b, t, [o1, o2]], beta)
chosen = rng.choice([opt1, opt2], p=ch_prob[s, b, t, [o1, o2]])
choices[s, b, t] = chosen
c = LETTER_TO_IDX[chosen]
outcomes_self[s, b, t] = int(all_outcomes[f'{chosen}_self'][t])
outcomes_other[s, b, t] = int(all_outcomes[f'{chosen}_other'][t])
pe_self[s, b, t] = outcomes_self[s, b, t] - EV[s, b, t, c]
pe_other[s, b, t] = outcomes_other[s, b, t] - EV[s, b, t, c]
pe_total = pe_self[s, b, t] + pe_other[s, b, t]
EV[s, b, t + 1] = EV[s, b, t]
if pe_total >= 0.0:
EV[s, b, t + 1, c] = EV[s, b, t, c] + alpha_pos * pe_total
else:
EV[s, b, t + 1, c] = EV[s, b, t, c] + alpha_neg * pe_total
return {
"params": np.column_stack((beta_all, alpha_pos_all, alpha_neg_all)),
"choices": choices,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"option_pairs": option_pairs,
"EV": EV,
"ch_prob": ch_prob,
"pe_self": pe_self,
"pe_other": pe_other
}
# ----------------------------------
# 1Q–2α–1β (valence) FIT
# ----------------------------------
def rw1q2a1b_valence_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters or indices
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha_pos = norm2alpha(params[1])
alpha_neg = norm2alpha(params[2])
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
for a in (alpha_pos, alpha_neg):
if not (0.0 <= float(a) <= 1.0):
return 1e7
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(LETTER_TO_IDX.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
op_arr = np.asarray(option_pairs)
if np.issubdtype(op_arr.dtype, np.number):
op_idx = op_arr.astype(int, copy=False)
else:
op_idx = np.vectorize(LETTER_TO_IDX.get)(op_arr)
nblocks, ntrials = outcomes_self.shape
EV = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
nll = 0.0
for b in range(nblocks):
EV[b, 0, :] = 0.0
for t in range(ntrials):
o1, o2 = int(op_idx[b, t, 0]), int(op_idx[b, t, 1])
c = int(ch_arr[b, t])
ch_prob[b, t, [o1, o2]] = softmax(EV[b, t, [o1, o2]], beta)
p_ch = ch_prob[b, t, c]
nll += -np.log(p_ch + 1e-12)
pe_self[b, t] = outcomes_self[b, t] - EV[b, t, c]
pe_other[b, t] = outcomes_other[b, t] - EV[b, t, c]
pe_total = pe_self[b, t] + pe_other[b, t]
EV[b, t + 1] = EV[b, t]
if pe_total >= 0.0:
EV[b, t + 1, c] = EV[b, t, c] + alpha_pos * pe_total
else:
EV[b, t + 1, c] = EV[b, t, c] + alpha_neg * pe_total
BIC = 3 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta, alpha_pos, alpha_neg],
"choices": ch_arr,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"option_pairs": option_pairs,
"EV": EV,
"ch_prob": ch_prob,
"pe_self": pe_self,
"pe_other": pe_other,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ----------------------------------------
# 1Q–4α–1β SIMULATE
# ----------------------------------------
def rw1q4a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
"""
1Q, 4α, 1β model:
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg.
Outcomes in {-1,+1} via the same '+'/'-' templates as 1q1a1b.
"""
assert nblocks % 6 == 0, "nblocks should be multiple of 6 for full counterbalancing"
# --- bounds / unpack ---
(beta_all,
alpha_self_pos_all,
alpha_self_neg_all,
alpha_other_pos_all,
alpha_other_neg_all) = (params[:, i].astype(float) for i in range(5))
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
for arr, name in [
(alpha_self_pos_all, "alpha_self_pos"),
(alpha_self_neg_all, "alpha_self_neg"),
(alpha_other_pos_all, "alpha_other_pos"),
(alpha_other_neg_all, "alpha_other_neg")
]:
if not ((0.0 <= arr) & (arr <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# task structure: each subject sees each pair exactly nblocks/6 times
reps_per_pair = nblocks // 6
block_orders = []
for _ in range(nsubjects):
pairs_for_subject = ALL_PAIRS * reps_per_pair
rng.shuffle(pairs_for_subject)
block_orders.append(pairs_for_subject)
# same outcome schedule as 1q1a1b: no zeros
opt_templates = {
'+': rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int),
'-': rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
}
# --- outputs ---
choices = np.zeros((nsubjects, nblocks, ntrials), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
option_pairs = np.zeros((nsubjects, nblocks, ntrials, 2), dtype=object)
EV = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_neg = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other_pos = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other_neg = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta = beta_all[s]
alpha_self_pos = alpha_self_pos_all[s]
alpha_self_neg = alpha_self_neg_all[s]
alpha_other_pos = alpha_other_pos_all[s]
alpha_other_neg = alpha_other_neg_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = LETTER_TO_IDX[opt1], LETTER_TO_IDX[opt2]
all_outcomes = {
f'{opt1}_self': rng.permutation(opt_templates[OPT_TYPES[opt1][0]]),
f'{opt1}_other': rng.permutation(opt_templates[OPT_TYPES[opt1][1]]),
f'{opt2}_self': rng.permutation(opt_templates[OPT_TYPES[opt2][0]]),
f'{opt2}_other': rng.permutation(opt_templates[OPT_TYPES[opt2][1]]),
}
EV[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t] = [opt1, opt2]
ch_prob[s, b, t, [o1, o2]] = softmax(EV[s, b, t, [o1, o2]], beta)
chosen = rng.choice([opt1, opt2], p=ch_prob[s, b, t, [o1, o2]])
choices[s, b, t] = chosen
c = LETTER_TO_IDX[chosen]
outcomes_self[s, b, t] = int(all_outcomes[f'{chosen}_self'][t])
outcomes_other[s, b, t] = int(all_outcomes[f'{chosen}_other'][t])
pe_self[s, b, t] = outcomes_self[s, b, t] - EV[s, b, t, c]
pe_other[s, b, t] = outcomes_other[s, b, t] - EV[s, b, t, c]
pe_self_pos[s, b, t] = pe_self[s, b, t] if pe_self[s, b, t] >= 0.0 else 0.0
pe_self_neg[s, b, t] = pe_self[s, b, t] if pe_self[s, b, t] < 0.0 else 0.0
pe_other_pos[s, b, t] = pe_other[s, b, t] if pe_other[s, b, t] >= 0.0 else 0.0
pe_other_neg[s, b, t] = pe_other[s, b, t] if pe_other[s, b, t] < 0.0 else 0.0
EV[s, b, t + 1] = EV[s, b, t]
EV[s, b, t + 1, c] = EV[s, b, t, c] + (
alpha_self_pos * pe_self_pos[s, b, t] +
alpha_self_neg * pe_self_neg[s, b, t] +
alpha_other_pos * pe_other_pos[s, b, t] +
alpha_other_neg * pe_other_neg[s, b, t]
)
return {
"params": np.column_stack((
beta_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all
)),
"choices": choices,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"option_pairs": option_pairs,
"EV": EV,
"ch_prob": ch_prob,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg
}
# ----------------------------------
# 1Q–4α–1β FIT
# ----------------------------------
def rw1q4a1b_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters or indices
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha_self_pos = norm2alpha(params[1])
alpha_self_neg = norm2alpha(params[2])
alpha_other_pos = norm2alpha(params[3])
alpha_other_neg = norm2alpha(params[4])
# bounds
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
for a in (alpha_self_pos, alpha_self_neg, alpha_other_pos, alpha_other_neg):
if not (0.0 <= float(a) <= 1.0):
return 1e7
choices_arr = np.asarray(choices)
if not np.issubdtype(choices_arr.dtype, np.number):
choices_arr = np.vectorize(LETTER_TO_IDX.get)(choices_arr)
choices_arr = choices_arr.astype(int, copy=False)
op_arr = np.asarray(option_pairs)
if np.issubdtype(op_arr.dtype, np.number):
op_idx = op_arr.astype(int, copy=False)
else:
op_idx = np.vectorize(LETTER_TO_IDX.get)(op_arr)
nblocks, ntrials = outcomes_self.shape
EV = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros((nblocks, ntrials), dtype=float)
pe_self_neg = np.zeros((nblocks, ntrials), dtype=float)
pe_other_pos = np.zeros((nblocks, ntrials), dtype=float)
pe_other_neg = np.zeros((nblocks, ntrials), dtype=float)
nll = 0.0
for b in range(nblocks):
EV[b, 0, :] = 0.0
for t in range(ntrials):
o1, o2 = int(op_idx[b, t, 0]), int(op_idx[b, t, 1])
c = int(choices_arr[b, t])
ch_prob[b, t, [o1, o2]] = softmax(EV[b, t, [o1, o2]], beta)
p_ch = ch_prob[b, t, c]
nll += -np.log(p_ch + 1e-12)
pe_self[b, t] = outcomes_self[b, t] - EV[b, t, c]
pe_other[b, t] = outcomes_other[b, t] - EV[b, t, c]
pe_self_pos[b, t] = pe_self[b, t] if pe_self[b, t] >= 0.0 else 0.0
pe_self_neg[b, t] = pe_self[b, t] if pe_self[b, t] < 0.0 else 0.0
pe_other_pos[b, t] = pe_other[b, t] if pe_other[b, t] >= 0.0 else 0.0
pe_other_neg[b, t] = pe_other[b, t] if pe_other[b, t] < 0.0 else 0.0
EV[b, t + 1] = EV[b, t]
EV[b, t + 1, c] = EV[b, t, c] + (
alpha_self_pos * pe_self_pos[b, t] +
alpha_self_neg * pe_self_neg[b, t] +
alpha_other_pos * pe_other_pos[b, t] +
alpha_other_neg * pe_other_neg[b, t]
)
# k = 5 free parameters
BIC = 5 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [
beta,
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg
],
"choices": choices_arr,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"option_pairs": option_pairs,
"EV": EV,
"ch_prob": ch_prob,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–1α–1β SIMULATE (EV_self, EV_other; β; α)
# params columns (2), per subject:
# [beta, alpha]
# Choice rule: v = beta * (EV_self + EV_other)
# ============================================================
def rw2q1a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
# --- bounds / unpack ---
(beta_all,
alpha_all) = (params[:, i].astype(float) for i in range(2))
# beta bounds
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
# alpha bounds
if not ((0.0 <= alpha_all) & (alpha_all <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure ---
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list,
nblocks=nblocks,
nsubjects=nsubjects))
# outcome templates: ±1 only, 75/25
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
# A:+/+ B:+/− C:−/+ D:−/− (first = self stream, second = other stream)
opt_types = {
'A': ('+', '+'),
'B': ('+', '-'),
'C': ('-', '+'),
'D': ('-', '-')
}
# --- outputs ---
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta = beta_all[s]
alpha = alpha_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
# pre-generate outcomes for the two shown options this block
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self = rng.permutation(stream_for(self_kind1))
opt1_other = rng.permutation(stream_for(other_kind1))
opt2_self = rng.permutation(stream_for(self_kind2))
opt2_other = rng.permutation(stream_for(other_kind2))
# reset EVs at block start
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
# choice rule: beta * (EV_self + EV_other), softmax β=1
q1 = EV_self[s, b, t, o1] + EV_other[s, b, t, o1]
q2 = EV_self[s, b, t, o2] + EV_other[s, b, t, o2]
v1 = beta * q1
v2 = beta * q2
p = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[s, b, t, o1] = p[0]
choice_probabilities[s, b, t, o2] = p[1]
chosen = rng.choice([opt1, opt2], p=p)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
# realize outcomes for chosen option (self/other streams)
if chosen == opt1:
r_self, r_other = int(opt1_self[t]), int(opt1_other[t])
else:
r_self, r_other = int(opt2_self[t]), int(opt2_other[t])
outcomes_self[s, b, t] = r_self
outcomes_other[s, b, t] = r_other
# PEs against their own stream
delta_self = r_self - EV_self[s, b, t, c]
delta_other = r_other - EV_other[s, b, t, c]
pe_self[s, b, t] = delta_self
pe_other[s, b, t] = delta_other
pe_self_pos[s, b, t] = max(delta_self, 0.0)
pe_self_neg[s, b, t] = min(delta_self, 0.0)
pe_other_pos[s, b, t] = max(delta_other, 0.0)
pe_other_neg[s, b, t] = min(delta_other, 0.0)
# carry forward then update chosen option in each stream
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = (
EV_self[s, b, t, c] + alpha * delta_self
)
EV_other[s, b, t+1, c] = (
EV_other[s, b, t, c] + alpha * delta_other
)
return {
"params": np.column_stack((beta_all, alpha_all)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–1α–1β FIT (EV_self, EV_other; β; α)
# Mirrors simulate; supports letter or index choices/option_pairs.
# params = [beta, alpha]
# ============================================================
def rw2q1a1b_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha = norm2alpha(params[1])
# bounds
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
if not (0.0 <= float(alpha) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(letter_to_idx.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(ch_arr[b, t])
# choice prob: beta * (EV_self + EV_other), softmax β=1
q1 = EV_self[b, t, o1] + EV_other[b, t, o1]
q2 = EV_self[b, t, o2] + EV_other[b, t, o2]
v1 = beta * q1
v2 = beta * q2
probs = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
# PEs (diagnostics; no sign-split in update)
delta_self = outcomes_self[b, t] - EV_self[b, t, c]
delta_other = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = delta_self
pe_other[b, t] = delta_other
pe_self_pos[b, t] = max(delta_self, 0.0)
pe_self_neg[b, t] = min(delta_self, 0.0)
pe_other_pos[b, t] = max(delta_other, 0.0)
pe_other_neg[b, t] = min(delta_other, 0.0)
# carry-forward + update chosen
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = (
EV_self[b, t, c] + alpha * delta_self
)
EV_other[b, t+1, c] = (
EV_other[b, t, c] + alpha * delta_other
)
# k = 2 free parameters
BIC = 2 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta, alpha],
"choices": ch_arr,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–1α–2β SIMULATE (EV_self, EV_other; β_self, β_other; α)
# params columns (3), per subject:
# [beta_self, beta_other, alpha]
# Choice rule: v = beta_self*EV_self + beta_other*EV_other
# ============================================================
def rw2q1a2b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
# --- bounds / unpack ---
(beta_self_all,
beta_other_all,
alpha_all) = (params[:, i].astype(float) for i in range(3))
# beta bounds
for array, name in [(beta_self_all, "beta_self"), (beta_other_all, "beta_other")]:
if not ((array > 1e-5) & (array <= 20.0)).all():
raise ValueError(f"{name} out of bounds (must be in (1e-5, 20]).")
# alpha bounds
if not ((0.0 <= alpha_all) & (alpha_all <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure ---
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
# outcome templates: ±1 only, 75/25
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
# A:+/+ B:+/− C:−/+ D:−/− (first = self stream, second = other stream)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
# --- outputs ---
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta_self = beta_self_all[s]
beta_other = beta_other_all[s]
alpha = alpha_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
# pre-generate outcomes for the two shown options this block
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self = rng.permutation(stream_for(self_kind1))
opt1_other = rng.permutation(stream_for(other_kind1))
opt2_self = rng.permutation(stream_for(self_kind2))
opt2_other = rng.permutation(stream_for(other_kind2))
# reset EVs at block start
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
# choice rule: beta_self*EV_self + beta_other*EV_other, softmax β=1
v1 = beta_self * EV_self[s, b, t, o1] + beta_other * EV_other[s, b, t, o1]
v2 = beta_self * EV_self[s, b, t, o2] + beta_other * EV_other[s, b, t, o2]
p = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[s, b, t, o1] = p[0]
choice_probabilities[s, b, t, o2] = p[1]
chosen = rng.choice([opt1, opt2], p=p)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
# realize outcomes for chosen option (self/other streams)
if chosen == opt1:
r_self, r_other = int(opt1_self[t]), int(opt1_other[t])
else:
r_self, r_other = int(opt2_self[t]), int(opt2_other[t])
outcomes_self[s, b, t] = r_self
outcomes_other[s, b, t] = r_other
# PEs against their own stream
delta_self = r_self - EV_self[s, b, t, c]
delta_other = r_other - EV_other[s, b, t, c]
pe_self[s, b, t] = delta_self
pe_other[s, b, t] = delta_other
pe_self_pos[s, b, t] = max(delta_self, 0.0)
pe_self_neg[s, b, t] = min(delta_self, 0.0)
pe_other_pos[s, b, t] = max(delta_other, 0.0)
pe_other_neg[s, b, t] = min(delta_other, 0.0)
# carry forward then update chosen option in each stream
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = (
EV_self[s, b, t, c] + alpha * delta_self
)
EV_other[s, b, t+1, c] = (
EV_other[s, b, t, c] + alpha * delta_other
)
return {
"params": np.column_stack((
beta_self_all, beta_other_all, alpha_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–1α–2β FIT (EV_self, EV_other; β_self, β_other; α)
# Mirrors simulate; supports letter or index choices/option_pairs.
# params = [beta_self, beta_other, alpha]
# ============================================================
def rw2q1a2b_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters
prior=None,
output: str = "npl"):
beta_self = norm2beta(params[0])
beta_other = norm2beta(params[1])
alpha = norm2alpha(params[2])
# bounds
if not (1e-5 <= float(beta_self) <= 20.0):
return 1e7
if not (1e-5 <= float(beta_other) <= 20.0):
return 1e7
if not (0.0 <= float(alpha) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(letter_to_idx.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(ch_arr[b, t])
# choice prob: beta_self*EV_self + beta_other*EV_other, softmax β=1
v1 = beta_self * EV_self[b, t, o1] + beta_other * EV_other[b, t, o1]
v2 = beta_self * EV_self[b, t, o2] + beta_other * EV_other[b, t, o2]
probs = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
# PEs and sign-split (for diagnostics; not used in update rule)
delta_self = outcomes_self[b, t] - EV_self[b, t, c]
delta_other = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = delta_self
pe_other[b, t] = delta_other
pe_self_pos[b, t] = max(delta_self, 0.0)
pe_self_neg[b, t] = min(delta_self, 0.0)
pe_other_pos[b, t] = max(delta_other, 0.0)
pe_other_neg[b, t] = min(delta_other, 0.0)
# carry-forward + update chosen
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = (
EV_self[b, t, c] + alpha * delta_self
)
EV_other[b, t+1, c] = (
EV_other[b, t, c] + alpha * delta_other
)
# k = 3 free parameters
BIC = 3 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta_self, beta_other, alpha],
"choices": ch_arr,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–2α–1β SIMULATE (EV_self, EV_other; β; α_self, α_other)
# params columns (3), per subject:
# [beta, alpha_self, alpha_other]
# Choice rule: v = beta * (EV_self + EV_other)
# ============================================================
def rw2q2a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
# --- bounds / unpack ---
(beta_all,
alpha_self_all,
alpha_other_all) = (params[:, i].astype(float) for i in range(3))
# beta bounds
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
# alpha bounds
for array, name in [(alpha_self_all, "alpha_self"), (alpha_other_all, "alpha_other")]:
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure ---
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
# outcome templates: ±1 only, 75/25
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
# A:+/+ B:+/− C:−/+ D:−/− (first = self stream, second = other stream)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
# --- outputs ---
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta = beta_all[s]
alpha_self = alpha_self_all[s]
alpha_other = alpha_other_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
# pre-generate outcomes for the two shown options this block
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self = rng.permutation(stream_for(self_kind1))
opt1_other = rng.permutation(stream_for(other_kind1))
opt2_self = rng.permutation(stream_for(self_kind2))
opt2_other = rng.permutation(stream_for(other_kind2))
# reset EVs at block start
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
# choice rule: beta * (EV_self + EV_other), softmax β=1
q1 = EV_self[s, b, t, o1] + EV_other[s, b, t, o1]
q2 = EV_self[s, b, t, o2] + EV_other[s, b, t, o2]
v1 = beta * q1
v2 = beta * q2
p = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[s, b, t, o1] = p[0]
choice_probabilities[s, b, t, o2] = p[1]
chosen = rng.choice([opt1, opt2], p=p)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
# realize outcomes for chosen option (self/other streams)
if chosen == opt1:
r_self, r_other = int(opt1_self[t]), int(opt1_other[t])
else:
r_self, r_other = int(opt2_self[t]), int(opt2_other[t])
outcomes_self[s, b, t] = r_self
outcomes_other[s, b, t] = r_other
# PEs against their own stream
delta_self = r_self - EV_self[s, b, t, c]
delta_other = r_other - EV_other[s, b, t, c]
pe_self[s, b, t] = delta_self
pe_other[s, b, t] = delta_other
pe_self_pos[s, b, t] = max(delta_self, 0.0)
pe_self_neg[s, b, t] = min(delta_self, 0.0)
pe_other_pos[s, b, t] = max(delta_other, 0.0)
pe_other_neg[s, b, t] = min(delta_other, 0.0)
# carry forward then update chosen option in each stream
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = (
EV_self[s, b, t, c] + alpha_self * delta_self
)
EV_other[s, b, t+1, c] = (
EV_other[s, b, t, c] + alpha_other * delta_other
)
return {
"params": np.column_stack((
beta_all, alpha_self_all, alpha_other_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–2α–1β FIT (EV_self, EV_other; β; α_self, α_other)
# Mirrors simulate; supports letter or index choices/option_pairs.
# params = [beta, alpha_self, alpha_other]
# ============================================================
def rw2q2a1b_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha_self = norm2alpha(params[1])
alpha_other = norm2alpha(params[2])
# bounds
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
for alpha_value in (alpha_self, alpha_other):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(letter_to_idx.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(ch_arr[b, t])
# choice prob: beta * (EV_self + EV_other), softmax β=1
q1 = EV_self[b, t, o1] + EV_other[b, t, o1]
q2 = EV_self[b, t, o2] + EV_other[b, t, o2]
v1 = beta * q1
v2 = beta * q2
probs = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
# PEs and sign-split (for diagnostics; not used in update rule)
delta_self = outcomes_self[b, t] - EV_self[b, t, c]
delta_other = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = delta_self
pe_other[b, t] = delta_other
pe_self_pos[b, t] = max(delta_self, 0.0)
pe_self_neg[b, t] = min(delta_self, 0.0)
pe_other_pos[b, t] = max(delta_other, 0.0)
pe_other_neg[b, t] = min(delta_other, 0.0)
# carry-forward + update chosen
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = (
EV_self[b, t, c] + alpha_self * delta_self
)
EV_other[b, t+1, c] = (
EV_other[b, t, c] + alpha_other * delta_other
)
# k = 3 free parameters
BIC = 3 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta, alpha_self, alpha_other],
"choices": ch_arr,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–2α–2β SIMULATE (EV_self, EV_other; β_self, β_other; α_self, α_other)
# params columns (4), per subject:
# [beta_self, beta_other, alpha_self, alpha_other]
# Choice rule: v = beta_self*EV_self + beta_other*EV_other
# ============================================================
def rw2q2a2b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
# --- bounds / unpack ---
(beta_self_all, beta_other_all,
alpha_self_all, alpha_other_all) = (params[:, i].astype(float) for i in range(4))
# beta bounds
for array, name in [(beta_self_all, "beta_self"), (beta_other_all, "beta_other")]:
if not ((array > 1e-5) & (array <= 20.0)).all():
raise ValueError(f"{name} out of bounds (must be in (1e-5, 20]).")
# alpha bounds
for array, name in [(alpha_self_all, "alpha_self"), (alpha_other_all, "alpha_other")]:
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure ---
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
# outcome templates: ±1 only, 75/25
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
# A:+/+ B:+/− C:−/+ D:−/− (first = self stream, second = other stream)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
# --- outputs ---
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta_self = beta_self_all[s]
beta_other = beta_other_all[s]
alpha_self = alpha_self_all[s]
alpha_other = alpha_other_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
# pre-generate outcomes for the two shown options this block
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self = rng.permutation(stream_for(self_kind1))
opt1_other = rng.permutation(stream_for(other_kind1))
opt2_self = rng.permutation(stream_for(self_kind2))
opt2_other = rng.permutation(stream_for(other_kind2))
# reset EVs at block start
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
# choice rule: (beta_self*EV_self + beta_other*EV_other), softmax β=1
v1 = beta_self * EV_self[s, b, t, o1] + beta_other * EV_other[s, b, t, o1]
v2 = beta_self * EV_self[s, b, t, o2] + beta_other * EV_other[s, b, t, o2]
p = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[s, b, t, o1] = p[0]
choice_probabilities[s, b, t, o2] = p[1]
chosen = rng.choice([opt1, opt2], p=p)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
# realize outcomes for chosen option (self/other streams)
if chosen == opt1:
r_self, r_other = int(opt1_self[t]), int(opt1_other[t])
else:
r_self, r_other = int(opt2_self[t]), int(opt2_other[t])
outcomes_self[s, b, t] = r_self
outcomes_other[s, b, t] = r_other
# PEs against their own stream
delta_self = r_self - EV_self[s, b, t, c]
delta_other = r_other - EV_other[s, b, t, c]
pe_self[s, b, t] = delta_self
pe_other[s, b, t] = delta_other
pe_self_pos[s, b, t] = max(delta_self, 0.0)
pe_self_neg[s, b, t] = min(delta_self, 0.0)
pe_other_pos[s, b, t] = max(delta_other, 0.0)
pe_other_neg[s, b, t] = min(delta_other, 0.0)
# carry forward then update chosen option in each stream
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = (
EV_self[s, b, t, c] + alpha_self * delta_self
)
EV_other[s, b, t+1, c] = (
EV_other[s, b, t, c] + alpha_other * delta_other
)
return {
"params": np.column_stack((
beta_self_all, beta_other_all,
alpha_self_all, alpha_other_all)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–2α–2β FIT (EV_self, EV_other; β_self, β_other; α_self, α_other)
# Mirrors simulate; supports letter or index choices/option_pairs.
# params = [beta_self, beta_other, alpha_self, alpha_other]
# ============================================================
def rw2q2a2b_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters
prior=None,
output: str = "npl"):
beta_self = norm2beta(params[0])
beta_other = norm2beta(params[1])
alpha_self = norm2alpha(params[2])
alpha_other = norm2alpha(params[3])
# bounds
if not (1e-5 <= float(beta_self) <= 20.0):
return 1e7
if not (1e-5 <= float(beta_other) <= 20.0):
return 1e7
for alpha_value in (alpha_self, alpha_other):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(letter_to_idx.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(ch_arr[b, t])
# choice prob: (beta_self*EV_self + beta_other*EV_other), softmax β=1
v1 = beta_self * EV_self[b, t, o1] + beta_other * EV_other[b, t, o1]
v2 = beta_self * EV_self[b, t, o2] + beta_other * EV_other[b, t, o2]
probs = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
# PEs and sign-split (for diagnostics; not used in update rule)
delta_self = outcomes_self[b, t] - EV_self[b, t, c]
delta_other = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = delta_self
pe_other[b, t] = delta_other
pe_self_pos[b, t] = max(delta_self, 0.0)
pe_self_neg[b, t] = min(delta_self, 0.0)
pe_other_pos[b, t] = max(delta_other, 0.0)
pe_other_neg[b, t] = min(delta_other, 0.0)
# carry-forward + update chosen
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = (
EV_self[b, t, c] + alpha_self * delta_self
)
EV_other[b, t+1, c] = (
EV_other[b, t, c] + alpha_other * delta_other
)
# k = 4 free parameters
BIC = 4 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta_self, beta_other, alpha_self, alpha_other],
"choices": ch_arr,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–4α–1β SIMULATE (EV_self, EV_other; single β)
# params columns (5), per subject:
# [beta,
# alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
# Choice rule: v = beta * (EV_self + EV_other)
# ============================================================
def rw2q4a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
# --- bounds / unpack ---
(beta_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all) = (params[:, i].astype(float) for i in range(5))
# beta bounds
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
# alpha bounds
for array, name in [
(alpha_self_pos_all, "alpha_self_pos"),
(alpha_self_neg_all, "alpha_self_neg"),
(alpha_other_pos_all, "alpha_other_pos"),
(alpha_other_neg_all, "alpha_other_neg")
]:
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure ---
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
# outcome templates: ±1 only, 75/25
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
# A:+/+ B:+/− C:−/+ D:−/− (first = self stream, second = other stream)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
# --- outputs ---
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta = beta_all[s]
alpha_self_pos = alpha_self_pos_all[s]
alpha_self_neg = alpha_self_neg_all[s]
alpha_other_pos = alpha_other_pos_all[s]
alpha_other_neg = alpha_other_neg_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
# pre-generate outcomes for the two shown options this block
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self = rng.permutation(stream_for(self_kind1))
opt1_other = rng.permutation(stream_for(other_kind1))
opt2_self = rng.permutation(stream_for(self_kind2))
opt2_other = rng.permutation(stream_for(other_kind2))
# reset EVs at block start
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
# choice rule: beta * (EV_self + EV_other), softmax β=1
q1 = EV_self[s, b, t, o1] + EV_other[s, b, t, o1]
q2 = EV_self[s, b, t, o2] + EV_other[s, b, t, o2]
v1 = beta * q1
v2 = beta * q2
p = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[s, b, t, o1] = p[0]
choice_probabilities[s, b, t, o2] = p[1]
chosen = rng.choice([opt1, opt2], p=p)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
# realize outcomes for chosen option (self/other streams)
if chosen == opt1:
r_self, r_other = int(opt1_self[t]), int(opt1_other[t])
else:
r_self, r_other = int(opt2_self[t]), int(opt2_other[t])
outcomes_self[s, b, t] = r_self
outcomes_other[s, b, t] = r_other
# PEs against their own stream
delta_self = r_self - EV_self[s, b, t, c]
delta_other = r_other - EV_other[s, b, t, c]
pe_self[s, b, t] = delta_self
pe_other[s, b, t] = delta_other
pe_self_pos[s, b, t] = max(delta_self, 0.0)
pe_self_neg[s, b, t] = min(delta_self, 0.0)
pe_other_pos[s, b, t] = max(delta_other, 0.0)
pe_other_neg[s, b, t] = min(delta_other, 0.0)
# carry forward then update chosen option in each stream
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = (
EV_self[s, b, t, c]
+ alpha_self_pos * pe_self_pos[s, b, t]
+ alpha_self_neg * pe_self_neg[s, b, t]
)
EV_other[s, b, t+1, c] = (
EV_other[s, b, t, c]
+ alpha_other_pos * pe_other_pos[s, b, t]
+ alpha_other_neg * pe_other_neg[s, b, t]
)
return {
"params": np.column_stack((
beta_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–4α–1β FIT (EV_self, EV_other; single β)
# Mirrors simulate; supports letter or index choices/option_pairs.
# params = [beta, alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
# ============================================================
def rw2q4a1b_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha_self_pos = norm2alpha(params[1])
alpha_self_neg = norm2alpha(params[2])
alpha_other_pos = norm2alpha(params[3])
alpha_other_neg = norm2alpha(params[4])
# bounds
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
for alpha_value in (alpha_self_pos, alpha_self_neg, alpha_other_pos, alpha_other_neg):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(letter_to_idx.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(ch_arr[b, t])
# choice prob: beta * (EV_self + EV_other), softmax β=1
q1 = EV_self[b, t, o1] + EV_other[b, t, o1]
q2 = EV_self[b, t, o2] + EV_other[b, t, o2]
v1 = beta * q1
v2 = beta * q2
probs = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
# PEs and sign-split
delta_self = outcomes_self[b, t] - EV_self[b, t, c]
delta_other = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = delta_self
pe_other[b, t] = delta_other
pe_self_pos[b, t] = max(delta_self, 0.0)
pe_self_neg[b, t] = min(delta_self, 0.0)
pe_other_pos[b, t] = max(delta_other, 0.0)
pe_other_neg[b, t] = min(delta_other, 0.0)
# carry-forward + update chosen
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = (
EV_self[b, t, c]
+ alpha_self_pos * pe_self_pos[b, t]
+ alpha_self_neg * pe_self_neg[b, t]
)
EV_other[b, t+1, c] = (
EV_other[b, t, c]
+ alpha_other_pos * pe_other_pos[b, t]
+ alpha_other_neg * pe_other_neg[b, t]
)
# k = 5 free parameters
BIC = 5 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta,
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg],
"choices": ch_arr,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–1w–4α–1β SIMULATE (EV_self, EV_other; weight w)
# ------------------------------------------------------------
# params columns (6), per subject:
# [beta, w,
# alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
#
# Q_total = w * Q_other + (1 - w) * Q_self
# choice rule: softmax(beta * Q_total)
# ============================================================
def rw2q1w4a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
# --- bounds / unpack ---
(beta_all, w_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all) = (params[:, i].astype(float) for i in range(6))
# beta bounds
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
# w bounds
if not ((0.0 <= w_all) & (w_all <= 1.0)).all():
raise ValueError("w out of bounds (must be in [0, 1]).")
# alpha bounds
for array, name in [
(alpha_self_pos_all, "alpha_self_pos"),
(alpha_self_neg_all, "alpha_self_neg"),
(alpha_other_pos_all, "alpha_other_pos"),
(alpha_other_neg_all, "alpha_other_neg")
]:
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure ---
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
# outcome templates: ±1 only, 75/25
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
# A:+/+ B:+/− C:−/+ D:−/− (first = self stream, second = other stream)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
# --- outputs ---
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta = beta_all[s]
w = w_all[s]
alpha_self_pos = alpha_self_pos_all[s]
alpha_self_neg = alpha_self_neg_all[s]
alpha_other_pos = alpha_other_pos_all[s]
alpha_other_neg = alpha_other_neg_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
# pre-generate outcomes for the two shown options this block
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self = rng.permutation(stream_for(self_kind1))
opt1_other = rng.permutation(stream_for(other_kind1))
opt2_self = rng.permutation(stream_for(self_kind2))
opt2_other = rng.permutation(stream_for(other_kind2))
# reset EVs at block start
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
# Q_total = w*Q_other + (1-w)*Q_self
q1 = w * EV_other[s, b, t, o1] + (1.0 - w) * EV_self[s, b, t, o1]
q2 = w * EV_other[s, b, t, o2] + (1.0 - w) * EV_self[s, b, t, o2]
v1 = beta * q1
v2 = beta * q2
p = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[s, b, t, o1] = p[0]
choice_probabilities[s, b, t, o2] = p[1]
chosen = rng.choice([opt1, opt2], p=p)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
# realize outcomes for chosen option (self/other streams)
if chosen == opt1:
r_self, r_other = int(opt1_self[t]), int(opt1_other[t])
else:
r_self, r_other = int(opt2_self[t]), int(opt2_other[t])
outcomes_self[s, b, t] = r_self
outcomes_other[s, b, t] = r_other
# PEs against their own stream
delta_self = r_self - EV_self[s, b, t, c]
delta_other = r_other - EV_other[s, b, t, c]
pe_self[s, b, t] = delta_self
pe_other[s, b, t] = delta_other
pe_self_pos[s, b, t] = max(delta_self, 0.0)
pe_self_neg[s, b, t] = min(delta_self, 0.0)
pe_other_pos[s, b, t] = max(delta_other, 0.0)
pe_other_neg[s, b, t] = min(delta_other, 0.0)
# carry forward then update chosen option in each stream
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = (
EV_self[s, b, t, c]
+ alpha_self_pos * pe_self_pos[s, b, t]
+ alpha_self_neg * pe_self_neg[s, b, t]
)
EV_other[s, b, t+1, c] = (
EV_other[s, b, t, c]
+ alpha_other_pos * pe_other_pos[s, b, t]
+ alpha_other_neg * pe_other_neg[s, b, t]
)
return {
"params": np.column_stack((
beta_all, w_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# helper: bounded alpha transform for fitting
# keeps alphas in [alpha_lo, alpha_hi] to avoid boundary issues
# ============================================================
def norm2alpha_bounded(z: float,
alpha_lo: float = 0.10,
alpha_hi: float = 0.90) -> float:
"""
Take unconstrained z -> (0,1) via norm2alpha, then rescale
to [alpha_lo, alpha_hi].
"""
a01 = norm2alpha(z) # in (0,1)
return alpha_lo + (alpha_hi - alpha_lo) * a01
# ============================================================
# 2Q–1w–4α–1β FIT (EV_self, EV_other; weight w)
# ------------------------------------------------------------
# params (unconstrained) passed in:
# [p0, p1, p2, p3, p4, p5] ->
# beta = norm2beta(p0)
# w = norm2alpha(p1) in (0,1)
# alpha_* = norm2alpha_bounded(pi) in [0.10,0.90]
#
# Priors:
# (1) global Gaussian-style on all 4 alphas:
# λ_global * (alpha - 0.5)^2
# (2) pair prior on self alphas:
# λ_pair * (alpha_self_pos - alpha_self_neg)^2
# ============================================================
def rw2q1w4a1b_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters
prior=None,
output: str = "npl"):
# ----- transforms -----
beta = norm2beta(params[0])
w = norm2alpha(params[1]) # [0,1]
alpha_self_pos = norm2alpha_bounded(params[2])
alpha_self_neg = norm2alpha_bounded(params[3])
alpha_other_pos = norm2alpha_bounded(params[4])
alpha_other_neg = norm2alpha_bounded(params[5])
# ----- hard bounds -----
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
if not (0.0 <= float(w) <= 1.0):
return 1e7
for alpha_value in (alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(letter_to_idx.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
# ----- main NLL -----
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(ch_arr[b, t])
# Q_total = w*Q_other + (1-w)*Q_self
q1 = w * EV_other[b, t, o1] + (1.0 - w) * EV_self[b, t, o1]
q2 = w * EV_other[b, t, o2] + (1.0 - w) * EV_self[b, t, o2]
v1 = beta * q1
v2 = beta * q2
probs = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
# PEs and sign-split
delta_self = outcomes_self[b, t] - EV_self[b, t, c]
delta_other = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = delta_self
pe_other[b, t] = delta_other
pe_self_pos[b, t] = max(delta_self, 0.0)
pe_self_neg[b, t] = min(delta_self, 0.0)
pe_other_pos[b, t] = max(delta_other, 0.0)
pe_other_neg[b, t] = min(delta_other, 0.0)
# carry-forward + update chosen
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = (
EV_self[b, t, c]
+ alpha_self_pos * pe_self_pos[b, t]
+ alpha_self_neg * pe_self_neg[b, t]
)
EV_other[b, t+1, c] = (
EV_other[b, t, c]
+ alpha_other_pos * pe_other_pos[b, t]
+ alpha_other_neg * pe_other_neg[b, t]
)
# ----- priors / regularization -----
ALPHA_PRIOR_MU = 0.5
ALPHA_PRIOR_LAMBDA_GLOBAL = 0.5 # global strength on all alphas
ALPHA_PRIOR_LAMBDA_PAIR = 0.25 # pair penalty on self_pos vs self_neg
alpha_vec = np.array([
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg
], dtype=float)
# global shrinkage toward 0.5
reg_global = ALPHA_PRIOR_LAMBDA_GLOBAL * np.sum((alpha_vec - ALPHA_PRIOR_MU) ** 2)
# encourage self_pos and self_neg not to diverge wildly
reg_pair = ALPHA_PRIOR_LAMBDA_PAIR * (alpha_self_pos - alpha_self_neg) ** 2
reg = reg_global + reg_pair
nll_reg = nll + reg
# k = 6 free parameters
BIC = 6 * np.log(nblocks * ntrials) + 2 * nll_reg
if output == "all":
return {
"params": [beta, w,
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg],
"choices": ch_arr,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll_reg,
"BIC": BIC
}
return calc_fval(nll_reg, params, prior=prior, output=output)
# ============================================================
# 2Q–4α–2β SIMULATE (EV_self, EV_other; β_self, β_other)
# params columns (6), per subject:
# [beta_self, beta_other,
# alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
# ============================================================
def rw2q4a2b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
# --- bounds / unpack ---
(beta_self_all, beta_other_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all) = (params[:, i].astype(float) for i in range(6))
for array, name in [(beta_self_all, "beta_self"), (beta_other_all, "beta_other")]:
if not ((array > 1e-5) & (array <= 20.0)).all():
raise ValueError(f"{name} out of bounds (must be in (1e-5, 20]).")
for array, name in [
(alpha_self_pos_all, "alpha_self_pos"),
(alpha_self_neg_all, "alpha_self_neg"),
(alpha_other_pos_all, "alpha_other_pos"),
(alpha_other_neg_all, "alpha_other_neg")
]:
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure ---
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
# outcome templates: ±1 only, 75/25
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
# A:+/+ B:+/− C:−/+ D:−/− (first = self stream, second = other stream)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
# --- outputs ---
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta_self = beta_self_all[s]
beta_other = beta_other_all[s]
alpha_self_pos = alpha_self_pos_all[s]
alpha_self_neg = alpha_self_neg_all[s]
alpha_other_pos = alpha_other_pos_all[s]
alpha_other_neg = alpha_other_neg_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
# pre-generate outcomes for the two shown options this block
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self = rng.permutation(stream_for(self_kind1))
opt1_other = rng.permutation(stream_for(other_kind1))
opt2_self = rng.permutation(stream_for(self_kind2))
opt2_other = rng.permutation(stream_for(other_kind2))
# reset EVs at block start
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
# choice rule: (beta_self*EV_self + beta_other*EV_other), softmax β=1
v1 = beta_self * EV_self[s, b, t, o1] + beta_other * EV_other[s, b, t, o1]
v2 = beta_self * EV_self[s, b, t, o2] + beta_other * EV_other[s, b, t, o2]
p = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[s, b, t, o1] = p[0]
choice_probabilities[s, b, t, o2] = p[1]
chosen = rng.choice([opt1, opt2], p=p)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
# realize outcomes for chosen option (self/other streams)
if chosen == opt1:
r_self, r_other = int(opt1_self[t]), int(opt1_other[t])
else:
r_self, r_other = int(opt2_self[t]), int(opt2_other[t])
outcomes_self[s, b, t] = r_self
outcomes_other[s, b, t] = r_other
# PEs against their own stream
delta_self = r_self - EV_self[s, b, t, c]
delta_other = r_other - EV_other[s, b, t, c]
pe_self[s, b, t] = delta_self
pe_other[s, b, t] = delta_other
pe_self_pos[s, b, t] = max(delta_self, 0.0)
pe_self_neg[s, b, t] = min(delta_self, 0.0)
pe_other_pos[s, b, t] = max(delta_other, 0.0)
pe_other_neg[s, b, t] = min(delta_other, 0.0)
# carry forward then update chosen option in each stream
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = (
EV_self[s, b, t, c]
+ alpha_self_pos * pe_self_pos[s, b, t]
+ alpha_self_neg * pe_self_neg[s, b, t]
)
EV_other[s, b, t+1, c] = (
EV_other[s, b, t, c]
+ alpha_other_pos * pe_other_pos[s, b, t]
+ alpha_other_neg * pe_other_neg[s, b, t]
)
return {
"params": np.column_stack((
beta_self_all, beta_other_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–4α–2β FIT (EV_self, EV_other; β_self, β_other)
# Mirrors simulate; supports letter or index choices/option_pairs.
# ============================================================
def rw2q4a2b_fit(params: np.ndarray,
choices: np.ndarray, # (B,T) letters or indices
outcomes_self: np.ndarray, # (B,T) in {-1,+1}
outcomes_other: np.ndarray, # (B,T) in {-1,+1}
option_pairs: np.ndarray, # (B,T,2) letters
prior=None,
output: str = "npl"):
beta_self = norm2beta(params[0])
beta_other = norm2beta(params[1])
alpha_self_pos = norm2alpha(params[2])
alpha_self_neg = norm2alpha(params[3])
alpha_other_pos = norm2alpha(params[4])
alpha_other_neg = norm2alpha(params[5])
# bounds
if not (1e-5 <= float(beta_self) <= 20.0): return 1e7
if not (1e-5 <= float(beta_other) <= 20.0): return 1e7
for alpha_value in (alpha_self_pos, alpha_self_neg, alpha_other_pos, alpha_other_neg):
if not (0.0 <= float(alpha_value) <= 1.0): return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ch_arr = np.asarray(choices)
if not np.issubdtype(ch_arr.dtype, np.number):
ch_arr = np.vectorize(letter_to_idx.get)(ch_arr)
ch_arr = ch_arr.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(ch_arr[b, t])
# choice prob: (beta_self*EV_self + beta_other*EV_other), softmax β=1
v1 = beta_self * EV_self[b, t, o1] + beta_other * EV_other[b, t, o1]
v2 = beta_self * EV_self[b, t, o2] + beta_other * EV_other[b, t, o2]
probs = softmax(np.array([v1, v2], dtype=float), 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
# PEs and sign-split
delta_self = outcomes_self[b, t] - EV_self[b, t, c]
delta_other = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = delta_self
pe_other[b, t] = delta_other
pe_self_pos[b, t] = max(delta_self, 0.0)
pe_self_neg[b, t] = min(delta_self, 0.0)
pe_other_pos[b, t] = max(delta_other, 0.0)
pe_other_neg[b, t] = min(delta_other, 0.0)
# carry-forward + update chosen
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = (
EV_self[b, t, c]
+ alpha_self_pos * pe_self_pos[b, t]
+ alpha_self_neg * pe_self_neg[b, t]
)
EV_other[b, t+1, c] = (
EV_other[b, t, c]
+ alpha_other_pos * pe_other_pos[b, t]
+ alpha_other_neg * pe_other_neg[b, t]
)
BIC = 6 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta_self, beta_other,
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg],
"choices": ch_arr,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–1α–1β SIMULATE (EV_self, EV_other; β; α)
# params columns (2), per subject:
# [beta, alpha]
# Choice rule: v = beta * (EV_self + EV_other)
# ============================================================
def rw2q1a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
(beta_all,
alpha_all) = (params[:, i].astype(float) for i in range(2))
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
if not ((0.0 <= alpha_all) & (alpha_all <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list,
nblocks=nblocks,
nsubjects=nsubjects))
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
opt_types = {
'A': ('+', '+'),
'B': ('+', '-'),
'C': ('-', '+'),
'D': ('-', '-')
}
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta = beta_all[s]
alpha = alpha_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self_stream = rng.permutation(stream_for(self_kind1))
opt1_other_stream = rng.permutation(stream_for(other_kind1))
opt2_self_stream = rng.permutation(stream_for(self_kind2))
opt2_other_stream = rng.permutation(stream_for(other_kind2))
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
values = beta * np.array([
EV_self[s, b, t, o1] + EV_other[s, b, t, o1],
EV_self[s, b, t, o2] + EV_other[s, b, t, o2]
], dtype=float)
probs = softmax(values, 1.0)
choice_probabilities[s, b, t, o1] = probs[0]
choice_probabilities[s, b, t, o2] = probs[1]
chosen = rng.choice([opt1, opt2], p=probs)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
if chosen == opt1:
outcome_self_value = int(opt1_self_stream[t])
outcome_other_value = int(opt1_other_stream[t])
else:
outcome_self_value = int(opt2_self_stream[t])
outcome_other_value = int(opt2_other_stream[t])
outcomes_self[s, b, t] = outcome_self_value
outcomes_other[s, b, t] = outcome_other_value
pe_self_value = outcome_self_value - EV_self[s, b, t, c]
pe_other_value = outcome_other_value - EV_other[s, b, t, c]
pe_self[s, b, t] = pe_self_value
pe_other[s, b, t] = pe_other_value
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = EV_self[s, b, t, c] + alpha * pe_self_value
EV_other[s, b, t+1, c] = EV_other[s, b, t, c] + alpha * pe_other_value
return {
"params": np.column_stack((beta_all, alpha_all)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
}
# ============================================================
# 2Q–1α–1β FIT (EV_self, EV_other; β; α)
# params = [beta, alpha]
# ============================================================
def rw2q1a1b_fit(params: np.ndarray,
choices: np.ndarray,
outcomes_self: np.ndarray,
outcomes_other: np.ndarray,
option_pairs: np.ndarray,
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha = norm2alpha(params[1])
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
if not (0.0 <= float(alpha) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
choice_array = np.asarray(choices)
if not np.issubdtype(choice_array.dtype, np.number):
choice_array = np.vectorize(letter_to_idx.get)(choice_array)
choice_array = choice_array.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(choice_array[b, t])
values = beta * np.array([
EV_self[b, t, o1] + EV_other[b, t, o1],
EV_self[b, t, o2] + EV_other[b, t, o2]
], dtype=float)
probs = softmax(values, 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
pe_self_value = outcomes_self[b, t] - EV_self[b, t, c]
pe_other_value = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = pe_self_value
pe_other[b, t] = pe_other_value
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = EV_self[b, t, c] + alpha * pe_self_value
EV_other[b, t+1, c] = EV_other[b, t, c] + alpha * pe_other_value
BIC = 2 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta, alpha],
"choices": choice_array,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–1α–2β SIMULATE (EV_self, EV_other; β_self, β_other; α)
# params columns (3), per subject:
# [beta_self, beta_other, alpha]
# Choice rule: v = beta_self*EV_self + beta_other*EV_other
# ============================================================
def rw2q1a2b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
(beta_self_all,
beta_other_all,
alpha_all) = (params[:, i].astype(float) for i in range(3))
for array, name in [(beta_self_all, "beta_self"), (beta_other_all, "beta_other")]:
if not ((array > 1e-5) & (array <= 20.0)).all():
raise ValueError(f"{name} out of bounds (must be in (1e-5, 20]).")
if not ((0.0 <= alpha_all) & (alpha_all <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta_self = beta_self_all[s]
beta_other = beta_other_all[s]
alpha = alpha_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self_stream = rng.permutation(stream_for(self_kind1))
opt1_other_stream = rng.permutation(stream_for(other_kind1))
opt2_self_stream = rng.permutation(stream_for(self_kind2))
opt2_other_stream = rng.permutation(stream_for(other_kind2))
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
values = np.array([
beta_self * EV_self[s, b, t, o1] + beta_other * EV_other[s, b, t, o1],
beta_self * EV_self[s, b, t, o2] + beta_other * EV_other[s, b, t, o2]
], dtype=float)
probs = softmax(values, 1.0)
choice_probabilities[s, b, t, o1] = probs[0]
choice_probabilities[s, b, t, o2] = probs[1]
chosen = rng.choice([opt1, opt2], p=probs)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
if chosen == opt1:
outcome_self_value = int(opt1_self_stream[t])
outcome_other_value = int(opt1_other_stream[t])
else:
outcome_self_value = int(opt2_self_stream[t])
outcome_other_value = int(opt2_other_stream[t])
outcomes_self[s, b, t] = outcome_self_value
outcomes_other[s, b, t] = outcome_other_value
pe_self_value = outcome_self_value - EV_self[s, b, t, c]
pe_other_value = outcome_other_value - EV_other[s, b, t, c]
pe_self[s, b, t] = pe_self_value
pe_other[s, b, t] = pe_other_value
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = EV_self[s, b, t, c] + alpha * pe_self_value
EV_other[s, b, t+1, c] = EV_other[s, b, t, c] + alpha * pe_other_value
return {
"params": np.column_stack((beta_self_all, beta_other_all, alpha_all)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
}
# ============================================================
# 2Q–1α–2β FIT (EV_self, EV_other; β_self, β_other; α)
# params = [beta_self, beta_other, alpha]
# ============================================================
def rw2q1a2b_fit(params: np.ndarray,
choices: np.ndarray,
outcomes_self: np.ndarray,
outcomes_other: np.ndarray,
option_pairs: np.ndarray,
prior=None,
output: str = "npl"):
beta_self = norm2beta(params[0])
beta_other = norm2beta(params[1])
alpha = norm2alpha(params[2])
if not (1e-5 <= float(beta_self) <= 20.0):
return 1e7
if not (1e-5 <= float(beta_other) <= 20.0):
return 1e7
if not (0.0 <= float(alpha) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
choice_array = np.asarray(choices)
if not np.issubdtype(choice_array.dtype, np.number):
choice_array = np.vectorize(letter_to_idx.get)(choice_array)
choice_array = choice_array.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(choice_array[b, t])
values = np.array([
beta_self * EV_self[b, t, o1] + beta_other * EV_other[b, t, o1],
beta_self * EV_self[b, t, o2] + beta_other * EV_other[b, t, o2]
], dtype=float)
probs = softmax(values, 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
pe_self_value = outcomes_self[b, t] - EV_self[b, t, c]
pe_other_value = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = pe_self_value
pe_other[b, t] = pe_other_value
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = EV_self[b, t, c] + alpha * pe_self_value
EV_other[b, t+1, c] = EV_other[b, t, c] + alpha * pe_other_value
BIC = 3 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta_self, beta_other, alpha],
"choices": choice_array,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–2α–1β SIMULATE (EV_self, EV_other; β; α_self, α_other)
# params columns (3), per subject:
# [beta, alpha_self, alpha_other]
# Choice rule: v = beta * (EV_self + EV_other)
# ============================================================
def rw2q2a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
(beta_all,
alpha_self_all,
alpha_other_all) = (params[:, i].astype(float) for i in range(3))
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
for array, name in [(alpha_self_all, "alpha_self"), (alpha_other_all, "alpha_other")]:
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta = beta_all[s]
alpha_self = alpha_self_all[s]
alpha_other = alpha_other_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self_stream = rng.permutation(stream_for(self_kind1))
opt1_other_stream = rng.permutation(stream_for(other_kind1))
opt2_self_stream = rng.permutation(stream_for(self_kind2))
opt2_other_stream = rng.permutation(stream_for(other_kind2))
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
values = beta * np.array([
EV_self[s, b, t, o1] + EV_other[s, b, t, o1],
EV_self[s, b, t, o2] + EV_other[s, b, t, o2]
], dtype=float)
probs = softmax(values, 1.0)
choice_probabilities[s, b, t, o1] = probs[0]
choice_probabilities[s, b, t, o2] = probs[1]
chosen = rng.choice([opt1, opt2], p=probs)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
if chosen == opt1:
outcome_self_value = int(opt1_self_stream[t])
outcome_other_value = int(opt1_other_stream[t])
else:
outcome_self_value = int(opt2_self_stream[t])
outcome_other_value = int(opt2_other_stream[t])
outcomes_self[s, b, t] = outcome_self_value
outcomes_other[s, b, t] = outcome_other_value
pe_self_value = outcome_self_value - EV_self[s, b, t, c]
pe_other_value = outcome_other_value - EV_other[s, b, t, c]
pe_self[s, b, t] = pe_self_value
pe_other[s, b, t] = pe_other_value
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = EV_self[s, b, t, c] + alpha_self * pe_self_value
EV_other[s, b, t+1, c] = EV_other[s, b, t, c] + alpha_other * pe_other_value
return {
"params": np.column_stack((beta_all, alpha_self_all, alpha_other_all)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
}
# ============================================================
# 2Q–2α–1β FIT (EV_self, EV_other; β; α_self, α_other)
# params = [beta, alpha_self, alpha_other]
# ============================================================
def rw2q2a1b_fit(params: np.ndarray,
choices: np.ndarray,
outcomes_self: np.ndarray,
outcomes_other: np.ndarray,
option_pairs: np.ndarray,
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha_self = norm2alpha(params[1])
alpha_other = norm2alpha(params[2])
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
for alpha_value in (alpha_self, alpha_other):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
choice_array = np.asarray(choices)
if not np.issubdtype(choice_array.dtype, np.number):
choice_array = np.vectorize(letter_to_idx.get)(choice_array)
choice_array = choice_array.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(choice_array[b, t])
values = beta * np.array([
EV_self[b, t, o1] + EV_other[b, t, o1],
EV_self[b, t, o2] + EV_other[b, t, o2]
], dtype=float)
probs = softmax(values, 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
pe_self_value = outcomes_self[b, t] - EV_self[b, t, c]
pe_other_value = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = pe_self_value
pe_other[b, t] = pe_other_value
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = EV_self[b, t, c] + alpha_self * pe_self_value
EV_other[b, t+1, c] = EV_other[b, t, c] + alpha_other * pe_other_value
BIC = 3 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta, alpha_self, alpha_other],
"choices": choice_array,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–2α–2β SIMULATE (EV_self, EV_other; β_self, β_other; α_self, α_other)
# params columns (4), per subject:
# [beta_self, beta_other, alpha_self, alpha_other]
# Choice rule: v = beta_self*EV_self + beta_other*EV_other
# ============================================================
def rw2q2a2b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
(beta_self_all, beta_other_all,
alpha_self_all, alpha_other_all) = (params[:, i].astype(float) for i in range(4))
for array, name in [(beta_self_all, "beta_self"), (beta_other_all, "beta_other")]:
if not ((array > 1e-5) & (array <= 20.0)).all():
raise ValueError(f"{name} out of bounds (must be in (1e-5, 20]).")
for array, name in [(alpha_self_all, "alpha_self"), (alpha_other_all, "alpha_other")]:
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError(f"{name} out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list, nblocks=nblocks, nsubjects=nsubjects))
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
opt_types = {'A': ('+', '+'), 'B': ('+', '-'), 'C': ('-', '+'), 'D': ('-', '-')}
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta_self = beta_self_all[s]
beta_other = beta_other_all[s]
alpha_self = alpha_self_all[s]
alpha_other = alpha_other_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[opt1]
self_kind2, other_kind2 = opt_types[opt2]
opt1_self_stream = rng.permutation(stream_for(self_kind1))
opt1_other_stream = rng.permutation(stream_for(other_kind1))
opt2_self_stream = rng.permutation(stream_for(self_kind2))
opt2_other_stream = rng.permutation(stream_for(other_kind2))
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = opt1
option_pairs[s, b, t, 1] = opt2
values = np.array([
beta_self * EV_self[s, b, t, o1] + beta_other * EV_other[s, b, t, o1],
beta_self * EV_self[s, b, t, o2] + beta_other * EV_other[s, b, t, o2]
], dtype=float)
probs = softmax(values, 1.0)
choice_probabilities[s, b, t, o1] = probs[0]
choice_probabilities[s, b, t, o2] = probs[1]
chosen = rng.choice([opt1, opt2], p=probs)
choices[s, b, t] = chosen
c = letter_to_idx[chosen]
if chosen == opt1:
outcome_self_value = int(opt1_self_stream[t])
outcome_other_value = int(opt1_other_stream[t])
else:
outcome_self_value = int(opt2_self_stream[t])
outcome_other_value = int(opt2_other_stream[t])
outcomes_self[s, b, t] = outcome_self_value
outcomes_other[s, b, t] = outcome_other_value
pe_self_value = outcome_self_value - EV_self[s, b, t, c]
pe_other_value = outcome_other_value - EV_other[s, b, t, c]
pe_self[s, b, t] = pe_self_value
pe_other[s, b, t] = pe_other_value
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, c] = EV_self[s, b, t, c] + alpha_self * pe_self_value
EV_other[s, b, t+1, c] = EV_other[s, b, t, c] + alpha_other * pe_other_value
return {
"params": np.column_stack((
beta_self_all, beta_other_all,
alpha_self_all, alpha_other_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
}
# ============================================================
# 2Q–2α–2β FIT (EV_self, EV_other; β_self, β_other; α_self, α_other)
# params = [beta_self, beta_other, alpha_self, alpha_other]
# ============================================================
def rw2q2a2b_fit(params: np.ndarray,
choices: np.ndarray,
outcomes_self: np.ndarray,
outcomes_other: np.ndarray,
option_pairs: np.ndarray,
prior=None,
output: str = "npl"):
beta_self = norm2beta(params[0])
beta_other = norm2beta(params[1])
alpha_self = norm2alpha(params[2])
alpha_other = norm2alpha(params[3])
if not (1e-5 <= float(beta_self) <= 20.0):
return 1e7
if not (1e-5 <= float(beta_other) <= 20.0):
return 1e7
for alpha_value in (alpha_self, alpha_other):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
choice_array = np.asarray(choices)
if not np.issubdtype(choice_array.dtype, np.number):
choice_array = np.vectorize(letter_to_idx.get)(choice_array)
choice_array = choice_array.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
opt1, opt2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
o1, o2 = letter_to_idx[opt1], letter_to_idx[opt2]
c = int(choice_array[b, t])
values = np.array([
beta_self * EV_self[b, t, o1] + beta_other * EV_other[b, t, o1],
beta_self * EV_self[b, t, o2] + beta_other * EV_other[b, t, o2]
], dtype=float)
probs = softmax(values, 1.0)
choice_probabilities[b, t, o1] = probs[0]
choice_probabilities[b, t, o2] = probs[1]
nll += -np.log((probs[0] if c == o1 else probs[1]) + 1e-12)
pe_self_value = outcomes_self[b, t] - EV_self[b, t, c]
pe_other_value = outcomes_other[b, t] - EV_other[b, t, c]
pe_self[b, t] = pe_self_value
pe_other[b, t] = pe_other_value
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, c] = EV_self[b, t, c] + alpha_self * pe_self_value
EV_other[b, t+1, c] = EV_other[b, t, c] + alpha_other * pe_other_value
BIC = 4 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta_self, beta_other, alpha_self, alpha_other],
"choices": choice_array,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–4α–1β SIMULATE (EV_self, EV_other; single β)
# params columns (5), per subject:
# [beta,
# alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
# Choice rule: value = beta * (EV_self + EV_other)
# ============================================================
def rw2q4a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
(beta_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all) = (params[:, i].astype(float) for i in range(5))
# bounds
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
for array in (alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all):
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# task structure and outcome templates (±1, 75/25)
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list,
nblocks=nblocks,
nsubjects=nsubjects))
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
opt_types = {
'A': ('+', '+'),
'B': ('+', '-'),
'C': ('-', '+'),
'D': ('-', '-')
}
# outputs
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta = beta_all[s]
alpha_self_pos = alpha_self_pos_all[s]
alpha_self_neg = alpha_self_neg_all[s]
alpha_other_pos = alpha_other_pos_all[s]
alpha_other_neg = alpha_other_neg_all[s]
for b in range(nblocks):
pair = block_orders[s][b]
option1, option2 = pair[0], pair[1]
idx1, idx2 = letter_to_idx[option1], letter_to_idx[option2]
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[option1]
self_kind2, other_kind2 = opt_types[option2]
option1_self_outcomes = rng.permutation(stream_for(self_kind1))
option1_other_outcomes = rng.permutation(stream_for(other_kind1))
option2_self_outcomes = rng.permutation(stream_for(self_kind2))
option2_other_outcomes = rng.permutation(stream_for(other_kind2))
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = option1
option_pairs[s, b, t, 1] = option2
value1 = beta * (EV_self[s, b, t, idx1] + EV_other[s, b, t, idx1])
value2 = beta * (EV_self[s, b, t, idx2] + EV_other[s, b, t, idx2])
probabilities = softmax(np.array([value1, value2], dtype=float), 1.0)
choice_probabilities[s, b, t, idx1] = probabilities[0]
choice_probabilities[s, b, t, idx2] = probabilities[1]
chosen_option = rng.choice([option1, option2], p=probabilities)
choices[s, b, t] = chosen_option
chosen_idx = letter_to_idx[chosen_option]
if chosen_option == option1:
outcome_self_value = int(option1_self_outcomes[t])
outcome_other_value = int(option1_other_outcomes[t])
else:
outcome_self_value = int(option2_self_outcomes[t])
outcome_other_value = int(option2_other_outcomes[t])
outcomes_self[s, b, t] = outcome_self_value
outcomes_other[s, b, t] = outcome_other_value
pe_self_value = outcome_self_value - EV_self[s, b, t, chosen_idx]
pe_other_value = outcome_other_value - EV_other[s, b, t, chosen_idx]
pe_self[s, b, t] = pe_self_value
pe_other[s, b, t] = pe_other_value
pe_self_pos[s, b, t] = max(pe_self_value, 0.0)
pe_self_neg[s, b, t] = min(pe_self_value, 0.0)
pe_other_pos[s, b, t] = max(pe_other_value, 0.0)
pe_other_neg[s, b, t] = min(pe_other_value, 0.0)
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, chosen_idx] = (
EV_self[s, b, t, chosen_idx]
+ alpha_self_pos * pe_self_pos[s, b, t]
+ alpha_self_neg * pe_self_neg[s, b, t]
)
EV_other[s, b, t+1, chosen_idx] = (
EV_other[s, b, t, chosen_idx]
+ alpha_other_pos * pe_other_pos[s, b, t]
+ alpha_other_neg * pe_other_neg[s, b, t]
)
return {
"params": np.column_stack((
beta_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–4α–1β FIT (EV_self, EV_other; single β)
# params = [beta, alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
# ============================================================
def rw2q4a1b_fit(params: np.ndarray,
choices: np.ndarray,
outcomes_self: np.ndarray,
outcomes_other: np.ndarray,
option_pairs: np.ndarray,
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
alpha_self_pos = norm2alpha(params[1])
alpha_self_neg = norm2alpha(params[2])
alpha_other_pos = norm2alpha(params[3])
alpha_other_neg = norm2alpha(params[4])
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
for alpha_value in (alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
choice_array = np.asarray(choices)
if not np.issubdtype(choice_array.dtype, np.number):
choice_array = np.vectorize(letter_to_idx.get)(choice_array)
choice_array = choice_array.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
option1, option2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
idx1, idx2 = letter_to_idx[option1], letter_to_idx[option2]
chosen_idx = int(choice_array[b, t])
value1 = beta * (EV_self[b, t, idx1] + EV_other[b, t, idx1])
value2 = beta * (EV_self[b, t, idx2] + EV_other[b, t, idx2])
probabilities = softmax(np.array([value1, value2], dtype=float), 1.0)
choice_probabilities[b, t, idx1] = probabilities[0]
choice_probabilities[b, t, idx2] = probabilities[1]
chosen_probability = probabilities[0] if chosen_idx == idx1 else probabilities[1]
nll += -np.log(chosen_probability + 1e-12)
outcome_self_value = outcomes_self[b, t]
outcome_other_value = outcomes_other[b, t]
pe_self_value = outcome_self_value - EV_self[b, t, chosen_idx]
pe_other_value = outcome_other_value - EV_other[b, t, chosen_idx]
pe_self[b, t] = pe_self_value
pe_other[b, t] = pe_other_value
pe_self_pos[b, t] = max(pe_self_value, 0.0)
pe_self_neg[b, t] = min(pe_self_value, 0.0)
pe_other_pos[b, t] = max(pe_other_value, 0.0)
pe_other_neg[b, t] = min(pe_other_value, 0.0)
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, chosen_idx] = (
EV_self[b, t, chosen_idx]
+ alpha_self_pos * pe_self_pos[b, t]
+ alpha_self_neg * pe_self_neg[b, t]
)
EV_other[b, t+1, chosen_idx] = (
EV_other[b, t, chosen_idx]
+ alpha_other_pos * pe_other_pos[b, t]
+ alpha_other_neg * pe_other_neg[b, t]
)
BIC = 5 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta,
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg],
"choices": choice_array,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
# ============================================================
# 2Q–1w–4α–1β SIMULATE (EV_self, EV_other; weight w)
# params columns (6), per subject:
# [beta, w,
# alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
#
# Q_total = w * EV_other + (1 - w) * EV_self
# choice rule: softmax(beta * Q_total)
# ============================================================
def rw2q1w4a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
(beta_all, w_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all) = (params[:, i].astype(float) for i in range(6))
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
if not ((0.0 <= w_all) & (w_all <= 1.0)).all():
raise ValueError("w out of bounds (must be in [0, 1]).")
for array in (alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all):
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list,
nblocks=nblocks,
nsubjects=nsubjects))
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
opt_types = {
'A': ('+', '+'),
'B': ('+', '-'),
'C': ('-', '+'),
'D': ('-', '-')
}
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta = beta_all[s]
w = w_all[s]
alpha_self_pos = alpha_self_pos_all[s]
alpha_self_neg = alpha_self_neg_all[s]
alpha_other_pos = alpha_other_pos_all[s]
alpha_other_neg = alpha_other_neg_all[s]
for b in range(nblocks):
pair = block_orders[s][b]
option1, option2 = pair[0], pair[1]
idx1, idx2 = letter_to_idx[option1], letter_to_idx[option2]
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[option1]
self_kind2, other_kind2 = opt_types[option2]
option1_self_outcomes = rng.permutation(stream_for(self_kind1))
option1_other_outcomes = rng.permutation(stream_for(other_kind1))
option2_self_outcomes = rng.permutation(stream_for(self_kind2))
option2_other_outcomes = rng.permutation(stream_for(other_kind2))
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = option1
option_pairs[s, b, t, 1] = option2
q1 = w * EV_other[s, b, t, idx1] + (1.0 - w) * EV_self[s, b, t, idx1]
q2 = w * EV_other[s, b, t, idx2] + (1.0 - w) * EV_self[s, b, t, idx2]
value1 = beta * q1
value2 = beta * q2
probabilities = softmax(np.array([value1, value2], dtype=float), 1.0)
choice_probabilities[s, b, t, idx1] = probabilities[0]
choice_probabilities[s, b, t, idx2] = probabilities[1]
chosen_option = rng.choice([option1, option2], p=probabilities)
choices[s, b, t] = chosen_option
chosen_idx = letter_to_idx[chosen_option]
if chosen_option == option1:
outcome_self_value = int(option1_self_outcomes[t])
outcome_other_value = int(option1_other_outcomes[t])
else:
outcome_self_value = int(option2_self_outcomes[t])
outcome_other_value = int(option2_other_outcomes[t])
outcomes_self[s, b, t] = outcome_self_value
outcomes_other[s, b, t] = outcome_other_value
pe_self_value = outcome_self_value - EV_self[s, b, t, chosen_idx]
pe_other_value = outcome_other_value - EV_other[s, b, t, chosen_idx]
pe_self[s, b, t] = pe_self_value
pe_other[s, b, t] = pe_other_value
pe_self_pos[s, b, t] = max(pe_self_value, 0.0)
pe_self_neg[s, b, t] = min(pe_self_value, 0.0)
pe_other_pos[s, b, t] = max(pe_other_value, 0.0)
pe_other_neg[s, b, t] = min(pe_other_value, 0.0)
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, chosen_idx] = (
EV_self[s, b, t, chosen_idx]
+ alpha_self_pos * pe_self_pos[s, b, t]
+ alpha_self_neg * pe_self_neg[s, b, t]
)
EV_other[s, b, t+1, chosen_idx] = (
EV_other[s, b, t, chosen_idx]
+ alpha_other_pos * pe_other_pos[s, b, t]
+ alpha_other_neg * pe_other_neg[s, b, t]
)
return {
"params": np.column_stack((
beta_all, w_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–1w–4α–1β FIT (EV_self, EV_other; weight w)
# params (unconstrained) passed in:
# [p0, p1, p2, p3, p4, p5] ->
# beta = norm2beta(p0)
# w = norm2alpha(p1) in (0,1)
# alpha_* = norm2alpha_bounded(pi) in [0.10,0.90]
# ============================================================
def rw2q1w4a1b_fit(params: np.ndarray,
choices: np.ndarray,
outcomes_self: np.ndarray,
outcomes_other: np.ndarray,
option_pairs: np.ndarray,
prior=None,
output: str = "npl"):
beta = norm2beta(params[0])
w = norm2alpha(params[1])
alpha_self_pos = norm2alpha_bounded(params[2])
alpha_self_neg = norm2alpha_bounded(params[3])
alpha_other_pos = norm2alpha_bounded(params[4])
alpha_other_neg = norm2alpha_bounded(params[5])
if not (1e-5 <= float(beta) <= 20.0):
return 1e7
if not (0.0 <= float(w) <= 1.0):
return 1e7
for alpha_value in (alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
choice_array = np.asarray(choices)
if not np.issubdtype(choice_array.dtype, np.number):
choice_array = np.vectorize(letter_to_idx.get)(choice_array)
choice_array = choice_array.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
option1, option2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
idx1, idx2 = letter_to_idx[option1], letter_to_idx[option2]
chosen_idx = int(choice_array[b, t])
q1 = w * EV_other[b, t, idx1] + (1.0 - w) * EV_self[b, t, idx1]
q2 = w * EV_other[b, t, idx2] + (1.0 - w) * EV_self[b, t, idx2]
value1 = beta * q1
value2 = beta * q2
probabilities = softmax(np.array([value1, value2], dtype=float), 1.0)
choice_probabilities[b, t, idx1] = probabilities[0]
choice_probabilities[b, t, idx2] = probabilities[1]
chosen_probability = probabilities[0] if chosen_idx == idx1 else probabilities[1]
nll += -np.log(chosen_probability + 1e-12)
outcome_self_value = outcomes_self[b, t]
outcome_other_value = outcomes_other[b, t]
pe_self_value = outcome_self_value - EV_self[b, t, chosen_idx]
pe_other_value = outcome_other_value - EV_other[b, t, chosen_idx]
pe_self[b, t] = pe_self_value
pe_other[b, t] = pe_other_value
pe_self_pos[b, t] = max(pe_self_value, 0.0)
pe_self_neg[b, t] = min(pe_self_value, 0.0)
pe_other_pos[b, t] = max(pe_other_value, 0.0)
pe_other_neg[b, t] = min(pe_other_value, 0.0)
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, chosen_idx] = (
EV_self[b, t, chosen_idx]
+ alpha_self_pos * pe_self_pos[b, t]
+ alpha_self_neg * pe_self_neg[b, t]
)
EV_other[b, t+1, chosen_idx] = (
EV_other[b, t, chosen_idx]
+ alpha_other_pos * pe_other_pos[b, t]
+ alpha_other_neg * pe_other_neg[b, t]
)
# priors on alphas
ALPHA_PRIOR_MU = 0.5
ALPHA_PRIOR_LAMBDA_GLOBAL = 0.5
ALPHA_PRIOR_LAMBDA_PAIR = 0.25
alpha_vec = np.array([
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg
], dtype=float)
reg_global = ALPHA_PRIOR_LAMBDA_GLOBAL * np.sum((alpha_vec - ALPHA_PRIOR_MU) ** 2)
reg_pair = ALPHA_PRIOR_LAMBDA_PAIR * (alpha_self_pos - alpha_self_neg) ** 2
reg = reg_global + reg_pair
nll_reg = nll + reg
BIC = 6 * np.log(nblocks * ntrials) + 2 * nll_reg
if output == "all":
return {
"params": [beta, w,
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg],
"choices": choice_array,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll_reg,
"BIC": BIC
}
return calc_fval(nll_reg, params, prior=prior, output=output)
# ============================================================
# 2Q–4α–2β SIMULATE (EV_self, EV_other; β_self, β_other)
# params columns (6), per subject:
# [beta_self, beta_other,
# alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
# Choice rule: value = beta_self*EV_self + beta_other*EV_other
# ============================================================
def rw2q4a2b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
assert nblocks % 6 == 0, "nblocks must be a multiple of 6 (counterbalance option pairs)."
(beta_self_all, beta_other_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all) = (params[:, i].astype(float) for i in range(6))
for array in (beta_self_all, beta_other_all):
if not ((array > 1e-5) & (array <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
for array in (alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all):
if not ((0.0 <= array) & (array <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
option_pairs_list = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
block_orders = list(gen_rnd_blocks(option_pairs_list,
nblocks=nblocks,
nsubjects=nsubjects))
tmpl_pos = rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int)
tmpl_neg = rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
opt_types = {
'A': ('+', '+'),
'B': ('+', '-'),
'C': ('-', '+'),
'D': ('-', '-')
}
choices = np.empty((nsubjects, nblocks, ntrials), dtype=object)
option_pairs = np.empty((nsubjects, nblocks, ntrials, 2), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
EV_self = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
for s in range(nsubjects):
beta_self = beta_self_all[s]
beta_other = beta_other_all[s]
alpha_self_pos = alpha_self_pos_all[s]
alpha_self_neg = alpha_self_neg_all[s]
alpha_other_pos = alpha_other_pos_all[s]
alpha_other_neg = alpha_other_neg_all[s]
for b in range(nblocks):
pair = block_orders[s][b]
option1, option2 = pair[0], pair[1]
idx1, idx2 = letter_to_idx[option1], letter_to_idx[option2]
def stream_for(kind: str) -> np.ndarray:
return np.array(tmpl_pos if kind == '+' else tmpl_neg, copy=True)
self_kind1, other_kind1 = opt_types[option1]
self_kind2, other_kind2 = opt_types[option2]
option1_self_outcomes = rng.permutation(stream_for(self_kind1))
option1_other_outcomes = rng.permutation(stream_for(other_kind1))
option2_self_outcomes = rng.permutation(stream_for(self_kind2))
option2_other_outcomes = rng.permutation(stream_for(other_kind2))
EV_self[s, b, 0, :] = 0.0
EV_other[s, b, 0, :] = 0.0
for t in range(ntrials):
option_pairs[s, b, t, 0] = option1
option_pairs[s, b, t, 1] = option2
value1 = (
beta_self * EV_self[s, b, t, idx1] +
beta_other * EV_other[s, b, t, idx1]
)
value2 = (
beta_self * EV_self[s, b, t, idx2] +
beta_other * EV_other[s, b, t, idx2]
)
probabilities = softmax(np.array([value1, value2], dtype=float), 1.0)
choice_probabilities[s, b, t, idx1] = probabilities[0]
choice_probabilities[s, b, t, idx2] = probabilities[1]
chosen_option = rng.choice([option1, option2], p=probabilities)
choices[s, b, t] = chosen_option
chosen_idx = letter_to_idx[chosen_option]
if chosen_option == option1:
outcome_self_value = int(option1_self_outcomes[t])
outcome_other_value = int(option1_other_outcomes[t])
else:
outcome_self_value = int(option2_self_outcomes[t])
outcome_other_value = int(option2_other_outcomes[t])
outcomes_self[s, b, t] = outcome_self_value
outcomes_other[s, b, t] = outcome_other_value
pe_self_value = outcome_self_value - EV_self[s, b, t, chosen_idx]
pe_other_value = outcome_other_value - EV_other[s, b, t, chosen_idx]
pe_self[s, b, t] = pe_self_value
pe_other[s, b, t] = pe_other_value
pe_self_pos[s, b, t] = max(pe_self_value, 0.0)
pe_self_neg[s, b, t] = min(pe_self_value, 0.0)
pe_other_pos[s, b, t] = max(pe_other_value, 0.0)
pe_other_neg[s, b, t] = min(pe_other_value, 0.0)
EV_self[s, b, t+1, :] = EV_self[s, b, t, :]
EV_other[s, b, t+1, :] = EV_other[s, b, t, :]
EV_self[s, b, t+1, chosen_idx] = (
EV_self[s, b, t, chosen_idx]
+ alpha_self_pos * pe_self_pos[s, b, t]
+ alpha_self_neg * pe_self_neg[s, b, t]
)
EV_other[s, b, t+1, chosen_idx] = (
EV_other[s, b, t, chosen_idx]
+ alpha_other_pos * pe_other_pos[s, b, t]
+ alpha_other_neg * pe_other_neg[s, b, t]
)
return {
"params": np.column_stack((
beta_self_all, beta_other_all,
alpha_self_pos_all, alpha_self_neg_all,
alpha_other_pos_all, alpha_other_neg_all
)),
"choices": choices,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
}
# ============================================================
# 2Q–4α–2β FIT (EV_self, EV_other; β_self, β_other)
# params = [beta_self, beta_other,
# alpha_self_pos, alpha_self_neg,
# alpha_other_pos, alpha_other_neg]
# ============================================================
def rw2q4a2b_fit(params: np.ndarray,
choices: np.ndarray,
outcomes_self: np.ndarray,
outcomes_other: np.ndarray,
option_pairs: np.ndarray,
prior=None,
output: str = "npl"):
beta_self = norm2beta(params[0])
beta_other = norm2beta(params[1])
alpha_self_pos = norm2alpha(params[2])
alpha_self_neg = norm2alpha(params[3])
alpha_other_pos = norm2alpha(params[4])
alpha_other_neg = norm2alpha(params[5])
if not (1e-5 <= float(beta_self) <= 20.0):
return 1e7
if not (1e-5 <= float(beta_other) <= 20.0):
return 1e7
for alpha_value in (alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg):
if not (0.0 <= float(alpha_value) <= 1.0):
return 1e7
letter_to_idx = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
choice_array = np.asarray(choices)
if not np.issubdtype(choice_array.dtype, np.number):
choice_array = np.vectorize(letter_to_idx.get)(choice_array)
choice_array = choice_array.astype(int, copy=False)
nblocks, ntrials = outcomes_self.shape
EV_self = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
EV_other = np.zeros((nblocks, ntrials + 1, 4), dtype=float)
choice_probabilities = np.zeros((nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nblocks, ntrials), dtype=float)
pe_other = np.zeros((nblocks, ntrials), dtype=float)
pe_self_pos = np.zeros_like(pe_self)
pe_self_neg = np.zeros_like(pe_self)
pe_other_pos = np.zeros_like(pe_other)
pe_other_neg = np.zeros_like(pe_other)
nll = 0.0
for b in range(nblocks):
for t in range(ntrials):
option1, option2 = option_pairs[b, t, 0], option_pairs[b, t, 1]
idx1, idx2 = letter_to_idx[option1], letter_to_idx[option2]
chosen_idx = int(choice_array[b, t])
value1 = (
beta_self * EV_self[b, t, idx1] +
beta_other * EV_other[b, t, idx1]
)
value2 = (
beta_self * EV_self[b, t, idx2] +
beta_other * EV_other[b, t, idx2]
)
probabilities = softmax(np.array([value1, value2], dtype=float), 1.0)
choice_probabilities[b, t, idx1] = probabilities[0]
choice_probabilities[b, t, idx2] = probabilities[1]
chosen_probability = probabilities[0] if chosen_idx == idx1 else probabilities[1]
nll += -np.log(chosen_probability + 1e-12)
outcome_self_value = outcomes_self[b, t]
outcome_other_value = outcomes_other[b, t]
pe_self_value = outcome_self_value - EV_self[b, t, chosen_idx]
pe_other_value = outcome_other_value - EV_other[b, t, chosen_idx]
pe_self[b, t] = pe_self_value
pe_other[b, t] = pe_other_value
pe_self_pos[b, t] = max(pe_self_value, 0.0)
pe_self_neg[b, t] = min(pe_self_value, 0.0)
pe_other_pos[b, t] = max(pe_other_value, 0.0)
pe_other_neg[b, t] = min(pe_other_value, 0.0)
EV_self[b, t+1, :] = EV_self[b, t, :]
EV_other[b, t+1, :] = EV_other[b, t, :]
EV_self[b, t+1, chosen_idx] = (
EV_self[b, t, chosen_idx]
+ alpha_self_pos * pe_self_pos[b, t]
+ alpha_self_neg * pe_self_neg[b, t]
)
EV_other[b, t+1, chosen_idx] = (
EV_other[b, t, chosen_idx]
+ alpha_other_pos * pe_other_pos[b, t]
+ alpha_other_neg * pe_other_neg[b, t]
)
BIC = 6 * np.log(nblocks * ntrials) + 2 * nll
if output == "all":
return {
"params": [beta_self, beta_other,
alpha_self_pos, alpha_self_neg,
alpha_other_pos, alpha_other_neg],
"choices": choice_array,
"option_pairs": option_pairs,
"outcomes_self": outcomes_self,
"outcomes_other": outcomes_other,
"EV_self": EV_self,
"EV_other": EV_other,
"choice_probabilities": choice_probabilities,
"pe_self": pe_self,
"pe_other": pe_other,
"pe_self_pos": pe_self_pos,
"pe_self_neg": pe_self_neg,
"pe_other_pos": pe_other_pos,
"pe_other_neg": pe_other_neg,
"nll": nll,
"BIC": BIC
}
return calc_fval(nll, params, prior=prior, output=output)
import numpy as np, random
from itertools import permutations, chain
# Absolute, not `from ..utils.math`. This file is written to sit inside the pyem package
# as pyem/models/rl_hp.py, and the relative form only resolves there. It is not installed
# there: the copy that exists is this one, in the repo, so `import rl_hp` was an
# ImportError and nothing here could be run without first copying the file into
# site-packages. Absolute works from both places.
from pyem.utils.math import softmax, norm2alpha, norm2beta, calc_fval
LETTER_TO_IDX = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
ALL_PAIRS = ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']
# A:+/+ B:+/− C:−/+ D:−/− (self, other)
OPT_TYPES = {
'A': ('+', '+'),
'B': ('+', '-'),
'C': ('-', '+'),
'D': ('-', '-'),
}
def gen_rnd_blocks(items, nblocks=2, nsubjects=100):
perms = list(permutations(items))
for _ in range(nsubjects):
blocks = random.choices(perms, k=nblocks)
combined = tuple(chain.from_iterable(blocks))
yield combined
# ----------------------------------------
# 1Q–1α–1β SIMULATE (1q1a1b)
# ----------------------------------------
def rw1q1a1b_sim(params: np.ndarray,
nblocks: int = 12,
ntrials: int = 20,
rng_seed: int | None = None):
"""
1Q, 1α, 1β model.
- One value per option (EV)
- One inverse temperature beta
- One learning rate alpha applied to the sum of self & other PEs.
Outcomes_self/other in {-1,+1} via '+'/'-' templates:
A: +/+
B: +/-
C: -/+
D: -/-
Each trial: choose between a fixed pair of options in that block.
"""
assert nblocks % 6 == 0, "nblocks should be multiple of 6 for full counterbalancing"
# --- bounds / unpack ---
(beta_all,
alpha_all) = (params[:, i].astype(float) for i in range(2))
if not ((beta_all > 1e-5) & (beta_all <= 20.0)).all():
raise ValueError("beta out of bounds (must be in (1e-5, 20]).")
if not ((0.0 <= alpha_all) & (alpha_all <= 1.0)).all():
raise ValueError("alpha out of bounds (must be in [0, 1]).")
rng = np.random.default_rng(rng_seed)
nsubjects = params.shape[0]
# --- task structure: each subject sees each pair exactly nblocks/6 times ---
reps_per_pair = nblocks // 6
block_orders = []
for _ in range(nsubjects):
pairs_for_subject = ALL_PAIRS * reps_per_pair # list of length nblocks
rng.shuffle(pairs_for_subject)
block_orders.append(pairs_for_subject)
# outcome templates for valence types: no zeros, non-deterministic
opt_templates = {
'+': rng.choice([1, -1], size=ntrials, p=[0.75, 0.25]).astype(int),
'-': rng.choice([-1, 1], size=ntrials, p=[0.75, 0.25]).astype(int)
}
# --- outputs ---
choices = np.zeros((nsubjects, nblocks, ntrials), dtype=object)
outcomes_self = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
outcomes_other = np.zeros((nsubjects, nblocks, ntrials), dtype=int)
option_pairs = np.zeros((nsubjects, nblocks, ntrials, 2), dtype=object)
EV = np.zeros((nsubjects, nblocks, ntrials + 1, 4), dtype=float)
ch_prob = np.zeros((nsubjects, nblocks, ntrials, 4), dtype=float)
pe_self = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
pe_other = np.zeros((nsubjects, nblocks, ntrials), dtype=float)
for s in range(nsubjects):
beta = beta_all[s]
alpha = alpha_all[s]
for b in range(nblocks):
opt1, opt2 = block_orders[s][b]
o1, o2 = LETTER_TO_IDX[opt1], LETTER_TO_IDX[opt2]
# pre-generate outcomes for this block (only for shown options)
all_outcomes = {
f'{opt1}_self': rng.permutation(opt_templates[OPT_TYPES[opt1][0]]),