braincoder 0.7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
braincoder/hrf.py ADDED
@@ -0,0 +1,272 @@
1
+ import numpy as np
2
+ import keras
3
+ from keras import ops
4
+ from .utils import logit
5
+ from .utils.backend import softplus_inverse
6
+
7
+
8
+ def bounded_sigmoid_transform(min_val, max_val):
9
+ """Return a (forward, backward) pair that maps reals → [min_val, max_val] via sigmoid."""
10
+ def forward(x):
11
+ return ops.sigmoid(x) * (max_val - min_val) + min_val
12
+ def backward(y):
13
+ y_scaled = (y - min_val) / (max_val - min_val)
14
+ return ops.log(y_scaled / (1.0 - y_scaled))
15
+ return (forward, backward)
16
+
17
+
18
+ class HRFModel(object):
19
+ """Base class that handles HRF generation and convolution with predictions."""
20
+
21
+ def _transform_parameters_forward(self, parameters):
22
+ """Map unconstrained optimizer parameters to the model's native space via ``self.transformations``."""
23
+ out = []
24
+ for i, t in enumerate(self.transformations):
25
+ param = parameters[:, i][:, None]
26
+ if isinstance(t, tuple):
27
+ out.append(t[0](param))
28
+ elif t == 'identity':
29
+ out.append(param)
30
+ elif t == 'softplus':
31
+ out.append(ops.softplus(param))
32
+ elif t == 'sigmoid':
33
+ out.append(ops.sigmoid(param))
34
+ else:
35
+ raise NotImplementedError(f"Unknown transform: {t!r}")
36
+ return ops.concatenate(out, axis=1)
37
+
38
+ def _transform_parameters_backward(self, parameters):
39
+ """Inverse of :meth:`_transform_parameters_forward`."""
40
+ out = []
41
+ for i, t in enumerate(self.transformations):
42
+ param = parameters[:, i][:, None]
43
+ if isinstance(t, tuple):
44
+ out.append(t[1](param))
45
+ elif t == 'identity':
46
+ out.append(param)
47
+ elif t == 'softplus':
48
+ out.append(softplus_inverse(param))
49
+ elif t == 'sigmoid':
50
+ out.append(ops.log(param / (1.0 - param)))
51
+ else:
52
+ raise NotImplementedError(f"Unknown transform: {t!r}")
53
+ return ops.concatenate(out, axis=1)
54
+
55
+ def convolve(self, timeseries, **kwargs):
56
+ hrf = self.get_hrf(**kwargs)
57
+ # Dispatch on HRF shape rather than stored state to avoid bugs when
58
+ # multiple models share the same hrf_model object with different
59
+ # flexible_hrf_parameters settings.
60
+ # Shape (n_hrf,) or (n_hrf, 1) → one shared HRF for all units.
61
+ # Shape (n_hrf, n_units) with n_units > 1 → one HRF per unit.
62
+ n_cols = int(hrf.shape[-1]) if hrf.ndim >= 2 else 1
63
+ if n_cols <= 1:
64
+ return self._convolve_shared(timeseries, hrf=hrf)
65
+ else:
66
+ return self._convolve_unique(timeseries, hrf=hrf)
67
+
68
+ def _convolve_shared(self, timeseries, hrf):
69
+ # timeseries: n_batch x n_timepoints x n_units
70
+ # hrf: n_hrf_timepoints (1D) or n_hrf_timepoints x 1
71
+ # Treat time as height, units as width: 2D conv with a (n_hrf, 1) filter
72
+ # slides only along the time axis, leaving units unchanged.
73
+ n_hrf = int(hrf.shape[0])
74
+ pad_ = ops.tile(timeseries[:, :1, :], [1, n_hrf, 1])
75
+ timeseries_padded = ops.concatenate((pad_, timeseries), axis=1)
76
+
77
+ hrf_1d = ops.reshape(hrf, (-1,)) # ensure 1D
78
+ # ops.conv with 4D kernel → 2D conv; reverse HRF for convolution vs cross-correlation
79
+ kernel = ops.reshape(ops.flip(hrf_1d, axis=0), (n_hrf, 1, 1, 1)) # (fH, fW, in_C, out_C)
80
+ cts = ops.conv(timeseries_padded[:, :, :, None], kernel,
81
+ strides=(1, 1), padding='valid')[:, :, :, 0]
82
+
83
+ return cts[:, 1:, :]
84
+
85
+ def _convolve_unique(self, timeseries, hrf):
86
+ # timeseries: n_batch x n_timepoints x n_units
87
+ # hrf: n_hrf_timepoints x n_units
88
+ # 1D depthwise conv: each unit gets its own HRF filter.
89
+ n, m = timeseries.shape[1], timeseries.shape[2]
90
+ n_hrf = int(hrf.shape[0])
91
+
92
+ pad_ = ops.tile(timeseries[:, :1, :], [1, n_hrf, 1])
93
+ timeseries_padded = ops.concatenate((pad_, timeseries), axis=1)
94
+ # timeseries_padded: (1, n+n_hrf, m) — (batch, steps, channels) for 1D depthwise conv
95
+
96
+ # kernel: (kernel_size, channels, depth_multiplier); reverse time axis for convolution
97
+ kernel = ops.reshape(ops.flip(hrf, axis=0), (n_hrf, m, 1))
98
+
99
+ convolved = ops.depthwise_conv(timeseries_padded, kernel, strides=1, padding='valid')
100
+ # convolved: (1, n+1, m) — trim leading timepoint
101
+ return convolved[:, 1:, :]
102
+
103
+
104
+ def gamma_pdf(t, a, d, eps=1e-6):
105
+ """Numerically stable gamma PDF."""
106
+ from .utils.backend import lgamma
107
+ t = ops.maximum(t, eps)
108
+ # In log space: t**(a-1) and d**a * Gamma(a) overflow float32 for shape
109
+ # a > ~35 (narrow HRFs), which gave inf / inf = NaN.
110
+ log_pdf = (a - 1.) * ops.log(t) - t / d - a * ops.log(d) - lgamma(a)
111
+ return ops.exp(log_pdf)
112
+
113
+
114
+ def gamma_pdf_with_loc(t, a, d, dt, loc=0.0):
115
+ """Gamma PDF shifted by a delay 'loc'."""
116
+ t = ops.convert_to_tensor(t, dtype='float32')
117
+ a = ops.convert_to_tensor(a, dtype='float32')
118
+ d = ops.convert_to_tensor(d, dtype='float32')
119
+
120
+ shifted_t = t - loc
121
+ mask = shifted_t >= 0
122
+ safe_t = ops.where(mask, shifted_t, ops.ones_like(shifted_t))
123
+ pdf_vals = ops.where(mask, gamma_pdf(safe_t, a, d), ops.zeros_like(shifted_t))
124
+
125
+ loc_steps = int(round(float(loc) / float(dt)))
126
+
127
+ if loc_steps > 0:
128
+ trimmed = pdf_vals[:-loc_steps, :]
129
+ padding = ops.zeros([loc_steps, ops.shape(trimmed)[1]], dtype='float32')
130
+ result = ops.concatenate([padding, trimmed], axis=0)
131
+ else:
132
+ result = pdf_vals
133
+
134
+ return result
135
+
136
+ def spm_hrf(t, a1=6., d1=1., a2=16., d2=1., c=1./6, highres_dt=0.1):
137
+ """Compute SPM canonical HRF(s)."""
138
+ from .utils.backend import interp_regular_1d_grid
139
+
140
+ t = ops.convert_to_tensor(t, dtype='float32')
141
+ a1 = ops.convert_to_tensor(a1, dtype='float32')
142
+ d1 = ops.convert_to_tensor(d1, dtype='float32')
143
+ a2 = ops.convert_to_tensor(a2, dtype='float32')
144
+ d2 = ops.convert_to_tensor(d2, dtype='float32')
145
+ c = ops.convert_to_tensor(c, dtype='float32')
146
+
147
+ t_min = ops.min(t)
148
+ t_max = ops.max(t)
149
+ n_steps = ops.cast(ops.ceil((t_max - t_min) / highres_dt) + 1, 'int32')
150
+ t_hr = t_min + ops.arange(n_steps, dtype='float32') * highres_dt
151
+ t_hr_2d = ops.expand_dims(t_hr, 1)
152
+
153
+ hrf1_hr = gamma_pdf_with_loc(t_hr_2d, a1, d1, highres_dt)
154
+ hrf2_hr = gamma_pdf_with_loc(t_hr_2d, a2, d2, highres_dt)
155
+ hrf_hr = hrf1_hr - c * hrf2_hr
156
+ hrf_hr /= ops.sum(hrf_hr, axis=0, keepdims=True)
157
+
158
+ x_ref_max = t_min + highres_dt * ops.cast(n_steps - 1, 'float32')
159
+ return interp_regular_1d_grid(t, t_min, x_ref_max, hrf_hr)
160
+
161
+ def _tr_time_stamps(tr, time_length, onset=0.):
162
+ """HRF sample times, exactly one TR apart, because convolution assumes that spacing."""
163
+ return (np.arange(0., time_length, tr) - onset).astype(np.float32)
164
+
165
+
166
+ class SPMHRFModel(HRFModel):
167
+ """SPM's canonical double-gamma HRF, sampled every TR.
168
+
169
+ The response is a gamma with shape ``delay / dispersion`` and scale ``dispersion``, as in
170
+ SPM's ``spm_hrf``. So ``delay=6`` and ``dispersion=1`` give the canonical HRF, which peaks at
171
+ ``delay - dispersion`` = 5 s.
172
+ """
173
+
174
+ parameter_labels = ['hrf_delay', 'hrf_dispersion']
175
+ n_parameters = 2
176
+
177
+ def __init__(self, tr, highres_dt=0.1, time_length=32., onset=0.,
178
+ delay=6., undershoot=16., dispersion=1.,
179
+ u_dispersion=1., ratio=0.167,
180
+ min_hrf_delay=4., max_hrf_delay=8.,
181
+ min_dispersion=0.3, max_dispersion=2.0):
182
+ self.tr = tr
183
+ self.highres_dt = highres_dt
184
+ self.time_length = time_length
185
+ self.onset = onset
186
+ self.hrf_delay = delay
187
+ self.undershoot = undershoot
188
+ self.hrf_dispersion = dispersion
189
+ self.u_dispersion = u_dispersion
190
+ self.ratio = ratio
191
+ self.min_hrf_delay = min_hrf_delay
192
+ self.max_hrf_delay = max_hrf_delay
193
+ self.min_dispersion = min_dispersion
194
+ self.max_dispersion = max_dispersion
195
+ self.dt = self.tr
196
+ self.time_stamps = _tr_time_stamps(self.tr, self.time_length, self.onset)
197
+
198
+ self.transformations = [
199
+ bounded_sigmoid_transform(self.min_hrf_delay, self.max_hrf_delay),
200
+ bounded_sigmoid_transform(self.min_dispersion, self.max_dispersion),
201
+ ]
202
+
203
+
204
+ def get_hrf(self, hrf_delay=None, hrf_dispersion=None):
205
+
206
+ if hrf_delay is None:
207
+ hrf_delay = self.hrf_delay
208
+
209
+ if hrf_dispersion is None:
210
+ hrf_dispersion = self.hrf_dispersion
211
+
212
+ peak_shape = hrf_delay / hrf_dispersion
213
+ undershoot_shape = self.undershoot / self.u_dispersion
214
+ hrf = spm_hrf(self.time_stamps,
215
+ a1=peak_shape, d1=hrf_dispersion,
216
+ a2=undershoot_shape, d2=self.u_dispersion,
217
+ c=self.ratio,
218
+ highres_dt=self.highres_dt)
219
+ return hrf
220
+
221
+
222
+ class SPMHRFDerivativeModel(HRFModel):
223
+ parameter_labels = ['delay_weight', 'dispersion_weight']
224
+ n_parameters = 2
225
+
226
+ def __init__(self, tr, highres_dt=0.1, time_length=32., onset=0.,
227
+ delay=6., dispersion=1., undershoot=16., u_dispersion=1., ratio=0.167,
228
+ max_weight=2.0):
229
+ self.tr = tr
230
+ self.highres_dt = highres_dt
231
+ self.time_length = time_length
232
+ self.onset = onset
233
+ self.delay = delay
234
+ self.dispersion = dispersion
235
+ self.undershoot = undershoot
236
+ self.u_dispersion = u_dispersion
237
+ self.ratio = ratio
238
+ self.max_weight = max_weight
239
+ self.time_stamps = _tr_time_stamps(self.tr, self.time_length, self.onset)[:, np.newaxis]
240
+ self.transformations = [
241
+ bounded_sigmoid_transform(-self.max_weight, self.max_weight),
242
+ bounded_sigmoid_transform(-self.max_weight, self.max_weight)
243
+ ]
244
+
245
+ def get_hrf(self, delay_weight=0., dispersion_weight=0.):
246
+ base_hrf = spm_hrf(self.time_stamps,
247
+ a1=self.delay / self.dispersion, d1=self.dispersion,
248
+ a2=self.undershoot / self.u_dispersion, d2=self.u_dispersion,
249
+ c=self.ratio,
250
+ highres_dt=self.highres_dt)
251
+
252
+ eps = 1e-2
253
+
254
+ d_delay = spm_hrf(self.time_stamps,
255
+ a1=(self.delay + eps) / self.dispersion, d1=self.dispersion,
256
+ a2=self.undershoot / self.u_dispersion, d2=self.u_dispersion,
257
+ c=self.ratio,
258
+ highres_dt=self.highres_dt)
259
+ derivative_delay = (d_delay - base_hrf) / eps
260
+
261
+ d_disp = spm_hrf(self.time_stamps,
262
+ a1=self.delay / (self.dispersion + eps), d1=self.dispersion + eps,
263
+ a2=self.undershoot / self.u_dispersion, d2=self.u_dispersion,
264
+ c=self.ratio,
265
+ highres_dt=self.highres_dt)
266
+ derivative_disp = (d_disp - base_hrf) / eps
267
+
268
+ hrf = base_hrf \
269
+ + delay_weight * derivative_delay \
270
+ + dispersion_weight * derivative_disp
271
+
272
+ return hrf
@@ -0,0 +1,21 @@
1
+ from .base import EncodingModel, EncodingRegressionModel, HRFEncodingModel
2
+ from .prf_1d import (GaussianPRF, RegressionGaussianPRF, VonMisesPRF, AxialVonMisesPRF,
3
+ LogGaussianPRF, GaussianPRFWithHRF, LogGaussianPRFWithHRF, AlphaGaussianPRF,
4
+ RegressionAlphaGaussianPRF, GaussianPRFOnGaussianSignal)
5
+ from .prf_2d import (GaussianPointPRF2D, GaussianMixturePRF2D, GaussianPRF2D,
6
+ GaussianPRF2DAngle, GaussianPRF2DWithHRF, GaussianPRF2DAngleWithHRF,
7
+ DifferenceOfGaussiansPRF2D, DifferenceOfGaussiansPRF2DWithHRF,
8
+ DivisiveNormalizationGaussianPRF2D, DivisiveNormalizationGaussianPRF2DWithHRF)
9
+ from .linear import DiscreteModel, LinearModel, LinearModelWithBaseline, LinearModelWithBaselineHRF
10
+
11
+ __all__ = [
12
+ 'EncodingModel', 'EncodingRegressionModel', 'HRFEncodingModel',
13
+ 'GaussianPRF', 'RegressionGaussianPRF', 'VonMisesPRF', 'AxialVonMisesPRF', 'LogGaussianPRF',
14
+ 'GaussianPRFWithHRF', 'LogGaussianPRFWithHRF', 'AlphaGaussianPRF',
15
+ 'RegressionAlphaGaussianPRF', 'GaussianPRFOnGaussianSignal',
16
+ 'GaussianPointPRF2D', 'GaussianMixturePRF2D', 'GaussianPRF2D',
17
+ 'GaussianPRF2DAngle', 'GaussianPRF2DWithHRF', 'GaussianPRF2DAngleWithHRF',
18
+ 'DifferenceOfGaussiansPRF2D', 'DifferenceOfGaussiansPRF2DWithHRF',
19
+ 'DivisiveNormalizationGaussianPRF2D', 'DivisiveNormalizationGaussianPRF2DWithHRF',
20
+ 'DiscreteModel', 'LinearModel', 'LinearModelWithBaseline', 'LinearModelWithBaselineHRF',
21
+ ]