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/utils/math.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
import keras
|
|
4
|
+
from keras import ops
|
|
5
|
+
|
|
6
|
+
from .backend import softplus_inverse
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# np.trapezoid was added in NumPy 2.0 (replacing np.trapz, which was
|
|
10
|
+
# removed in 2.0). Pick whichever is available so the package works on
|
|
11
|
+
# both old cluster installs (1.x → only trapz) and current ones
|
|
12
|
+
# (2.x → only trapezoid).
|
|
13
|
+
if hasattr(np, 'trapezoid'):
|
|
14
|
+
_trapezoid = np.trapezoid
|
|
15
|
+
else:
|
|
16
|
+
_trapezoid = np.trapz
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def norm(x, mu, sigma):
|
|
20
|
+
kernel = ops.exp(-.5 * (x - mu)**2. / sigma**2)
|
|
21
|
+
return kernel
|
|
22
|
+
|
|
23
|
+
def norm2d(x, y, mu_x, mu_y, sigma_x, sigma_y, rho=None):
|
|
24
|
+
if rho is None:
|
|
25
|
+
rho = 0.0
|
|
26
|
+
z = ((x - mu_x) ** 2 / sigma_x ** 2) + \
|
|
27
|
+
((y - mu_y) ** 2 / sigma_y ** 2) - \
|
|
28
|
+
(2 * rho * (x - mu_x) * (y - mu_y) / (sigma_x * sigma_y))
|
|
29
|
+
kernel = ops.exp(-z / (2 * (1 - rho ** 2)))
|
|
30
|
+
return kernel
|
|
31
|
+
|
|
32
|
+
def logit(x):
|
|
33
|
+
""" Computes the logit function, i.e. the logistic sigmoid inverse. """
|
|
34
|
+
return ops.clip(-ops.log(1. / x - 1.), -1e12, 1e12)
|
|
35
|
+
|
|
36
|
+
def logistic_transfer(x, lower_bound, upper_bound):
|
|
37
|
+
return lower_bound + (upper_bound - lower_bound) / (1 + ops.exp(-x))
|
|
38
|
+
|
|
39
|
+
def log2(x):
|
|
40
|
+
return ops.log(x) / ops.log(ops.convert_to_tensor(2.))
|
|
41
|
+
|
|
42
|
+
def restrict_radians(x):
|
|
43
|
+
x = x + np.pi
|
|
44
|
+
return x - ops.floor(x / (2*np.pi)) * 2*np.pi - np.pi
|
|
45
|
+
|
|
46
|
+
def lognormalpdf_n(x, mu_n, sigma_n, normalize=False):
|
|
47
|
+
|
|
48
|
+
denom = 1 + sigma_n**2/mu_n**2
|
|
49
|
+
|
|
50
|
+
part2 = ops.exp(-((ops.log(x) - ops.log(mu_n / ops.sqrt(denom)))**2 / (2*ops.log(denom))))
|
|
51
|
+
|
|
52
|
+
if normalize:
|
|
53
|
+
part1 = 1. / (x*ops.sqrt(2*np.pi*ops.log(denom)))
|
|
54
|
+
return part1*part2
|
|
55
|
+
else:
|
|
56
|
+
return part2
|
|
57
|
+
|
|
58
|
+
def lognormal_pdf_mode_fwhm(x, mode, fwhm):
|
|
59
|
+
|
|
60
|
+
sigma = 1./(ops.sqrt(2.*ops.log(ops.convert_to_tensor(2.)))) * ops.arcsinh(fwhm/(mode*2.))
|
|
61
|
+
sigma2 = sigma**2
|
|
62
|
+
p = (mode / x) * ops.exp(.5*sigma2 - .5 *((ops.log(x/mode) - sigma2)**2)/sigma2)
|
|
63
|
+
|
|
64
|
+
return p
|
|
65
|
+
|
|
66
|
+
def von_mises_pdf(x, mu, kappa):
|
|
67
|
+
from .backend import bessel_i0
|
|
68
|
+
TWO_PI = 2 * np.pi
|
|
69
|
+
pdf = ops.exp(kappa * ops.cos(x - mu)) / (TWO_PI * bessel_i0(kappa))
|
|
70
|
+
return pdf
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def axial_von_mises_pdf(x, mu, kappa):
|
|
74
|
+
"""Von Mises PDF for axial (π-periodic) data such as gabor orientations.
|
|
75
|
+
|
|
76
|
+
Orientations are π-periodic: 0° and 180° represent the same stimulus.
|
|
77
|
+
The standard Von Mises uses cos(x − μ), which is 2π-periodic and therefore
|
|
78
|
+
incorrect for orientation space. The axial Von Mises doubles the angle:
|
|
79
|
+
|
|
80
|
+
f(x; μ, κ) = exp(κ · cos(2(x − μ))) / (π · I₀(κ))
|
|
81
|
+
|
|
82
|
+
This gives a distribution that is π-periodic, with peaks at x = μ and
|
|
83
|
+
x = μ + π, correctly treating 0° and 180° as equivalent.
|
|
84
|
+
|
|
85
|
+
Parameters
|
|
86
|
+
----------
|
|
87
|
+
x : stimulus orientation in radians, in [0, π)
|
|
88
|
+
mu : preferred orientation in radians, in [0, π)
|
|
89
|
+
kappa : concentration parameter (≥ 0); higher = sharper tuning
|
|
90
|
+
"""
|
|
91
|
+
from .backend import bessel_i0
|
|
92
|
+
TWO = np.float32(2.0)
|
|
93
|
+
PI = np.float32(np.pi)
|
|
94
|
+
pdf = ops.exp(kappa * ops.cos(TWO * (x - mu))) / (PI * bessel_i0(kappa))
|
|
95
|
+
return pdf
|
|
96
|
+
|
|
97
|
+
# Aggressive softplus with alpha=100
|
|
98
|
+
alpha = 100
|
|
99
|
+
aggressive_softplus = lambda x: (1./alpha) * ops.softplus(alpha*x)
|
|
100
|
+
aggressive_softplus_inverse = lambda y: (1./alpha) * softplus_inverse(alpha * y)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def get_expected_value(stimulus_pdf, normalize=True):
|
|
104
|
+
|
|
105
|
+
x = stimulus_pdf.columns.astype(np.float32)
|
|
106
|
+
|
|
107
|
+
if normalize:
|
|
108
|
+
stimulus_pdf /= _trapezoid(stimulus_pdf, x=x, axis=1)[:, np.newaxis]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
E = _trapezoid(stimulus_pdf * x, x=x, axis=1)
|
|
112
|
+
|
|
113
|
+
return pd.Series(E, name='E', index=stimulus_pdf.index)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def get_sd_posterior(stimulus_pdf, E=None, normalize=True):
|
|
117
|
+
|
|
118
|
+
x = stimulus_pdf.columns.astype(np.float32).values
|
|
119
|
+
|
|
120
|
+
if normalize:
|
|
121
|
+
stimulus_pdf /= _trapezoid(stimulus_pdf, x=x, axis=1)[:, np.newaxis]
|
|
122
|
+
|
|
123
|
+
if E is None:
|
|
124
|
+
E = get_expected_value(stimulus_pdf, normalize=normalize).values
|
|
125
|
+
else:
|
|
126
|
+
if hasattr(E, 'values'):
|
|
127
|
+
E = E.values
|
|
128
|
+
|
|
129
|
+
sd = np.sqrt(_trapezoid(stimulus_pdf * (x[np.newaxis, :] - E[:, np.newaxis]) ** 2, x=x, axis=1))
|
|
130
|
+
|
|
131
|
+
return pd.Series(sd, name='sd', index=stimulus_pdf.index)
|
braincoder/utils/mcmc.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import tensorflow as tf
|
|
2
|
+
import tensorflow_probability as tfp
|
|
3
|
+
from tensorflow_probability import bijectors as tfb
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from timeit import default_timer as timer
|
|
6
|
+
|
|
7
|
+
def cleanup_chain(chain, name, time_index):
|
|
8
|
+
|
|
9
|
+
n_chains = chain.shape[1]
|
|
10
|
+
n_samples = chain.shape[0]
|
|
11
|
+
|
|
12
|
+
chain_index = pd.Index(range(n_chains), name='chain')
|
|
13
|
+
|
|
14
|
+
if not issubclass(type(time_index), pd.core.indexes.base.Index):
|
|
15
|
+
time_index = pd.Index(frames, name='frame')
|
|
16
|
+
else:
|
|
17
|
+
time_index = time_index
|
|
18
|
+
|
|
19
|
+
sample_index = pd.Index(range(n_samples), name='sample')
|
|
20
|
+
|
|
21
|
+
chain = [pd.DataFrame(chain[:, ix, :], index=sample_index,
|
|
22
|
+
columns=time_index) for ix in range(n_chains)]
|
|
23
|
+
chain = pd.concat(chain, keys=chain_index)
|
|
24
|
+
|
|
25
|
+
return chain.stack(list(range(chain.columns.nlevels))).to_frame(name).sort_index()
|
|
26
|
+
|
|
27
|
+
@tf.function
|
|
28
|
+
def sample_hmc(
|
|
29
|
+
init_state,
|
|
30
|
+
step_size,
|
|
31
|
+
target_log_prob_fn,
|
|
32
|
+
unconstraining_bijectors,
|
|
33
|
+
target_accept_prob=0.85,
|
|
34
|
+
unrolled_leapfrog_steps=1,
|
|
35
|
+
max_tree_depth=10,
|
|
36
|
+
num_steps=50,
|
|
37
|
+
burnin=50):
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def trace_fn(_, pkr):
|
|
41
|
+
return {
|
|
42
|
+
'log_prob': pkr.inner_results.inner_results.target_log_prob,
|
|
43
|
+
'diverging': pkr.inner_results.inner_results.has_divergence,
|
|
44
|
+
'is_accepted': pkr.inner_results.inner_results.is_accepted,
|
|
45
|
+
'accept_ratio': tf.exp(pkr.inner_results.inner_results.log_accept_ratio),
|
|
46
|
+
'leapfrogs_taken': pkr.inner_results.inner_results.leapfrogs_taken,
|
|
47
|
+
'step_size': pkr.inner_results.inner_results.step_size}
|
|
48
|
+
|
|
49
|
+
hmc = tfp.mcmc.NoUTurnSampler(
|
|
50
|
+
target_log_prob_fn,
|
|
51
|
+
unrolled_leapfrog_steps=unrolled_leapfrog_steps,
|
|
52
|
+
max_tree_depth=max_tree_depth,
|
|
53
|
+
step_size=step_size)
|
|
54
|
+
|
|
55
|
+
hmc = tfp.mcmc.TransformedTransitionKernel(
|
|
56
|
+
inner_kernel=hmc,
|
|
57
|
+
bijector=unconstraining_bijectors)
|
|
58
|
+
|
|
59
|
+
adaptive_sampler = tfp.mcmc.DualAveragingStepSizeAdaptation(
|
|
60
|
+
inner_kernel=hmc,
|
|
61
|
+
num_adaptation_steps=int(0.8 * burnin),
|
|
62
|
+
target_accept_prob=target_accept_prob,
|
|
63
|
+
# NUTS inside of a TTK requires custom getter/setter functions.
|
|
64
|
+
step_size_setter_fn=lambda pkr, new_step_size: pkr._replace(
|
|
65
|
+
inner_results=pkr.inner_results._replace(
|
|
66
|
+
step_size=new_step_size)
|
|
67
|
+
),
|
|
68
|
+
step_size_getter_fn=lambda pkr: pkr.inner_results.step_size,
|
|
69
|
+
log_accept_prob_getter_fn=lambda pkr: pkr.inner_results.log_accept_ratio,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
start = timer()
|
|
73
|
+
# Sampling from the chain.
|
|
74
|
+
samples, stats = tfp.mcmc.sample_chain(
|
|
75
|
+
num_results=burnin + num_steps,
|
|
76
|
+
current_state=init_state,
|
|
77
|
+
kernel=adaptive_sampler,
|
|
78
|
+
trace_fn=trace_fn)
|
|
79
|
+
|
|
80
|
+
duration = timer() - start
|
|
81
|
+
stats['elapsed_time'] = duration
|
|
82
|
+
|
|
83
|
+
return samples, stats
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Periodic(tfb.Bijector):
|
|
88
|
+
|
|
89
|
+
def __init__(self, low, high, validate_args=False, name='periodic'):
|
|
90
|
+
|
|
91
|
+
self.low = low
|
|
92
|
+
self.high = high
|
|
93
|
+
self.width = high - low
|
|
94
|
+
|
|
95
|
+
super(Periodic, self).__init__(
|
|
96
|
+
is_constant_jacobian=True,
|
|
97
|
+
validate_args=validate_args,
|
|
98
|
+
forward_min_event_ndims=0,
|
|
99
|
+
name=name)
|
|
100
|
+
|
|
101
|
+
def _forward(self, x):
|
|
102
|
+
return ((x - self.low) % self.width) + self.low
|
|
103
|
+
|
|
104
|
+
def _inverse(self, y):
|
|
105
|
+
return y
|
|
106
|
+
|
|
107
|
+
# def _inverse_log_det_jacobian(self, y):
|
|
108
|
+
# return -self._forward_log_det_jacobian(self._inverse(y))
|
|
109
|
+
|
|
110
|
+
# def _forward_log_det_jacobian(self, x):
|
|
111
|
+
# # The full log jacobian determinant would be tf.zero_like(x).
|
|
112
|
+
# # However, we circumvent materializing that, since the jacobian
|
|
113
|
+
# # calculation is input independent, and we specify it for one input.
|
|
114
|
+
# return tf.constant(0., x.dtype)
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def _logit(r2):
|
|
5
|
+
return np.log(r2 / (1.0 - r2))
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _inv_logit(z):
|
|
9
|
+
return 1.0 / (1.0 + np.exp(-z))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def fit_r2_mixture(r2, n_init=8, max_iter=500, seed=0):
|
|
13
|
+
"""Fit a 2-component Gaussian mixture on ``logit(R²) = log(R²/(1-R²))``.
|
|
14
|
+
|
|
15
|
+
The logit pulls apart the low-R² region so the noise and signal
|
|
16
|
+
components don't overlap on a near-singular support, and Gaussians
|
|
17
|
+
(unlike Betas) can't go pathologically U-shaped.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
r2: array-like of per-voxel/per-vertex R² values.
|
|
21
|
+
n_init: number of EM restarts (sklearn default = 1; 8 is safer).
|
|
22
|
+
max_iter: max EM iterations per restart.
|
|
23
|
+
seed: random state.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
``dict`` with keys
|
|
27
|
+
``{mixture, noise_mu, noise_sigma, noise_weight, noise_mean_r2,
|
|
28
|
+
signal_mu, signal_sigma, signal_weight, signal_mean_r2,
|
|
29
|
+
log_likelihood, n_voxels}``. ``_mu``/``_sigma`` are on the
|
|
30
|
+
logit scale; ``_mean_r2`` is ``inv_logit(_mu)``.
|
|
31
|
+
|
|
32
|
+
Raises:
|
|
33
|
+
ValueError: fewer than 50 finite R² values in (0, 0.99).
|
|
34
|
+
"""
|
|
35
|
+
from sklearn.mixture import GaussianMixture
|
|
36
|
+
r2 = np.asarray(r2, dtype=float).ravel()
|
|
37
|
+
r2 = r2[np.isfinite(r2) & (r2 > 0) & (r2 < 0.99)]
|
|
38
|
+
if len(r2) < 50:
|
|
39
|
+
raise ValueError(
|
|
40
|
+
f"need ≥50 finite R² values in (0, 0.99); got {len(r2)}")
|
|
41
|
+
r2 = np.clip(r2, 1e-6, 1 - 1e-6)
|
|
42
|
+
z = _logit(r2).reshape(-1, 1)
|
|
43
|
+
gmm = GaussianMixture(n_components=2, n_init=n_init,
|
|
44
|
+
max_iter=max_iter, random_state=seed,
|
|
45
|
+
reg_covar=1e-6).fit(z)
|
|
46
|
+
means = gmm.means_.flatten()
|
|
47
|
+
sds = np.sqrt(gmm.covariances_.flatten())
|
|
48
|
+
ws = gmm.weights_
|
|
49
|
+
n_idx, s_idx = int(np.argmin(means)), int(np.argmax(means))
|
|
50
|
+
return {
|
|
51
|
+
'mixture': 'gmm_logit',
|
|
52
|
+
'noise_mu': float(means[n_idx]),
|
|
53
|
+
'noise_sigma': float(sds[n_idx]),
|
|
54
|
+
'noise_weight': float(ws[n_idx]),
|
|
55
|
+
'noise_mean_r2': float(_inv_logit(means[n_idx])),
|
|
56
|
+
'signal_mu': float(means[s_idx]),
|
|
57
|
+
'signal_sigma': float(sds[s_idx]),
|
|
58
|
+
'signal_weight': float(ws[s_idx]),
|
|
59
|
+
'signal_mean_r2': float(_inv_logit(means[s_idx])),
|
|
60
|
+
'log_likelihood': float(gmm.score(z) * len(z)),
|
|
61
|
+
'n_voxels': int(len(r2)),
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def r2_fdr_threshold(r2_or_fit, alpha=0.05, n_grid=4000):
|
|
66
|
+
"""R² threshold at which the 2-component mixture's tail-FDR is ≤ α.
|
|
67
|
+
|
|
68
|
+
FDR(t) = w_n · P(R² > t | noise) /
|
|
69
|
+
[w_n · P(R² > t | noise) + w_s · P(R² > t | signal)]
|
|
70
|
+
|
|
71
|
+
Accepts either an R² array (fits a fresh mixture via
|
|
72
|
+
:func:`fit_r2_mixture`) or a previously-fitted dict (faster — no
|
|
73
|
+
refit). Returns ``np.inf`` if no threshold in (0, 1) achieves the
|
|
74
|
+
requested α (usually a near-degenerate mixture).
|
|
75
|
+
"""
|
|
76
|
+
from scipy.stats import norm
|
|
77
|
+
if not isinstance(r2_or_fit, dict):
|
|
78
|
+
fit = fit_r2_mixture(r2_or_fit)
|
|
79
|
+
else:
|
|
80
|
+
fit = r2_or_fit
|
|
81
|
+
z_grid = np.linspace(fit['noise_mu'] - 5 * fit['noise_sigma'],
|
|
82
|
+
fit['signal_mu'] + 8 * fit['signal_sigma'],
|
|
83
|
+
n_grid)
|
|
84
|
+
sf_n = 1.0 - norm.cdf(z_grid, fit['noise_mu'], fit['noise_sigma'])
|
|
85
|
+
sf_s = 1.0 - norm.cdf(z_grid, fit['signal_mu'], fit['signal_sigma'])
|
|
86
|
+
denom = fit['noise_weight'] * sf_n + fit['signal_weight'] * sf_s
|
|
87
|
+
fdr = np.where(denom > 1e-12,
|
|
88
|
+
fit['noise_weight'] * sf_n / np.maximum(denom, 1e-12),
|
|
89
|
+
1.0)
|
|
90
|
+
hits = np.where(fdr <= alpha)[0]
|
|
91
|
+
if len(hits) == 0:
|
|
92
|
+
return float('inf')
|
|
93
|
+
return float(_inv_logit(z_grid[hits[0]]))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def r2_posterior_signal(r2, fit):
|
|
97
|
+
"""Posterior P(signal | r²) from a 2-component mixture fit.
|
|
98
|
+
|
|
99
|
+
Per-voxel responsibility of the *signal* (higher-mean) component:
|
|
100
|
+
|
|
101
|
+
P(signal | z) = w_s · N(z | μ_s, σ_s²) /
|
|
102
|
+
[w_n · N(z | μ_n, σ_n²) + w_s · N(z | μ_s, σ_s²)]
|
|
103
|
+
|
|
104
|
+
where ``z = logit(R²)``. Values outside the open interval
|
|
105
|
+
``(0, 1)`` map to 0 (cannot be signal under the logit-Gaussian
|
|
106
|
+
mixture).
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
r2: array-like of per-voxel R² values.
|
|
110
|
+
fit: dict returned by :func:`fit_r2_mixture`.
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
``np.ndarray`` of P(signal | r²) values aligned with ``r2``.
|
|
114
|
+
"""
|
|
115
|
+
from scipy.stats import norm
|
|
116
|
+
r2 = np.asarray(r2, dtype=float).ravel()
|
|
117
|
+
out = np.zeros_like(r2)
|
|
118
|
+
valid = np.isfinite(r2) & (r2 > 0) & (r2 < 1)
|
|
119
|
+
if not valid.any():
|
|
120
|
+
return out
|
|
121
|
+
r2_safe = np.clip(r2[valid], 1e-6, 1 - 1e-6)
|
|
122
|
+
z = _logit(r2_safe)
|
|
123
|
+
p_n = fit['noise_weight'] * norm.pdf(z, fit['noise_mu'],
|
|
124
|
+
fit['noise_sigma'])
|
|
125
|
+
p_s = fit['signal_weight'] * norm.pdf(z, fit['signal_mu'],
|
|
126
|
+
fit['signal_sigma'])
|
|
127
|
+
denom = p_n + p_s
|
|
128
|
+
out[valid] = np.where(denom > 0, p_s / np.maximum(denom, 1e-300), 0.0)
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def r2_p_signal_threshold(r2_or_fit, p=0.5, n_grid=4000):
|
|
133
|
+
"""R² value at which P(signal | r²) first crosses ``p``.
|
|
134
|
+
|
|
135
|
+
Searches a logit grid from below the noise mean to above the
|
|
136
|
+
signal mean for the smallest r² with P(signal | r²) ≥ p. Returns
|
|
137
|
+
``np.inf`` if the posterior never reaches ``p`` on that grid
|
|
138
|
+
(near-degenerate mixture).
|
|
139
|
+
|
|
140
|
+
Accepts either an R² array (fits a fresh mixture via
|
|
141
|
+
:func:`fit_r2_mixture`) or a previously-fitted dict.
|
|
142
|
+
"""
|
|
143
|
+
if not isinstance(r2_or_fit, dict):
|
|
144
|
+
fit = fit_r2_mixture(r2_or_fit)
|
|
145
|
+
else:
|
|
146
|
+
fit = r2_or_fit
|
|
147
|
+
z_grid = np.linspace(fit['noise_mu'] - 5 * fit['noise_sigma'],
|
|
148
|
+
fit['signal_mu'] + 8 * fit['signal_sigma'],
|
|
149
|
+
n_grid)
|
|
150
|
+
r2_grid = _inv_logit(z_grid)
|
|
151
|
+
p_signal = r2_posterior_signal(r2_grid, fit)
|
|
152
|
+
hits = np.where(p_signal >= p)[0]
|
|
153
|
+
if len(hits) == 0:
|
|
154
|
+
return float('inf')
|
|
155
|
+
return float(r2_grid[hits[0]])
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def plot_r2_mixture(fit, r2=None, alpha=None, threshold=None, ax=None,
|
|
159
|
+
title=None):
|
|
160
|
+
"""Diagnostic plot for :func:`fit_r2_mixture`.
|
|
161
|
+
|
|
162
|
+
Histogram of ``logit(R²)`` with the two Gaussian component PDFs and
|
|
163
|
+
(optionally) the FDR threshold overlaid. X-ticks are labelled on
|
|
164
|
+
the raw R² scale for readability. Pass ``alpha`` to compute the
|
|
165
|
+
threshold from the mixture, or pass ``threshold`` directly.
|
|
166
|
+
"""
|
|
167
|
+
import matplotlib.pyplot as plt
|
|
168
|
+
from scipy.stats import norm
|
|
169
|
+
if ax is None:
|
|
170
|
+
fig, ax = plt.subplots(figsize=(6, 4))
|
|
171
|
+
else:
|
|
172
|
+
fig = ax.figure
|
|
173
|
+
|
|
174
|
+
z_lo = fit['noise_mu'] - 4 * fit['noise_sigma']
|
|
175
|
+
z_hi = fit['signal_mu'] + 4 * fit['signal_sigma']
|
|
176
|
+
|
|
177
|
+
if r2 is not None:
|
|
178
|
+
r2 = np.asarray(r2, dtype=float).ravel()
|
|
179
|
+
r2 = r2[np.isfinite(r2) & (r2 > 0) & (r2 < 0.99)]
|
|
180
|
+
z_data = _logit(np.clip(r2, 1e-6, 1 - 1e-6))
|
|
181
|
+
z_lo = min(z_lo, float(np.percentile(z_data, 0.1)))
|
|
182
|
+
z_hi = max(z_hi, float(np.percentile(z_data, 99.9)))
|
|
183
|
+
ax.hist(z_data, bins=80, density=True, color='0.85',
|
|
184
|
+
edgecolor='0.5', alpha=0.9,
|
|
185
|
+
label=f'data (n={len(r2)})')
|
|
186
|
+
|
|
187
|
+
z_grid = np.linspace(z_lo, z_hi, 500)
|
|
188
|
+
p_n = (fit['noise_weight']
|
|
189
|
+
* norm.pdf(z_grid, fit['noise_mu'], fit['noise_sigma']))
|
|
190
|
+
p_s = (fit['signal_weight']
|
|
191
|
+
* norm.pdf(z_grid, fit['signal_mu'], fit['signal_sigma']))
|
|
192
|
+
ax.plot(z_grid, p_n, color='#1f77b4', lw=2,
|
|
193
|
+
label=f"Noise (w={fit['noise_weight']:.2f})")
|
|
194
|
+
ax.plot(z_grid, p_s, color='#d62728', lw=2,
|
|
195
|
+
label=f"Signal (w={fit['signal_weight']:.2f})")
|
|
196
|
+
ax.plot(z_grid, p_n + p_s, color='k', lw=1, ls='--', alpha=0.6)
|
|
197
|
+
|
|
198
|
+
if threshold is None and alpha is not None:
|
|
199
|
+
threshold = r2_fdr_threshold(fit, alpha=alpha)
|
|
200
|
+
if threshold is not None and np.isfinite(threshold):
|
|
201
|
+
z_thr = _logit(np.clip(threshold, 1e-6, 1 - 1e-6))
|
|
202
|
+
label = f'Threshold R²={threshold:.3f}'
|
|
203
|
+
if alpha is not None:
|
|
204
|
+
label += f' (α={alpha})'
|
|
205
|
+
ax.axvline(z_thr, color='k', ls=':', lw=1.3, label=label)
|
|
206
|
+
|
|
207
|
+
r2_ticks_all = [0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5]
|
|
208
|
+
z_ticks = [_logit(t) for t in r2_ticks_all]
|
|
209
|
+
keep = [(z, t) for z, t in zip(z_ticks, r2_ticks_all) if z_lo <= z <= z_hi]
|
|
210
|
+
if keep:
|
|
211
|
+
ax.set_xticks([z for z, _ in keep])
|
|
212
|
+
ax.set_xticklabels([f'{t:g}' for _, t in keep])
|
|
213
|
+
ax.set_xlabel('R² (logit-scaled axis)')
|
|
214
|
+
ax.set_ylabel('Density')
|
|
215
|
+
ax.set_yscale('log')
|
|
216
|
+
ax.legend(loc='upper right', fontsize=8)
|
|
217
|
+
if title is not None:
|
|
218
|
+
ax.set_title(title)
|
|
219
|
+
return fig
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def get_map(p):
|
|
223
|
+
stimuli = p.columns.to_frame(index=False).T
|
|
224
|
+
return stimuli.groupby(level=0).apply(lambda d: (p * d.values).sum(1) / p.sum(1)).T
|
|
225
|
+
|
|
226
|
+
def get_rsq(data, predictions, zerovartonan=True, allow_biased_residuals=False):
|
|
227
|
+
"""Per-voxel R² of ``predictions`` for ``data`` (DataFrames, aligned by label).
|
|
228
|
+
|
|
229
|
+
Raises ``ValueError`` if the labels of the two frames do not line up:
|
|
230
|
+
pandas would otherwise fill the gaps with NaN, and because a sum skips NaN,
|
|
231
|
+
R² would come out as exactly 1 when no rows overlap.
|
|
232
|
+
"""
|
|
233
|
+
aligned_data, _ = data.align(predictions, join='outer')
|
|
234
|
+
if aligned_data.shape != data.shape:
|
|
235
|
+
raise ValueError(
|
|
236
|
+
f'get_rsq: data {data.shape} and predictions {predictions.shape} have '
|
|
237
|
+
f'different row or column labels (together {aligned_data.shape}). Give '
|
|
238
|
+
'them the same index and columns, e.g. predict with a paradigm that '
|
|
239
|
+
'has the index of the data.')
|
|
240
|
+
|
|
241
|
+
resid = data - predictions
|
|
242
|
+
|
|
243
|
+
ssq_data = ((data - data.mean(axis=0))**2).sum(axis=0)
|
|
244
|
+
if allow_biased_residuals:
|
|
245
|
+
ssq_resid = ((resid - resid.mean(axis=0))**2).sum(axis=0, min_count=1)
|
|
246
|
+
else:
|
|
247
|
+
ssq_resid = (resid**2).sum(axis=0, min_count=1)
|
|
248
|
+
|
|
249
|
+
r2 = (1 - (ssq_resid / ssq_data))
|
|
250
|
+
|
|
251
|
+
if zerovartonan:
|
|
252
|
+
r2[data.var() == 0] = np.nan
|
|
253
|
+
|
|
254
|
+
r2.name = 'r2'
|
|
255
|
+
|
|
256
|
+
return r2
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def get_r(data, predictions):
|
|
260
|
+
|
|
261
|
+
data_ = data - data.mean(axis=0)
|
|
262
|
+
predictions_ = predictions - predictions.mean(0)
|
|
263
|
+
|
|
264
|
+
r = (data_*predictions_ ).sum(0)
|
|
265
|
+
r = r / (np.sqrt((data_**2).sum(0) * (predictions_**2).sum(0)))
|
|
266
|
+
|
|
267
|
+
return r
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def show_animation(images, vmin=None, vmax=None):
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
import matplotlib.animation as animation
|
|
7
|
+
from IPython.display import HTML
|
|
8
|
+
|
|
9
|
+
fig = plt.figure(figsize=(6, 4))
|
|
10
|
+
ims = []
|
|
11
|
+
|
|
12
|
+
if vmin is None:
|
|
13
|
+
vmin = np.percentile(images, 5)
|
|
14
|
+
|
|
15
|
+
if vmax is None:
|
|
16
|
+
vmax = np.percentile(images, 95)
|
|
17
|
+
|
|
18
|
+
for t in range(len(images)):
|
|
19
|
+
im = plt.imshow(images[t], animated=True, cmap='gray', vmin=vmin, vmax=vmax)
|
|
20
|
+
plt.axis('off')
|
|
21
|
+
ims.append([im])
|
|
22
|
+
|
|
23
|
+
ani = animation.ArtistAnimation(
|
|
24
|
+
fig, ims, interval=150, blit=True, repeat_delay=1500)
|
|
25
|
+
|
|
26
|
+
return HTML(ani.to_html5_video())
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: braincoder
|
|
3
|
+
Version: 0.7.1
|
|
4
|
+
Summary: Fit encoding models to fMRI data and invert them for Bayesian decoding
|
|
5
|
+
Author: Maike Renkert, Christian C. Ruff, Tomas H. Knapen
|
|
6
|
+
Author-email: Gilles de Hollander <gilles.de.hollander@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Documentation, https://braincoder-devs.github.io/
|
|
9
|
+
Project-URL: Source, https://github.com/Gilles86/braincoder
|
|
10
|
+
Project-URL: Changelog, https://github.com/Gilles86/braincoder/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: fMRI,encoding models,population receptive field,pRF,Bayesian decoding,neuroimaging
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: keras>=3.0
|
|
21
|
+
Requires-Dist: matplotlib
|
|
22
|
+
Requires-Dist: seaborn
|
|
23
|
+
Requires-Dist: pandas
|
|
24
|
+
Requires-Dist: pandas_flavor
|
|
25
|
+
Requires-Dist: scipy
|
|
26
|
+
Requires-Dist: scikit-learn
|
|
27
|
+
Requires-Dist: tqdm
|
|
28
|
+
Requires-Dist: patsy
|
|
29
|
+
Provides-Extra: tensorflow
|
|
30
|
+
Requires-Dist: tensorflow>=2.16; extra == "tensorflow"
|
|
31
|
+
Provides-Extra: jax
|
|
32
|
+
Requires-Dist: jax; extra == "jax"
|
|
33
|
+
Provides-Extra: torch
|
|
34
|
+
Requires-Dist: torch; extra == "torch"
|
|
35
|
+
Provides-Extra: test
|
|
36
|
+
Requires-Dist: pytest; extra == "test"
|
|
37
|
+
Provides-Extra: docs
|
|
38
|
+
Requires-Dist: sphinx; extra == "docs"
|
|
39
|
+
Requires-Dist: sphinx-gallery; extra == "docs"
|
|
40
|
+
Requires-Dist: sphinxcontrib-bibtex; extra == "docs"
|
|
41
|
+
Requires-Dist: furo; extra == "docs"
|
|
42
|
+
Requires-Dist: myst-parser; extra == "docs"
|
|
43
|
+
Requires-Dist: ipython; extra == "docs"
|
|
44
|
+
Dynamic: license-file
|
|
45
|
+
|
|
46
|
+
<p align="center">
|
|
47
|
+
<picture>
|
|
48
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Gilles86/braincoder/main/docs/_static/logo_dark.png">
|
|
49
|
+
<img src="https://raw.githubusercontent.com/Gilles86/braincoder/main/docs/_static/logo.png" alt="BrainCoder: neural encoding/decoding models" width="360">
|
|
50
|
+
</picture>
|
|
51
|
+
</p>
|
|
52
|
+
|
|
53
|
+
# Braincoder
|
|
54
|
+
|
|
55
|
+
[](https://doi.org/10.5281/zenodo.10778413)
|
|
56
|
+
|
|
57
|
+
**Braincoder** is a package to fit encoding models to neural data (for now fMRI) and
|
|
58
|
+
to then *invert* those models to decode stimulus information from neural data. It
|
|
59
|
+
wraps stimulus handling, model definition, HRF convolution, and optimization into a
|
|
60
|
+
single [Keras 3](https://keras.io)-based toolkit that runs on TensorFlow, JAX, or PyTorch.
|
|
61
|
+
|
|
62
|
+
## Highlights
|
|
63
|
+
|
|
64
|
+
- **Composable models.** Pick from ready-made encoding models (Gaussian PRF, HRF-aware, linear) or subclass `EncodingModel` to implement your own.
|
|
65
|
+
- **End-to-end workflow.** Utilities for simulation, fitting, and decoding stay in pandas/tensor-friendly formats.
|
|
66
|
+
- **Backend-agnostic.** Runs on TensorFlow, JAX, or PyTorch via Keras 3.
|
|
67
|
+
|
|
68
|
+
## Links
|
|
69
|
+
|
|
70
|
+
- Source code: https://github.com/Gilles86/braincoder
|
|
71
|
+
- Documentation: https://braincoder-devs.github.io/
|
|
72
|
+
|
|
73
|
+
## Installation
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
pip install "braincoder[tensorflow]" # or [jax], or [torch]
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Pin the version in your project's environment, e.g. `braincoder[tensorflow]==0.7.1`, so that its results stay reproducible.
|
|
80
|
+
|
|
81
|
+
For development, use conda/mamba. Clone the repo, then create the environment:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
git clone https://github.com/Gilles86/braincoder.git
|
|
85
|
+
cd braincoder
|
|
86
|
+
conda env create -f environment.yml
|
|
87
|
+
conda activate braincoder
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
This installs braincoder in editable mode (`pip install -e .`) along with a TensorFlow backend and dev tools. See the [installation docs](https://braincoder-devs.github.io/installation.html) for other backends (JAX, PyTorch) and pip-only setups.
|
|
91
|
+
|
|
92
|
+
## Quick start
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
import numpy as np
|
|
96
|
+
import pandas as pd
|
|
97
|
+
from braincoder.models import GaussianPRF
|
|
98
|
+
|
|
99
|
+
paradigm = pd.DataFrame({"x": np.linspace(-5, 5, 100)},
|
|
100
|
+
index=pd.Index(np.arange(100), name="time"))
|
|
101
|
+
parameters = pd.DataFrame({"mu": [0.0, 1.0], "sd": [1.0, 2.0], "amplitude": [1.0, 1.0], "baseline": [0.0, 0.0]},
|
|
102
|
+
index=pd.Index(["v1", "v2"], name="voxel"))
|
|
103
|
+
|
|
104
|
+
model = GaussianPRF()
|
|
105
|
+
predicted = model.predict(paradigm=paradigm, parameters=parameters)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
See the [tutorials](https://braincoder-devs.github.io/tutorial/index.html) for full fitting and decoding pipelines.
|
|
109
|
+
|
|
110
|
+
## Using an AI coding assistant
|
|
111
|
+
|
|
112
|
+
The [braincoder skill for Claude Code](https://github.com/Gilles86/gilles-claude-skills/tree/main/skills/braincoder) gives an assistant a step-by-step manual for new projects, the common silent errors, and measured runtimes. It is also readable on its own. Install it with:
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
git clone https://github.com/Gilles86/gilles-claude-skills.git
|
|
116
|
+
ln -s "$PWD/gilles-claude-skills/skills/braincoder" ~/.claude/skills/braincoder
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Related software
|
|
120
|
+
|
|
121
|
+
[prfmodel](https://popylar-org.github.io/prfmodel/) is a Python package for population receptive field modelling, also built on Keras 3. It covers further pRF models, such as CSS, delayed normalization and connective fields.
|
|
122
|
+
|
|
123
|
+
## How to cite
|
|
124
|
+
|
|
125
|
+
de Hollander, G., Renkert, M., Ruff, C. C., & Knapen, T. H. (2024). *Braincoder: A package for fitting encoding models to neural data and decoding stimulus features*. Zenodo. DOI: [10.5281/zenodo.10778413](https://doi.org/10.5281/zenodo.10778413).
|
|
126
|
+
|
|
127
|
+
```bibtex
|
|
128
|
+
@software{deHollander2024braincoder,
|
|
129
|
+
author = {Gilles de Hollander and Maike Renkert and Christian C. Ruff and Tomas H. Knapen},
|
|
130
|
+
title = {braincoder: A package for fitting encoding models to neural data and decoding stimulus features},
|
|
131
|
+
year = {2024},
|
|
132
|
+
publisher = {Zenodo},
|
|
133
|
+
doi = {10.5281/zenodo.10778413},
|
|
134
|
+
url = {https://github.com/Gilles86/braincoder}
|
|
135
|
+
}
|
|
136
|
+
```
|