cpm-toolbox 0.26.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. cpm/__init__.py +26 -0
  2. cpm/__version__.py +1 -0
  3. cpm/applications/__init__.py +3 -0
  4. cpm/applications/_backend.py +154 -0
  5. cpm/applications/_sessions.py +317 -0
  6. cpm/applications/decision_making.py +716 -0
  7. cpm/applications/reinforcement_learning.py +402 -0
  8. cpm/applications/signal_detection.py +637 -0
  9. cpm/brainexplorer/__init__.py +4 -0
  10. cpm/brainexplorer/_utils.py +70 -0
  11. cpm/brainexplorer/bandits.py +243 -0
  12. cpm/brainexplorer/information_gathering.py +167 -0
  13. cpm/brainexplorer/perceptual_decision_making.py +263 -0
  14. cpm/brainexplorer/risky_decision_making.py +408 -0
  15. cpm/core/__init__.py +0 -0
  16. cpm/core/_jit.py +160 -0
  17. cpm/core/data.py +258 -0
  18. cpm/core/diagnostics.py +203 -0
  19. cpm/core/exports.py +50 -0
  20. cpm/core/generators.py +125 -0
  21. cpm/core/optimisers.py +433 -0
  22. cpm/core/parallel.py +129 -0
  23. cpm/cpm.py +0 -0
  24. cpm/datasets/__init__.py +7 -0
  25. cpm/datasets/base.py +336 -0
  26. cpm/datasets/data/__init__.py +0 -0
  27. cpm/datasets/data/bandit_small.csv +14400 -0
  28. cpm/datasets/data/blocking_ratings.csv +2461 -0
  29. cpm/datasets/data/metacognition_data.csv +23931 -0
  30. cpm/datasets/data/model_based_model_free.csv +8002 -0
  31. cpm/datasets/data/risky_choices.csv +11775 -0
  32. cpm/datasets/data/two_step_adults.csv +3361 -0
  33. cpm/generators/__init__.py +10 -0
  34. cpm/generators/_fast_priors.py +172 -0
  35. cpm/generators/parameters.py +690 -0
  36. cpm/generators/session.py +308 -0
  37. cpm/generators/simulator.py +187 -0
  38. cpm/generators/wrapper.py +299 -0
  39. cpm/hierarchical/__init__.py +4 -0
  40. cpm/hierarchical/_chains.py +92 -0
  41. cpm/hierarchical/empirical.py +437 -0
  42. cpm/hierarchical/variational.py +776 -0
  43. cpm/models/__init__.py +7 -0
  44. cpm/models/activation.py +473 -0
  45. cpm/models/attention.py +128 -0
  46. cpm/models/decision.py +509 -0
  47. cpm/models/kernels.py +520 -0
  48. cpm/models/learning.py +671 -0
  49. cpm/models/utils.py +48 -0
  50. cpm/optimisation/__init__.py +9 -0
  51. cpm/optimisation/bads.py +429 -0
  52. cpm/optimisation/compare.py +60 -0
  53. cpm/optimisation/fmin.py +823 -0
  54. cpm/optimisation/free.py +363 -0
  55. cpm/optimisation/genetic.py +216 -0
  56. cpm/optimisation/minimise.py +470 -0
  57. cpm/utils/__init__.py +4 -0
  58. cpm/utils/data.py +273 -0
  59. cpm/utils/metad.py +280 -0
  60. cpm_toolbox-0.26.0.dist-info/METADATA +186 -0
  61. cpm_toolbox-0.26.0.dist-info/RECORD +65 -0
  62. cpm_toolbox-0.26.0.dist-info/WHEEL +5 -0
  63. cpm_toolbox-0.26.0.dist-info/licenses/LICENSE +661 -0
  64. cpm_toolbox-0.26.0.dist-info/licenses/LICENSES-BUNDLE +19 -0
  65. cpm_toolbox-0.26.0.dist-info/top_level.txt +1 -0
cpm/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ __author__ = "Lenard Dome"
2
+ __email__ = "lenarddome@gmail.com"
3
+ __license__ = "AGPL-3.0"
4
+
5
+ """
6
+ This is the main module of the package.
7
+ It contains the main class of the package, any kind of setup that has to happen during loading and filtering of warning messages.
8
+ Here, we will also define the main function of the package by importing it from subdirectories.
9
+ """
10
+
11
+ import os
12
+ import sys
13
+ import logging
14
+ import warnings
15
+
16
+ from .__version__ import __version__
17
+ from . import generators
18
+ from . import models
19
+ from . import applications
20
+ from . import optimisation
21
+ from . import hierarchical
22
+ from . import utils
23
+ from . import datasets
24
+ from . import brainexplorer
25
+
26
+ del os, sys, warnings, logging
cpm/__version__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.26.0"
@@ -0,0 +1,3 @@
1
+ from . import reinforcement_learning
2
+ from . import signal_detection
3
+ from . import decision_making
@@ -0,0 +1,154 @@
1
+ """
2
+ Shared machinery of the built-in applications.
3
+
4
+ Each application computes all trials of a participant in one call of a loop in
5
+ `cpm.applications._sessions`, compiled with numba if numba is installed and
6
+ plain Python otherwise. The `Application` base class keeps the interface of a
7
+ per-trial `cpm.generators.Wrapper` on top of that:
8
+
9
+ - `model` is a per-trial model function, `model(parameters, trial)`, which
10
+ returns the outputs of one trial as a dictionary. It runs the same loop on that
11
+ single trial, so there is only one implementation of each model.
12
+ - `simulation` is the list of these per-trial dictionaries for the last run,
13
+ built from the outputs of the run when it is first read.
14
+ """
15
+
16
+ import copy
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ from ..core import _jit
22
+ from ..generators.session import SessionWrapper, session_data, trial_view
23
+
24
+ __all__ = ["Application", "SessionModel", "TrialModel", "indices", "require", "uniforms"]
25
+
26
+
27
+ class SessionModel:
28
+ """
29
+ A model function for `SessionWrapper` that runs a loop of `cpm.applications._sessions`.
30
+
31
+ Subclasses implement `__call__(parameters, data)`. The loops are looked up
32
+ by backend when needed, rather than stored, so that the model function pickles
33
+ by reference and can be sent to other processes for parallel fits.
34
+
35
+ Parameters
36
+ ----------
37
+ generate : bool
38
+ Whether the model samples its choices.
39
+
40
+ Attributes
41
+ ----------
42
+ backend : str
43
+ "numba" if numba is installed and not disabled, "python" otherwise.
44
+ """
45
+
46
+ def __init__(self, generate=False):
47
+ self.generate = generate
48
+ self.backend = _jit.resolve_backend("auto")
49
+
50
+ @property
51
+ def sessions(self):
52
+ return _jit.kernels("cpm.applications._sessions", python=self.backend == "python")
53
+
54
+
55
+ def one_trial(trial):
56
+ """The data of a single trial (a `pandas.Series` or a dict) as one-row data."""
57
+ items = trial.items() if isinstance(trial, (pd.Series, dict)) else dict(trial).items()
58
+ return {key: np.asarray([value]) for key, value in items}
59
+
60
+
61
+ class TrialModel:
62
+ """
63
+ The per-trial model function of an application: its session model, run on one trial.
64
+
65
+ Called as `model(parameters, trial)`, like the model function of a per-trial
66
+ `Wrapper`, it computes one trial from the states in `parameters` and returns
67
+ that trial's outputs, including the updated states.
68
+ """
69
+
70
+ def __init__(self, session_model, prepare, shapes):
71
+ self.session_model = session_model
72
+ self.prepare = prepare
73
+ self.shapes = shapes
74
+
75
+ def __call__(self, parameters, trial, generate=None):
76
+ model, prepare = self.session_model, self.prepare
77
+ if generate is not None and generate != model.generate:
78
+ model = copy.copy(model)
79
+ model.generate = generate
80
+ if hasattr(prepare, "generate"):
81
+ prepare = copy.copy(prepare)
82
+ prepare.generate = generate
83
+ output = model(parameters=parameters, data=prepare(one_trial(trial)))
84
+ return trial_view(output, 0, self.shapes)
85
+
86
+
87
+ class Application(SessionWrapper):
88
+ """
89
+ The base class of the built-in applications, see the module docstring.
90
+
91
+ Subclasses call `_setup` from their constructor, and set `_trial_shapes` for
92
+ outputs whose per-trial value is not simply a row of the session output.
93
+ """
94
+
95
+ def _setup(self, data, parameters, session_model, prepare):
96
+ super().__init__(model=session_model, data=data, parameters=parameters, prepare=prepare)
97
+ self._session_model = session_model
98
+ self.model = TrialModel(session_model, prepare, self._trial_shapes)
99
+
100
+ def _run_session(self):
101
+ return self._session_model(parameters=self.parameters, data=self.session)
102
+
103
+
104
+ def require(data, columns, model):
105
+ """Raise a helpful error if the prepared data lack any of `columns`."""
106
+ missing = [column for column in columns if column not in data]
107
+ if missing:
108
+ raise KeyError(
109
+ f"{model} needs the column(s) {missing} in the data, which has "
110
+ f"{sorted(data)}."
111
+ )
112
+
113
+
114
+ def uniforms(trials, needed):
115
+ """One uniform random number per trial from `numpy.random` if `needed`, else an empty array."""
116
+ if needed:
117
+ return np.random.random_sample(trials)
118
+ return np.empty(0)
119
+
120
+
121
+ def indices(values):
122
+ """
123
+ `values` as int64 indices.
124
+
125
+ Casting NaN or infinity to an integer gives a different number on different
126
+ platforms (0 on ARM), so they become an index out of any range instead, which
127
+ the loops of `cpm.applications._sessions` reject where they use it.
128
+ """
129
+ values = np.asarray(values)
130
+ if values.dtype.kind == "f":
131
+ values = np.where(np.isfinite(values), values, np.iinfo(np.int32).min)
132
+ return np.ascontiguousarray(values, dtype=np.int64)
133
+
134
+
135
+ def prepared(data):
136
+ """`session_data`, with integer and boolean columns as int64 and all others as float64 where possible."""
137
+ out = {}
138
+ for key, value in session_data(data).items():
139
+ if value.dtype.kind in "iub":
140
+ out[key] = np.ascontiguousarray(value, dtype=np.int64)
141
+ elif value.dtype.kind == "f":
142
+ out[key] = np.ascontiguousarray(value, dtype=np.float64)
143
+ else:
144
+ out[key] = value
145
+ return out
146
+
147
+
148
+ def ordered_columns(data, pattern):
149
+ """The columns of `data` whose name contains `pattern`, in the order of the data."""
150
+ if isinstance(data, pd.DataFrame):
151
+ names = list(data.columns)
152
+ else:
153
+ names = [k for k in data if k != "ppt"]
154
+ return [name for name in names if pattern in name]
@@ -0,0 +1,317 @@
1
+ """
2
+ The models of the built-in applications.
3
+
4
+ Each function computes all trials of one participant for one of the
5
+ applications (`RLRW`, `HybridMBMF`, `PTSM`, `PTSM1992` and `PTSM2025`), from
6
+ plain floats and numpy arrays, using the kernels of `cpm.models.kernels`. They
7
+ are the only implementation of these models: the per-trial `model` function of
8
+ an application runs the same loop on a single trial. With numba installed, they
9
+ are compiled as a whole; `cpm.core._jit.kernels` loads this module either
10
+ compiled or as plain Python.
11
+
12
+ Random choices are made from uniform random numbers drawn with NumPy before
13
+ the loop, one per trial, which `kernels.choose` turns into the choice that
14
+ `numpy.random.choice` would have made. Simulations are therefore reproducible
15
+ with `numpy.random.seed`, identical across backends, and identical to the
16
+ former per-trial implementations of the applications.
17
+ """
18
+
19
+ import numpy as np
20
+
21
+ from ..core import _jit
22
+
23
+ njit = _jit.decorator(globals())
24
+ kernels = _jit.kernels("cpm.models.kernels", python=globals().get(_jit.PYTHON_FLAG, False))
25
+
26
+ softmax = kernels.softmax
27
+ choose = kernels.choose
28
+ sarsa_trace_update = kernels.sarsa_trace_update
29
+ separable_rule = kernels.separable_rule
30
+ prospect_utility = kernels.prospect_utility
31
+ prospect_weight = kernels.prospect_weight
32
+ expected_utility = kernels.expected_utility
33
+
34
+
35
+ @njit
36
+ def check_activations(activations):
37
+ """Raise ValueError for NaN or infinite activations, as `cpm.models.decision.Softmax` does."""
38
+ if np.isfinite(activations).all(): # one call on every trial, the cheap one in plain Python
39
+ return
40
+ if np.isnan(activations).any():
41
+ raise ValueError("Activations contain NaN values. Please remove or impute missing values.")
42
+ if np.isinf(activations).any():
43
+ raise ValueError(
44
+ "Activations contain infinite values. Please remove or impute infinite values."
45
+ )
46
+
47
+
48
+ @njit
49
+ def rlrw(alpha, temperature, initial_values, arms, rewards, response, generate, uniforms):
50
+ """
51
+ All trials of `RLRW`.
52
+
53
+ Parameters
54
+ ----------
55
+ alpha, temperature : float
56
+ initial_values : numpy.ndarray
57
+ The initial value of each stimulus, shape (stimuli,).
58
+ arms : numpy.ndarray
59
+ The stimulus on each arm (1-based, as in the data), shape (trials, arms).
60
+ rewards : numpy.ndarray
61
+ The reward of each arm, shape (trials, arms).
62
+ response : numpy.ndarray
63
+ The chosen arm on each trial (0-based); ignored if `generate`.
64
+ generate : bool
65
+ Whether to choose from the policy instead.
66
+ uniforms : numpy.ndarray
67
+ One uniform random number per trial if `generate`.
68
+
69
+ Returns
70
+ -------
71
+ policy, response, reward, values, change, dependent : numpy.ndarray
72
+ `response` is the arm chosen on each trial: the sampled one if
73
+ `generate`, otherwise the observed one.
74
+ """
75
+ n, k = arms.shape
76
+ d = initial_values.shape[0]
77
+ ## numba does not check indices, so the data are checked here, as the
78
+ ## per-trial models did by raising IndexError
79
+ if k < 2:
80
+ raise ValueError("RLRW needs at least two arms.")
81
+ values = initial_values.copy()
82
+ policy = np.empty((n, k))
83
+ out_response = np.empty(n, dtype=np.int64)
84
+ reward = np.empty(n)
85
+ history = np.empty((n, d))
86
+ change = np.empty((n, d))
87
+ activations = np.empty(k)
88
+ mute = np.zeros(d)
89
+ feedback = np.empty(1)
90
+ for t in range(n):
91
+ for j in range(k):
92
+ if not -d <= arms[t, j] - 1 < d:
93
+ raise IndexError("RLRW: the arm columns must hold stimuli from 1 to dimensions.")
94
+ activations[j] = values[arms[t, j] - 1]
95
+ check_activations(activations)
96
+ policy[t] = softmax(activations, temperature)
97
+ choice = choose(policy[t], uniforms[t]) if generate else response[t]
98
+ if not -k <= choice < k:
99
+ raise IndexError("RLRW: response must be an arm, from 0 to the number of arms - 1.")
100
+ if choice < 0:
101
+ choice += k
102
+ out_response[t] = choice
103
+ stimulus = arms[t, choice] - 1
104
+ if stimulus < 0:
105
+ stimulus += d
106
+ teacher = rewards[t, choice]
107
+ reward[t] = teacher
108
+ ## the update of SeparableRule, for the chosen stimulus only
109
+ mute[:] = 0.0
110
+ mute[stimulus] = 1.0
111
+ feedback[0] = teacher
112
+ update, _ = separable_rule(values.reshape(1, d), feedback, mute, alpha)
113
+ change[t] = update[0]
114
+ values += update[0]
115
+ history[t] = values
116
+ return policy, out_response, reward, history, change, policy[:, 1].copy()
117
+
118
+
119
+ @njit
120
+ def hybrid_mbmf(inv_temperature, learning_rate, eligibility_trace, mb_weight,
121
+ choice_stickiness, response_stickiness, q_mf_0, q2_0, m_0, r_0,
122
+ s1, stimuli_first, action, s2, reward, position, reward_0, reward_1,
123
+ generate, uniforms):
124
+ """
125
+ All trials of `HybridMBMF`.
126
+
127
+ The data arrays are one value per trial. `action`, `s2`, `reward` and
128
+ `position` are ignored if `generate`, and `reward_0` and `reward_1` are
129
+ used only then. Returns the outputs of `HybridMBMF`, one row per trial.
130
+ """
131
+ n = s1.shape[0]
132
+ q_mf = q_mf_0.copy()
133
+ q2 = q2_0.copy()
134
+ m = m_0.copy()
135
+ r = r_0.copy()
136
+ out_policy = np.empty((n, 2))
137
+ out_action = np.empty(n, dtype=np.int64)
138
+ out_s2 = np.empty(n, dtype=np.int64)
139
+ out_reward = np.empty(n)
140
+ out_position = np.empty(n, dtype=np.int64)
141
+ out_pe1 = np.empty(n)
142
+ out_pe2 = np.empty(n)
143
+ out_q_mf = np.empty((n, 2, 2))
144
+ out_q2 = np.empty((n, 2))
145
+ out_m = np.empty((n, 2, 2))
146
+ out_r = np.empty((n, 2))
147
+ q_hybrid = np.empty(2)
148
+ for t in range(n):
149
+ state = s1[t]
150
+ ## numba does not check indices, see rlrw
151
+ if not -2 <= state < 2:
152
+ raise IndexError("HybridMBMF: s1, stimuli_first, action, s2 and position must be 0 or 1.")
153
+ first = stimuli_first[t]
154
+ ## the model-based value of action 0 is that of state 1, and vice versa
155
+ for i in range(2):
156
+ r_action = r[1 - i] if first == 1 else r[i]
157
+ q_hybrid[i] = (
158
+ mb_weight * q2[1 - i]
159
+ + (1 - mb_weight) * q_mf[state, i]
160
+ + choice_stickiness * m[state, i]
161
+ + response_stickiness * r_action
162
+ )
163
+ check_activations(q_hybrid)
164
+ policy = softmax(q_hybrid, inv_temperature)
165
+ if generate:
166
+ chosen = choose(policy, uniforms[t])
167
+ reached = 1 - chosen
168
+ payout = reward_1[t] if reached == 1 else reward_0[t]
169
+ side = first ^ chosen
170
+ else:
171
+ chosen = action[t]
172
+ reached = s2[t]
173
+ payout = reward[t]
174
+ side = position[t]
175
+ if not (-2 <= chosen < 2 and -2 <= reached < 2 and -2 <= side < 2):
176
+ raise IndexError("HybridMBMF: s1, stimuli_first, action, s2 and position must be 0 or 1.")
177
+ m[:, :] = 0.0
178
+ m[state, chosen] = 1.0
179
+ r[:] = 0.0
180
+ r[side] = 1.0
181
+ pe1, pe2 = sarsa_trace_update(q_mf, q2, state, chosen, reached, payout,
182
+ learning_rate, eligibility_trace)
183
+ out_policy[t] = policy
184
+ out_action[t] = chosen
185
+ out_s2[t] = reached
186
+ out_reward[t] = payout
187
+ out_position[t] = side
188
+ out_pe1[t] = pe1
189
+ out_pe2[t] = pe2
190
+ out_q_mf[t] = q_mf
191
+ out_q2[t] = q2
192
+ out_m[t] = m
193
+ out_r[t] = r
194
+ return (out_policy, out_action, out_s2, out_reward, out_position, out_pe1, out_pe2,
195
+ out_q_mf, out_q2, out_m, out_r)
196
+
197
+
198
+ @njit
199
+ def prospect_softmax(alpha, beta, lambda_loss, gamma, delta, temperature, safe, risky,
200
+ probability, observed, weighting, utilities, custom_utilities,
201
+ choose_always, generate, uniforms, dependent_chosen):
202
+ """
203
+ All trials of `PTSM` and `PTSM1992`: prospect-theory utilities and a softmax.
204
+
205
+ Parameters
206
+ ----------
207
+ alpha, beta, lambda_loss, gamma, delta, temperature : float
208
+ safe, risky, probability, observed : numpy.ndarray
209
+ One value per trial.
210
+ weighting : int
211
+ The weighting function, see `kernels.WEIGHTING`.
212
+ utilities : numpy.ndarray
213
+ The utilities of the safe and risky magnitude on each trial, shape
214
+ (trials, 2), if `custom_utilities` (computed by a user-supplied
215
+ utility curve); otherwise ignored.
216
+ choose_always : bool
217
+ Whether a choice is sampled on every trial (as `PTSM1992` does), or only
218
+ if `generate` (as `PTSM` does).
219
+ dependent_chosen : bool
220
+ Whether the dependent variable is the probability of the observed choice
221
+ (`PTSM`) rather than of the risky option (`PTSM1992`).
222
+
223
+ Returns
224
+ -------
225
+ policy, dependent, chosen, is_optimal, objective_best, ev_safe, ev_risk, u_safe, u_risk
226
+ """
227
+ n = safe.shape[0]
228
+ out_policy = np.empty((n, 2))
229
+ out_dependent = np.empty(n)
230
+ out_chosen = np.empty(n, dtype=np.int64)
231
+ out_optimal = np.empty(n, dtype=np.int64)
232
+ out_best = np.empty(n, dtype=np.int64)
233
+ out_ev_risk = np.empty(n)
234
+ out_u_safe = np.empty(n)
235
+ out_u_risk = np.empty(n)
236
+ ## the expected utilities of the two options (safe, risky) on all trials at
237
+ ## once, as ProspectUtility computes them for options with one outcome each;
238
+ ## they do not depend on earlier trials. The safe option pays with probability 1.
239
+ magnitudes = np.empty((n, 2))
240
+ magnitudes[:, 0] = safe
241
+ magnitudes[:, 1] = risky
242
+ probabilities = np.ones((n, 2))
243
+ probabilities[:, 1] = probability
244
+ weights = prospect_weight(probabilities, magnitudes, gamma, delta, weighting)
245
+ if custom_utilities:
246
+ outcome_utilities = utilities
247
+ else:
248
+ outcome_utilities = prospect_utility(magnitudes, alpha, beta, lambda_loss)
249
+ expected_all = expected_utility(
250
+ weights.reshape(2 * n, 1), outcome_utilities.reshape(2 * n, 1)
251
+ ).reshape(n, 2)
252
+ for t in range(n):
253
+ ev_risk = risky[t] * probability[t]
254
+ best = 1 if ev_risk >= safe[t] else 0
255
+ expected = expected_all[t]
256
+ check_activations(expected)
257
+ policy = softmax(expected, temperature)
258
+ ## numba does not check indices, see rlrw
259
+ if (dependent_chosen or not (choose_always or generate)) and not -2 <= observed[t] < 2:
260
+ raise IndexError("observed must be 0 (safe) or 1 (risky).")
261
+ if choose_always or generate:
262
+ chosen = choose(policy, uniforms[t])
263
+ else:
264
+ chosen = observed[t]
265
+ out_policy[t] = policy
266
+ out_dependent[t] = policy[observed[t]] if dependent_chosen else policy[1]
267
+ out_chosen[t] = chosen
268
+ out_optimal[t] = 1 if chosen == best else 0
269
+ out_best[t] = best
270
+ out_ev_risk[t] = ev_risk
271
+ out_u_safe[t] = expected[0]
272
+ out_u_risk[t] = expected[1]
273
+ return (out_policy, out_dependent, out_chosen, out_optimal, out_best, out_ev_risk,
274
+ out_u_safe, out_u_risk)
275
+
276
+
277
+ @njit
278
+ def power_utility(x, alpha):
279
+ """The piecewise power utility of `PTSM2025`, which its parameters also hold as `utility_curvature`."""
280
+ return x ** alpha if x >= 0 else -np.abs(x) ** alpha
281
+
282
+
283
+ @njit
284
+ def ptsm2025(eta, phi_gain, phi_loss, temperature, alpha, safe, risky, probability,
285
+ ambiguity, uniforms):
286
+ """
287
+ All trials of `PTSM2025`.
288
+
289
+ Returns
290
+ -------
291
+ policy, model_choice, u_safe, u_risk : numpy.ndarray
292
+ """
293
+ n = safe.shape[0]
294
+ out_policy = np.empty(n)
295
+ out_choice = np.empty(n, dtype=np.int64)
296
+ out_u_safe = np.empty(n)
297
+ out_u_risk = np.empty(n)
298
+ pair = np.empty(2)
299
+ terms = np.empty(2)
300
+ for t in range(n):
301
+ subjective = probability[t] - eta * ambiguity[t]
302
+ subjective = min(max(subjective, 0.0), 1.0)
303
+ u_safe = power_utility(safe[t], alpha)
304
+ u_risk = subjective * power_utility(risky[t], alpha)
305
+ phi = phi_gain if risky[t] >= 0 else phi_loss
306
+ ## the policy of PTSM2025: a softmax of the scaled utilities, with the
307
+ ## gambling bias added to the risky one
308
+ terms[0] = temperature * u_safe
309
+ terms[1] = temperature * u_risk + phi
310
+ p = softmax(terms, 1.0)[1]
311
+ pair[0] = 1 - p
312
+ pair[1] = p
313
+ out_policy[t] = p
314
+ out_choice[t] = choose(pair, uniforms[t])
315
+ out_u_safe[t] = u_safe
316
+ out_u_risk[t] = u_risk
317
+ return out_policy, out_choice, out_u_safe, out_u_risk