API Reference¶
This section documents the most frequently used modules. All classes operate
on numpy arrays or pandas DataFrame inputs and run on TensorFlow, JAX or
PyTorch through Keras 3. Models hold only their configuration: pass the paradigm,
parameters, weights and noise model to each method.
Encoding models¶
- class braincoder.models.EncodingModel(n_dimensions=1, verbosity=20, **kwargs)¶
Bases:
objectAbstract base class for encoding models.
- get_paradigm(paradigm)¶
Return the paradigm as a cleaned DataFrame.
- get_parameter_labels()¶
Return the ordered list of parameter labels used by the model.
- get_stimulus_pdf(data, stimulus_range, parameters=None, weights=None, omega=None, dof=None, normalize=True, include_multidimensional_stimulus_index=False, noise_model=None, temperature=None)¶
Evaluate posterior over stimuli for each time point given data.
- Parameters:
data (DataFrame or array (n_timepoints, n_voxels))
stimulus_range (array (n_stimuli,) or (n_stimuli, n_dims)) – Grid of candidate stimuli (flat prior over the grid).
parameters (DataFrame) – Encoding parameters, and basis weights for basis-function models.
weights (DataFrame) – Encoding parameters, and basis weights for basis-function models.
omega (array, float, optional) – Dense noise covariance and Student-t degrees of freedom, e.g. from
ResidualFitter.fit.dof=Nonemeans Gaussian. Pass eitheromegaornoise_model.dof (array, float, optional) – Dense noise covariance and Student-t degrees of freedom, e.g. from
ResidualFitter.fit.dof=Nonemeans Gaussian. Pass eitheromegaornoise_model.noise_model (braincoder.noise.LowRankNoise, optional) – Factored noise model (low-rank + diagonal Ω, Gaussian or Student-t). The likelihood is evaluated with the Woodbury identity (no dense V × V matrix). Its
temperatureis applied unlesstemperatureis passed explicitly.temperature (float, optional) – Likelihood temperature T: posterior ∝ likelihood^(1/T). Default
None= 1 (or the noise model’s own temperature).np.infgives a flat posterior.
- predict(paradigm, parameters=None, weights=None)¶
Return pandas predictions for the provided paradigm/parameters.
- predict_stimulus_grid(stimulus_range, parameters=None, weights=None)¶
Predicted response to every stimulus of a decoding grid.
Returns a float64 array
(n_stimuli, n_voxels). Uses the same batching asget_stimulus_pdf()(one batch per grid point).
- simulate(paradigm, parameters=None, weights=None, noise=1.0, dof=None, n_repeats=1)¶
Generate synthetic data by adding noise to predictions.
- class braincoder.models.LinearModelWithBaseline(n_dimensions=1, verbosity=20, **kwargs)¶
Bases:
EncodingModelLinear encoding model that adds a voxel-specific baseline parameter.
- class braincoder.models.LinearModelWithBaselineHRF(hrf_model=None, verbosity=20, **kwargs)¶
Bases:
LinearModelWithBaseline,HRFEncodingModelLinearModelWithBaseline variant that automatically applies an HRF convolution.
HRF utilities¶
- class braincoder.hrf.HRFModel¶
Bases:
objectBase class that handles HRF generation and convolution with predictions.
- class braincoder.hrf.SPMHRFModel(tr, highres_dt=0.1, time_length=32.0, onset=0.0, delay=6.0, undershoot=16.0, dispersion=1.0, u_dispersion=1.0, ratio=0.167, min_hrf_delay=4.0, max_hrf_delay=8.0, min_dispersion=0.3, max_dispersion=2.0)¶
Bases:
HRFModelSPM’s canonical double-gamma HRF, sampled every TR.
The response is a gamma with shape
delay / dispersionand scaledispersion, as in SPM’sspm_hrf. Sodelay=6anddispersion=1give the canonical HRF, which peaks atdelay - dispersion= 5 s.
- braincoder.hrf.spm_hrf(t, a1=6.0, d1=1.0, a2=16.0, d2=1.0, c=0.16666666666666666, highres_dt=0.1)¶
Compute SPM canonical HRF(s).
Optimization helpers¶
- class braincoder.optimize.WeightFitter(model, parameters, data, paradigm)¶
Bases:
objectClosed-form solver for voxel weights given fixed parameters.
Uses least-squares to compute weights that best map basis predictions to measured data, optionally with L2 regularization via
alpha.- fit(alpha=0.0, fit_intercept=False)¶
Solve for weights using least squares with optional L2 regularization.
fit_intercept=Trueprepends a column of ones to the basis design matrix and solves for a per-voxel intercept jointly with the weights, in the same closed-form regression. This is the general fix for basis models (e.g.LinearModelWithBaseline, or any model whose_basis_predictionsignoresparameters) that declare a baseline/offset without folding it into the fit: without an intercept term,WeightFitterregresses data on the raw basis through the origin, which only recovers the correct slope when the basis already happens to be mean-zero — otherwise the fitted weight is biased by whatever DC level the basis has. Returns(weights, intercept)instead of plainweightswhen enabled. The intercept column is excluded from the L2 penalty whenalpha>0(standard ridge convention — the offset isn’t shrunk).Mutually exclusive with the
LinearModelWithBaselinefixed-known- baseline path below (that path already subtracts a suppliedparameters['baseline']from the data before the regression; jointly fitting an intercept on top of an already-baseline-removed target is redundant / ill-posed). Passparameters=Nonewhen constructing the fitter if you wantfit_interceptto estimate the baseline itself instead of supplying one.
- class braincoder.optimize.ParameterFitter(model, data, paradigm, memory_limit=666666666, log_dir=False)¶
Bases:
objectIterative optimizer that estimates model parameters for each voxel.
Single trainable
(n_voxels, n_pars)keras Variable; only the masked positions (meaningful voxels × non-fixed params) receive gradients. Shared parameters are realized by a smaller Variable that’s broadcast back across voxels via a selector matrix.- Parameters:
model (EncodingModel)
data (pd.DataFrame) – Timeseries, shape
(n_timepoints, n_voxels).paradigm (array-like) – Stimulus paradigm; passed through
model.get_paradigm.memory_limit (int) – Soft budget for the grid-fit chunk size.
log_dir (str | None | False) – TensorBoard log dir.
False(default) disables logging.
- fit(max_n_iterations=1000, min_n_iterations=100, init_pars=None, confounds=None, optimizer=None, fixed_pars=None, shared_pars=None, noise_model='ssq', store_intermediate_parameters=False, r2_atol=0.0001, lag=100, learning_rate=0.01, progressbar=True, **kwargs)¶
Estimate per-voxel parameters by iterative optimization.
- Parameters:
noise_model ({‘ssq’, ‘gaussian’}, default
'ssq') – Loss function.'ssq'minimizes the sum of squared residuals.'gaussian'minimizes a per-voxel Gaussian negative log-likelihood with a free σ²ᵥ per voxel, stored inself.estimated_sigma2. Both have the same per-voxel optimum (withoutshared_pars). From a good grid start they follow nearly the same path, and'gaussian'costs about 25% more per iteration. From a poor start it can get there in fewer iterations, with equal or unequal noise across voxels.fixed_pars (list[str] | None) – Parameter names to hold at their init value (
fixed_pars) or to tie to a single shared value across voxels (shared_pars).shared_pars (list[str] | None) – Parameter names to hold at their init value (
fixed_pars) or to tie to a single shared value across voxels (shared_pars).r2_atol (float, int, int) – Early-stop: stop when mean R² has improved by less than
r2_atolover the lastlagsteps, aftermin_n_iterations. Use a smallerr2_atol(the default was 1e-6 before 0.7) when you need a fully converged fit.lag (float, int, int) – Early-stop: stop when mean R² has improved by less than
r2_atolover the lastlagsteps, aftermin_n_iterations. Use a smallerr2_atol(the default was 1e-6 before 0.7) when you need a fully converged fit.min_n_iterations (float, int, int) – Early-stop: stop when mean R² has improved by less than
r2_atolover the lastlagsteps, aftermin_n_iterations. Use a smallerr2_atol(the default was 1e-6 before 0.7) when you need a fully converged fit.**kwargs – Forwarded to
keras.optimizers.Adamwhenoptimizer is None.
- Returns:
Per-voxel parameter estimates, indexed by voxel. Voxels that contain any NaN or have zero variance cannot be fitted: they get a warning, and NaN in both the parameters and
self.r2.- Return type:
pd.DataFrame
- class braincoder.optimize.ResidualFitter(model, data, paradigm=None, parameters=None, weights=None, lambd=0.0)¶
Bases:
objectFit a parametric noise covariance Ω (and Student-t ν) to residuals.
Ω = ρ ττᵀ + (1 − ρ) diag(τ²) + σ² WWᵀ (optionally mixed with the sample covariance via
lambd).With a pairwise distance matrix
Dpassed tofit(), the shared factor becomes distance-dependent:Ω = ρ [α (e^{−β D̃} ∘ ττᵀ) + (1 − α) ττᵀ] + (1 − ρ) diag(τ²) + σ² WWᵀ
with α ∈ (0, 1), β > 0 and D̃ the classical-MDS Euclidean embedding of
D(seebraincoder.optimize.gp_prior.mds_embed_distances()). It nests the model above at α = 0 and at β = 0. Each term is positive semi-definite for every parameter value: e^{−β D̃} because D̃ is Euclidean (Schoenberg 1938), its Hadamard product with ττᵀ by the Schur product theorem, and WWᵀ as a Gram matrix. With ρ < 1 and τ > 0 the diagonal term makes Ω positive definite, also when voxels share a location (D̃ = 0).Warning
Ω has a single shared factor. On real single-trial fMRI betas the residuals typically need tens of factors, and this Ω underestimates held-out noise (held-out Mahalanobis distances ~4× too large on 7T data), giving overconfident decoding posteriors.
lambd > 0is unsafe when n_voxels > n_trials (rank-deficient sample covariance). The pseudo-WWᵀ fromget_pseudoWWTis uncentred. For calibrated decoding seebraincoder.noise.LowRankNoiseand the “Noise models for decoding” docs page.- fit(init_rho=0.1, init_tau=None, init_dof=1.0, init_sigma2=0.001, D=None, max_n_iterations=1000, resid_dist='gauss', min_n_iterations=100, method='gauss', residuals=None, normalize_WWT=True, use_wwt=True, learning_rate=0.02, rtol=1e-06, lag=100, init_alpha=0.99, init_beta=None, spherical=False, progressbar=True, max_consecutive_failures=50, stimulus_range=None, WWT=None, psd_correction='mds', cholesky=None)¶
use_wwt(default True): include theσ² · WᵀWterm in Ω. When False, Ω is built without the tuning-similarity contribution — useful for testing whetherWᵀWis doing real spatial-noise modeling or just creating signal-correlation structure that interacts with regularized encoding fits.σ²stays in the trainable set but has zero effect on Ω (gradient → 0; Adam leaves it inert).The
WWTterm comes from, in order: theWWTargument; theweightsof the fitter; or the model’s pseudo-WWT, which needsstimulus_rangefor models that are not image-based.Failure handling: a step whose cost or gradients are non-finite, or which raises a numerical error (e.g. a Cholesky failure), is rolled back to the best values so far and the learning rate is reduced by 10%.
max_consecutive_failures(default 50) such steps in a row raiseRuntimeError. Programming errors (TypeError– including JAX tracer-conversion errors –AttributeError,NameError, …) are re-raised immediately. If no step ever produces a finite cost the fit raises instead of returning an unfitted Ω. The number of rolled-back steps is stored inself.n_failed_steps.Distance-dependent noise (
D):Dis an(n_voxels, n_voxels)symmetric, finite, non-negative distance matrix. β is constrained positive with a softplus; α lies in (0, 1).init_betamust be > 0 and defaults to1 / median(off-diagonal D̃).psd_correction:'mds'(default) replacesDby its classical-MDS Euclidean embedding D̃ before the fit, which is what makes Ω positive definite by construction. Exponential kernels on raw graph or geodesic distances need not be PSD.'none'usesDas given, only for distances you know are Euclidean. The embedded matrix and its diagnostics are stored inself.distance_matrix_embedded_andself.mds_info_.cholesky:'strict'factorises Ω as it is, with no jitter, and counts any numerical failure inn_failed_steps.'safe'usessafe_cholesky(), which adds adaptive jitter to the diagonal. The default is'strict'withDand'safe'without, so fits withoutDare unchanged. Passcholesky='strict'when comparing a fit withoutDwith one withD, so that the kernel is the only difference. In strict mode the smallest eigenvalue of the returned Ω (float64) is stored inself.omega_min_eigenvalue_.
Noise models for decoding¶
See Noise models for decoding: low-rank Ω and temperature for the workflow.
- class braincoder.noise.LowRankNoise(scale, factors, psi, dof=None, temperature=1.0, voxels=None)¶
Bases:
objectLow-rank + diagonal (Gaussian or Student-t) noise model for decoding.
Ω = D (F Fᵀ + Ψ) D, stored in factored form. Construct with
fit()(recommended: chooseskand the temperatureTby nested grouped cross-validation on the decoding objective) orfrom_residuals()(covariance only, fixedk).- k¶
Number of factors.
- Type:
int
- temperature¶
Likelihood temperature applied by
get_stimulus_pdf(inf= flat posterior).- Type:
float
- dof¶
Student-t degrees of freedom (
None= Gaussian).- Type:
float or None
- scale¶
Per-voxel scale
s(includes the ML scale factor).- Type:
ndarray (V,)
- psi¶
Diagonal uniquenesses on the correlation scale.
- Type:
ndarray (V,)
- voxels¶
Voxel labels (columns of the training data), used to align test data.
- Type:
pandas.Index or None
- cv_scores_¶
Cross-validated decoding score for every (k, T): mean held-out log posterior probability of the true stimulus per trial, minus that of a flat posterior (nats; > 0 = better than uniform). Rows = k, columns = T.
- Type:
pandas.DataFrame or None
- classmethod fit(model, data, paradigm, parameters=None, stimulus_range=None, groups=None, weights=None, k='cv', temperature='cv', dof='fit', k_grid=(0, 1, 2, 5, 10, 20, 40, 80), temperature_grid=(np.float64(0.25), np.float64(0.29730177875068026), np.float64(0.3535533905932738), np.float64(0.42044820762685725), np.float64(0.5), np.float64(0.5946035575013605), np.float64(0.7071067811865476), np.float64(0.8408964152537145), np.float64(1.0), np.float64(1.189207115002721), np.float64(1.4142135623730951), np.float64(1.681792830507429), np.float64(2.0), np.float64(2.378414230005442), np.float64(2.8284271247461903), np.float64(3.363585661014858), np.float64(4.0), np.float64(4.756828460010884), np.float64(5.656854249492381), np.float64(6.727171322029716), np.float64(8.0), np.float64(9.513656920021768), np.float64(11.313708498984761), np.float64(13.454342644059432), np.float64(16.0), np.float64(19.027313840043536), np.float64(22.627416997969522), np.float64(26.908685288118864), np.float64(32.0), np.float64(38.05462768008707), np.float64(45.254833995939045), np.float64(53.81737057623773), np.float64(64.0), np.float64(76.10925536017415), np.float64(90.50966799187809), np.float64(107.63474115247546), np.float64(128.0), np.float64(152.2185107203483), np.float64(181.01933598375618), np.float64(215.2694823049509), np.float64(256.0), np.float64(304.4370214406966), np.float64(362.03867196751236), np.float64(430.5389646099018), np.float64(512.0), np.float64(608.8740428813932), np.float64(724.0773439350247), np.float64(861.0779292198037), np.float64(1024.0), np.float64(1217.7480857627863), np.float64(1448.1546878700494), np.float64(1722.1558584396073), np.float64(2048.0), np.float64(2435.4961715255727), np.float64(2896.309375740099), np.float64(3444.3117168792146), np.float64(4096.0), np.float64(inf)), inner_parameters=None, psi_floor=0.02, n_folds=5, progressbar=False)¶
Fit a low-rank noise model; choose
kandTby nested CV.- Parameters:
model (EncodingModel)
data (DataFrame (n_trials, V)) – Training data only (the test data must never be passed here).
paradigm (DataFrame or array (n_trials, n_stim_dims)) – True stimulus of every training trial.
parameters (DataFrame, optional) – Encoding parameters (
Noneonly for models without parameters).stimulus_range (array (n_stimuli,) or (n_stimuli, n_dims)) – The decoding grid — use the same grid as for
get_stimulus_pdf. Required whenkortemperatureis chosen by CV. True training stimuli are matched to the nearest grid point.groups (array (n_trials,), optional) – Group label per training trial (e.g. run). Inner CV leaves one group out at a time. Strongly recommended: trials within a run share noise. Without it,
n_foldscontiguous blocks are used.k ('cv' or int)
temperature (‘cv’ or float (
np.inf= flat posterior))dof ('fit', None or float) – Student-t ν by ML (‘fit’), Gaussian (
None) or fixed.k_grid (sequences) – Candidates for CV.
kvalues ≥ the number of inner-training trials or voxels are dropped.temperature_grid (sequences) – Candidates for CV.
kvalues ≥ the number of inner-training trials or voxels are dropped.inner_parameters (None, dict or callable) –
Encoding parameters used inside inner fold
g.None(default):parametersare held fixed. The inner held-out trials were then part of the data the encoding model was fitted on, so their predictions are slightly optimistic and the chosenTis, if anything, too small (posteriors a bit too sharp).dict{group: parameters}: precomputed parameters that did not see groupg(e.g. existing leave-one-run-out fits).callable
f(train_data, train_paradigm, group) -> parameters: refit the encoding model on the inner-training trials.
In fold
g, Ω is fitted on the residuals of the inner-training trials under these parameters, and the held-out trials are decoded with them.psi_floor (float) – Floor on the diagonal uniquenesses (correlation scale).
- Returns:
Fitted on all training trials with the chosen
k; carries the chosentemperature,cv_scores_andcv_info_.- Return type:
Notes
The CV objective is the summed held-out log posterior probability of the true stimulus on the grid,
log p_T(s* | y), under a flat prior over the grid. This is the decoding objective; it is not the covariance likelihood (which prefers ever largerkon fMRI data while decoding gets worse). For every inner fold and everyk, Ω(k) and ν are refitted on the inner-training residuals; allTare evaluated on the same likelihood table at no extra cost.
- classmethod from_residuals(residuals, k=40, dof='fit', psi_floor=0.02, temperature=1.0, _svd=None)¶
Fit Ω (and ν) to residuals for a fixed rank
k.Principal-factor model of the residual correlation (one closed-form step, no iteration): F = first k eigenvectors × √eigenvalues, Ψ = 1 − diag(F Fᵀ), floored at
psi_floor; then an overall scale c and ν are fitted by maximum likelihood (Student-t;dof=Nonefor Gaussian, a number to fix ν).- Parameters:
residuals (DataFrame or array (n_trials, V))
k (int) – Number of factors (capped at
min(n_trials, V) − 1).
- grid_log_likelihood(data, predictions)¶
Log-likelihood table
(n_trials, n_stimuli).data: (n_trials, V);predictions: (n_stimuli, V), the model prediction for every candidate stimulus. Computed as d²(t, s) = q(y_t) + q(μ_s) − 2⟨y_t, μ_s⟩ with all terms in factored form — one (n_trials × V) · (V × n_stimuli) product, no dense Ω and no (n_stimuli × n_trials × V) residual tensor. float64 numpy.
- log_prob(residuals)¶
Log density of each row of
residuals(numpy, float64).
- log_prob_backend(residuals)¶
Log density of each row, in Keras ops (float32, differentiable).
Same factored computation as
log_prob(), usable inside a TensorFlow / JAX / PyTorch graph (e.g. gradient-based stimulus fitting).residuals: tensor (n, V).
- mahalanobis(residuals)¶
Squared Mahalanobis distance rᵀ Ω⁻¹ r of each row (Woodbury).
- summary()¶
Human-readable summary: k, T, ν, and the CV table (if any).
- to_dense()¶
Dense
(omega, dof), drop-in forResidualFitter.fitoutput.For code paths that take
omega=/dof=. Note the temperature is not part of (omega, dof); passtemperature=noise.temperaturetoget_stimulus_pdfas well.
- braincoder.noise.fit_lowrank_omega(residuals, k=40, dof='fit', psi_floor=0.02)¶
Functional / legacy path: dense
(omega, dof)of a low-rank fit.Drop-in replacement for the
(omega, dof)returned byResidualFitter.fit(pass them asomega=/dof=). PreferLowRankNoisefor large V (no dense matrix) and for choosingkand the temperature by cross-validation.
Calibration diagnostics¶
Calibration metrics for grid posteriors (e.g. from get_stimulus_pdf).
All functions take a posterior DataFrame — rows = trials, columns = grid
stimuli — and the true stimulus of every trial. Rows are renormalised to sum
to one (discrete masses over the grid), so both the trapezoid-normalised 1-D
densities and the max-normalised multi-dimensional output of
get_stimulus_pdf can be passed directly.
A calibrated posterior gives
randomised PIT values ~ Uniform(0, 1) (1-D only; SD ≈ 0.289, slightly less on a coarse discrete grid), U-shaped = overconfident, ∩-shaped = underconfident;
randomised HPD levels of the truth ~ Uniform(0, 1), i.e. the q-HDI contains the truth on a fraction q of trials (any dimensionality);
a log score that is not below that of a flat posterior.
Randomisation (a uniform draw within the probability mass of the true grid cell) makes the statistics exactly uniform for a calibrated discrete posterior instead of biased by ties and grid coarseness.
- braincoder.utils.calibration.calibration_summary(pdf, true_stimulus, grid=None, levels=(0.5, 0.95), rng=0)¶
One-row summary: log score vs uniform, HDI coverage, PIT SD (1-D), posterior mean r / MAE / posterior SD (1-D).
- braincoder.utils.calibration.hdi_coverage(pdf, true_stimulus, levels=(0.5, 0.95), grid=None, rng=0)¶
Fraction of trials whose q-HDI contains the truth, for each q.
- braincoder.utils.calibration.hpd_level(pdf, true_stimulus, grid=None, rng=0)¶
Randomised level of the smallest HDI that contains the truth.
h = P(p(s) > p(s*)) + U · P(p(s) = p(s*)). The q-HDI covers the truth iff h < q. Works for any dimensionality.
- braincoder.utils.calibration.log_score(pdf, true_stimulus, grid=None, relative_to_uniform=True)¶
Per-trial log posterior mass of the true grid cell.
With
relative_to_uniform(default)log(1/n_stimuli)is subtracted, so 0 = as good as a flat posterior and > 0 = informative and calibrated enough to beat it.
- braincoder.utils.calibration.marginalize(pdf, dimension, grid=None)¶
Marginal posterior over one stimulus dimension (int or level name).
- braincoder.utils.calibration.pit(pdf, true_stimulus, grid=None, rng=0)¶
Randomised probability integral transform (1-D posteriors).
F(s* − 1) + U · p(s*), U ~ U(0, 1). For a multi-dimensional posterior, first
marginalize()it.
- braincoder.utils.calibration.plot_calibration(pdf, true_stimulus, grid=None, rng=0, axes=None, label=None, levels=array([0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]))¶
Two-panel diagnostic: coverage vs nominal HDI level, and PIT histogram (1-D) or HPD-level histogram (multi-D). Returns the axes.
- braincoder.utils.calibration.posterior_grid(pdf, grid=None)¶
(P, grid): row-normalised masses (n_trials, n_stimuli) and the grid.
gridis taken from the columns (numeric Index or MultiIndex) unless passed explicitly (needed whenget_stimulus_pdfwas called on a multi-dimensional grid withoutinclude_multidimensional_stimulus_index).
- braincoder.utils.calibration.true_stimulus_index(true_stimulus, grid)¶
Index of the nearest grid point for every true stimulus.
Stimulus parameterisations¶
Decode a few stimulus parameters (e.g. a bar’s orientation, position and width) instead of an image: a grid over the parameters is an exact posterior per volume, and a differentiable rendering gives gradient-based MAP estimates.
Stimulus parameterisations: decode a few stimulus parameters instead of an image.
An encoding model f(s; θ) is defined on a stimulus space S, for a pRF model the
pixels of an image. Many experiments only show a small family of images, which a
few numbers describe: a moving bar is fixed by the position of its centre line
along the normal, the orientation of that normal and its width. A
stimulus parameterisation is the map
g: Φ → S, φ ↦ image,
and decoding then targets the posterior over φ instead of over images:
p(φ | y) ∝ p(y | f(g(φ); θ)) p(φ).
The encoding model is unchanged; only the candidate set (a grid over φ, or a
continuous φ for gradient methods) is generated through g. Over a few
dimensions the posterior is a low-dimensional integral, so it can be computed
exactly on a grid, which is what EncodingModel.get_stimulus_pdf() already
does for a list of candidate images.
Contents¶
- ParametricStimulus
Base class: named parameters, bounds, a differentiable
to_imageinkeras.ops(TensorFlow, JAX and PyTorch), grids and candidate sets.- BarStimulus
A bar: hard-edged or soft-edged (differentiable), optional contrast (presence), optional aperture mask.
- get_parametric_stimulus_pdf
Grid posterior over φ (plus an optional blank state) through
get_stimulus_pdf, with a prior.- marginalize
Marginal posterior over a subset of parameters.
- forward_backward
Exact posterior marginals of a hidden Markov model over a candidate set (e.g. φ grid over time, with a Markov prior on the bar’s motion).
- ParametricStimulusFitter (in
braincoder.optimize) Gradient-based MAP over φ, per volume or, with a
*WithHRFmodel, for a whole time series.
Orientation convention: orientation is the direction of the bar’s normal
in degrees (0 = vertical bar, moving horizontally), position the signed
distance of the bar’s centre line from the origin along that normal. The bar
with (orientation + 180, -position) is the same image, so g is two-to-one on
the full circle. Grids use orientation in [0, 180) with a signed position,
which has no duplicates; continuous optimisation uses the full circle (no wrap
boundary) and BarStimulus.canonicalize() maps results back.
- class braincoder.parametric.BarStimulus(grid_coordinates, edge='hard', edge_width=None, contrast=False, aperture=None, max_width=None, min_width=None, width_prior=None)¶
A bar of given orientation, position and width, optionally with a contrast.
image(x, y) = contrast · edge(width / 2 − |x cos θ + y sin θ − position|) · aperturewith θ =
orientation(degrees, direction of the bar’s normal).- Parameters:
grid_coordinates ((n_pixels, 2))
edge ('hard' or 'soft') – ‘hard’: 1 inside the bar, 0 outside (
|d| <= width / 2, as a binary stimulus aperture); piecewise constant, so no useful gradient. ‘soft’: a logistic edge,sigmoid((width / 2 − |d|) / edge_width), differentiable in every parameter (|d|is smoothed at 0).edge_width (float, optional) – Logistic scale of the soft edge in the units of the grid. Default: a quarter of the pixel spacing, so the edge is within about one pixel.
contrast (bool) – Add a
contrastparameter in [0, 1] that multiplies the image. With a contrast, “no bar” is the point contrast = 0, where orientation, position and width are not identified; a discrete blank state (include_blankincandidates()) is usually the better model of blank frames.aperture ((n_pixels,) array, optional) – Mask that multiplies the bar (e.g. a bar seen only inside a 4° aperture).
max_width (float, optional) – Upper bound on width for continuous optimisation (default: the field radius).
min_width (float, optional) – Lower bound on width for continuous optimisation (default: half a pixel).
width_prior (LogWidthPrior or dict, optional) – A proper prior on the width, bounded away from 0 and from the field (see
LogWidthPrior; a dict is passed to its constructor). The bounds replacemin_widthandmax_width, the unconstrained width coordinate becomes the prior’szeta(log-scaled logit), andlog_prior_unconstrained()gives the log prior in that coordinate for a fitter or sampler.
- canonicalize(phi)¶
Orientation into [0, 180), flipping the sign of position where it moved by 180°.
- static centre(phi)¶
Foot point of the bar’s centre line, (position cos θ, position sin θ): invariant to the 180° symmetry.
- from_unconstrained(u)¶
Unconstrained (tensor, n x n_parameters) → parameters (tensor). Default: identity.
- log_prior_unconstrained(u)¶
Log prior of the unconstrained coordinates, summed over rows (keras ops): the width prior’s density in its
zetacoordinate, 0 when nowidth_priorwas given (flat in the unconstrained space).
- to_unconstrained(phi)¶
orientation, position: identity (orientation is periodic in g itself); width: logit between min_width and max_width; contrast: logit.
- class braincoder.parametric.LogWidthPrior(min_width, max_width, median=None, scale=1.0)¶
A proper prior on a bar’s width with support bounded away from 0 and from the field.
Log width
uis a logit-scaled variable on(log min_width, log max_width):u = log(min_width) + (log(max_width) - log(min_width)) * sigmoid(zeta), zeta ~ Normal(m, scale**2),
where
mputs the prior median atmedian(default: the geometric mean of the bounds). The width is therefore strictly inside(min_width, max_width), the density is smooth (no wall for HMC or NUTS, which samplezeta), andscalesets how concentrated it is: about 1 gives a bell in log width, about 2 or more is nearly flat over the interval.- Parameters:
min_width (float) – Bounds in the units of the stimulus grid. A sensible minimum is one pixel; a sensible maximum is clearly below the field (e.g. 1.5 times the widest bar the design shows).
max_width (float) – Bounds in the units of the stimulus grid. A sensible minimum is one pixel; a sensible maximum is clearly below the field (e.g. 1.5 times the widest bar the design shows).
median (float, optional)
scale (float) – SD of
zeta(default 1).
- cell_log_masses(widths)¶
Log prior mass of each candidate width, each owning the cell of log widths nearest to it (cells clipped at the bounds); widths outside the bounds get
-inf. For a grid over widths: a prior that sums to 1 over the candidates.
- log_prob(width)¶
Log density of the width itself (numpy);
-infoutside the bounds.
- log_prob_log_width(u)¶
Log density of log width (numpy);
-infoutside the bounds.
- log_prob_zeta(zeta)¶
Log density of the prior in the unconstrained coordinate (keras ops), the quantity a sampler or MAP uses.
- width(zeta)¶
Width of an unconstrained coordinate, keras ops (any backend).
- zeta(width)¶
Unconstrained coordinate of a width (numpy).
- class braincoder.parametric.ParametricStimulus(grid_coordinates, aperture=None)¶
A map
gfrom a few named parameters to an image on a pixel grid.Subclasses set
parameter_labelsand implement_render()(keras ops, differentiable where the subclass says so) and, optionally,_render_numpy()(exact numpy rendering for candidate sets).- Parameters:
grid_coordinates ((n_pixels, 2) array or DataFrame) – x and y of every pixel, in the same order as the encoding model’s
grid_coordinates.aperture ((n_pixels,) array, optional) – Multiplies every image (e.g. a circular field, or a 4° aperture).
- candidates(grid, include_blank=False, min_area=None)¶
Candidate set (table, images) for decoding from a grid over φ.
- Parameters:
grid (DataFrame) – Rows of φ (e.g. from
grid()).include_blank (bool) – Prepend an empty image as row 0, with NaN parameters: the presence state “no stimulus”, where φ is undefined.
min_area (float, optional) – Drop candidates whose image sum is below
min_areatimes the median image sum (stimuli almost entirely outside the field).
- Returns:
table (DataFrame, one row per candidate, columns
parameter_labels)images (float32 array (n_candidates, n_pixels))
- canonicalize(phi)¶
Map equivalent parameter values to one representative. Default: unchanged.
- from_unconstrained(u)¶
Unconstrained (tensor, n x n_parameters) → parameters (tensor). Default: identity.
- grid(**values)¶
Full factorial grid over φ as a DataFrame with columns
parameter_labels.Every parameter needs a list of values, e.g.
grid(orientation=np.arange(0, 180, 15), position=np.arange(-8, 8.01, .5), width=[1., 2.]).
- images(phi)¶
Images of
phi(DataFrame or array) as a float32 numpy array (n, n_pixels).NaN rows (a blank, see
candidates()) give an empty image.
- to_image(phi)¶
Images of
phi(tensor or array, n x n_parameters) as a tensor (n, n_pixels), in keras ops.
- to_unconstrained(phi)¶
Parameters → unconstrained space (numpy). Default: identity.
- braincoder.parametric.forward_backward(log_emission, log_transition, log_initial=None)¶
Exact posterior marginals of a hidden Markov model (log-space forward–backward).
For a stimulus that changes slowly over time (a sweeping bar), a Markov prior over a candidate set turns per-frame evidence into a posterior over the whole sequence whose frame marginals this computes exactly, at a cost of O(n K²). Use it on emissions that are conditionally independent over frames: e.g. per-frame scores of a deconvolved (HRF-removed) image sequence, not raw BOLD volumes, whose overlapping HRFs couple frames.
- Parameters:
log_emission ((n, K) array) – Log p(evidence_t | state k), up to a constant per frame.
log_transition ((K, K) array) – Log p(state_{t+1} = j | state_t = i), rows i.
log_initial ((K,) array, optional) – Log prior of the first state (default: stationary-free uniform).
- Returns:
marginals ((n, K) array, rows sum to 1)
log_evidence (float, log p(all evidence) up to the per-frame constants)
- braincoder.parametric.get_parametric_stimulus_pdf(model, data, stimulus, grid, parameters=None, weights=None, noise_model=None, omega=None, dof=None, temperature=None, log_prior=None, include_blank=False, blank_prior=None, min_area=None)¶
Posterior over a grid of stimulus parameters, per row of
data.The candidate images are
stimulus.candidates(grid); the likelihood is the one ofEncodingModel.get_stimulus_pdf()(same noise models, temperature); the prior islog_priorover the grid rows (default flat) and, withinclude_blank, a discrete blank state with prior probabilityblank_prior(the rest spread over the grid bylog_prior). Because the grid enumerates φ, the result is the exact posterior on that grid; marginals over parameters are sums (marginalize()).Note: a grid is a quadrature of the posterior over continuous φ. Its spacing should be small against the posterior width, and a flat prior over φ is not flat over images (it is the prior of this parameterisation).
- Parameters:
model (EncodingModel (not
*WithHRF: decode single responses or betas))data ((n, n_voxels) DataFrame or array)
stimulus (ParametricStimulus)
grid (DataFrame of φ rows)
log_prior ((n_grid,) array, optional) – Log prior over the grid rows (need not be normalised).
include_blank (bool)
blank_prior (float in (0, 1), required with
include_blank)
- Returns:
DataFrame (n, n_candidates), rows sum to 1; columns are a MultiIndex of
the parameter values (the blank, if any, first, with NaN values).
- braincoder.parametric.marginalize(pdf, labels)¶
Marginal posterior over
labels(a parameter name or a list) from a grid posterior.The blank state (NaN parameters) is kept as its own column (NaN).
- class braincoder.optimize.ParametricStimulusFitter(model, stimulus, data, parameters=None, weights=None, noise_model=None, omega=None, dof=None, temperature=None)¶
MAP of stimulus parameters φ given data, by gradient descent through
stimulus.to_image.Two modes, set by the model:
a model without HRF (single responses or betas): every row of
datais one independent stimulus, φ_t is fitted per row;a
*WithHRFmodel and a BOLD time series: the images of all frames go through the HRF together, so the fit is over the whole sequence φ_1..φ_n. An optional Gaussian random-walk prior (smoothness) couples neighbouring frames.
The stimulus must be differentiable (e.g.
BarStimulus(edge='soft')). The objective is-sum_t log p(y_t | f(g(φ_t))) / T - log prior; the likelihood is the noise model’s (LowRankNoiseor denseomega/dof).- Parameters:
model (EncodingModel)
stimulus (ParametricStimulus)
data ((n, n_voxels) DataFrame or array)
parameters (encoding parameters (as for
predict))weights (encoding parameters (as for
predict))noise_model (LowRankNoise, optional)
omega (dense noise covariance and Student-t dof, optional)
dof (dense noise covariance and Student-t dof, optional)
temperature (float, optional (default: the noise model's, else 1))
- fit(init_phi, max_n_iterations=500, learning_rate=0.05, fixed=None, smoothness=None, rtol=1e-07, min_n_iterations=50, lag=50, decay=True, progressbar=False, use_width_prior=False)¶
Gradient descent (Adam) on φ in the stimulus’ unconstrained space.
- Parameters:
init_phi (DataFrame (columns
stimulus.parameter_labels) or array, one row per frame) – Start, e.g. the grid MAP ofget_parametric_stimulus_pdf().fixed (list of parameter labels, optional) – Kept at their start values (clamped), e.g.
['orientation', 'width'].smoothness (dict label -> SD per frame, optional) – Gaussian random-walk prior over frames (sequence mode); orientation differences are wrapped to ±90°.
decay (bool) – Cosine decay of the learning rate over
max_n_iterations(default True).use_width_prior (bool) – Add the stimulus’
width_prior(aLogWidthPrior, in its unconstrained coordinate) to the objective: a MAP with a proper bounded prior on width instead of a flat one.
- Return type:
DataFrame of fitted φ (canonicalized), index as
data. The loss trace is inself.costs.
- log_posterior(phi, smoothness=None, use_width_prior=False)¶
Objective (log likelihood / T + log prior) at
phi(DataFrame or array), as a float.