Skip to content

API Reference

This reference is generated automatically from the package docstrings via mkdocstrings.

Top-level package

CircularDiffusionModel(threshold_dynamic='fixed')

Circular Diffusion Model

Parameters:

Name Type Description Default
threshold_dynamic str

The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'

'fixed'
Source code in src/jeam/Models/Circular.py
14
15
16
17
18
19
20
21
22
23
24
25
26
def __init__(self, threshold_dynamic='fixed'):
    '''
    Parameters
    ----------
    threshold_dynamic : str, optional
        The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'
    '''
    self.name = 'Circular Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angle

Parameters:

Name Type Description Default
rt array - like

Response times

required
theta array - like

Choice angles in radians

required
drift_vec (array - like, shape(2) or (n_samples, 2))

The drift vector [drift_x, drift_y]

required
ndt (float or array - like, shape(n_samples))

The non-decision time

required
threshold float

The initial decision threshold

required
decay float

The decay rate of the threshold (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Type Description
array - like

The joint log-probability density evaluated at (rt, theta) with same shape as rt and theta

Source code in src/jeam/Models/Circular.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angle

    Parameters
    ----------
    rt : array-like
        Response times
    theta : array-like
        Choice angles in radians
    drift_vec : array-like, shape (2,) or (n_samples, 2)
        The drift vector [drift_x, drift_y]
    ndt : float or array-like, shape (n_samples,)
        The non-decision time
    threshold : float
        The initial decision threshold
    decay : float
        The decay rate of the threshold (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    array-like
        The joint log-probability density evaluated at (rt, theta) with same shape as rt and theta
    '''

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 2))

    if drift_vec.shape[1] != 2 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (2,) or (n_samples, 2)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = cdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * cdm_short_t_fpt_z(sigma**2 * tt/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = cdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * cdm_short_t_fpt_z(sigma**2 * T/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 2*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 2*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 2*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 2*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)

    # Girsanov:
    if s_v == 0:
        # No drift variability
        mu_dot_x0 = drift_vec[:, 0] * np.cos(theta)
        mu_dot_x1 = drift_vec[:, 1] * np.sin(theta)

        if s_t == 0:
            # No non-decision time variability
            term1 = a * (mu_dot_x0 + mu_dot_x1) / sigma**2
            term2 = 0.5 * (drift_vec[:, 0]**2 + drift_vec[:, 1]**2) * tt / sigma**2
            log_density = term1 - term2 + np.log(fpt_z) - np.log(2*np.pi)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            norm2_drift = drift_vec[:, 0]**2 + drift_vec[:, 1]**2
            mu_dot_x = (mu_dot_x0 + mu_dot_x1) / sigma**2
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        integrand = np.exp(- 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density =  np.exp(threshold * mu_dot_x[i]) * trapz_1d(integrand, eps) * 0.5/np.pi
                    elif self.threshold_dynamic == 'linear':
                        integrand = np.exp((threshold - decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * 0.5/np.pi
                    elif self.threshold_dynamic == 'exponential':
                        integrand = np.exp(threshold*np.exp(-decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * 0.5/np.pi
                    elif self.threshold_dynamic == 'hyperbolic':
                        integrand = np.exp(threshold/(1  + decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * 0.5/np.pi
                    elif self.threshold_dynamic == 'custom':
                        integrand = np.exp(threshold_function(tt[i] - eps) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * 0.5/np.pi

                    if density > 0.1**14:
                        log_density[i] = np.log(density)

    else:
        # With drift variability
        if s_t == 0:
            # No non-decision time variability     
            s_v2 = s_v**2
            x0 =  a * np.cos(theta)
            x1 =  a * np.sin(theta)
            fixed = 1/(np.sqrt(s_v2/sigma**2 * tt + 1))
            exponent0 = -0.5*drift_vec[:, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[:, 0])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent1 = -0.5*drift_vec[:, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[:, 1])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))

            log_density = 2*np.log(fixed) + exponent0 + exponent1 + np.log(fpt_z) - np.log(2*np.pi)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        x0 =  threshold * np.cos(theta[i])
                        x1 =  threshold * np.sin(theta[i])
                    elif self.threshold_dynamic == 'linear':
                        x0 =  (threshold - decay * (tt[i]-eps)) * np.cos(theta[i])
                        x1 =  (threshold - decay * (tt[i]-eps)) * np.sin(theta[i])
                    elif self.threshold_dynamic == 'exponential':
                        x0 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.cos(theta[i])
                        x1 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i])
                    elif self.threshold_dynamic == 'hyperbolic':
                        x0 =  (threshold / (1 + decay * (tt[i]-eps))) * np.cos(theta[i])
                        x1 =  (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i])
                    elif self.threshold_dynamic == 'custom':
                        x0 =  threshold_function(tt[i]-eps) * np.cos(theta[i])
                        x1 =  threshold_function(tt[i]-eps) * np.sin(theta[i])
                    fixed = 1/(np.sqrt(s_v2/sigma**2 * (tt[i]-eps) + 1))
                    exponent0 = -0.5*drift_vec[i, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[i, 0])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i]-eps) + 1))
                    exponent1 = -0.5*drift_vec[i, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[i, 1])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i]-eps) + 1))

                    integrand = fixed**2 * np.exp(exponent0 + exponent1) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                    density = trapz_1d(integrand, eps) * 0.5/np.pi
                    if density > 0.1**14:
                        log_density[i] = np.log(density)

    log_density[rt - ndt - s_t <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate data from the Circular Diffusion Model with collapsing boundaries

Parameters:

Name Type Description Default
drift_vec (array - like, shape(2) or (n_samples, 2))

The drift vector [drift_x, drift_y]

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float or array-like with the shape of (n_samples,)

The initial decision threshold (default is 1)

1
decay float or array-like with the shape of (n_samples,)

The decay rate of the threshold (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

The time step for simulation (default is 0.001)

0.001
n_sample int

The number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/Circular.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate data from the Circular Diffusion Model with collapsing boundaries

    Parameters
    ----------
    drift_vec : array-like, shape (2,) or (n_samples, 2)
        The drift vector [drift_x, drift_y]
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float or array-like with the shape of (n_samples,)
        The initial decision threshold (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        The decay rate of the threshold (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        The time step for simulation (default is 0.001)
    n_sample : int, optional
        The number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample,))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 2))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n] = simulate_CDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n], 
                                                  threshold_dynamic=self.threshold_dynamic,
                                                  decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n] = simulate_custom_threshold_CDM_trial(threshold_function,
                                                                   drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                   s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)

    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response'])

HyperSphericalDiffusionModel(threshold_dynamic='fixed')

Hyper-Spherical Diffusion Model

Parameters:

Name Type Description Default
threshold_dynamic str

The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'

'fixed'
Source code in src/jeam/Models/HyperSpherical.py
15
16
17
18
19
20
21
22
23
24
25
26
27
def __init__(self, threshold_dynamic='fixed'):
    '''
    Parameters
    ----------
    threshold_dynamic : str, optional
        The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'
    '''
    self.name = 'Hyper-Spherical Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angles

Parameters:

Name Type Description Default
rt (array - like, shape(n_samples))

The response times

required
theta (array - like, shape(n_samples, 3))

The choice angles in spherical coordinates (theta1, theta2, theta3)

required
drift_vec (array - like, shape(4) or (n_samples, 4))

The drift rates in each dimension

required
ndt (float or array - like, shape(n_samples))

The non-decision time

required
threshold float

The decision threshold (default is 1)

required
decay float

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Name Type Description
log_density (array - like, shape(n_samples))

The joint log-probability density of response time and choice angles

Source code in src/jeam/Models/HyperSpherical.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angles

    Parameters
    ----------
    rt : array-like, shape (n_samples,)
        The response times
    theta : array-like, shape (n_samples, 3)
        The choice angles in spherical coordinates (theta1, theta2, theta3)
    drift_vec : array-like, shape (4,) or (n_samples, 4)
        The drift rates in each dimension
    ndt : float or array-like, shape (n_samples,)
        The non-decision time
    threshold : float
        The decision threshold (default is 1)
    decay : float, optional
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    log_density : array-like, shape (n_samples,)
        The joint log-probability density of response time and choice angles
    '''

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 4))

    if drift_vec.shape[1] != 4 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (4,) or (n_samples, 4)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = hsdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * hsdm_short_t_fpt_z(sigma**2 * tt/threshold**2, sigma**2 * 0.1**8/threshold**2)
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1) 
            fpt_lt = hsdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * hsdm_short_t_fpt_z(sigma**2 * T/threshold**2, sigma**2 * 0.1**8/threshold**2)
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)

    # Girsanov:
    if s_v == 0:
        # No drift variability
        mu_dot_x0 = drift_vec[:, 0]*np.cos(theta[:, 0])
        mu_dot_x1 = drift_vec[:, 1]*np.sin(theta[:, 0])*np.cos(theta[:, 1]) 
        mu_dot_x2 = drift_vec[:, 2]*np.sin(theta[:, 0])*np.sin(theta[:, 1])*np.cos(theta[:, 2])
        mu_dot_x3 = drift_vec[:, 3]*np.sin(theta[:, 0])*np.sin(theta[:, 1])*np.sin(theta[:, 2])
        if s_t == 0:
            # No non-decision time variability
            term1 = a * (mu_dot_x0 + mu_dot_x1 + mu_dot_x2 + mu_dot_x3) / sigma**2
            term2 = 0.5 * (drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2 + drift_vec[:, 3]**2) * tt / sigma**2
            log_density = term1 - term2 + np.log(fpt_z) - 2*np.log(2*np.pi)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            norm2_drift = drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2 + drift_vec[:, 3]**2
            mu_dot_x = (mu_dot_x0 + mu_dot_x1 + mu_dot_x2 + mu_dot_x3) / sigma**2

            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        integrand = np.exp(- 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = np.exp(threshold * mu_dot_x[i]) * trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    elif self.threshold_dynamic == 'linear':
                        integrand = np.exp((threshold - decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    elif self.threshold_dynamic == 'exponential':
                        integrand = np.exp(threshold*np.exp(-decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    elif self.threshold_dynamic == 'hyperbolic':
                        integrand = np.exp(threshold/(1  + decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    elif self.threshold_dynamic == 'custom':
                        integrand = np.exp(threshold_function(tt[i] - eps) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**2

                    if density > 0.1**14:
                        log_density[i] = np.log(density)
    else:
        # With drift variability
        if s_t == 0:
            s_v2 = s_v**2
            x0 =  a * np.cos(theta[:, 0])
            x1 =  a * np.sin(theta[:, 0])*np.cos(theta[:, 1])
            x2 =  a * np.sin(theta[:, 0])*np.sin(theta[:, 1])*np.cos(theta[:, 2])
            x3 =  a * np.sin(theta[:, 0])*np.sin(theta[:, 1])*np.sin(theta[:, 2])
            fixed = 1/(np.sqrt(s_v2/sigma**2 * tt + 1))
            exponent0 = -0.5*drift_vec[:, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[:, 0])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent1 = -0.5*drift_vec[:, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[:, 1])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent2 = -0.5*drift_vec[:, 2]**2/s_v2 + 0.5*(x2 * s_v2/sigma**2 + drift_vec[:, 2])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent3 = -0.5*drift_vec[:, 3]**2/s_v2 + 0.5*(x3 * s_v2/sigma**2 + drift_vec[:, 3])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))

            # the joint density of choice and RT for the full process
            log_density = 4*np.log(fixed) + exponent0 + exponent1 + exponent2 + exponent3 + np.log(fpt_z) - 2*np.log(2*np.pi)
        else:
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        x0 =  threshold * np.cos(theta[i, 0])
                        x1 =  threshold * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  threshold * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  threshold * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    elif self.threshold_dynamic == 'linear':
                        x0 =  (threshold - decay * (tt[i]-eps)) * np.cos(theta[i, 0])
                        x1 =  (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    elif self.threshold_dynamic == 'exponential':
                        x0 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.cos(theta[i, 0])
                        x1 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    elif self.threshold_dynamic == 'hyperbolic':
                        x0 =  (threshold / (1 + decay * (tt[i]-eps))) * np.cos(theta[i, 0])
                        x1 =  (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    elif self.threshold_dynamic == 'custom':
                        x0 =  threshold_function(tt[i]-eps) * np.cos(theta[i, 0])
                        x1 =  threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    fixed = 1/(np.sqrt(s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent0 = -0.5*drift_vec[i, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[i, 0])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent1 = -0.5*drift_vec[i, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[i, 1])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent2 = -0.5*drift_vec[i, 2]**2/s_v2 + 0.5*(x2 * s_v2/sigma**2 + drift_vec[i, 2])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent3 = -0.5*drift_vec[i, 3]**2/s_v2 + 0.5*(x3 * s_v2/sigma**2 + drift_vec[i, 3])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))

                    integrand = fixed**4 * np.exp(exponent0 + exponent1 + exponent2 + exponent3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                    density = trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    if density > 0.1**14:
                        log_density[i] = np.log(density)

    log_density[rt - ndt <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate data from the Hyper-Spherical Diffusion Model

Parameters:

Name Type Description Default
drift_vec (array - like, shape(4) or (n_samples, 4))

The drift rates in each dimension

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float or array-like with the shape of (n_samples,)

The decision threshold (default is 1)

1
decay float or array-like with the shape of (n_samples,)

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

Time step for the simulation (default is 0.001)

0.001
n_sample int

Number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/HyperSpherical.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate data from the Hyper-Spherical Diffusion Model

    Parameters
    ----------
    drift_vec : array-like, shape (4,) or (n_samples, 4)
        The drift rates in each dimension
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float or array-like with the shape of (n_samples,)
        The decision threshold (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        Time step for the simulation (default is 0.001)
    n_sample : int, optional
        Number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample, 3))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 4))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_HSDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n],
                                                      threshold_dynamic=self.threshold_dynamic, 
                                                      decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_custom_threshold_HSDM_trial(threshold_function,
                                                                       drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                       s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response1', 'response2', 'response3'])

ProjectedHyperSphericalDiffusionModel(threshold_dynamic='fixed')

Projected Hyper-Spherical Diffusion Model

Source code in src/jeam/Models/HyperSpherical.py
298
299
300
301
302
303
304
def __init__(self, threshold_dynamic='fixed'):
    self.name = 'Projected Hyper-Spherical Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angles for the Projected Hyper-Spherical Diffusion Model

Parameters:

Name Type Description Default
rt (array - like, shape(n_samples))

The response times

required
theta (array - like, shape(n_samples, 2))

The choice angles in spherical coordinates (theta1, theta2)

required
drift_vec (array - like, shape(3) or (n_samples, 3))

The drift rates in each dimension

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float

The decision threshold (default is 1)

required
decay float

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Name Type Description
log_density (array - like, shape(n_samples))

The joint log-probability density of response time and choice angles

Source code in src/jeam/Models/HyperSpherical.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angles for the Projected Hyper-Spherical Diffusion Model

    Parameters
    ----------
    rt : array-like, shape (n_samples,)
        The response times
    theta : array-like, shape (n_samples, 2)
        The choice angles in spherical coordinates (theta1, theta2)
    drift_vec : array-like, shape (3,) or (n_samples, 3)
        The drift rates in each dimension
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float
        The decision threshold (default is 1)
    decay : float, optional
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    log_density : array-like, shape (n_samples,)
        The joint log-probability density of response time and choice angles
    '''
    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 3))

    if drift_vec.shape[1] != 3 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (3,) or (n_samples, 3)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = hsdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = 1/threshold**2 * hsdm_short_t_fpt_z(tt/threshold**2, 0.1**8/threshold**2)   
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = hsdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = 1/threshold**2 * hsdm_short_t_fpt_z(T/threshold**2, 0.1**8/threshold**2)   
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)
    norm_mu = np.sqrt(drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2)

    theta1_mu = np.arctan2(drift_vec[:, 2], drift_vec[:, 0])
    theta2_mu = np.arctan2(drift_vec[:, 2], drift_vec[:, 1])

    # Girsanov:
    if s_v == 0:
        # No drift variability
        if s_t == 0:
            # No non-decision time variability
            x0 = np.cos(theta1_mu) * np.cos(theta[:, 0])
            x1 = np.sin(theta1_mu) * np.sin(theta[:, 0]) * np.cos(theta2_mu) * np.cos(theta[:, 1])
            term1 = np.exp(a * norm_mu * (x0 + x1) / sigma**2)
            term2 = iv(0, a * norm_mu * np.sin(theta1_mu) * np.sin(theta[:, 0]) * np.sin(theta2_mu) * np.sin(theta[:, 1])/sigma**2)
            term3 = -0.5 * norm_mu**2 * tt

            log_density = np.log(2*np.pi) + np.log(term1) + np.log(term2) + term3 + np.log(fpt_z)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp(threshold * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, threshold * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * term1 * term2 * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'linear':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp((threshold - decay * (tt[i] - eps)) * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, (threshold - decay * (tt[i] - eps)) * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'exponential':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp(threshold*np.exp(-decay * (tt[i] - eps)) * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, threshold*np.exp(-decay * (tt[i] - eps)) * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'hyperbolic':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp(threshold/(1  + decay * (tt[i] - eps)) * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, threshold/(1  + decay * (tt[i] - eps)) * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'custom':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp(threshold_function(tt[i] - eps) * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, threshold_function(tt[i] - eps) * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    if density > 0.1**14:
                        log_density[i] = np.log(density)
    else:
        # With drift variability
        if s_t == 0:
            # No non-decision time variability
            s_v2 = s_v**2
            c1 = a * np.sin(theta[:, 0]) * np.sin(theta[:, 1]) * s_v2
            c2 = 2*s_v2 * (s_v2 * tt + 1)
            term1 = 2*np.pi * iv(0, 2*c1 * drift_vec[:, 2]/c2)
            term2 = 1/(s_v2 * tt + 1)**2
            p1 = (c1**2 + drift_vec[:, 2]**2)/c2
            p2 = (a * np.cos(theta[:, 0]) * s_v2 + drift_vec[:, 0])**2 / c2
            p3 = (a * np.sin(theta[:, 0]) * np.cos(theta[:, 1]) * s_v2 + drift_vec[:, 1])**2 / c2
            p4 = (norm_mu**2)/(2*s_v2)

            log_density = np.log(term1) + np.log(term2) + (p1 + p2 + p3 - p4) + np.log(fpt_z)
        else:
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2

            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    c2 = 2*s_v2 * (s_v2 * (tt[i] - eps) + 1)
                    if self.threshold_dynamic == 'fixed':
                        c1 = threshold * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = (threshold * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = (threshold * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2
                    elif self.threshold_dynamic == 'linear':
                        c1 = (threshold - decay*(tt[i]-eps)) * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = ((threshold - decay*(tt[i]-eps)) * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = ((threshold - decay*(tt[i]-eps)) * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2
                    elif self.threshold_dynamic == 'exponential':
                        c1 = (threshold * np.exp(-decay*(tt[i]-eps))) * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = ((threshold * np.exp(-decay*(tt[i]-eps))) * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = ((threshold * np.exp(-decay*(tt[i]-eps))) * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2
                    elif self.threshold_dynamic == 'hyperbolic':
                        c1 = (threshold / (1 + decay*(tt[i]-eps))) * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = ((threshold / (1 + decay*(tt[i]-eps))) * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = ((threshold / (1 + decay*(tt[i]-eps))) * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2
                    elif self.threshold_dynamic == 'custom':
                        c1 = threshold_function(tt[i]-eps) * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = (threshold_function(tt[i]-eps) * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = (threshold_function(tt[i]-eps) * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2

                    term1 = 2*np.pi * iv(0, 2*c1 * drift_vec[:, 2]/c2)
                    term2 = 1/(s_v2 * (tt[i] - eps) + 1)**2
                    p4 = (norm_mu**2)/(2*s_v2)
                    term3 = np.exp(p1 + p2 + p3 - p4)
                    integrand = term1 * term2 * term3 * np.interp(tt[i]-eps, T, fpt_z)/s_t

                    density = trapz_1d(integrand, eps)

                    if density > 0.1**14:
                            log_density[i] = np.log(density)

    log_density[rt - ndt <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate data from the Projected Hyper-Spherical Diffusion Model

Parameters:

Name Type Description Default
drift_vec (array - like, shape(3) or (n_samples, 3))

The drift vector [drift_x, drift_y, drift_z]. Note that drift_z must be non-negative, as it represents the projection onto the upper hemisphere.

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float or array-like with the shape of (n_samples,)

The decision threshold (default is 1)

1
decay float or array-like with the shape of (n_samples,)

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

Time step for the simulation (default is 0.001)

0.001
n_sample int

Number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/HyperSpherical.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate data from the Projected Hyper-Spherical Diffusion Model

    Parameters
    ----------
    drift_vec : array-like, shape (3,) or (n_samples, 3)
        The drift vector [drift_x, drift_y, drift_z]. Note that drift_z must be non-negative, as it represents the projection onto the upper hemisphere.
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float or array-like with the shape of (n_samples,)
        The decision threshold (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        Time step for the simulation (default is 0.001)
    n_sample : int, optional
        Number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample, 2))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 3))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_PHSDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n],
                                                       threshold_dynamic=self.threshold_dynamic, 
                                                       decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_custom_threshold_PHSDM_trial(threshold_function,
                                                                        drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                        s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response1', 'response2'])

ProjectedSphericalDiffusionModel(threshold_dynamic='fixed')

Projected Spherical Diffusion Model

Parameters:

Name Type Description Default
threshold_dynamic str

The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'

'fixed'
Source code in src/jeam/Models/Spherical.py
291
292
293
294
295
296
297
298
299
300
301
302
303
def __init__(self, threshold_dynamic='fixed'):
    '''
    Parameters
    ----------
    threshold_dynamic : str, optional
        The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'
    '''
    self.name = 'Projected Spherical Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angle

Parameters:

Name Type Description Default
rt (array - like, shape(n_samples))

The response times

required
theta (array - like, shape(n_samples))

The choice angles in radians

required
drift_vec (array - like, shape(2) or (n_samples, 2))

The drift vector [drift_x, drift_y]

required
ndt (float or array - like, shape(n_samples))

The non-decision time

required
threshold float

The decision threshold (default is 1)

required
decay float

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Name Type Description
log_density (array - like, shape(n_samples))

The joint log-probability density of response time and choice angle

Source code in src/jeam/Models/Spherical.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angle

    Parameters
    ----------
    rt : array-like, shape (n_samples,)
        The response times
    theta : array-like, shape (n_samples,)
        The choice angles in radians
    drift_vec : array-like, shape (2,) or (n_samples, 2)
        The drift vector [drift_x, drift_y]
    ndt : float or array-like, shape (n_samples,)
        The non-decision time
    threshold : float
        The decision threshold (default is 1)
    decay : float, optional
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    log_density : array-like, shape (n_samples,)
        The joint log-probability density of response time and choice angle
    '''

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 2))

    if drift_vec.shape[1] != 2 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (2,) or (n_samples, 2)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = sdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * sdm_short_t_fpt_z(sigma**2 * tt/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = sdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * sdm_short_t_fpt_z(sigma**2 * T/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)

    norm_mu = np.sqrt(drift_vec[:, 0]**2 + drift_vec[:, 1]**2)
    theta_mu = np.arctan2(drift_vec[:, 1], drift_vec[:, 0])

    # Girsanov:
    if s_v == 0:
        # No drift variability
        if s_t == 0:
            # No non-decision time variability
            term1 = np.exp(a/sigma**2 * norm_mu * np.cos(theta_mu) * np.cos(theta))
            term2 = iv(0, a/sigma**2 * norm_mu * np.sin(theta_mu) * np.sin(theta))
            term3 = -0.5 * norm_mu**2 * tt / sigma**2
            log_density = np.log(2*np.pi) + np.log(term1) + np.log(term2) + term3 + np.log(fpt_z)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        term1 = np.exp(threshold/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, threshold/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * term1 * term2 * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'linear':
                        term1 = np.exp((threshold - decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, (threshold - decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'exponential':
                        term1 = np.exp(threshold*np.exp(-decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, threshold*np.exp(-decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'hyperbolic':
                        term1 = np.exp(threshold/(1  + decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, threshold/(1  + decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'custom':
                        term1 = np.exp(threshold_function(tt[i] - eps)/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, threshold_function(tt[i] - eps)/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    if density > 0.1**14:
                        log_density[i] = np.log(density)
    else:
        # With drift variability
        if s_t == 0:
            # No non-decision time variability
            s_v2 = s_v**2
            c1 = a * np.sin(theta) * s_v2/sigma**2
            c2 = 2*s_v2 * (s_v2/sigma**2 * tt + 1)
            term1 = 2*np.pi * iv(0, 2*c1 * drift_vec[:, 1]/c2)
            term2 = (1/(np.sqrt(s_v2/sigma**2 * tt + 1)))**3
            p1 = (c1**2 + drift_vec[:, 1]**2)/c2
            p2 = (a * np.cos(theta) * s_v2/sigma**2 + drift_vec[:, 0])**2 / c2
            p3 = (norm_mu**2)/(2*s_v2)
            # term3 = np.exp(p1 + p2 - p3)
            # log_density = np.log(term1) + np.log(term2) + np.log(term3) + np.log(fpt_z)

            term3 = p1 + p2 - p3
            log_density = np.log(term1) + np.log(term2) + term3 + np.log(fpt_z)
        else:
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2

            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    c2 = 2*s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1)
                    if self.threshold_dynamic == 'fixed':
                        c1 = threshold * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = (threshold * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2
                    elif self.threshold_dynamic == 'linear':
                        c1 = (threshold - decay*(tt[i]-eps)) * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = ((threshold - decay*(tt[i]-eps)) * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2
                    elif self.threshold_dynamic == 'exponential':
                        c1 = (threshold * np.exp(-decay*(tt[i]-eps))) * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = ((threshold * np.exp(-decay*(tt[i]-eps))) * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2
                    elif self.threshold_dynamic == 'hyperbolic':
                        c1 = (threshold / (1 + decay*(tt[i]-eps))) * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = ((threshold / (1 + decay*(tt[i]-eps))) * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2
                    elif self.threshold_dynamic == 'custom':
                        c1 = threshold_function(tt[i]-eps) * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = (threshold_function(tt[i]-eps) * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2

                    term1 = 2*np.pi * iv(0, 2*c1 * drift_vec[i, 1]/c2)
                    term2 = (1/(np.sqrt(s_v2/sigma**2 * (tt[i] - eps) + 1)))**3
                    p1 = (c1**2 + drift_vec[i, 1]**2)/c2
                    p3 = (norm_mu[i]**2)/(2*s_v2)
                    term3 = np.exp(p1 + p2 - p3)
                    integrand = term1 * term2 * term3 * np.interp(tt[i]-eps, T, fpt_z)/s_t

                    density = trapz_1d(integrand, eps)

                    if density > 0.1**14:
                            log_density[i] = np.log(density)

    log_density[rt - ndt <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate response times and choices from the Projected Spherical Diffusion Model

Parameters:

Name Type Description Default
drift_vec (array - like, shape(2) or (n_samples, 2))

The drift vector [drift_x, drift_y]. Note that drift_y must be non-negative, as it represents the projection onto the upper half-plane.

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float or array-like with the shape of (n_samples,)

The decision threshold (default is 1)

1
decay float or array-like with the shape of (n_samples,)

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

Time step for the simulation (default is 0.001)

0.001
n_sample int

Number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/Spherical.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate response times and choices from the Projected Spherical Diffusion Model

    Parameters
    ----------
    drift_vec : array-like, shape (2,) or (n_samples, 2)
        The drift vector [drift_x, drift_y]. Note that drift_y must be non-negative, as it represents the projection onto the upper half-plane.
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float or array-like with the shape of (n_samples,)
        The decision threshold (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        Time step for the simulation (default is 0.001)
    n_sample : int, optional
        Number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''    
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample,))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 2))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n] = simulate_PSDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n],
                                                   threshold_dynamic=self.threshold_dynamic,
                                                   decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n] = simulate_custom_threshold_PSDM_trial(threshold_function,
                                                                    drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                    s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)

    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response'])

SphericalDiffusionModel(threshold_dynamic='fixed')

Spherical Diffusion Model

Parameters:

Name Type Description Default
threshold_dynamic str

The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'

'fixed'
Source code in src/jeam/Models/Spherical.py
15
16
17
18
19
20
21
22
23
24
25
26
27
def __init__(self, threshold_dynamic='fixed'):
    '''
    Parameters
    ----------
    threshold_dynamic : str, optional
        The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'
    '''
    self.name = 'Spherical Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angles

Parameters:

Name Type Description Default
rt (array - like, shape(n_samples))

The response times

required
theta (array - like, shape(n_samples, 2))

The choice angles in spherical coordinates (theta1, theta2)

required
drift_vec (array - like, shape(3) or (n_samples, 3))

The drift rates in each dimension

required
ndt (float or array - like, shape(n_samples))

The non-decision time

required
threshold float

The decision threshold (default is 1)

required
decay float

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Name Type Description
log_density (array - like, shape(n_samples))

The joint log-probability density of response time and choice angles

Source code in src/jeam/Models/Spherical.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angles

    Parameters
    ----------
    rt : array-like, shape (n_samples,)
        The response times
    theta : array-like, shape (n_samples, 2)
        The choice angles in spherical coordinates (theta1, theta2)
    drift_vec : array-like, shape (3,) or (n_samples, 3)
        The drift rates in each dimension
    ndt : float or array-like, shape (n_samples,)
        The non-decision time
    threshold : float
        The decision threshold (default is 1)
    decay : float, optional
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    log_density : array-like, shape (n_samples,)
        The joint log-probability density of response time and choice angles
    '''

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 3))

    if drift_vec.shape[1] != 3 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (3,) or (n_samples, 3)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = sdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * sdm_short_t_fpt_z(sigma**2 * tt/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = sdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * sdm_short_t_fpt_z(sigma**2 * T/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)

    # Girsanov:
    if s_v == 0:
        # No drift variability
        mu_dot_x0 = drift_vec[:, 0]*np.cos(theta[:, 0])
        mu_dot_x1 = drift_vec[:, 1]*np.sin(theta[:, 0])*np.cos(theta[:, 1]) 
        mu_dot_x2 = drift_vec[:, 2]*np.sin(theta[:, 0])*np.sin(theta[:, 1])

        if s_t == 0:
            # No non-decision time variability
            term1 = a * (mu_dot_x0 + mu_dot_x1 + mu_dot_x2) / sigma**2
            term2 = 0.5 * (drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2) * tt / sigma**2
            log_density = term1 - term2 + np.log(fpt_z) - 1.5*np.log(2*np.pi)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            norm2_drift = drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2
            mu_dot_x = (mu_dot_x0 + mu_dot_x1 + mu_dot_x2) / sigma**2

            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        integrand = np.exp(- 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = np.exp(threshold * mu_dot_x[i]) * trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    elif self.threshold_dynamic == 'linear':
                        integrand = np.exp((threshold - decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    elif self.threshold_dynamic == 'exponential':
                        integrand = np.exp(threshold*np.exp(-decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    elif self.threshold_dynamic == 'hyperbolic':
                        integrand = np.exp(threshold/(1  + decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    elif self.threshold_dynamic == 'custom':
                        integrand = np.exp(threshold_function(tt[i] - eps) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5

                    if density > 0.1**14:
                        log_density[i] = np.log(density)
    else:
        # With drift variability
        if s_t == 0:
            # No non-decision time variability
            s_v2 = s_v**2
            x0 =  a * np.cos(theta[:, 0])
            x1 =  a * np.sin(theta[:, 0])*np.cos(theta[:, 1]) 
            x2 =  a * np.sin(theta[:, 0])*np.sin(theta[:, 1])
            fixed = 1/(np.sqrt(s_v2/sigma**2 * tt + 1))
            exponent0 = -0.5*drift_vec[:, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[:, 0])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent1 = -0.5*drift_vec[:, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[:, 1])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent2 = -0.5*drift_vec[:, 2]**2/s_v2 + 0.5*(x2 * s_v2/sigma**2 + drift_vec[:, 2])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            log_density = 3*np.log(fixed) + exponent0 + exponent1 + exponent2 + np.log(fpt_z) - 1.5*np.log(2*np.pi)
        else:
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        x0 = threshold * np.cos(theta[i, 0])
                        x1 = threshold * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = threshold * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    elif self.threshold_dynamic == 'linear':
                        x0 = (threshold - decay * (tt[i]-eps)) * np.cos(theta[i, 0])
                        x1 = (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    elif self.threshold_dynamic == 'exponential':
                        x0 = (threshold * np.exp(-decay * (tt[i]-eps))) * np.cos(theta[i, 0])
                        x1 = (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    elif self.threshold_dynamic == 'hyperbolic':
                        x0 = (threshold / (1 + decay * (tt[i]-eps))) * np.cos(theta[i, 0])
                        x1 = (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    elif self.threshold_dynamic == 'custom':
                        x0 = threshold_function(tt[i]-eps) * np.cos(theta[i, 0])
                        x1 = threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    fixed = 1/(np.sqrt(s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent0 = -0.5*drift_vec[i, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[i, 0])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent1 = -0.5*drift_vec[i, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[i, 1])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent2 = -0.5*drift_vec[i, 2]**2/s_v2 + 0.5*(x2 * s_v2/sigma**2 + drift_vec[i, 2])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))

                    integrand = fixed**3 * np.exp(exponent0 + exponent1 + exponent2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                    density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    if density > 0.1**14:
                        log_density[i] = np.log(density)

    log_density[rt - ndt <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate data from the Spherical Diffusion Model

Parameters:

Name Type Description Default
drift_vec (array - like, shape(3) or (n_samples, 3))

Drift vector; a three-dimensional array

required
ndt float or array-like with the shape of (n_samples,)

Non-decision time; a positive floating number

required
threshold float or array-like with the shape of (n_samples,)

Decision threshold; a positive floating number (default is 1)

1
decay float or array-like with the shape of (n_samples,)

Decay rate of the collapsing boundary (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

Time step for the simulation (default is 0.001)

0.001
n_sample int

Number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/Spherical.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate data from the Spherical Diffusion Model

    Parameters
    ----------
    drift_vec : array-like, shape (3,) or (n_samples, 3)
        Drift vector; a three-dimensional array
    ndt : float or array-like with the shape of (n_samples,)
        Non-decision time; a positive floating number
    threshold : float or array-like with the shape of (n_samples,)
        Decision threshold; a positive floating number (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        Decay rate of the collapsing boundary (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        Time step for the simulation (default is 0.001)
    n_sample : int, optional
        Number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample, 2))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 3))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_SDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n], 
                                                     threshold_dynamic=self.threshold_dynamic, 
                                                     decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_custom_threshold_SDM_trial(threshold_function,
                                                                      drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                      s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)

    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response1', 'response2'])

iv_numba(v, x)

Modified Bessel function of the first kind I_v(x) for real v and real x. Uses series for small x and asymptotic for large x.

WARNING: I_v(x) grows like exp(x)/sqrt(x), so iv_numba will overflow to inf for sufficiently large x (around x > ~709 in float64).

Source code in src/jeam/utility/helpers.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
@jit(nopython=False)
def iv_numba(v, x):
    """
    Modified Bessel function of the first kind I_v(x) for real v and real x.
    Uses series for small x and asymptotic for large x.

    WARNING: I_v(x) grows like exp(x)/sqrt(x), so iv_numba will overflow to inf
    for sufficiently large x (around x > ~709 in float64).
    """
    ax = np.abs(x)
    if ax == 0.0:
        if v == 0.0:
            return 1.0
        return 0.0

    if ax < 18.0:
        return _iv_series(v, ax)
    else:
        # Use ive asymptotic then multiply by exp(ax) if safe
        scaled = _ive_asymptotic(v, ax)
        # exp(709.78...) is near float64 max
        if ax > 709.0:
            return np.inf
        return scaled * np.exp(ax)

ive_numba(v, x)

Exponentially scaled modified Bessel I: ive(v,x) = exp(-abs(x)) * I_v(x) for real v and real x.

This implementation assumes x >= 0 for best behavior.

Source code in src/jeam/utility/helpers.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@jit(nopython=False)
def ive_numba(v, x):
    """
    Exponentially scaled modified Bessel I:
      ive(v,x) = exp(-abs(x)) * I_v(x)
    for real v and real x.

    This implementation assumes x >= 0 for best behavior.
    """
    ax = np.abs(x)
    if ax == 0.0:
        # ive(v,0) = I_v(0)
        if v == 0.0:
            return 1.0
        return 0.0

    # Threshold where asymptotic is usually accurate and faster than the series
    if ax < 18.0:
        # compute I_v(ax) then scale
        iv = _iv_series(v, ax)
        return iv * np.exp(-ax)
    else:
        return _ive_asymptotic(v, ax)

load_fennell2023()

Load data from experiment one in Fennell and Ratcliff (2023).

Returns:

Type Description
DataFrame

A dataframe containing the data with columns: 'subjectNumber', 'blockNumber', 'trialNumber', 'rt', 'numberOfStimulus', 'responseError'

Source code in src/jeam/utility/datasets.py
13
14
15
16
17
18
19
20
21
22
def load_fennell2023():
    '''
    Load data from experiment one in Fennell and Ratcliff (2023).

    Returns
    -------
    pd.DataFrame
        A dataframe containing the data with columns: 'subjectNumber', 'blockNumber', 'trialNumber', 'rt', 'numberOfStimulus', 'responseError'
    '''
    return _read_csv("Fennell2023_exp4.csv", index_col=0)

load_kvam2019()

Load data from Kvam et al. (2019).

Returns:

Type Description
DataFrame

A dataframe containing the data with columns:

Source code in src/jeam/utility/datasets.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def load_kvam2019():
    '''
    Load data from Kvam et al. (2019).

    Returns
    -------
    pd.DataFrame
        A dataframe containing the data with columns: 
    '''
    data = _read_csv("Kvam2019.csv")
    data = data.drop(
        columns=[
            "isCued",
            "cueOrientation",
            "cueDeflections",
            "points",
            "jitterLevel",
            "targetOrientation",
        ]
    )
    data = data.rename(columns={"RT": "rt"})
    data["deviation"] *= 2
    data["absoluteDeviation"] = np.abs(data["deviation"])
    return data

simulate_CDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the circular diffusion model (CDM).

Parameters:

Name Type Description Default
threshold float

A positive floating number representing the decision threshold.

required
drift_vec (array_like, shape(2))

A two-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
threshold_dynamic (fixed, linear, exponential, hyperbolic)

Type of threshold collapse. Default is 'fixed'.

'fixed'
decay float

Decay rate of the collapsing boundary. Default is 0.

0
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta float

Response angle between [-pi, pi].

Source code in src/jeam/utility/simulators.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@jit(nopython=True)
def simulate_CDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the circular diffusion model (CDM).

    Parameters
    ----------
    threshold : float
        A positive floating number representing the decision threshold.
    drift_vec : array_like, shape (2,)
        A two-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    threshold_dynamic : {'fixed', 'linear', 'exponential', 'hyperbolic'}, optional
        Type of threshold collapse. Default is 'fixed'.
    decay : float, optional
        Decay rate of the collapsing boundary. Default is 0.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : float
        Response angle between [-pi, pi].
    '''
    x = np.zeros((2,))

    rt = 0

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt

    if s_v>0:
        mu_t = drift_vec + s_v*np.random.randn(2)
    else:
        mu_t = drift_vec

    if threshold_dynamic == 'fixed':
        while np.linalg.norm(x) < threshold:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(2)
            rt += dt
    elif threshold_dynamic == 'linear':
        while np.linalg.norm(x) < threshold - decay*rt:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(2)
            rt += dt
    elif threshold_dynamic == 'exponential':
        while np.linalg.norm(x) < threshold * np.exp(-decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(2)
            rt += dt
    elif threshold_dynamic == 'hyperbolic':
        while np.linalg.norm(x) < threshold / (1 + decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(2)
            rt += dt
    theta = np.arctan2(x[1], x[0]) 
    return ndt_t+rt, theta

simulate_HSDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the hyper spherical diffusion model (HSDM).

Parameters:

Name Type Description Default
threshold float

A positive floating number representing the decision threshold.

required
drift_vec (array_like, shape(4))

A four-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
threshold_dynamic (fixed, linear, exponential, hyperbolic)

Type of threshold collapse. Default is 'fixed'.

'fixed'
decay float

Decay rate of the collapsing boundary. Default is 0.

0
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta tuple

A tuple of response angles (theta1, theta2, theta3); theta[0] and theta[1] between [0, pi], and theta[2] between [-pi, pi]

Source code in src/jeam/utility/simulators.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
@jit(nopython=True)
def simulate_HSDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the hyper spherical diffusion model (HSDM).

    Parameters
    ----------
    threshold : float
        A positive floating number representing the decision threshold.
    drift_vec : array_like, shape (4,)
        A four-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    threshold_dynamic : {'fixed', 'linear', 'exponential', 'hyperbolic'}, optional
        Type of threshold collapse. Default is 'fixed'.
    decay : float, optional
        Decay rate of the collapsing boundary. Default is 0.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : tuple
        A tuple of response angles (theta1, theta2, theta3); theta[0] and theta[1] between [0, pi], and theta[2] between [-pi, pi]
    '''
    x = np.zeros((4,))

    rt = 0

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt

    if s_v>0:
        mu_t = drift_vec + s_v*np.random.randn(4)
    else:
        mu_t = drift_vec

    if threshold_dynamic == 'fixed':
        while np.linalg.norm(x) < threshold:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
            rt += dt
    elif threshold_dynamic == 'linear':
        while np.linalg.norm(x) < threshold - decay*rt:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
            rt += dt
    elif threshold_dynamic == 'exponential':
        while np.linalg.norm(x) < threshold * np.exp(-decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
            rt += dt
    elif threshold_dynamic == 'hyperbolic':
        while np.linalg.norm(x) < threshold / (1 + decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
            rt += dt

    theta1 = np.arctan2(np.sqrt(x[3]**2 + x[2]**2 + x[1]**2), x[0])
    theta2 = np.arctan2(np.sqrt(x[3]**2 + x[2]**2), x[1])
    theta3 = np.arctan2(x[3], x[2])

    return ndt_t+rt, (theta1, theta2, theta3)

simulate_PHSDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the projected hyper spherical diffusion model (PHSDM).

Parameters:

Name Type Description Default
threshold float

A positive floating number representing the decision threshold.

required
drift_vec (array_like, shape(3))

A three-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
threshold_dynamic (fixed, linear, exponential, hyperbolic)

Type of threshold collapse. Default is 'fixed'.

'fixed'
decay float

Decay rate of the collapsing boundary. Default is 0.

0
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta tuple

A tuple of response angles (theta1, theta2); theta[0] and theta[1] between [0, pi]

Source code in src/jeam/utility/simulators.py
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
@jit(nopython=True)
def simulate_PHSDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the projected hyper spherical diffusion model (PHSDM).

    Parameters
    ----------
    threshold : float
        A positive floating number representing the decision threshold.
    drift_vec : array_like, shape (3,)
        A three-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    threshold_dynamic : {'fixed', 'linear', 'exponential', 'hyperbolic'}, optional
        Type of threshold collapse. Default is 'fixed'.
    decay : float, optional
        Decay rate of the collapsing boundary. Default is 0.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : tuple
        A tuple of response angles (theta1, theta2); theta[0] and theta[1] between [0, pi]
    '''

    x = np.zeros((4,))
    muw = drift_vec[0]
    muz = drift_vec[1]
    eta = drift_vec[2]

    norm_mu = np.sqrt(eta**2 + muz**2 + muw**2)
    theta1_mu = np.arctan2(eta, muw)
    theta2_mu = np.arctan2(eta, muz)

    rt = 0
    rphi = np.pi/4 # it is not important (just a dummpy value)
    mux = norm_mu * np.sin(theta1_mu) * np.sin(theta2_mu) * np.cos(rphi)
    muy = norm_mu * np.sin(theta1_mu) * np.sin(theta2_mu) * np.sin(rphi)

    mu = np.array([mux, muy, muz, muw])

    if s_v>0:
        mu_t = mu + s_v*np.random.randn(4)
    else:
        mu_t = mu

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt

    if threshold_dynamic == 'fixed':
        while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2 + x[3]**2) < threshold:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
            rt += dt
    elif threshold_dynamic == 'linear':
        while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2 + x[3]**2) < threshold - decay*rt:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
            rt += dt
    elif threshold_dynamic == 'exponential':
        while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2 + x[3]**2) < threshold * np.exp(-decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
            rt += dt
    elif threshold_dynamic == 'hyperbolic':
        while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2 + x[3]**2) < threshold / (1 + decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
            rt += dt

    theta1 = np.arctan2(np.sqrt(x[0]**2 + x[1]**2), x[3])
    theta2 = np.arctan2(np.sqrt(x[0]**2 + x[1]**2), x[2])   

    return ndt_t+rt, (theta1, theta2)

simulate_PSDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the projected spherical diffusion model (PSDM).

Parameters:

Name Type Description Default
threshold float

A positive floating number representing the decision threshold.

required
drift_vec (array_like, shape(2))

A two-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
threshold_dynamic (fixed, linear, exponential, hyperbolic)

Type of threshold collapse. Default is 'fixed'.

'fixed'
decay float

Decay rate of the collapsing boundary. Default is 0.

0
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta float

Response angle between [0, pi]

Source code in src/jeam/utility/simulators.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
@jit(nopython=True)
def simulate_PSDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the projected spherical diffusion model (PSDM).

    Parameters
    ----------
    threshold : float
        A positive floating number representing the decision threshold.
    drift_vec : array_like, shape (2,)
        A two-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    threshold_dynamic : {'fixed', 'linear', 'exponential', 'hyperbolic'}, optional
        Type of threshold collapse. Default is 'fixed'.
    decay : float, optional
        Decay rate of the collapsing boundary. Default is 0.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : float
        Response angle between [0, pi]
    '''
    x = np.zeros((3,))
    muz = drift_vec[0]
    eta = drift_vec[1]

    norm_mu = np.sqrt(eta**2 + muz**2)
    theta_mu = np.arctan2(eta, muz)

    rt = 0
    rphi = np.pi/4 # it is not important (just a dummpy value)
    mux = norm_mu * np.sin(theta_mu) * np.cos(rphi)
    muy = norm_mu * np.sin(theta_mu) * np.sin(rphi)

    mu = np.array([mux, muy, muz])

    if s_v>0:
        mu_t = mu + s_v*np.random.randn(3)
    else:
        mu_t = mu

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt

    if threshold_dynamic == 'fixed':
        while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) < threshold:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
            rt += dt
    elif threshold_dynamic == 'linear':
        while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) < threshold - decay*rt:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
            rt += dt
    elif threshold_dynamic == 'exponential':
        while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) < threshold * np.exp(-decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
            rt += dt
    elif threshold_dynamic == 'hyperbolic':
        while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) < threshold / (1 + decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
            rt += dt

    theta = np.arctan2(np.sqrt(x[0]**2 + x[1]**2), x[2])    

    return ndt_t+rt, theta

simulate_SDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the spherical diffusion model (SDM).

Parameters:

Name Type Description Default
threshold float

A positive floating number representing the decision threshold.

required
drift_vec (array_like, shape(3))

A three-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
threshold_dynamic (fixed, linear, exponential, hyperbolic)

Type of threshold collapse. Default is 'fixed'.

'fixed'
decay float

Decay rate of the collapsing boundary. Default is 0.

0
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta tuple

A tuple of response angles (theta1, theta2); theta[0] between [0, pi] and theta[1] between [-pi, pi]

Source code in src/jeam/utility/simulators.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
@jit(nopython=True)
def simulate_SDM_trial(threshold, drift_vec, ndt, threshold_dynamic='fixed', decay=0, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the spherical diffusion model (SDM).

    Parameters
    ----------
    threshold : float
        A positive floating number representing the decision threshold.
    drift_vec : array_like, shape (3,)
        A three-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    threshold_dynamic : {'fixed', 'linear', 'exponential', 'hyperbolic'}, optional
        Type of threshold collapse. Default is 'fixed'.
    decay : float, optional
        Decay rate of the collapsing boundary. Default is 0.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : tuple
        A tuple of response angles (theta1, theta2); theta[0] between [0, pi] and theta[1] between [-pi, pi]
    '''
    x = np.zeros((3,))

    rt = 0

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt

    if s_v>0:
        mu_t = drift_vec + s_v*np.random.randn(3)
    else:
        mu_t = drift_vec

    if threshold_dynamic == 'fixed':
        while np.linalg.norm(x) < threshold:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
            rt += dt
    elif threshold_dynamic == 'linear':
        while np.linalg.norm(x) < threshold - decay*rt:
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
            rt += dt
    elif threshold_dynamic == 'exponential':
        while np.linalg.norm(x) < threshold * np.exp(-decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
            rt += dt
    elif threshold_dynamic == 'hyperbolic':
        while np.linalg.norm(x) < threshold / (1 + decay*rt):
            x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
            rt += dt

    theta1 = np.arctan2(np.sqrt(x[2]**2 + x[1]**2), x[0])
    theta2 = np.arctan2(x[2], x[1])

    return ndt_t+rt, (theta1, theta2)

simulate_custom_threshold_CDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the circular diffusion model (CDM) with a user defined threshold function.

Parameters:

Name Type Description Default
threshold_function callable

A function that takes time t and returns the threshold at time t.

required
drift_vec (array_like, shape(2))

A two-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
drift_vec (array_like, shape(2))

A two-dimensional array representing the drift vector.

required
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta float

Response angle between [-pi, pi].

Source code in src/jeam/utility/simulators.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def simulate_custom_threshold_CDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the circular diffusion model (CDM) with a user defined threshold function.

    Parameters
    ----------
    threshold_function : callable
        A function that takes time t and returns the threshold at time t.
    drift_vec : array_like, shape (2,)
        A two-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    drift_vec : array_like, shape (2,)
        A two-dimensional array representing the drift vector.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : float
        Response angle between [-pi, pi].
    '''
    x = np.zeros((2,))

    rt = 0

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand() - s_t
    else:
        ndt_t = ndt

    if s_v>0:
        mu_t = drift_vec + s_v*np.random.randn(2)
    else:
        mu_t = drift_vec

    while np.linalg.norm(x) < threshold_function(rt):
        x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(2)
        rt += dt

    theta = np.arctan2(x[1], x[0]) 

    return ndt_t+rt, theta

simulate_custom_threshold_HSDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the hyper spherical diffusion model (HSDM) with a user defined threshold function.

Parameters:

Name Type Description Default
threshold_function callable

A function that takes time and returns the threshold at that time.

required
drift_vec (array_like, shape(4))

A four-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta tuple

A tuple of response angles (theta1, theta2, theta3); theta[0] and theta[1] between [0, pi], and theta[2] between [-pi, pi]

Source code in src/jeam/utility/simulators.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
def simulate_custom_threshold_HSDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the hyper spherical diffusion model (HSDM) with a user defined threshold function.

    Parameters
    ----------
    threshold_function : callable
        A function that takes time and returns the threshold at that time.
    drift_vec : array_like, shape (4,)
        A four-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : tuple
        A tuple of response angles (theta1, theta2, theta3); theta[0] and theta[1] between [0, pi], and theta[2] between [-pi, pi]
    '''
    x = np.zeros((4,))

    rt = 0

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt

    if s_v>0:
        mu_t = drift_vec + s_v*np.random.randn(4)
    else:
        mu_t = drift_vec

    while np.linalg.norm(x) < threshold_function(rt):
        x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
        rt += dt

    theta1 = np.arctan2(np.sqrt(x[3]**2 + x[2]**2 + x[1]**2), x[0])
    theta2 = np.arctan2(np.sqrt(x[3]**2 + x[2]**2), x[1])
    theta3 = np.arctan2(x[3], x[2])

    return ndt_t+rt, (theta1, theta2, theta3)

simulate_custom_threshold_PHSDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the projected hyper spherical diffusion model (PHSDM) with a user defined threshold function.

Parameters:

Name Type Description Default
threshold_function callable

A function that takes a time value and returns the threshold at that time.

required
drift_vec (array_like, shape(3))

A three-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta tuple

A tuple of response angles (theta1, theta2); theta[0] and theta[1] between [0, pi]

Source code in src/jeam/utility/simulators.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
def simulate_custom_threshold_PHSDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the projected hyper spherical diffusion model (PHSDM) with a user defined threshold function.

    Parameters
    ----------
    threshold_function : callable
        A function that takes a time value and returns the threshold at that time.
    drift_vec : array_like, shape (3,)
        A three-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : tuple
        A tuple of response angles (theta1, theta2); theta[0] and theta[1] between [0, pi]
    '''
    x = np.zeros((4,))
    muw = drift_vec[0]
    muz = drift_vec[1]
    eta = drift_vec[2]

    norm_mu = np.sqrt(eta**2 + muz**2 + muw**2)
    theta1_mu = np.arctan2(eta, muw)
    theta2_mu = np.arctan2(eta, muz)

    rt = 0
    rphi = np.pi/4 # it is not important (just a dummpy value)
    mux = norm_mu * np.sin(theta1_mu) * np.sin(theta2_mu) * np.cos(rphi)
    muy = norm_mu * np.sin(theta1_mu) * np.sin(theta2_mu) * np.sin(rphi)

    mu = np.array([mux, muy, muz, muw])

    if s_v>0:
        mu_t = mu + s_v*np.random.randn(4)
    else:
        mu_t = mu

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt


    while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2 + x[3]**2) < threshold_function(rt):
        x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(4)
        rt += dt


    theta1 = np.arctan2(np.sqrt(x[0]**2 + x[1]**2), x[3])
    theta2 = np.arctan2(np.sqrt(x[0]**2 + x[1]**2), x[2])   

    return ndt_t+rt, (theta1, theta2)

simulate_custom_threshold_PSDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the projected spherical diffusion model (PSDM) with a user defined threshold function.

Parameters:

Name Type Description Default
threshold_function callable

A function that takes time and returns threshold.

required
drift_vec (array_like, shape(2))

A two-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta float

Response angle between [0, pi]

Source code in src/jeam/utility/simulators.py
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
def simulate_custom_threshold_PSDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the projected spherical diffusion model (PSDM) with a user defined threshold function.

    Parameters
    ----------
    threshold_function : callable
        A function that takes time and returns threshold.
    drift_vec : array_like, shape (2,)
        A two-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001. 

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : float
        Response angle between [0, pi]
    '''
    x = np.zeros((3,))
    muz = drift_vec[0]
    eta = drift_vec[1]

    norm_mu = np.sqrt(eta**2 + muz**2)
    theta_mu = np.arctan2(eta, muz)

    rt = 0
    rphi = np.pi/4 # it is not important (just a dummpy value)
    mux = norm_mu * np.sin(theta_mu) * np.cos(rphi)
    muy = norm_mu * np.sin(theta_mu) * np.sin(rphi)

    mu = np.array([mux, muy, muz])

    if s_v>0:
        mu_t = mu + s_v*np.random.randn(3)
    else:
        mu_t = mu

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt

    while np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) < threshold_function(rt):
        x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)

        rt += dt

    theta = np.arctan2(np.sqrt(x[0]**2 + x[1]**2), x[2])    

    return ndt_t+rt, theta

simulate_custom_threshold_SDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001)

Simulate a single trial of the spherical diffusion model (SDM) with a user defined threshold function.

Parameters:

Name Type Description Default
threshold_function callable

A function that takes time t and returns the threshold at time t.

required
drift_vec (array_like, shape(3))

A three-dimensional array representing the drift vector.

required
ndt float

A positive floating number representing the non-decision time.

required
s_v float

Standard deviation of drift rate variability. Default is 0.

0
s_t float

Range of non-decision time variability. Default is 0.

0
sigma float

Diffusion coefficient (standard deviation of the diffusion process). Default is 1.

1
dt float

Time step for the simulation. Default is 0.001.

0.001

Returns:

Name Type Description
rt float

Response time in seconds.

theta tuple

A tuple of response angles (theta1, theta2); theta[0] between [0, pi] and theta[1] between [-pi, pi]

Source code in src/jeam/utility/simulators.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def simulate_custom_threshold_SDM_trial(threshold_function, drift_vec, ndt, s_v=0, s_t=0, sigma=1, dt=0.001):
    '''
    Simulate a single trial of the spherical diffusion model (SDM) with a user defined threshold function.

    Parameters
    ----------
    threshold_function : callable
        A function that takes time t and returns the threshold at time t.
    drift_vec : array_like, shape (3,)
        A three-dimensional array representing the drift vector.
    ndt : float
        A positive floating number representing the non-decision time.
    s_v : float, optional
        Standard deviation of drift rate variability. Default is 0.
    s_t : float, optional
        Range of non-decision time variability. Default is 0.
    sigma : float, optional
        Diffusion coefficient (standard deviation of the diffusion process). Default is 1.
    dt : float, optional
        Time step for the simulation. Default is 0.001.

    Returns
    -------
    rt : float
        Response time in seconds.
    theta : tuple
        A tuple of response angles (theta1, theta2); theta[0] between [0, pi] and theta[1] between [-pi, pi]
    '''

    x = np.zeros((3,))

    rt = 0

    if s_t>0:
        ndt_t = ndt + s_t*np.random.rand()
    else:
        ndt_t = ndt

    if s_v>0:
        mu_t = drift_vec + s_v*np.random.randn(3)
    else:
        mu_t = drift_vec

    while np.linalg.norm(x) < threshold_function(rt):
        x += mu_t*dt + sigma*np.sqrt(dt)*np.random.randn(3)
        rt += dt

    theta1 = np.arctan2(np.sqrt(x[2]**2 + x[1]**2), x[0])
    theta2 = np.arctan2(x[2], x[1])

    return ndt_t+rt, (theta1, theta2)

trapz_1d(y, x)

Trapezoidal integral of y over x. Both 1D, same length.

Source code in src/jeam/utility/helpers.py
171
172
173
174
175
176
177
178
179
180
@njit(cache=True, fastmath=True)
def trapz_1d(y, x):
    """
    Trapezoidal integral of y over x. Both 1D, same length.
    """
    s = 0.0
    for i in range(x.shape[0] - 1):
        dx = x[i + 1] - x[i]
        s += 0.5 * (y[i] + y[i + 1]) * dx
    return s

Models

Circular diffusion model

CircularDiffusionModel(threshold_dynamic='fixed')

Circular Diffusion Model

Parameters:

Name Type Description Default
threshold_dynamic str

The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'

'fixed'
Source code in src/jeam/Models/Circular.py
14
15
16
17
18
19
20
21
22
23
24
25
26
def __init__(self, threshold_dynamic='fixed'):
    '''
    Parameters
    ----------
    threshold_dynamic : str, optional
        The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'
    '''
    self.name = 'Circular Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angle

Parameters:

Name Type Description Default
rt array - like

Response times

required
theta array - like

Choice angles in radians

required
drift_vec (array - like, shape(2) or (n_samples, 2))

The drift vector [drift_x, drift_y]

required
ndt (float or array - like, shape(n_samples))

The non-decision time

required
threshold float

The initial decision threshold

required
decay float

The decay rate of the threshold (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Type Description
array - like

The joint log-probability density evaluated at (rt, theta) with same shape as rt and theta

Source code in src/jeam/Models/Circular.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angle

    Parameters
    ----------
    rt : array-like
        Response times
    theta : array-like
        Choice angles in radians
    drift_vec : array-like, shape (2,) or (n_samples, 2)
        The drift vector [drift_x, drift_y]
    ndt : float or array-like, shape (n_samples,)
        The non-decision time
    threshold : float
        The initial decision threshold
    decay : float
        The decay rate of the threshold (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    array-like
        The joint log-probability density evaluated at (rt, theta) with same shape as rt and theta
    '''

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 2))

    if drift_vec.shape[1] != 2 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (2,) or (n_samples, 2)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = cdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * cdm_short_t_fpt_z(sigma**2 * tt/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = cdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * cdm_short_t_fpt_z(sigma**2 * T/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 2*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 2*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 2*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 2*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)

    # Girsanov:
    if s_v == 0:
        # No drift variability
        mu_dot_x0 = drift_vec[:, 0] * np.cos(theta)
        mu_dot_x1 = drift_vec[:, 1] * np.sin(theta)

        if s_t == 0:
            # No non-decision time variability
            term1 = a * (mu_dot_x0 + mu_dot_x1) / sigma**2
            term2 = 0.5 * (drift_vec[:, 0]**2 + drift_vec[:, 1]**2) * tt / sigma**2
            log_density = term1 - term2 + np.log(fpt_z) - np.log(2*np.pi)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            norm2_drift = drift_vec[:, 0]**2 + drift_vec[:, 1]**2
            mu_dot_x = (mu_dot_x0 + mu_dot_x1) / sigma**2
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        integrand = np.exp(- 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density =  np.exp(threshold * mu_dot_x[i]) * trapz_1d(integrand, eps) * 0.5/np.pi
                    elif self.threshold_dynamic == 'linear':
                        integrand = np.exp((threshold - decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * 0.5/np.pi
                    elif self.threshold_dynamic == 'exponential':
                        integrand = np.exp(threshold*np.exp(-decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * 0.5/np.pi
                    elif self.threshold_dynamic == 'hyperbolic':
                        integrand = np.exp(threshold/(1  + decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * 0.5/np.pi
                    elif self.threshold_dynamic == 'custom':
                        integrand = np.exp(threshold_function(tt[i] - eps) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * 0.5/np.pi

                    if density > 0.1**14:
                        log_density[i] = np.log(density)

    else:
        # With drift variability
        if s_t == 0:
            # No non-decision time variability     
            s_v2 = s_v**2
            x0 =  a * np.cos(theta)
            x1 =  a * np.sin(theta)
            fixed = 1/(np.sqrt(s_v2/sigma**2 * tt + 1))
            exponent0 = -0.5*drift_vec[:, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[:, 0])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent1 = -0.5*drift_vec[:, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[:, 1])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))

            log_density = 2*np.log(fixed) + exponent0 + exponent1 + np.log(fpt_z) - np.log(2*np.pi)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        x0 =  threshold * np.cos(theta[i])
                        x1 =  threshold * np.sin(theta[i])
                    elif self.threshold_dynamic == 'linear':
                        x0 =  (threshold - decay * (tt[i]-eps)) * np.cos(theta[i])
                        x1 =  (threshold - decay * (tt[i]-eps)) * np.sin(theta[i])
                    elif self.threshold_dynamic == 'exponential':
                        x0 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.cos(theta[i])
                        x1 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i])
                    elif self.threshold_dynamic == 'hyperbolic':
                        x0 =  (threshold / (1 + decay * (tt[i]-eps))) * np.cos(theta[i])
                        x1 =  (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i])
                    elif self.threshold_dynamic == 'custom':
                        x0 =  threshold_function(tt[i]-eps) * np.cos(theta[i])
                        x1 =  threshold_function(tt[i]-eps) * np.sin(theta[i])
                    fixed = 1/(np.sqrt(s_v2/sigma**2 * (tt[i]-eps) + 1))
                    exponent0 = -0.5*drift_vec[i, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[i, 0])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i]-eps) + 1))
                    exponent1 = -0.5*drift_vec[i, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[i, 1])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i]-eps) + 1))

                    integrand = fixed**2 * np.exp(exponent0 + exponent1) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                    density = trapz_1d(integrand, eps) * 0.5/np.pi
                    if density > 0.1**14:
                        log_density[i] = np.log(density)

    log_density[rt - ndt - s_t <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate data from the Circular Diffusion Model with collapsing boundaries

Parameters:

Name Type Description Default
drift_vec (array - like, shape(2) or (n_samples, 2))

The drift vector [drift_x, drift_y]

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float or array-like with the shape of (n_samples,)

The initial decision threshold (default is 1)

1
decay float or array-like with the shape of (n_samples,)

The decay rate of the threshold (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

The time step for simulation (default is 0.001)

0.001
n_sample int

The number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/Circular.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate data from the Circular Diffusion Model with collapsing boundaries

    Parameters
    ----------
    drift_vec : array-like, shape (2,) or (n_samples, 2)
        The drift vector [drift_x, drift_y]
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float or array-like with the shape of (n_samples,)
        The initial decision threshold (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        The decay rate of the threshold (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        The time step for simulation (default is 0.001)
    n_sample : int, optional
        The number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample,))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 2))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n] = simulate_CDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n], 
                                                  threshold_dynamic=self.threshold_dynamic,
                                                  decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n] = simulate_custom_threshold_CDM_trial(threshold_function,
                                                                   drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                   s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)

    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response'])

Spherical diffusion models

ProjectedSphericalDiffusionModel(threshold_dynamic='fixed')

Projected Spherical Diffusion Model

Parameters:

Name Type Description Default
threshold_dynamic str

The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'

'fixed'
Source code in src/jeam/Models/Spherical.py
291
292
293
294
295
296
297
298
299
300
301
302
303
def __init__(self, threshold_dynamic='fixed'):
    '''
    Parameters
    ----------
    threshold_dynamic : str, optional
        The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'
    '''
    self.name = 'Projected Spherical Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angle

Parameters:

Name Type Description Default
rt (array - like, shape(n_samples))

The response times

required
theta (array - like, shape(n_samples))

The choice angles in radians

required
drift_vec (array - like, shape(2) or (n_samples, 2))

The drift vector [drift_x, drift_y]

required
ndt (float or array - like, shape(n_samples))

The non-decision time

required
threshold float

The decision threshold (default is 1)

required
decay float

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Name Type Description
log_density (array - like, shape(n_samples))

The joint log-probability density of response time and choice angle

Source code in src/jeam/Models/Spherical.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angle

    Parameters
    ----------
    rt : array-like, shape (n_samples,)
        The response times
    theta : array-like, shape (n_samples,)
        The choice angles in radians
    drift_vec : array-like, shape (2,) or (n_samples, 2)
        The drift vector [drift_x, drift_y]
    ndt : float or array-like, shape (n_samples,)
        The non-decision time
    threshold : float
        The decision threshold (default is 1)
    decay : float, optional
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    log_density : array-like, shape (n_samples,)
        The joint log-probability density of response time and choice angle
    '''

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 2))

    if drift_vec.shape[1] != 2 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (2,) or (n_samples, 2)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = sdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * sdm_short_t_fpt_z(sigma**2 * tt/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = sdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * sdm_short_t_fpt_z(sigma**2 * T/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)

    norm_mu = np.sqrt(drift_vec[:, 0]**2 + drift_vec[:, 1]**2)
    theta_mu = np.arctan2(drift_vec[:, 1], drift_vec[:, 0])

    # Girsanov:
    if s_v == 0:
        # No drift variability
        if s_t == 0:
            # No non-decision time variability
            term1 = np.exp(a/sigma**2 * norm_mu * np.cos(theta_mu) * np.cos(theta))
            term2 = iv(0, a/sigma**2 * norm_mu * np.sin(theta_mu) * np.sin(theta))
            term3 = -0.5 * norm_mu**2 * tt / sigma**2
            log_density = np.log(2*np.pi) + np.log(term1) + np.log(term2) + term3 + np.log(fpt_z)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        term1 = np.exp(threshold/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, threshold/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * term1 * term2 * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'linear':
                        term1 = np.exp((threshold - decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, (threshold - decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'exponential':
                        term1 = np.exp(threshold*np.exp(-decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, threshold*np.exp(-decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'hyperbolic':
                        term1 = np.exp(threshold/(1  + decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, threshold/(1  + decay * (tt[i] - eps))/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'custom':
                        term1 = np.exp(threshold_function(tt[i] - eps)/sigma**2 * norm_mu[i] * np.cos(theta_mu[i]) * np.cos(theta[i]))
                        term2 = iv(0, threshold_function(tt[i] - eps)/sigma**2 * norm_mu[i] * np.sin(theta_mu[i]) * np.sin(theta[i]))
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps) / sigma**2
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    if density > 0.1**14:
                        log_density[i] = np.log(density)
    else:
        # With drift variability
        if s_t == 0:
            # No non-decision time variability
            s_v2 = s_v**2
            c1 = a * np.sin(theta) * s_v2/sigma**2
            c2 = 2*s_v2 * (s_v2/sigma**2 * tt + 1)
            term1 = 2*np.pi * iv(0, 2*c1 * drift_vec[:, 1]/c2)
            term2 = (1/(np.sqrt(s_v2/sigma**2 * tt + 1)))**3
            p1 = (c1**2 + drift_vec[:, 1]**2)/c2
            p2 = (a * np.cos(theta) * s_v2/sigma**2 + drift_vec[:, 0])**2 / c2
            p3 = (norm_mu**2)/(2*s_v2)
            # term3 = np.exp(p1 + p2 - p3)
            # log_density = np.log(term1) + np.log(term2) + np.log(term3) + np.log(fpt_z)

            term3 = p1 + p2 - p3
            log_density = np.log(term1) + np.log(term2) + term3 + np.log(fpt_z)
        else:
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2

            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    c2 = 2*s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1)
                    if self.threshold_dynamic == 'fixed':
                        c1 = threshold * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = (threshold * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2
                    elif self.threshold_dynamic == 'linear':
                        c1 = (threshold - decay*(tt[i]-eps)) * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = ((threshold - decay*(tt[i]-eps)) * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2
                    elif self.threshold_dynamic == 'exponential':
                        c1 = (threshold * np.exp(-decay*(tt[i]-eps))) * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = ((threshold * np.exp(-decay*(tt[i]-eps))) * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2
                    elif self.threshold_dynamic == 'hyperbolic':
                        c1 = (threshold / (1 + decay*(tt[i]-eps))) * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = ((threshold / (1 + decay*(tt[i]-eps))) * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2
                    elif self.threshold_dynamic == 'custom':
                        c1 = threshold_function(tt[i]-eps) * np.sin(theta[i]) * s_v2/sigma**2
                        p2 = (threshold_function(tt[i]-eps) * np.cos(theta[i]) * s_v2/sigma**2 + drift_vec[i, 0])**2 / c2

                    term1 = 2*np.pi * iv(0, 2*c1 * drift_vec[i, 1]/c2)
                    term2 = (1/(np.sqrt(s_v2/sigma**2 * (tt[i] - eps) + 1)))**3
                    p1 = (c1**2 + drift_vec[i, 1]**2)/c2
                    p3 = (norm_mu[i]**2)/(2*s_v2)
                    term3 = np.exp(p1 + p2 - p3)
                    integrand = term1 * term2 * term3 * np.interp(tt[i]-eps, T, fpt_z)/s_t

                    density = trapz_1d(integrand, eps)

                    if density > 0.1**14:
                            log_density[i] = np.log(density)

    log_density[rt - ndt <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate response times and choices from the Projected Spherical Diffusion Model

Parameters:

Name Type Description Default
drift_vec (array - like, shape(2) or (n_samples, 2))

The drift vector [drift_x, drift_y]. Note that drift_y must be non-negative, as it represents the projection onto the upper half-plane.

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float or array-like with the shape of (n_samples,)

The decision threshold (default is 1)

1
decay float or array-like with the shape of (n_samples,)

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

Time step for the simulation (default is 0.001)

0.001
n_sample int

Number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/Spherical.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate response times and choices from the Projected Spherical Diffusion Model

    Parameters
    ----------
    drift_vec : array-like, shape (2,) or (n_samples, 2)
        The drift vector [drift_x, drift_y]. Note that drift_y must be non-negative, as it represents the projection onto the upper half-plane.
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float or array-like with the shape of (n_samples,)
        The decision threshold (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        Time step for the simulation (default is 0.001)
    n_sample : int, optional
        Number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''    
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample,))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 2))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n] = simulate_PSDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n],
                                                   threshold_dynamic=self.threshold_dynamic,
                                                   decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n] = simulate_custom_threshold_PSDM_trial(threshold_function,
                                                                    drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                    s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)

    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response'])

SphericalDiffusionModel(threshold_dynamic='fixed')

Spherical Diffusion Model

Parameters:

Name Type Description Default
threshold_dynamic str

The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'

'fixed'
Source code in src/jeam/Models/Spherical.py
15
16
17
18
19
20
21
22
23
24
25
26
27
def __init__(self, threshold_dynamic='fixed'):
    '''
    Parameters
    ----------
    threshold_dynamic : str, optional
        The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'
    '''
    self.name = 'Spherical Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angles

Parameters:

Name Type Description Default
rt (array - like, shape(n_samples))

The response times

required
theta (array - like, shape(n_samples, 2))

The choice angles in spherical coordinates (theta1, theta2)

required
drift_vec (array - like, shape(3) or (n_samples, 3))

The drift rates in each dimension

required
ndt (float or array - like, shape(n_samples))

The non-decision time

required
threshold float

The decision threshold (default is 1)

required
decay float

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Name Type Description
log_density (array - like, shape(n_samples))

The joint log-probability density of response time and choice angles

Source code in src/jeam/Models/Spherical.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angles

    Parameters
    ----------
    rt : array-like, shape (n_samples,)
        The response times
    theta : array-like, shape (n_samples, 2)
        The choice angles in spherical coordinates (theta1, theta2)
    drift_vec : array-like, shape (3,) or (n_samples, 3)
        The drift rates in each dimension
    ndt : float or array-like, shape (n_samples,)
        The non-decision time
    threshold : float
        The decision threshold (default is 1)
    decay : float, optional
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    log_density : array-like, shape (n_samples,)
        The joint log-probability density of response time and choice angles
    '''

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 3))

    if drift_vec.shape[1] != 3 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (3,) or (n_samples, 3)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = sdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * sdm_short_t_fpt_z(sigma**2 * tt/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = sdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * sdm_short_t_fpt_z(sigma**2 * T/threshold**2, sigma**2 * 0.1**8/threshold**2)   
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 3*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)

    # Girsanov:
    if s_v == 0:
        # No drift variability
        mu_dot_x0 = drift_vec[:, 0]*np.cos(theta[:, 0])
        mu_dot_x1 = drift_vec[:, 1]*np.sin(theta[:, 0])*np.cos(theta[:, 1]) 
        mu_dot_x2 = drift_vec[:, 2]*np.sin(theta[:, 0])*np.sin(theta[:, 1])

        if s_t == 0:
            # No non-decision time variability
            term1 = a * (mu_dot_x0 + mu_dot_x1 + mu_dot_x2) / sigma**2
            term2 = 0.5 * (drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2) * tt / sigma**2
            log_density = term1 - term2 + np.log(fpt_z) - 1.5*np.log(2*np.pi)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            norm2_drift = drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2
            mu_dot_x = (mu_dot_x0 + mu_dot_x1 + mu_dot_x2) / sigma**2

            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        integrand = np.exp(- 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = np.exp(threshold * mu_dot_x[i]) * trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    elif self.threshold_dynamic == 'linear':
                        integrand = np.exp((threshold - decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    elif self.threshold_dynamic == 'exponential':
                        integrand = np.exp(threshold*np.exp(-decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    elif self.threshold_dynamic == 'hyperbolic':
                        integrand = np.exp(threshold/(1  + decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    elif self.threshold_dynamic == 'custom':
                        integrand = np.exp(threshold_function(tt[i] - eps) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5

                    if density > 0.1**14:
                        log_density[i] = np.log(density)
    else:
        # With drift variability
        if s_t == 0:
            # No non-decision time variability
            s_v2 = s_v**2
            x0 =  a * np.cos(theta[:, 0])
            x1 =  a * np.sin(theta[:, 0])*np.cos(theta[:, 1]) 
            x2 =  a * np.sin(theta[:, 0])*np.sin(theta[:, 1])
            fixed = 1/(np.sqrt(s_v2/sigma**2 * tt + 1))
            exponent0 = -0.5*drift_vec[:, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[:, 0])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent1 = -0.5*drift_vec[:, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[:, 1])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent2 = -0.5*drift_vec[:, 2]**2/s_v2 + 0.5*(x2 * s_v2/sigma**2 + drift_vec[:, 2])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            log_density = 3*np.log(fixed) + exponent0 + exponent1 + exponent2 + np.log(fpt_z) - 1.5*np.log(2*np.pi)
        else:
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        x0 = threshold * np.cos(theta[i, 0])
                        x1 = threshold * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = threshold * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    elif self.threshold_dynamic == 'linear':
                        x0 = (threshold - decay * (tt[i]-eps)) * np.cos(theta[i, 0])
                        x1 = (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    elif self.threshold_dynamic == 'exponential':
                        x0 = (threshold * np.exp(-decay * (tt[i]-eps))) * np.cos(theta[i, 0])
                        x1 = (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    elif self.threshold_dynamic == 'hyperbolic':
                        x0 = (threshold / (1 + decay * (tt[i]-eps))) * np.cos(theta[i, 0])
                        x1 = (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    elif self.threshold_dynamic == 'custom':
                        x0 = threshold_function(tt[i]-eps) * np.cos(theta[i, 0])
                        x1 = threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.cos(theta[i, 1]) 
                        x2 = threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.sin(theta[i, 1])
                    fixed = 1/(np.sqrt(s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent0 = -0.5*drift_vec[i, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[i, 0])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent1 = -0.5*drift_vec[i, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[i, 1])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent2 = -0.5*drift_vec[i, 2]**2/s_v2 + 0.5*(x2 * s_v2/sigma**2 + drift_vec[i, 2])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))

                    integrand = fixed**3 * np.exp(exponent0 + exponent1 + exponent2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                    density = trapz_1d(integrand, eps) * (0.5/np.pi)**1.5
                    if density > 0.1**14:
                        log_density[i] = np.log(density)

    log_density[rt - ndt <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate data from the Spherical Diffusion Model

Parameters:

Name Type Description Default
drift_vec (array - like, shape(3) or (n_samples, 3))

Drift vector; a three-dimensional array

required
ndt float or array-like with the shape of (n_samples,)

Non-decision time; a positive floating number

required
threshold float or array-like with the shape of (n_samples,)

Decision threshold; a positive floating number (default is 1)

1
decay float or array-like with the shape of (n_samples,)

Decay rate of the collapsing boundary (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

Time step for the simulation (default is 0.001)

0.001
n_sample int

Number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/Spherical.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate data from the Spherical Diffusion Model

    Parameters
    ----------
    drift_vec : array-like, shape (3,) or (n_samples, 3)
        Drift vector; a three-dimensional array
    ndt : float or array-like with the shape of (n_samples,)
        Non-decision time; a positive floating number
    threshold : float or array-like with the shape of (n_samples,)
        Decision threshold; a positive floating number (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        Decay rate of the collapsing boundary (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        Time step for the simulation (default is 0.001)
    n_sample : int, optional
        Number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample, 2))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 3))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_SDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n], 
                                                     threshold_dynamic=self.threshold_dynamic, 
                                                     decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_custom_threshold_SDM_trial(threshold_function,
                                                                      drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                      s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)

    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response1', 'response2'])

Hyper-spherical diffusion models

HyperSphericalDiffusionModel(threshold_dynamic='fixed')

Hyper-Spherical Diffusion Model

Parameters:

Name Type Description Default
threshold_dynamic str

The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'

'fixed'
Source code in src/jeam/Models/HyperSpherical.py
15
16
17
18
19
20
21
22
23
24
25
26
27
def __init__(self, threshold_dynamic='fixed'):
    '''
    Parameters
    ----------
    threshold_dynamic : str, optional
        The type of threshold collapse ('fixed', 'linear', 'exponential', 'hyperbolic', or 'custom'), default is 'fixed'
    '''
    self.name = 'Hyper-Spherical Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angles

Parameters:

Name Type Description Default
rt (array - like, shape(n_samples))

The response times

required
theta (array - like, shape(n_samples, 3))

The choice angles in spherical coordinates (theta1, theta2, theta3)

required
drift_vec (array - like, shape(4) or (n_samples, 4))

The drift rates in each dimension

required
ndt (float or array - like, shape(n_samples))

The non-decision time

required
threshold float

The decision threshold (default is 1)

required
decay float

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Name Type Description
log_density (array - like, shape(n_samples))

The joint log-probability density of response time and choice angles

Source code in src/jeam/Models/HyperSpherical.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angles

    Parameters
    ----------
    rt : array-like, shape (n_samples,)
        The response times
    theta : array-like, shape (n_samples, 3)
        The choice angles in spherical coordinates (theta1, theta2, theta3)
    drift_vec : array-like, shape (4,) or (n_samples, 4)
        The drift rates in each dimension
    ndt : float or array-like, shape (n_samples,)
        The non-decision time
    threshold : float
        The decision threshold (default is 1)
    decay : float, optional
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    log_density : array-like, shape (n_samples,)
        The joint log-probability density of response time and choice angles
    '''

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 4))

    if drift_vec.shape[1] != 4 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (4,) or (n_samples, 4)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = hsdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * hsdm_short_t_fpt_z(sigma**2 * tt/threshold**2, sigma**2 * 0.1**8/threshold**2)
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1) 
            fpt_lt = hsdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = sigma**2/threshold**2 * hsdm_short_t_fpt_z(sigma**2 * T/threshold**2, sigma**2 * 0.1**8/threshold**2)
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)

    # Girsanov:
    if s_v == 0:
        # No drift variability
        mu_dot_x0 = drift_vec[:, 0]*np.cos(theta[:, 0])
        mu_dot_x1 = drift_vec[:, 1]*np.sin(theta[:, 0])*np.cos(theta[:, 1]) 
        mu_dot_x2 = drift_vec[:, 2]*np.sin(theta[:, 0])*np.sin(theta[:, 1])*np.cos(theta[:, 2])
        mu_dot_x3 = drift_vec[:, 3]*np.sin(theta[:, 0])*np.sin(theta[:, 1])*np.sin(theta[:, 2])
        if s_t == 0:
            # No non-decision time variability
            term1 = a * (mu_dot_x0 + mu_dot_x1 + mu_dot_x2 + mu_dot_x3) / sigma**2
            term2 = 0.5 * (drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2 + drift_vec[:, 3]**2) * tt / sigma**2
            log_density = term1 - term2 + np.log(fpt_z) - 2*np.log(2*np.pi)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            norm2_drift = drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2 + drift_vec[:, 3]**2
            mu_dot_x = (mu_dot_x0 + mu_dot_x1 + mu_dot_x2 + mu_dot_x3) / sigma**2

            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        integrand = np.exp(- 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = np.exp(threshold * mu_dot_x[i]) * trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    elif self.threshold_dynamic == 'linear':
                        integrand = np.exp((threshold - decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    elif self.threshold_dynamic == 'exponential':
                        integrand = np.exp(threshold*np.exp(-decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    elif self.threshold_dynamic == 'hyperbolic':
                        integrand = np.exp(threshold/(1  + decay * (tt[i] - eps)) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    elif self.threshold_dynamic == 'custom':
                        integrand = np.exp(threshold_function(tt[i] - eps) * mu_dot_x[i] - 0.5 * norm2_drift[i] * (tt[i] - eps)/sigma**2) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = trapz_1d(integrand, eps) * (0.5/np.pi)**2

                    if density > 0.1**14:
                        log_density[i] = np.log(density)
    else:
        # With drift variability
        if s_t == 0:
            s_v2 = s_v**2
            x0 =  a * np.cos(theta[:, 0])
            x1 =  a * np.sin(theta[:, 0])*np.cos(theta[:, 1])
            x2 =  a * np.sin(theta[:, 0])*np.sin(theta[:, 1])*np.cos(theta[:, 2])
            x3 =  a * np.sin(theta[:, 0])*np.sin(theta[:, 1])*np.sin(theta[:, 2])
            fixed = 1/(np.sqrt(s_v2/sigma**2 * tt + 1))
            exponent0 = -0.5*drift_vec[:, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[:, 0])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent1 = -0.5*drift_vec[:, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[:, 1])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent2 = -0.5*drift_vec[:, 2]**2/s_v2 + 0.5*(x2 * s_v2/sigma**2 + drift_vec[:, 2])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))
            exponent3 = -0.5*drift_vec[:, 3]**2/s_v2 + 0.5*(x3 * s_v2/sigma**2 + drift_vec[:, 3])**2 / (s_v2 * (s_v2/sigma**2 * tt + 1))

            # the joint density of choice and RT for the full process
            log_density = 4*np.log(fixed) + exponent0 + exponent1 + exponent2 + exponent3 + np.log(fpt_z) - 2*np.log(2*np.pi)
        else:
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        x0 =  threshold * np.cos(theta[i, 0])
                        x1 =  threshold * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  threshold * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  threshold * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    elif self.threshold_dynamic == 'linear':
                        x0 =  (threshold - decay * (tt[i]-eps)) * np.cos(theta[i, 0])
                        x1 =  (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  (threshold - decay * (tt[i]-eps)) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    elif self.threshold_dynamic == 'exponential':
                        x0 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.cos(theta[i, 0])
                        x1 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  (threshold * np.exp(-decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    elif self.threshold_dynamic == 'hyperbolic':
                        x0 =  (threshold / (1 + decay * (tt[i]-eps))) * np.cos(theta[i, 0])
                        x1 =  (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  (threshold / (1 + decay * (tt[i]-eps))) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    elif self.threshold_dynamic == 'custom':
                        x0 =  threshold_function(tt[i]-eps) * np.cos(theta[i, 0])
                        x1 =  threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.cos(theta[i, 1])
                        x2 =  threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.cos(theta[i, 2])
                        x3 =  threshold_function(tt[i]-eps) * np.sin(theta[i, 0])*np.sin(theta[i, 1])*np.sin(theta[i, 2])
                    fixed = 1/(np.sqrt(s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent0 = -0.5*drift_vec[i, 0]**2/s_v2 + 0.5*(x0 * s_v2/sigma**2 + drift_vec[i, 0])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent1 = -0.5*drift_vec[i, 1]**2/s_v2 + 0.5*(x1 * s_v2/sigma**2 + drift_vec[i, 1])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent2 = -0.5*drift_vec[i, 2]**2/s_v2 + 0.5*(x2 * s_v2/sigma**2 + drift_vec[i, 2])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))
                    exponent3 = -0.5*drift_vec[i, 3]**2/s_v2 + 0.5*(x3 * s_v2/sigma**2 + drift_vec[i, 3])**2 / (s_v2 * (s_v2/sigma**2 * (tt[i] - eps) + 1))

                    integrand = fixed**4 * np.exp(exponent0 + exponent1 + exponent2 + exponent3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                    density = trapz_1d(integrand, eps) * (0.5/np.pi)**2
                    if density > 0.1**14:
                        log_density[i] = np.log(density)

    log_density[rt - ndt <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate data from the Hyper-Spherical Diffusion Model

Parameters:

Name Type Description Default
drift_vec (array - like, shape(4) or (n_samples, 4))

The drift rates in each dimension

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float or array-like with the shape of (n_samples,)

The decision threshold (default is 1)

1
decay float or array-like with the shape of (n_samples,)

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

Time step for the simulation (default is 0.001)

0.001
n_sample int

Number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/HyperSpherical.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate data from the Hyper-Spherical Diffusion Model

    Parameters
    ----------
    drift_vec : array-like, shape (4,) or (n_samples, 4)
        The drift rates in each dimension
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float or array-like with the shape of (n_samples,)
        The decision threshold (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        Time step for the simulation (default is 0.001)
    n_sample : int, optional
        Number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample, 3))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 4))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_HSDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n],
                                                      threshold_dynamic=self.threshold_dynamic, 
                                                      decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_custom_threshold_HSDM_trial(threshold_function,
                                                                       drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                       s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response1', 'response2', 'response3'])

ProjectedHyperSphericalDiffusionModel(threshold_dynamic='fixed')

Projected Hyper-Spherical Diffusion Model

Source code in src/jeam/Models/HyperSpherical.py
298
299
300
301
302
303
304
def __init__(self, threshold_dynamic='fixed'):
    self.name = 'Projected Hyper-Spherical Diffusion Model'

    if threshold_dynamic in ['fixed', 'linear', 'exponential', 'hyperbolic', 'custom']:
        self.threshold_dynamic = threshold_dynamic
    else:
        raise ValueError("\'threshold_dynamic\' must be one of \'fixed\', \'linear\', \'exponential\', \'hyperbolic\', or \'custom\'. However, got \'{}\'".format(threshold_dynamic))

joint_lpdf(rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01)

Compute the joint log-probability density function of response time and choice angles for the Projected Hyper-Spherical Diffusion Model

Parameters:

Name Type Description Default
rt (array - like, shape(n_samples))

The response times

required
theta (array - like, shape(n_samples, 2))

The choice angles in spherical coordinates (theta1, theta2)

required
drift_vec (array - like, shape(3) or (n_samples, 3))

The drift rates in each dimension

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float

The decision threshold (default is 1)

required
decay float

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
dt_threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the derivative of the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
approximation_step float

The time step for numerical estimation of first-passage time densities (default is 0.01)

0.01

Returns:

Name Type Description
log_density (array - like, shape(n_samples))

The joint log-probability density of response time and choice angles

Source code in src/jeam/Models/HyperSpherical.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def joint_lpdf(self, rt, theta, drift_vec, ndt, threshold, decay=0, threshold_function=None, dt_threshold_function=None, s_v=0, s_t=0, sigma=1, approximation_step=0.01):
    '''
    Compute the joint log-probability density function of response time and choice angles for the Projected Hyper-Spherical Diffusion Model

    Parameters
    ----------
    rt : array-like, shape (n_samples,)
        The response times
    theta : array-like, shape (n_samples, 2)
        The choice angles in spherical coordinates (theta1, theta2)
    drift_vec : array-like, shape (3,) or (n_samples, 3)
        The drift rates in each dimension
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float
        The decision threshold (default is 1)
    decay : float, optional
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    dt_threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the derivative of the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    approximation_step : float, optional
        The time step for numerical estimation of first-passage time densities (default is 0.01)

    Returns
    -------
    log_density : array-like, shape (n_samples,)
        The joint log-probability density of response time and choice angles
    '''
    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((rt.shape[0], 3))

    if drift_vec.shape[1] != 3 or drift_vec.ndim != 2:
        raise ValueError("drift_vec must have shape (3,) or (n_samples, 3)")

    tt = np.maximum(rt - ndt, 0)

    # first-passage time density of zero drift process
    if self.threshold_dynamic == 'fixed':
        a = threshold
        s0 = 0.002
        s1 = 0.02
        if s_t == 0:
            s = tt/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = hsdm_long_t_fpt_z(tt, threshold, sigma=sigma)
            fpt_st = 1/threshold**2 * hsdm_short_t_fpt_z(tt/threshold**2, 0.1**8/threshold**2)   
        else:
            T = np.arange(0, tt.max()+0.05, 0.05)
            s = T/threshold**2
            w = np.minimum(np.maximum((s - s0) / (s1 - s0), 0), 1)
            fpt_lt = hsdm_long_t_fpt_z(T, threshold, sigma=sigma)
            fpt_st = 1/threshold**2 * hsdm_short_t_fpt_z(T/threshold**2, 0.1**8/threshold**2)   
        fpt_z =  (1 - w) * fpt_st + w * fpt_lt
    elif self.threshold_dynamic == 'linear':
        a = threshold - decay*tt
        T_max = min(rt.max(), threshold/decay)
        g_z, T = ie_fpt_linear(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=T_max)
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'exponential':
        a = threshold * np.exp(-decay*tt)
        g_z, T = ie_fpt_exponential(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'hyperbolic':
        a = threshold / (1 + decay*tt)
        g_z, T = ie_fpt_hyperbolic(threshold, decay, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)
    elif self.threshold_dynamic == 'custom':
        threshold_function2 = lambda t: threshold_function(t)**2
        dt_threshold_function2 = lambda t: 2 * dt_threshold_function(t) * threshold_function(t)
        a = threshold_function(tt)
        g_z, T = ie_fpt_custom(threshold_function2, dt_threshold_function2, 4*sigma**2, 0.000001, sigma=2*sigma**2, dt=approximation_step, T_max=rt.max())
        fpt_z = np.interp(tt, T, g_z)

    fpt_z = np.maximum(fpt_z, 0.1**14)
    norm_mu = np.sqrt(drift_vec[:, 0]**2 + drift_vec[:, 1]**2 + drift_vec[:, 2]**2)

    theta1_mu = np.arctan2(drift_vec[:, 2], drift_vec[:, 0])
    theta2_mu = np.arctan2(drift_vec[:, 2], drift_vec[:, 1])

    # Girsanov:
    if s_v == 0:
        # No drift variability
        if s_t == 0:
            # No non-decision time variability
            x0 = np.cos(theta1_mu) * np.cos(theta[:, 0])
            x1 = np.sin(theta1_mu) * np.sin(theta[:, 0]) * np.cos(theta2_mu) * np.cos(theta[:, 1])
            term1 = np.exp(a * norm_mu * (x0 + x1) / sigma**2)
            term2 = iv(0, a * norm_mu * np.sin(theta1_mu) * np.sin(theta[:, 0]) * np.sin(theta2_mu) * np.sin(theta[:, 1])/sigma**2)
            term3 = -0.5 * norm_mu**2 * tt

            log_density = np.log(2*np.pi) + np.log(term1) + np.log(term2) + term3 + np.log(fpt_z)
        else:
            # With non-decision time variability
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    if self.threshold_dynamic == 'fixed':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp(threshold * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, threshold * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * term1 * term2 * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'linear':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp((threshold - decay * (tt[i] - eps)) * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, (threshold - decay * (tt[i] - eps)) * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'exponential':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp(threshold*np.exp(-decay * (tt[i] - eps)) * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, threshold*np.exp(-decay * (tt[i] - eps)) * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'hyperbolic':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp(threshold/(1  + decay * (tt[i] - eps)) * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, threshold/(1  + decay * (tt[i] - eps)) * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    elif self.threshold_dynamic == 'custom':
                        x0 = np.cos(theta1_mu[i]) * np.cos(theta[i, 0])
                        x1 = np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.cos(theta2_mu[i]) * np.cos(theta[i, 1])
                        term1 = np.exp(threshold_function(tt[i] - eps) * norm_mu[i] * (x0 + x1) / sigma**2)
                        term2 = iv(0, threshold_function(tt[i] - eps) * norm_mu[i] * np.sin(theta1_mu[i]) * np.sin(theta[i, 0]) * np.sin(theta2_mu[i]) * np.sin(theta[i, 1])/sigma**2)
                        term3 = -0.5 * norm_mu[i]**2 * (tt[i] - eps)
                        integrand = term1 * term2 * np.exp(term3) * np.interp(tt[i]-eps, T, fpt_z)/s_t
                        density = 2*np.pi * trapz_1d(integrand, eps)
                    if density > 0.1**14:
                        log_density[i] = np.log(density)
    else:
        # With drift variability
        if s_t == 0:
            # No non-decision time variability
            s_v2 = s_v**2
            c1 = a * np.sin(theta[:, 0]) * np.sin(theta[:, 1]) * s_v2
            c2 = 2*s_v2 * (s_v2 * tt + 1)
            term1 = 2*np.pi * iv(0, 2*c1 * drift_vec[:, 2]/c2)
            term2 = 1/(s_v2 * tt + 1)**2
            p1 = (c1**2 + drift_vec[:, 2]**2)/c2
            p2 = (a * np.cos(theta[:, 0]) * s_v2 + drift_vec[:, 0])**2 / c2
            p3 = (a * np.sin(theta[:, 0]) * np.cos(theta[:, 1]) * s_v2 + drift_vec[:, 1])**2 / c2
            p4 = (norm_mu**2)/(2*s_v2)

            log_density = np.log(term1) + np.log(term2) + (p1 + p2 + p3 - p4) + np.log(fpt_z)
        else:
            log_density = np.log(0.1**14) * np.ones(rt.shape[0])
            eps = np.linspace(0, s_t, max(2, int(s_t//0.02)))
            s_v2 = s_v**2

            for i in range(rt.shape[0]):
                if tt[i] - s_t > 0:
                    c2 = 2*s_v2 * (s_v2 * (tt[i] - eps) + 1)
                    if self.threshold_dynamic == 'fixed':
                        c1 = threshold * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = (threshold * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = (threshold * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2
                    elif self.threshold_dynamic == 'linear':
                        c1 = (threshold - decay*(tt[i]-eps)) * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = ((threshold - decay*(tt[i]-eps)) * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = ((threshold - decay*(tt[i]-eps)) * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2
                    elif self.threshold_dynamic == 'exponential':
                        c1 = (threshold * np.exp(-decay*(tt[i]-eps))) * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = ((threshold * np.exp(-decay*(tt[i]-eps))) * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = ((threshold * np.exp(-decay*(tt[i]-eps))) * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2
                    elif self.threshold_dynamic == 'hyperbolic':
                        c1 = (threshold / (1 + decay*(tt[i]-eps))) * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = ((threshold / (1 + decay*(tt[i]-eps))) * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = ((threshold / (1 + decay*(tt[i]-eps))) * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2
                    elif self.threshold_dynamic == 'custom':
                        c1 = threshold_function(tt[i]-eps) * np.sin(theta[i, 0]) * np.sin(theta[i, 1]) * s_v2
                        p2 = (threshold_function(tt[i]-eps) * np.cos(theta[i, 0]) * s_v2 + drift_vec[i, 0])**2 / c2
                        p3 = (threshold_function(tt[i]-eps) * np.sin(theta[i, 0]) * np.cos(theta[i, 1]) * s_v2 + drift_vec[i, 1])**2 / c2

                    term1 = 2*np.pi * iv(0, 2*c1 * drift_vec[:, 2]/c2)
                    term2 = 1/(s_v2 * (tt[i] - eps) + 1)**2
                    p4 = (norm_mu**2)/(2*s_v2)
                    term3 = np.exp(p1 + p2 + p3 - p4)
                    integrand = term1 * term2 * term3 * np.interp(tt[i]-eps, T, fpt_z)/s_t

                    density = trapz_1d(integrand, eps)

                    if density > 0.1**14:
                            log_density[i] = np.log(density)

    log_density[rt - ndt <= 0] = np.log(0.1**14)
    log_density = np.maximum(log_density, np.log(0.1**14))

    return log_density

simulate(drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1)

Simulate data from the Projected Hyper-Spherical Diffusion Model

Parameters:

Name Type Description Default
drift_vec (array - like, shape(3) or (n_samples, 3))

The drift vector [drift_x, drift_y, drift_z]. Note that drift_z must be non-negative, as it represents the projection onto the upper hemisphere.

required
ndt float or array-like with the shape of (n_samples,)

The non-decision time

required
threshold float or array-like with the shape of (n_samples,)

The decision threshold (default is 1)

1
decay float or array-like with the shape of (n_samples,)

The threshold decay rate (default is 0)

0
threshold_function callable, if threshold_dynamic is 'custom'

A function that takes time t and returns the threshold at time t

None
s_v float

The standard deviation of drift variability (default is 0)

0
s_t float

The standard deviation of non-decision time variability (default is 0)

0
sigma float

The diffusion coefficient (default is 1)

1
dt float

Time step for the simulation (default is 0.001)

0.001
n_sample int

Number of samples to simulate (default is 1)

1

Returns:

Type Description
DataFrame

A DataFrame containing simulated response times and choice angles

Source code in src/jeam/Models/HyperSpherical.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def simulate(self, drift_vec, ndt, threshold=1, decay=0, threshold_function=None, s_v=0, s_t=0, sigma=1, dt=0.001, n_sample=1):
    '''
    Simulate data from the Projected Hyper-Spherical Diffusion Model

    Parameters
    ----------
    drift_vec : array-like, shape (3,) or (n_samples, 3)
        The drift vector [drift_x, drift_y, drift_z]. Note that drift_z must be non-negative, as it represents the projection onto the upper hemisphere.
    ndt : float or array-like with the shape of (n_samples,)
        The non-decision time
    threshold : float or array-like with the shape of (n_samples,)
        The decision threshold (default is 1)
    decay : float or array-like with the shape of (n_samples,)
        The threshold decay rate (default is 0)
    threshold_function : callable, if threshold_dynamic is 'custom'
        A function that takes time t and returns the threshold at time t
    s_v : float, optional
        The standard deviation of drift variability (default is 0)
    s_t : float, optional
        The standard deviation of non-decision time variability (default is 0)
    sigma : float, optional
        The diffusion coefficient (default is 1)
    dt : float, optional
        Time step for the simulation (default is 0.001)
    n_sample : int, optional
        Number of samples to simulate (default is 1)

    Returns
    -------
    pd.DataFrame
        A DataFrame containing simulated response times and choice angles
    '''
    RT = np.empty((n_sample,))
    Choice = np.empty((n_sample, 2))

    if drift_vec.ndim == 1:
        drift_vec = drift_vec * np.ones((n_sample, 3))
    elif drift_vec.shape[0] != n_sample:
        raise ValueError("Number of rows in drift_vec must be equal to n_sample")

    if isinstance(ndt, (float, np.floating)) or isinstance(ndt, (int, np.integer)):
        ndt = np.full((n_sample,), ndt)
    elif len(ndt) != n_sample:
        raise ValueError("Length of ndt must be equal to n_sample")

    if isinstance(threshold, (float, np.floating)) or isinstance(threshold, (int, np.integer)):
        threshold = np.full((n_sample,), threshold)
    elif len(threshold) != n_sample:
        raise ValueError("Length of threshold must be equal to n_sample")

    if isinstance(decay, (float, np.floating)) or isinstance(decay, (int, np.integer)):
        decay = np.full((n_sample,), decay)
    elif len(decay) != n_sample:
        raise ValueError("Length of decay must be equal to n_sample")

    if threshold_function is None and self.threshold_dynamic == 'custom':
        raise ValueError("threshold_function must be provided when threshold_dynamic is 'custom'")

    if threshold_function is not None and self.threshold_dynamic != 'custom':
        raise ValueError("threshold_function should be None when threshold_dynamic is not 'custom'")

    if s_v < 0:
        raise ValueError("s_v must be non-negative")
    if s_t < 0:
        raise ValueError("s_t must be non-negative")

    if self.threshold_dynamic != 'custom':
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_PHSDM_trial(threshold[n], drift_vec[n, :].astype(np.float64), ndt[n],
                                                       threshold_dynamic=self.threshold_dynamic, 
                                                       decay=decay[n], s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    else:
        for n in range(n_sample):
            RT[n], Choice[n, :] = simulate_custom_threshold_PHSDM_trial(threshold_function,
                                                                        drift_vec[n, :].astype(np.float64), ndt[n], 
                                                                        s_v=s_v, s_t=s_t, sigma=sigma, dt=dt)
    return pd.DataFrame(np.c_[RT, Choice], columns=['rt', 'response1', 'response2'])