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/__init__.py +27 -0
- braincoder/barstimuli.py +569 -0
- braincoder/data/szinte2024/dm_gazecenter.npz +0 -0
- braincoder/data/szinte2024/gauss_parameters.tsv +2366 -0
- braincoder/data/szinte2024/grid_coordinates.tsv +3601 -0
- braincoder/data/szinte2024/mask-v1_bold.tsv.gz +0 -0
- braincoder/hrf.py +272 -0
- braincoder/models/__init__.py +21 -0
- braincoder/models/base.py +1004 -0
- braincoder/models/linear.py +100 -0
- braincoder/models/prf_1d.py +369 -0
- braincoder/models/prf_2d.py +824 -0
- braincoder/noise.py +614 -0
- braincoder/optimize/__init__.py +22 -0
- braincoder/optimize/bayesian_fitter.py +467 -0
- braincoder/optimize/gp_prior.py +361 -0
- braincoder/optimize/parameter_fitter.py +666 -0
- braincoder/optimize/residual_fitter.py +563 -0
- braincoder/optimize/stimulus_fitter.py +656 -0
- braincoder/optimize/weight_fitter.py +112 -0
- braincoder/stimuli.py +224 -0
- braincoder/utils/__init__.py +4 -0
- braincoder/utils/backend.py +533 -0
- braincoder/utils/calibration.py +186 -0
- braincoder/utils/cortex.py +141 -0
- braincoder/utils/data.py +252 -0
- braincoder/utils/formatting.py +63 -0
- braincoder/utils/math.py +131 -0
- braincoder/utils/mcmc.py +114 -0
- braincoder/utils/stats.py +267 -0
- braincoder/utils/visualize.py +26 -0
- braincoder-0.7.1.dist-info/METADATA +136 -0
- braincoder-0.7.1.dist-info/RECORD +36 -0
- braincoder-0.7.1.dist-info/WHEEL +5 -0
- braincoder-0.7.1.dist-info/licenses/LICENSE +22 -0
- braincoder-0.7.1.dist-info/top_level.txt +1 -0
braincoder/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Top-level package for braincoder."""
|
|
2
|
+
|
|
3
|
+
__author__ = """Gilles de Hollander"""
|
|
4
|
+
__email__ = 'gilles.de.hollander@gmail.com'
|
|
5
|
+
__version__ = '0.7.1'
|
|
6
|
+
|
|
7
|
+
from .models import (
|
|
8
|
+
EncodingModel, EncodingRegressionModel, HRFEncodingModel,
|
|
9
|
+
GaussianPRF, RegressionGaussianPRF, VonMisesPRF, AxialVonMisesPRF, LogGaussianPRF,
|
|
10
|
+
GaussianPRFWithHRF, LogGaussianPRFWithHRF, AlphaGaussianPRF,
|
|
11
|
+
RegressionAlphaGaussianPRF, GaussianPRFOnGaussianSignal,
|
|
12
|
+
GaussianPointPRF2D, GaussianMixturePRF2D, GaussianPRF2D,
|
|
13
|
+
GaussianPRF2DAngle, GaussianPRF2DWithHRF, GaussianPRF2DAngleWithHRF,
|
|
14
|
+
DifferenceOfGaussiansPRF2D, DifferenceOfGaussiansPRF2DWithHRF,
|
|
15
|
+
DivisiveNormalizationGaussianPRF2D, DivisiveNormalizationGaussianPRF2DWithHRF,
|
|
16
|
+
DiscreteModel, LinearModel, LinearModelWithBaseline, LinearModelWithBaselineHRF,
|
|
17
|
+
)
|
|
18
|
+
from .optimize import WeightFitter, ParameterFitter, ResidualFitter
|
|
19
|
+
from . import noise
|
|
20
|
+
from .noise import LowRankNoise
|
|
21
|
+
try:
|
|
22
|
+
from .optimize import (
|
|
23
|
+
StimulusFitter, CustomStimulusFitter,
|
|
24
|
+
SzinteStimulus, SzinteStimulus2, make_aperture_stimuli,
|
|
25
|
+
)
|
|
26
|
+
except ImportError:
|
|
27
|
+
pass
|
braincoder/barstimuli.py
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
from tqdm import tqdm
|
|
2
|
+
import tensorflow as tf
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from .optimize import StimulusFitter
|
|
6
|
+
import logging
|
|
7
|
+
import tensorflow_probability as tfp
|
|
8
|
+
from tensorflow_probability import bijectors as tfb
|
|
9
|
+
from .utils.mcmc import cleanup_chain, sample_hmc, Periodic
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BarStimulusFitter(StimulusFitter):
|
|
13
|
+
|
|
14
|
+
def __init__(self, data, model, grid_coordinates, omega, dof=None,
|
|
15
|
+
max_radius=None, max_width=None, bar_intensity=1.0,
|
|
16
|
+
max_intensity=None,
|
|
17
|
+
baseline_image=None, parameters=None, weights=None):
|
|
18
|
+
|
|
19
|
+
self.data = data
|
|
20
|
+
self.model = model
|
|
21
|
+
self.grid_coordinates = pd.DataFrame(
|
|
22
|
+
grid_coordinates, columns=['x', 'y'])
|
|
23
|
+
self.omega = omega
|
|
24
|
+
self.omega_chol = tf.linalg.cholesky(omega).numpy()
|
|
25
|
+
self.dof = dof
|
|
26
|
+
self.parameters = model._get_parameters(parameters)
|
|
27
|
+
self.weights = weights
|
|
28
|
+
self.bar_intensity = bar_intensity
|
|
29
|
+
|
|
30
|
+
if max_intensity is None:
|
|
31
|
+
self.max_intensity = self.bar_intensity
|
|
32
|
+
else:
|
|
33
|
+
self.max_intensity = max_intensity
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if baseline_image is None:
|
|
37
|
+
self.baseline_image = None
|
|
38
|
+
else:
|
|
39
|
+
self.baseline_image = baseline_image.reshape(len(self.grid_coordinates))
|
|
40
|
+
|
|
41
|
+
self.min_x, self.max_x = self.grid_coordinates['x'].min(
|
|
42
|
+
), self.grid_coordinates['x'].max()
|
|
43
|
+
self.min_y, self.max_y = self.grid_coordinates['y'].min(
|
|
44
|
+
), self.grid_coordinates['y'].max()
|
|
45
|
+
|
|
46
|
+
if max_radius is None:
|
|
47
|
+
self.max_radius = np.sqrt(
|
|
48
|
+
np.max(self.grid_coordinates['x'])**2 + np.max(self.grid_coordinates['y'])**2)
|
|
49
|
+
else:
|
|
50
|
+
self.max_radius = max_radius
|
|
51
|
+
|
|
52
|
+
if max_width is None:
|
|
53
|
+
self.max_width = .5 * self.max_radius
|
|
54
|
+
else:
|
|
55
|
+
self.max_width = max_width
|
|
56
|
+
|
|
57
|
+
self.max_radius = np.float32(self.max_radius)
|
|
58
|
+
self.max_width = np.float32(self.max_width)
|
|
59
|
+
|
|
60
|
+
def fit_grid(self, x, y, width, parameterization='xy', include_xy=True):
|
|
61
|
+
|
|
62
|
+
if parameterization == 'xy':
|
|
63
|
+
|
|
64
|
+
grid = pd.MultiIndex.from_product(
|
|
65
|
+
[x, y, width], names=['x', 'y', 'width']).to_frame(index=False).astype(np.float32)
|
|
66
|
+
|
|
67
|
+
logging.info('Built grid of {len(par_grid)} bar settings...')
|
|
68
|
+
|
|
69
|
+
bars = make_bar_stimuli(self.grid_coordinates.values,
|
|
70
|
+
grid['x'].values[np.newaxis, ...],
|
|
71
|
+
grid['y'].values[np.newaxis, ...],
|
|
72
|
+
grid['width'].values[np.newaxis, ...],
|
|
73
|
+
intensity=self.bar_intensity)[0]
|
|
74
|
+
|
|
75
|
+
if self.baseline_image is not None:
|
|
76
|
+
bars = bars + self.baseline_image[tf.newaxis, ...]
|
|
77
|
+
bars = tf.clip_by_value(bars, 0, self.max_intensity)
|
|
78
|
+
|
|
79
|
+
else:
|
|
80
|
+
raise NotImplementedError
|
|
81
|
+
|
|
82
|
+
return self._fit_grid(grid, bars)
|
|
83
|
+
|
|
84
|
+
def _fit_grid(self, grid, bars):
|
|
85
|
+
|
|
86
|
+
data = self.data.values
|
|
87
|
+
model = self.model
|
|
88
|
+
parameters = self.parameters.values[np.newaxis, ...]
|
|
89
|
+
weights = None if self.weights is None else self.weights.values[np.newaxis, ...]
|
|
90
|
+
|
|
91
|
+
if hasattr(self.model, 'hrf_model'):
|
|
92
|
+
|
|
93
|
+
bars = tf.concat((tf.zeros((bars.shape[0],
|
|
94
|
+
1,
|
|
95
|
+
bars.shape[1])),
|
|
96
|
+
bars[:, tf.newaxis, :],
|
|
97
|
+
tf.zeros((bars.shape[0],
|
|
98
|
+
len(self.model.hrf_model.hrf)-1,
|
|
99
|
+
bars.shape[1]))),
|
|
100
|
+
1)
|
|
101
|
+
|
|
102
|
+
hrf_shift = np.argmax(model.hrf_model.hrf)
|
|
103
|
+
|
|
104
|
+
ts_prediction = model._predict(bars, parameters, weights)
|
|
105
|
+
|
|
106
|
+
baseline = ts_prediction[:, 0, :]
|
|
107
|
+
|
|
108
|
+
ts_prediction_summed_over_hrf = tf.reduce_sum(
|
|
109
|
+
ts_prediction - baseline[:, tf.newaxis, :], 1) / tf.reduce_sum(model.hrf_model.hrf) + baseline
|
|
110
|
+
|
|
111
|
+
ll = self.model._likelihood_timeseries(data[tf.newaxis, ...],
|
|
112
|
+
ts_prediction_summed_over_hrf[:,
|
|
113
|
+
tf.newaxis, :],
|
|
114
|
+
self.omega_chol,
|
|
115
|
+
self.dof,
|
|
116
|
+
logp=True,
|
|
117
|
+
normalize=False)
|
|
118
|
+
|
|
119
|
+
ll = tf.concat((tf.roll(ll, -hrf_shift, 1)
|
|
120
|
+
[:, :-hrf_shift], tf.ones((len(bars), hrf_shift)) * -1e12), 1)
|
|
121
|
+
|
|
122
|
+
else:
|
|
123
|
+
bars = bars[:, tf.newaxis, :]
|
|
124
|
+
|
|
125
|
+
ll = self.model._likelihood(bars, data[tf.newaxis, ...], parameters, weights,
|
|
126
|
+
self.omega_chol, self.dof, logp=True)
|
|
127
|
+
ll = pd.DataFrame(ll.numpy().T, columns=pd.MultiIndex.from_frame(grid))
|
|
128
|
+
|
|
129
|
+
best_pars = ll.columns.to_frame().iloc[ll.values.argmax(1)]
|
|
130
|
+
best_pars.index = self.data.index
|
|
131
|
+
|
|
132
|
+
if 'x' not in best_pars.columns:
|
|
133
|
+
best_pars['x'] = np.cos(best_pars['angle']) * best_pars['radius']
|
|
134
|
+
best_pars['y'] = np.sin(best_pars['angle']) * best_pars['radius']
|
|
135
|
+
|
|
136
|
+
if 'angle' not in best_pars.columns:
|
|
137
|
+
best_pars = get_angle_radius_from_xy(best_pars)
|
|
138
|
+
|
|
139
|
+
return best_pars.astype(np.float32)
|
|
140
|
+
|
|
141
|
+
def fit(self, init_pars, learning_rate=0.01, max_n_iterations=500, min_n_iterations=100, lag=100,
|
|
142
|
+
relevant_frames=None, rtol=1e-7, parameterization='xy', include_xy=True):
|
|
143
|
+
|
|
144
|
+
opt = tf.optimizers.Adam(learning_rate=learning_rate)
|
|
145
|
+
|
|
146
|
+
# init_pars: x, y, width
|
|
147
|
+
|
|
148
|
+
if parameterization == 'xy':
|
|
149
|
+
if hasattr(init_pars, 'values'):
|
|
150
|
+
init_pars = init_pars[['x', 'y', 'width']].values
|
|
151
|
+
|
|
152
|
+
if np.any(init_pars[:, 0] < self.min_x):
|
|
153
|
+
raise ValueError(
|
|
154
|
+
f'All x-values should not be less than {self.min_x}')
|
|
155
|
+
|
|
156
|
+
if np.any(init_pars[:, 0] > self.max_x):
|
|
157
|
+
raise ValueError(
|
|
158
|
+
f'All x-values should not be more than {self.max_x}')
|
|
159
|
+
|
|
160
|
+
if np.any(init_pars[:, 1] < self.min_y):
|
|
161
|
+
raise ValueError(
|
|
162
|
+
f'All y-values should not be less than {self.min_y}')
|
|
163
|
+
|
|
164
|
+
if np.any(init_pars[:, 1] > self.max_y):
|
|
165
|
+
raise ValueError(
|
|
166
|
+
f'All y-values should not be more than {self.max_y}')
|
|
167
|
+
|
|
168
|
+
if np.any(np.abs(init_pars[:, 2]) < 0.0):
|
|
169
|
+
raise ValueError('All widths should be positive')
|
|
170
|
+
|
|
171
|
+
if np.any(np.abs(init_pars[:, 2]) > self.max_width):
|
|
172
|
+
raise ValueError(
|
|
173
|
+
f'All widths should be less than {self.max_width}')
|
|
174
|
+
|
|
175
|
+
if (relevant_frames is not None) and (len(init_pars) > len(relevant_frames)):
|
|
176
|
+
init_pars = init_pars[relevant_frames, :]
|
|
177
|
+
|
|
178
|
+
x_bijector = Periodic(low=np.float32(self.min_x - self.max_width/2.),
|
|
179
|
+
high=np.float32(self.max_x + self.max_width/2.))
|
|
180
|
+
|
|
181
|
+
y_bijector = Periodic(low=np.float32(self.min_y - self.max_width/2.),
|
|
182
|
+
high=np.float32(self.max_y + self.max_width/2.))
|
|
183
|
+
|
|
184
|
+
x_ = tf.Variable(name='x',
|
|
185
|
+
shape=len(init_pars),
|
|
186
|
+
initial_value=init_pars[:, 0])
|
|
187
|
+
|
|
188
|
+
y_ = tf.Variable(name='y',
|
|
189
|
+
shape=len(init_pars),
|
|
190
|
+
initial_value=init_pars[:, 1])
|
|
191
|
+
|
|
192
|
+
elif parameterization == 'angle':
|
|
193
|
+
|
|
194
|
+
if hasattr(init_pars, 'values'):
|
|
195
|
+
init_pars = init_pars[['angle', 'radius', 'width']].values
|
|
196
|
+
|
|
197
|
+
if np.any(init_pars[:, 0] < -.5*np.pi):
|
|
198
|
+
raise ValueError(
|
|
199
|
+
'All angles should be more than -1/2 pi radians')
|
|
200
|
+
|
|
201
|
+
if np.any(init_pars[:, 0] > .5*np.pi):
|
|
202
|
+
raise ValueError(
|
|
203
|
+
'All angles should be less than 1/2 pi radians')
|
|
204
|
+
|
|
205
|
+
if np.any(np.abs(init_pars[:, 1]) > self.max_radius):
|
|
206
|
+
raise ValueError(
|
|
207
|
+
f'All radiuses should be within (-{self.max_radius}, {self.max_radius})')
|
|
208
|
+
|
|
209
|
+
if np.any(np.abs(init_pars[:, 2]) < 0.0):
|
|
210
|
+
raise ValueError('All widths should be positive')
|
|
211
|
+
|
|
212
|
+
if np.any(np.abs(init_pars[:, 2]) > self.max_width):
|
|
213
|
+
raise ValueError(
|
|
214
|
+
f'All widths should be less than {self.max_width}')
|
|
215
|
+
|
|
216
|
+
if (relevant_frames is not None) and (len(init_pars) > len(relevant_frames)):
|
|
217
|
+
init_pars = init_pars[relevant_frames, :]
|
|
218
|
+
|
|
219
|
+
init_pars[:, 0] = tf.clip_by_value(
|
|
220
|
+
init_pars[:, 0], -.5*np.pi + 1e-6, .5 * np.pi-1e-6)
|
|
221
|
+
init_pars[:, 1] = tf.clip_by_value(
|
|
222
|
+
init_pars[:, 1], -self.max_radius + 1e-6, self.max_radius - 1e-6)
|
|
223
|
+
init_pars[:, 2] = tf.clip_by_value(
|
|
224
|
+
init_pars[:, 2], 1e-6, self.max_width - 1e-6)
|
|
225
|
+
|
|
226
|
+
orient_x = tf.Variable(name='orient_x',
|
|
227
|
+
shape=len(init_pars),
|
|
228
|
+
initial_value=np.cos(init_pars[:, 0]))
|
|
229
|
+
|
|
230
|
+
orient_y = tf.Variable(name='orient_y',
|
|
231
|
+
shape=len(init_pars),
|
|
232
|
+
initial_value=np.sin(init_pars[:, 0]))
|
|
233
|
+
|
|
234
|
+
radius_bijector = Periodic(low=np.float32(-self.max_radius),
|
|
235
|
+
high=np.float32(self.max_radius))
|
|
236
|
+
|
|
237
|
+
radius_ = tf.Variable(name='radius',
|
|
238
|
+
shape=len(init_pars),
|
|
239
|
+
initial_value=radius_bijector.inverse(init_pars[:, 1]))
|
|
240
|
+
|
|
241
|
+
else:
|
|
242
|
+
raise NotImplementedError
|
|
243
|
+
|
|
244
|
+
width_bijector = tfb.Sigmoid(low=np.float32(0.0),
|
|
245
|
+
high=np.float32(self.max_width))
|
|
246
|
+
|
|
247
|
+
width_ = tf.Variable(name='width',
|
|
248
|
+
shape=len(init_pars),
|
|
249
|
+
initial_value=width_bijector.inverse(init_pars[:, 2]))
|
|
250
|
+
|
|
251
|
+
if parameterization == 'xy':
|
|
252
|
+
trainable_vars = [x_, y_, width_]
|
|
253
|
+
bijectors = [x_bijector, y_bijector, width_bijector]
|
|
254
|
+
par_names = ['x', 'y', 'width']
|
|
255
|
+
elif parameterization == 'angle':
|
|
256
|
+
trainable_vars = [orient_x, orient_y, radius_, width_]
|
|
257
|
+
bijectors = [tfb.Identity(), tfb.Identity(),
|
|
258
|
+
radius_bijector, width_bijector]
|
|
259
|
+
par_names = ['orient_x', 'orient_y', 'radius', 'width']
|
|
260
|
+
|
|
261
|
+
pbar = tqdm(range(max_n_iterations))
|
|
262
|
+
self.costs = np.ones(max_n_iterations) * 1e12
|
|
263
|
+
|
|
264
|
+
likelihood = self.build_likelihood_function(relevant_frames, parameterization=parameterization)
|
|
265
|
+
|
|
266
|
+
for step in pbar:
|
|
267
|
+
with tf.GradientTape() as tape:
|
|
268
|
+
|
|
269
|
+
untransformed_pars = [bijector.forward(
|
|
270
|
+
par) for bijector, par in zip(bijectors, trainable_vars)]
|
|
271
|
+
ll = likelihood(*untransformed_pars)[0]
|
|
272
|
+
cost = -ll
|
|
273
|
+
|
|
274
|
+
gradients = tape.gradient(cost,
|
|
275
|
+
trainable_vars)
|
|
276
|
+
|
|
277
|
+
opt.apply_gradients(zip(gradients, trainable_vars))
|
|
278
|
+
|
|
279
|
+
pbar.set_description(f'LL: {ll:6.4f}')
|
|
280
|
+
|
|
281
|
+
self.costs[step] = cost.numpy()
|
|
282
|
+
|
|
283
|
+
previous_cost = self.costs[np.max((step - lag, 0))]
|
|
284
|
+
if step > min_n_iterations:
|
|
285
|
+
if np.sign(previous_cost) == np.sign(cost):
|
|
286
|
+
if np.sign(cost) == 1:
|
|
287
|
+
if (cost / previous_cost) > 1 - rtol:
|
|
288
|
+
break
|
|
289
|
+
else:
|
|
290
|
+
if (cost / previous_cost) < 1 - rtol:
|
|
291
|
+
break
|
|
292
|
+
|
|
293
|
+
fitted_pars_ = np.concatenate(
|
|
294
|
+
[par.numpy()[:, np.newaxis] for par in untransformed_pars], axis=1)
|
|
295
|
+
|
|
296
|
+
if relevant_frames is None:
|
|
297
|
+
fitted_pars = pd.DataFrame(fitted_pars_, columns=par_names,
|
|
298
|
+
index=self.data.index,
|
|
299
|
+
dtype=np.float32)
|
|
300
|
+
else:
|
|
301
|
+
|
|
302
|
+
fitted_pars = pd.DataFrame(np.nan * np.zeros((self.data.shape[0], len(trainable_vars))), columns=par_names,
|
|
303
|
+
index=self.data.index,
|
|
304
|
+
dtype=np.float32)
|
|
305
|
+
fitted_pars.iloc[relevant_frames, :] = fitted_pars_
|
|
306
|
+
|
|
307
|
+
print(fitted_pars)
|
|
308
|
+
if parameterization == 'xy':
|
|
309
|
+
fitted_pars = get_angle_radius_from_xy(fitted_pars)
|
|
310
|
+
|
|
311
|
+
elif parameterization == 'angle':
|
|
312
|
+
print(relevant_frames)
|
|
313
|
+
fitted_pars.at[relevant_frames, 'angle'] = tf.math.atan(orient_y / orient_x).numpy()
|
|
314
|
+
fitted_pars['x'] = np.cos(
|
|
315
|
+
fitted_pars['angle']) * fitted_pars['radius']
|
|
316
|
+
fitted_pars['y'] = np.sin(
|
|
317
|
+
fitted_pars['angle']) * fitted_pars['radius']
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
return fitted_pars
|
|
321
|
+
|
|
322
|
+
def build_likelihood_function(self, relevant_frames=None, falloff_speed=1000., parameterization='xy', n_batches=1):
|
|
323
|
+
|
|
324
|
+
data = self.data.values[tf.newaxis, ...]
|
|
325
|
+
grid_coordinates = self.grid_coordinates
|
|
326
|
+
model = self.model
|
|
327
|
+
parameters = self.parameters.values[tf.newaxis, ...]
|
|
328
|
+
weights = None if self.weights is None else self.weights.values[tf.newaxis, ...]
|
|
329
|
+
|
|
330
|
+
if self.baseline_image is None:
|
|
331
|
+
@tf.function
|
|
332
|
+
def add_baseline(bars):
|
|
333
|
+
return bars
|
|
334
|
+
else:
|
|
335
|
+
print('Including base image (e.g., fixation image) into estimation')
|
|
336
|
+
@tf.function
|
|
337
|
+
def add_baseline(bars):
|
|
338
|
+
bars = bars + self.baseline_image[tf.newaxis, :]
|
|
339
|
+
bars = tf.clip_by_value(bars, 0, self.max_intensity)
|
|
340
|
+
return bars
|
|
341
|
+
|
|
342
|
+
if relevant_frames is None:
|
|
343
|
+
|
|
344
|
+
if parameterization == 'xy':
|
|
345
|
+
@tf.function
|
|
346
|
+
def likelihood(x, y, width):
|
|
347
|
+
|
|
348
|
+
bars = make_bar_stimuli(
|
|
349
|
+
grid_coordinates,
|
|
350
|
+
x[tf.newaxis, ...],
|
|
351
|
+
y[tf.newaxis, ...],
|
|
352
|
+
width[tf.newaxis, ...],
|
|
353
|
+
falloff_speed=falloff_speed,
|
|
354
|
+
intensity=self.bar_intensity)
|
|
355
|
+
|
|
356
|
+
bars = add_baseline(bars)
|
|
357
|
+
|
|
358
|
+
ll = self.model._likelihood(
|
|
359
|
+
bars, data, parameters, weights, self.omega_chol, dof=self.dof, logp=True)
|
|
360
|
+
|
|
361
|
+
return tf.reduce_sum(ll, 1)
|
|
362
|
+
|
|
363
|
+
elif parameterization == 'angle':
|
|
364
|
+
@tf.function
|
|
365
|
+
def likelihood(orient_x, orient_y, radius, width):
|
|
366
|
+
|
|
367
|
+
angle = tf.math.atan(orient_y/orient_x)
|
|
368
|
+
|
|
369
|
+
bars = make_bar_stimuli2(
|
|
370
|
+
grid_coordinates,
|
|
371
|
+
angle[tf.newaxis, ...],
|
|
372
|
+
radius[tf.newaxis, ...],
|
|
373
|
+
width[tf.newaxis, ...],
|
|
374
|
+
falloff_speed=falloff_speed,
|
|
375
|
+
intensity=self.bar_intensity)
|
|
376
|
+
|
|
377
|
+
bars = add_baseline(bars)
|
|
378
|
+
|
|
379
|
+
ll = self.model._likelihood(
|
|
380
|
+
bars, data, parameters, weights, self.omega_chol, dof=self.dof, logp=True)
|
|
381
|
+
|
|
382
|
+
return tf.reduce_sum(ll, 1)
|
|
383
|
+
else:
|
|
384
|
+
raise NotImplementedError
|
|
385
|
+
|
|
386
|
+
else:
|
|
387
|
+
relevant_frames = tf.constant(relevant_frames, tf.int32)
|
|
388
|
+
|
|
389
|
+
size_ = (n_batches, data.shape[1], len(grid_coordinates))
|
|
390
|
+
size_ = tf.constant(size_, dtype=tf.int32)
|
|
391
|
+
|
|
392
|
+
time_ix, batch_ix = np.meshgrid(relevant_frames, range(n_batches))
|
|
393
|
+
indices = np.zeros(
|
|
394
|
+
(n_batches, len(relevant_frames), 2), dtype=np.int32)
|
|
395
|
+
indices[..., 0] = batch_ix
|
|
396
|
+
indices[..., 1] = time_ix
|
|
397
|
+
|
|
398
|
+
if parameterization == 'xy':
|
|
399
|
+
@tf.function
|
|
400
|
+
def likelihood(x,
|
|
401
|
+
y,
|
|
402
|
+
width):
|
|
403
|
+
|
|
404
|
+
bars = make_bar_stimuli(
|
|
405
|
+
grid_coordinates.values, x, y, width,
|
|
406
|
+
falloff_speed=falloff_speed,
|
|
407
|
+
intensity=self.bar_intensity)
|
|
408
|
+
|
|
409
|
+
bars = add_baseline(bars)
|
|
410
|
+
|
|
411
|
+
stimulus = tf.scatter_nd(indices,
|
|
412
|
+
bars,
|
|
413
|
+
size_)
|
|
414
|
+
|
|
415
|
+
ll = self.model._likelihood(
|
|
416
|
+
stimulus, data, parameters, weights, self.omega_chol, dof=self.dof, logp=True)
|
|
417
|
+
|
|
418
|
+
sll = tf.reduce_sum(ll, 1)
|
|
419
|
+
|
|
420
|
+
return sll
|
|
421
|
+
|
|
422
|
+
elif parameterization == 'angle':
|
|
423
|
+
|
|
424
|
+
@tf.function
|
|
425
|
+
def likelihood(orient_x,
|
|
426
|
+
orient_y,
|
|
427
|
+
radius,
|
|
428
|
+
width):
|
|
429
|
+
|
|
430
|
+
angle = tf.math.atan(orient_y/orient_x)
|
|
431
|
+
|
|
432
|
+
bars = make_bar_stimuli2(
|
|
433
|
+
grid_coordinates,
|
|
434
|
+
angle[tf.newaxis, ...],
|
|
435
|
+
radius[tf.newaxis, ...],
|
|
436
|
+
width[tf.newaxis, ...],
|
|
437
|
+
falloff_speed=falloff_speed,
|
|
438
|
+
intensity=self.bar_intensity)
|
|
439
|
+
|
|
440
|
+
bars = add_baseline(bars)
|
|
441
|
+
|
|
442
|
+
stimulus = tf.scatter_nd(indices,
|
|
443
|
+
bars,
|
|
444
|
+
size_)
|
|
445
|
+
|
|
446
|
+
ll = self.model._likelihood(
|
|
447
|
+
stimulus, data, parameters, weights, self.omega_chol, dof=self.dof, logp=True)
|
|
448
|
+
|
|
449
|
+
sll = tf.reduce_sum(ll, 1)
|
|
450
|
+
|
|
451
|
+
return sll
|
|
452
|
+
|
|
453
|
+
return likelihood
|
|
454
|
+
|
|
455
|
+
def sample_posterior(self,
|
|
456
|
+
init_pars,
|
|
457
|
+
n_chains,
|
|
458
|
+
relevant_frames=None,
|
|
459
|
+
step_size=0.0001,
|
|
460
|
+
n_burnin=10,
|
|
461
|
+
n_samples=10,
|
|
462
|
+
max_tree_depth=10,
|
|
463
|
+
unrolled_leapfrog_steps=1,
|
|
464
|
+
falloff_speed=1000.,
|
|
465
|
+
target_accept_prob=0.85,
|
|
466
|
+
parameterization='xy'):
|
|
467
|
+
|
|
468
|
+
init_pars = init_pars.astype(np.float32)
|
|
469
|
+
|
|
470
|
+
if (relevant_frames is not None) and (len(init_pars) > len(relevant_frames)):
|
|
471
|
+
init_pars = init_pars.iloc[relevant_frames, :]
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
if parameterization == 'xy':
|
|
475
|
+
|
|
476
|
+
init_pars = init_pars[['x', 'y', 'width']]
|
|
477
|
+
|
|
478
|
+
bijectors = [Periodic(low=self.min_x - self.max_width/2.,
|
|
479
|
+
high=self.max_x + self.max_width/2.), # x
|
|
480
|
+
Periodic(low=self.min_y - self.max_width/2.,
|
|
481
|
+
high=self.max_y + self.max_width/2.),
|
|
482
|
+
tfb.Sigmoid(low=np.float32(0.0), high=self.max_width)] # width
|
|
483
|
+
|
|
484
|
+
initial_state = list(
|
|
485
|
+
np.repeat(init_pars.values.T[:, np.newaxis, :], n_chains, 1))
|
|
486
|
+
|
|
487
|
+
likelihood = self.build_likelihood_function(
|
|
488
|
+
relevant_frames, falloff_speed=falloff_speed, n_batches=n_chains, parameterization=parameterization)
|
|
489
|
+
|
|
490
|
+
step_size = [tf.fill([n_chains] + [1] * (len(s.shape) - 1),
|
|
491
|
+
tf.constant(step_size, np.float32)) for s in initial_state]
|
|
492
|
+
samples, stats = sample_hmc(
|
|
493
|
+
initial_state, step_size, likelihood, bijectors, num_steps=n_samples, burnin=n_burnin,
|
|
494
|
+
target_accept_prob=target_accept_prob, unrolled_leapfrog_steps=unrolled_leapfrog_steps,
|
|
495
|
+
max_tree_depth=max_tree_depth)
|
|
496
|
+
|
|
497
|
+
if relevant_frames is None:
|
|
498
|
+
frame_index = self.data.index
|
|
499
|
+
else:
|
|
500
|
+
frame_index = self.data.index[relevant_frames]
|
|
501
|
+
|
|
502
|
+
cleaned_up_chains = [cleanup_chain(chain.numpy(), init_pars.columns[ix], frame_index) for ix, chain in enumerate(samples)]
|
|
503
|
+
|
|
504
|
+
samples = pd.concat(cleaned_up_chains, 1)
|
|
505
|
+
|
|
506
|
+
return samples, stats
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
@tf.function
|
|
510
|
+
def make_bar_stimuli(grid_coordinates, x, y, width, falloff_speed=1000., intensity=1.0):
|
|
511
|
+
|
|
512
|
+
x_ = grid_coordinates[:, 0]
|
|
513
|
+
y_ = grid_coordinates[:, 1]
|
|
514
|
+
|
|
515
|
+
radius2 = x**2 + y**2
|
|
516
|
+
radius = tf.math.sqrt(radius2)
|
|
517
|
+
a = x / radius
|
|
518
|
+
b = y / radius
|
|
519
|
+
c = -radius2 / radius
|
|
520
|
+
|
|
521
|
+
distance = tf.abs(a[..., tf.newaxis] * x_[tf.newaxis, tf.newaxis, ...] +
|
|
522
|
+
b[..., tf.newaxis] * y_[tf.newaxis, tf.newaxis, ...] +
|
|
523
|
+
c[..., tf.newaxis]) / tf.sqrt(a[..., tf.newaxis]**2 + b[..., tf.newaxis]**2)
|
|
524
|
+
|
|
525
|
+
bar = tf.math.sigmoid(
|
|
526
|
+
(-distance + width[..., tf.newaxis] / 2) * falloff_speed) * intensity
|
|
527
|
+
|
|
528
|
+
return bar
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
@tf.function
|
|
532
|
+
def make_bar_stimuli2(grid_coordinates, angle, radius, width, falloff_speed=1000., intensity=1.0):
|
|
533
|
+
|
|
534
|
+
# batch x stimulus x stimulus_dimension
|
|
535
|
+
|
|
536
|
+
x = grid_coordinates[:, 0]
|
|
537
|
+
y = grid_coordinates[:, 1]
|
|
538
|
+
|
|
539
|
+
a = tf.cos(angle)
|
|
540
|
+
b = tf.sin(angle)
|
|
541
|
+
c = tf.sqrt(a**2 + b**2) * - radius
|
|
542
|
+
|
|
543
|
+
distance = tf.abs(a[..., tf.newaxis] * x[tf.newaxis, tf.newaxis, ...] +
|
|
544
|
+
b[..., tf.newaxis] * y[tf.newaxis, tf.newaxis, ...] +
|
|
545
|
+
c[..., tf.newaxis]) / tf.sqrt(a[..., tf.newaxis]**2 + b[..., tf.newaxis]**2)
|
|
546
|
+
|
|
547
|
+
bar = tf.math.sigmoid(
|
|
548
|
+
(-distance + width[..., tf.newaxis] / 2) * falloff_speed) * intensity
|
|
549
|
+
|
|
550
|
+
return bar
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def get_angle_radius_from_xy(d):
|
|
554
|
+
d = d.assign(angle=np.arctan2(d['y'], d['x']))
|
|
555
|
+
d = d.assign(radius=np.sqrt(d['y']**2 + d['x']**2))
|
|
556
|
+
d = d.assign(ecc=np.abs(d['radius']))
|
|
557
|
+
|
|
558
|
+
return constrain_angle(d)
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def constrain_angle(d):
|
|
563
|
+
|
|
564
|
+
pi5 = .5 * np.pi
|
|
565
|
+
d = d.assign(radius=d['radius'].where(d['angle'].abs() < pi5, -d['radius']))
|
|
566
|
+
d = d.assign(angle=d['angle'].where(d['angle'] < pi5, d['angle'] - np.pi))
|
|
567
|
+
d = d.assign(angle=d['angle'].where(d['angle'] > -pi5, d['angle'] + np.pi))
|
|
568
|
+
|
|
569
|
+
return d
|
|
Binary file
|