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.
@@ -0,0 +1,112 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ import keras
4
+ from keras import ops
5
+ from ..utils import format_data, format_parameters
6
+
7
+ from ..models import LinearModelWithBaseline
8
+
9
+ class WeightFitter(object):
10
+ """Closed-form solver for voxel weights given fixed parameters.
11
+
12
+ Uses least-squares to compute weights that best map basis predictions
13
+ to measured data, optionally with L2 regularization via ``alpha``.
14
+ """
15
+
16
+ def __init__(self, model, parameters, data, paradigm):
17
+ self.model = model
18
+ self.parameters = format_parameters(parameters)
19
+ self.data = format_data(data)
20
+ self.paradigm = self.model.get_paradigm(paradigm)
21
+
22
+ def fit(self, alpha=0.0, fit_intercept=False):
23
+ """Solve for weights using least squares with optional L2 regularization.
24
+
25
+ ``fit_intercept=True`` prepends a column of ones to the basis design
26
+ matrix and solves for a per-voxel intercept *jointly* with the
27
+ weights, in the same closed-form regression. This is the general fix
28
+ for basis models (e.g. ``LinearModelWithBaseline``, or any model
29
+ whose ``_basis_predictions`` ignores ``parameters``) that declare a
30
+ baseline/offset without folding it into the fit: without an
31
+ intercept term, ``WeightFitter`` regresses data on the raw basis
32
+ *through the origin*, which only recovers the correct slope when the
33
+ basis already happens to be mean-zero — otherwise the fitted weight
34
+ is biased by whatever DC level the basis has. Returns
35
+ ``(weights, intercept)`` instead of plain ``weights`` when enabled.
36
+ The intercept column is excluded from the L2 penalty when
37
+ ``alpha>0`` (standard ridge convention — the offset isn't shrunk).
38
+
39
+ Mutually exclusive with the ``LinearModelWithBaseline`` fixed-known-
40
+ baseline path below (that path already subtracts a supplied
41
+ ``parameters['baseline']`` from the data before the regression;
42
+ jointly fitting an intercept on top of an already-baseline-removed
43
+ target is redundant / ill-posed). Pass ``parameters=None`` when
44
+ constructing the fitter if you want ``fit_intercept`` to estimate
45
+ the baseline itself instead of supplying one.
46
+ """
47
+ parameters = self.model._get_parameters(self.parameters) if self.parameters is not None else None
48
+ parameters_ = (ops.convert_to_tensor(parameters.values[np.newaxis, ...], dtype='float32')
49
+ if parameters is not None else None)
50
+
51
+ basis_predictions = self.model._basis_predictions(
52
+ ops.convert_to_tensor(self.paradigm.values[np.newaxis, ...], dtype='float32'), parameters_)
53
+
54
+ A = basis_predictions[0] # (n_timepoints, n_basis)
55
+ b = self.data.values # (n_timepoints, n_voxels)
56
+
57
+ # LinearModelWithBaseline predicts basis@weights + baseline; the baseline
58
+ # is a fixed known parameter, so regress the baseline-removed data.
59
+ # Otherwise the all-positive value feature absorbs each voxel's DC offset
60
+ # and the inverted (decoding) posterior is flat in the candidate stimulus
61
+ # (decodes at r≈0). Gated to this model; GaussianPRF/LinearModel untouched.
62
+ has_fixed_baseline = ((parameters is not None)
63
+ and (type(self.model) == LinearModelWithBaseline))
64
+ if has_fixed_baseline:
65
+ b = b - parameters['baseline'].values[np.newaxis, :]
66
+
67
+ if fit_intercept:
68
+ if has_fixed_baseline:
69
+ raise ValueError(
70
+ "fit_intercept=True is redundant with LinearModelWithBaseline's "
71
+ "own fixed-baseline handling (parameters['baseline'] is already "
72
+ "subtracted above) — either pass parameters=None so "
73
+ "fit_intercept estimates the baseline itself, or keep "
74
+ "fit_intercept=False and supply the baseline yourself.")
75
+ A_t = ops.convert_to_tensor(A, dtype='float32')
76
+ ones = ops.ones((ops.shape(A_t)[0], 1), dtype='float32')
77
+ A = ops.concatenate([ones, A_t], axis=1)
78
+
79
+ if alpha > 0.0:
80
+ # Tikhonov-regularized least squares: (A^T A + alpha*I) x = A^T b
81
+ n_basis = A.shape[-1] if A.shape[-1] is not None else ops.shape(A)[-1]
82
+ n_basis = int(n_basis)
83
+ reg_diag = np.ones(n_basis, dtype=np.float32)
84
+ if fit_intercept:
85
+ reg_diag[0] = 0.0 # don't shrink the intercept
86
+ reg = alpha * ops.diag(ops.convert_to_tensor(reg_diag))
87
+ AtA = ops.matmul(ops.transpose(A), A) + reg
88
+ Atb = ops.matmul(ops.transpose(A), ops.convert_to_tensor(b, dtype='float32'))
89
+ weights_vals = ops.solve(AtA, Atb)
90
+ else:
91
+ weights_vals = ops.lstsq(A, ops.convert_to_tensor(b, dtype='float32'))
92
+
93
+ weights_vals = ops.convert_to_numpy(weights_vals)
94
+
95
+ intercept_vals = None
96
+ if fit_intercept:
97
+ intercept_vals = weights_vals[0]
98
+ weights_vals = weights_vals[1:]
99
+
100
+ if (parameters is None) or type(self.model) == LinearModelWithBaseline:
101
+ weights = pd.DataFrame(weights_vals,
102
+ columns=self.data.columns)
103
+ else:
104
+ weights = pd.DataFrame(weights_vals, index=self.parameters.index,
105
+ columns=self.data.columns)
106
+
107
+ if fit_intercept:
108
+ intercept = pd.Series(intercept_vals, index=self.data.columns,
109
+ name='intercept')
110
+ return weights, intercept
111
+
112
+ return weights
braincoder/stimuli.py ADDED
@@ -0,0 +1,224 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ import logging
4
+ from keras import ops
5
+
6
+ try:
7
+ import keras.ops as _keras_ops
8
+ def _softplus(x):
9
+ return _keras_ops.softplus(x)
10
+ def _log(x):
11
+ return _keras_ops.log(x)
12
+ def _exp(x):
13
+ return _keras_ops.exp(x)
14
+ except ImportError:
15
+ def _softplus(x):
16
+ x = np.asarray(x, dtype=np.float32)
17
+ return np.log1p(np.exp(-np.abs(x))) + np.maximum(x, 0)
18
+ def _log(x):
19
+ return np.log(np.asarray(x, dtype=np.float32))
20
+ def _exp(x):
21
+ return np.exp(np.asarray(x, dtype=np.float32))
22
+
23
+
24
+ class _Identity:
25
+ """Backend-agnostic identity bijector (replaces tfp.bijectors.Identity)."""
26
+ def __init__(self, name=None):
27
+ self.name = name
28
+
29
+ def forward(self, x):
30
+ return x
31
+
32
+ def inverse(self, y):
33
+ return y
34
+
35
+
36
+ class _Softplus:
37
+ """Backend-agnostic softplus bijector (replaces tfp.bijectors.Softplus)."""
38
+ def __init__(self, name=None):
39
+ self.name = name
40
+
41
+ def forward(self, x):
42
+ return _softplus(x)
43
+
44
+ def inverse(self, y):
45
+ return _log(_exp(y) - 1.0)
46
+
47
+
48
+ class _Periodic:
49
+ """Backend-agnostic periodic (wrapping) bijector (replaces TFP Periodic)."""
50
+ def __init__(self, low, high, name=None):
51
+ self.low = low
52
+ self.high = high
53
+ self.width = high - low
54
+ self.name = name
55
+
56
+ def forward(self, x):
57
+ return ((x - self.low) % self.width) + self.low
58
+
59
+ def inverse(self, y):
60
+ return y
61
+
62
+ class Stimulus(object):
63
+
64
+ dimension_labels = ['x']
65
+
66
+ def __init__(self, n_dimensions=1):
67
+ if n_dimensions != 1:
68
+ self.dimension_labels = [f'dim_{ix}' for ix in range(n_dimensions)]
69
+
70
+ self.bijectors = [_Identity(name=label) for label in self.dimension_labels]
71
+
72
+ def clean_paradigm(self, paradigm):
73
+
74
+ if (not isinstance(paradigm, pd.DataFrame)) and (paradigm is not None):
75
+
76
+ if isinstance(paradigm, pd.Series):
77
+ paradigm = paradigm.to_frame()
78
+ paradigm.columns = self.dimension_labels
79
+ else:
80
+ if paradigm.ndim == 1:
81
+ paradigm = paradigm[:, np.newaxis]
82
+
83
+ labels = self.dimension_labels
84
+ if paradigm.shape[1] != len(labels):
85
+ labels = [f'dim_{ix}' for ix in range(paradigm.shape[1])]
86
+
87
+ paradigm = pd.DataFrame(paradigm, columns=pd.Index(labels, name='stimulus dimensions'),
88
+ index=pd.Index(np.arange(len(paradigm)), name='frame')).astype(np.float32)
89
+
90
+ if isinstance(paradigm, pd.DataFrame):
91
+ paradigm = paradigm.astype(np.float32)
92
+
93
+ return paradigm
94
+
95
+ def _clean_paradigm(self, paradigm):
96
+ if paradigm is not None:
97
+ if isinstance(paradigm, pd.DataFrame):
98
+ return paradigm.values.astype(np.float32)
99
+ elif isinstance(paradigm, np.ndarray):
100
+ return paradigm.astype(np.float32)
101
+
102
+ return paradigm
103
+
104
+ def _generate_stimulus(self, paradigm):
105
+ return paradigm
106
+
107
+ def generate_stimulus(self, paradigm):
108
+ return self.clean_paradigm(paradigm)
109
+
110
+ def generate_empty_stimulus(self, size):
111
+ stimulus = np.ones((size, len(self.dimension_labels)), dtype=np.float32) * 1e-6
112
+
113
+ if self.bijectors is not None:
114
+
115
+ if isinstance(self.bijectors, list):
116
+ stimulus = np.stack([ops.convert_to_numpy(bijector.forward(stimulus[:, ix])) for ix, bijector in enumerate(self.bijectors)], axis=1)
117
+ else:
118
+ stimulus = ops.convert_to_numpy(self.bijectors.forward(stimulus))
119
+
120
+ return stimulus.astype(np.float32)
121
+
122
+
123
+ class OneDimensionalStimulusWithAmplitude(Stimulus):
124
+ dimension_labels = ['x', 'amplitude']
125
+
126
+ def __init__(self, positive_only=True):
127
+ super().__init__()
128
+
129
+ if positive_only:
130
+ self.bijectors = [_Identity(name='x'), _Softplus(name='amplitude')]
131
+
132
+ class TwoDimensionalStimulus(Stimulus):
133
+ dimension_labels = ['x', 'y']
134
+
135
+
136
+ class OneDimensionalRadialStimulus(Stimulus):
137
+ dimension_labels = ['x (radians)']
138
+
139
+ def __init__(self):
140
+
141
+ super().__init__()
142
+ self.bijectors = [_Periodic(low=0.0, high=2*np.pi, name='x')]
143
+
144
+
145
+ class OneDimensionalOrientationStimulus(Stimulus):
146
+ """Stimulus for π-periodic orientation data (e.g. gabor gratings).
147
+
148
+ Orientations in [0, π) — 0 rad and π rad represent the same grating,
149
+ so the periodic wrap point is π, not 2π.
150
+ """
151
+ dimension_labels = ['x (radians, orientation)']
152
+
153
+ def __init__(self):
154
+ super().__init__()
155
+ self.bijectors = [_Periodic(low=0.0, high=np.pi, name='x')]
156
+
157
+
158
+ class OneDimensionalRadialStimulusWithAmplitude(OneDimensionalStimulusWithAmplitude):
159
+ dimension_labels = ['x (radians)', 'amplitude']
160
+
161
+ def __init__(self, positive_only=True):
162
+
163
+ super().__init__()
164
+
165
+ if positive_only:
166
+ self.bijectors = [_Periodic(low=0.0, high=2*np.pi, name='x'), _Softplus(name='amplitude')]
167
+ else:
168
+ self.bijectors = [_Periodic(low=0.0, high=2*np.pi, name='x'), _Identity(name='amplitude')]
169
+
170
+ class OneDimensionalGaussianStimulus(Stimulus):
171
+ dimension_labels = ['x', 'sd']
172
+
173
+ def __init__(self, positive_only=True):
174
+ super().__init__()
175
+
176
+ self.bijectors = [_Identity(name='x'), _Softplus(name='sd')]
177
+
178
+
179
+ class OneDimensionalGaussianStimulusWithAmplitude(Stimulus):
180
+ dimension_labels = ['x', 'sd', 'amplitude']
181
+
182
+ def __init__(self, positive_only=True):
183
+ super().__init__()
184
+
185
+ if positive_only:
186
+ self.bijectors = [_Identity(name='x'), _Softplus(name='sd'), _Softplus(name='amplitude')]
187
+ else:
188
+ self.bijectors = [_Identity(name='x'), _Softplus(name='sd'), _Identity(name='amplitude')]
189
+
190
+
191
+ class ImageStimulus(Stimulus):
192
+
193
+ def __init__(self, grid_coordinates, positive_only=True):
194
+ self.grid_coordinates = pd.DataFrame(grid_coordinates, columns=['x', 'y'])
195
+
196
+ if positive_only:
197
+ self.bijectors = _Softplus(name='intensity')
198
+ else:
199
+ self.bijectors = _Identity(name='intensity')
200
+
201
+ self.dimension_labels = pd.MultiIndex.from_frame(self.grid_coordinates)
202
+
203
+ def clean_paradigm(self, paradigm):
204
+
205
+ if (not isinstance(paradigm, pd.DataFrame)) and (paradigm is not None):
206
+
207
+ if paradigm.ndim == 3:
208
+ paradigm = paradigm[:, np.newaxis]
209
+
210
+ paradigm = paradigm.reshape((paradigm.shape[0], -1))
211
+ elif paradigm.ndim == 2:
212
+ pass
213
+ else:
214
+ raise ValueError('Paradigm should be 2 or 3 dimensional')
215
+
216
+ paradigm = pd.DataFrame(paradigm, columns=self.dimension_labels, index=pd.Index(np.arange(len(paradigm)), name='frame')).astype(np.float32)
217
+
218
+ if isinstance(paradigm, pd.DataFrame):
219
+ paradigm = paradigm.astype(np.float32)
220
+
221
+ return paradigm
222
+
223
+ def generate_empty_stimulus(self, size):
224
+ return np.ones((size, len(self.dimension_labels)), dtype=np.float32) * 1e-6
@@ -0,0 +1,4 @@
1
+ from .math import logit, norm, log2, restrict_radians, lognormalpdf_n, von_mises_pdf, axial_von_mises_pdf, lognormal_pdf_mode_fwhm, norm2d
2
+ from .formatting import format_data, format_paradigm, format_weights, format_parameters
3
+ from .stats import get_map, get_rsq, get_r
4
+ from .visualize import show_animation