What’s new

0.9.0 highlights (2026-11-18)

  • Gain-field PRF models (Gain fields (attention fields)): GainFieldPRF2D, GainFieldDoGPRF2D and their WithHRF versions multiply the stimulus by fields around chosen locations (attended, salient, target, …) before the PRF pools it. Any number of locations and named gain types, several fields of different shapes (GaussianField, DoGField, or your own FieldShape), tied and zero-sum parameters, image-scale masks, and GainFieldMixin for other PRF kernels. The paradigm helper is braincoder.stimuli.make_gain_field_paradigm. Tutorial: Gain fields: attention modulates population receptive fields.

0.8.0 highlights (2026-11-18)

  • braincoder.parametric: write a stimulus class as a map from a few named parameters to an image (ParametricStimulus; BarStimulus with a hard or soft edge, an optional contrast and an optional aperture). get_parametric_stimulus_pdf gives the exact grid posterior over the parameters (with a blank state and a prior) through get_stimulus_pdf; marginalize sums it; forward_backward gives exact HMM marginals over a candidate set for slowly changing stimuli.

  • LogWidthPrior: a proper, smooth prior on a bar’s width, bounded away from 0 and from the field.

  • optimize.ParametricStimulusFitter: MAP over the parameters by gradient descent, per volume, or for a whole BOLD series with a *WithHRF model and a random-walk prior; parameters can be clamped.

  • GeodesicGPPrior(mean=..., transform=...): a constant (estimated) or fixed prior mean, and a log transform. Defaults are unchanged.

0.7.1 highlights (2026-11-16)

Bug-fix release. Refit if you used either of the first two:

  • SPMHRFModel is now SPM’s canonical HRF, peaking at 5 s (it peaked at 6 s) and sampled exactly one TR apart (samples were 32 / (n - 1) s apart). This changes the fitted values of any *WithHRF model built with hrf_model=SPMHRFModel(...). Bounds on a fitted hrf_delay move to 4-8 so the range of peak times is unchanged.

  • ResidualFitter.fit(D=...): β is constrained positive and Ω is positive definite by construction (the kernel uses the classical-MDS Euclidean embedding of D, and no jitter). D with lambd > 0 or spherical=True now raises.

  • Torch: ParameterFitter.fit no longer accumulates an autograd graph every iteration, which ran large fits out of GPU memory.

  • gamma_pdf no longer returns NaN for gamma shapes above about 35.

0.7.0 highlights (2026-11-02)

  • Models no longer hold data or fitted values. Pass paradigm, parameters, weights, omega and dof to each method. See the migration guide.

  • New ParameterFitter.fit default: r2_atol=1e-4. noise_model stays 'ssq', contrary to what 0.6 announced: see the changelog below.

  • On PyPI: pip install "braincoder[tensorflow]".

  • Torch on Apple GPUs now runs the whole library.

0.6.2 highlights (2026-11-02)

Bug-fix release. Inputs that gave plausible-looking wrong results now give the right result or a clear error. Recompute cvR² from frames with different indices (R² could be exactly 1), refit if data and paradigm had different indices, and re-decode anything decoded with a *WithHRF model. Voxels that cannot be fitted now return NaN rather than zeros and r2 == -1000. Details are in the changelog below.

0.6.0 highlights (2026-10-25)

  • Calibrated decoding. braincoder.noise.LowRankNoise models the noise covariance as low-rank + diagonal (Student-t or Gaussian) and tempers the likelihood; rank k and temperature T are chosen by nested, run-grouped cross-validation on the decoding objective. Use it with get_stimulus_pdf(..., noise_model=noise) (or temperature= with a dense omega=). Guide: Noise models for decoding; worked example: example 04.

  • Calibration tools. braincoder.utils.calibration: HDI coverage, randomised PIT, HPD level of the truth, log score vs. a flat posterior, calibration_summary and plot_calibration, for any get_stimulus_pdf output (API).

  • New fitting options. ParameterFitter(noise_model='gaussian') (per-voxel Gaussian likelihood; default stays 'ssq'), r2_history_ / loss_history_, a GP spatial prior (GeodesicGPPrior, BayesianParameterFitter), R² mixture / FDR voxel-selection helpers (example 01), analytical Student-t Fisher information and get_expected_uncertainty (Fisher information).

  • Key fixes. safe_cholesky (adaptive jitter, NaN check); ResidualFitter no longer swallows errors; differentiable _lgamma (Student-t ν was biased low on TF and never fitted on JAX — refit Ω/ν from older checkouts); TF compute_jacobian int32 overflow; MC Fisher information on JAX / torch; NumPy 2 trapezoid.

  • Documented caveat. ResidualFitter’s one-factor Ω underestimates held-out noise on single-trial fMRI; prefer LowRankNoise for decoding (see Noise models for decoding).

Full changelog

0.9.0 (2026-11-18)

New features; no behaviour changes for existing code.

Gain-field PRF models (braincoder.models.gain_field)

Fields around chosen locations (attended, salient, target, distractor, …) multiply the stimulus image before each voxel’s PRF pools it. With all gains at 0 the model is exactly the PRF model underneath.

  • GainFieldPRF2D, GainFieldDoGPRF2D and their WithHRF versions, for single-trial betas and BOLD time courses. GainFieldMixin adds fields to any image PRF kernel.

  • Any number of field locations, anywhere, and any number of named gain types. The per-frame role of every location (weights, 0/1 or fractional) is part of the paradigm, built with braincoder.stimuli.make_gain_field_paradigm or model.make_paradigm.

  • Several fields per model (GainField), each with its own shape (FieldShape subclasses: GaussianField, DoGField, or your own), gains (signed, positive or negative), and inside or outside the clip at 0. The combination rule is pluggable.

  • ties: parameters fixed to a constant, equal to another, or a linear combination of others (zero-sum gains, shared widths). image_scales: a model-level factor for part of the image.

  • Field parameters are model-level and fitted with ParameterFitter(..., shared_pars=...), typically with the PRFs fixed. The forward pass costs about as much as the PRF model underneath.

  • Documentation: a gain-field page (docs/gain_fields.rst) and a gallery tutorial (examples/02_gain_fields, lesson 8).

Fixes

  • StimulusFitter on images is about 100 times faster. The L1/L2 penalties looped over every pixel of every trial in eager mode, and free decoding passed each pixel as a separate tensor. Results are unchanged.

0.8.0 (2026-11-18)

New features; no behaviour changes for existing code (all defaults are unchanged).

Stimulus parameterisations: braincoder.parametric

Decode a few named stimulus parameters (for example the position, width and orientation of a bar) instead of a free pixel image.

  • ParametricStimulus is a stimulus class defined as a map from named parameters to an image; BarStimulus is a bar with a hard or soft edge, an optional contrast and an optional aperture.

  • get_parametric_stimulus_pdf gives the exact grid posterior over the parameters (with a blank state and a prior) through get_stimulus_pdf; marginalize sums it over parameters; forward_backward gives exact HMM marginals over a candidate set for slowly changing stimuli.

  • LogWidthPrior is a proper prior on a bar’s width, bounded away from 0 and from the field. Log width is a logit-scaled variable on (log min_width, log max_width) with a normal prior on the unconstrained scale, so the density is smooth (no wall for HMC or NUTS) and scale sets how concentrated it is.

  • optimize.ParametricStimulusFitter finds the MAP over the parameters by gradient descent, per volume, or for a whole BOLD series with a *WithHRF model and a random-walk prior. Parameters can be clamped.

GeodesicGPPrior: mean and transform

  • mean= 'zero' (default, unchanged), 'constant' (a scalar estimated together with the kernel hyperparameters: type-II ML in fit_hyperparameters, type-II MAP in fit_map(joint_hyperparams=True), initialised at the median of the classical estimates) or a fixed number.

  • transform= 'identity' (default, unchanged) or 'log' (the prior is on log theta; the MAP is the mode in log coordinates).

  • With the defaults, fits are unchanged. BayesianParameterFitter centres a constant-mean prior on the classical estimates before stage 2 or 3.

Other

  • Documentation: pip-first install instructions; the braincoder skill is shipped in the repository as a Claude Code plugin.

0.7.1 (2026-11-16)

Bug-fix release. Two of the fixes change fitted values: refit anything fitted with SPMHRFModel / SPMHRFDerivativeModel (the usual hrf_model of the *WithHRF models), and anything fitted with ResidualFitter.fit(D=...).

Behaviour change: SPMHRFModel is SPM’s canonical HRF

Changes fitted values for anyone using SPMHRFModel, SPMHRFDerivativeModel or spm_hrf.

SPMHRFModel now gives SPM’s canonical HRF. Two things were different:

  • It peaked at 6 s instead of 5 s. The response gamma had shape delay / dispersion + 1, not delay / dispersion. delay=6 still means what it does in SPM, so the default now peaks at 5 s.

  • Samples weren’t one TR apart. They came from linspace(1e-4, 32, n), so the spacing was 32 / (n - 1): 1.6 s at a TR of 1.5 s, for example. Convolution assumes one TR, which compressed the HRF by a few percent. Samples are now exactly one TR apart, from 0.

The bounds on a fitted hrf_delay move from 3-7 to 4-8, so the range of fitted peak times stays the same. To reproduce an older fit, use SPMHRFModel(tr=tr, delay=7.) for about the old peak time; the sampling change can’t be undone.

Distance-dependent noise model

Fixes to the distance-dependent noise model, ResidualFitter.fit(D=...): Ω = ρ[α(e^{−βD̃} ∘ ττᵀ) + (1−α)ττᵀ] + (1−ρ)diag(τ²) + σ²WWᵀ. Refit anything fitted with D= before this.

  • β is constrained positive (softplus). It was an unconstrained variable, so a step to β < 0 made the kernel grow with distance. The default init_beta changes from 0, which is no longer in the domain, to 1 / median(off-diagonal D̃); an init_beta ≤ 0 raises. Without D, nothing changes.

  • Ω is positive definite by construction. The kernel is now computed on D̃, the classical-MDS Euclidean embedding of D (the embedding GeodesicGPPrior already used), not on raw graph distances, where an exponential kernel need not be PSD. psd_correction='none' keeps D as given, for distances known to be Euclidean. MDS lengthens non-Euclidean distances, so β is on the scale of D̃: compare fitter.distance_matrix_embedded_ with D, and see fitter.mds_info_['negative_eigenvalue_fraction'].

  • No jitter with D. New cholesky='strict'|'safe' argument, default 'strict' with D and 'safe' (unchanged) without it. safe_cholesky always adds at least 1e-4 · mean(diag Ω), so the fitted likelihood was that of a different matrix from the one returned. A numerical failure is now a rolled-back step, counted in n_failed_steps, and fitter.omega_min_eigenvalue_ reports the returned Ω. Pass cholesky='strict' to a fit without D as well when comparing the two, so that the kernel is the only difference.

  • D combined with lambd > 0 or spherical=True now raises. lambd > 0 silently dropped D; spherical=True crashed with an unrelated error. A non-finite D (unreachable vertices on a disconnected patch) raises as well.

  • fitted_omega_parameters['beta'] is now the constrained value.

  • mds_embed_distances (braincoder.optimize.gp_prior) is public, can return diagnostics, and uses O(n²) memory instead of an n × n × r difference tensor, which needed about 4 GB at n = 800 and about 64 GB at n = 2000. GeodesicGPPrior output is unchanged.

  • init_tau is cast to float32, so float64 residuals work on torch with MPS.

Other fixes

  • Torch: ParameterFitter.fit no longer leaks memory. The forward pass that tracks R² between gradient steps ran with autograd on, and the best-so-far R² and parameters kept that graph alive, so voxels × pixels tensors piled up every iteration until the GPU ran out of memory (on CPU, 3,000 voxels × 961 pixels: about 2.2 GB of live tensors after 40 iterations, 0 MB now, same loss). Results are unchanged; TensorFlow and JAX were not affected.

  • gamma_pdf is computed in log space. t**(a-1) and d**a · Γ(a) overflowed float32 for shapes above about 35, so very narrow gamma HRFs gave NaN. Values for ordinary shapes are unchanged up to float32 rounding.

  • ParameterFitter.fit with fixed_pars on regression models no longer crashes while logging (their parameter labels are tuples).

  • ResidualFitter raises a clear error on data with 0 voxels and fits a single voxel with spherical=True.

0.7.0 (2026-11-02)

Breaking. Models no longer hold data or fitted values. See the migration guide; most scripts need only a few mechanical edits, and old constructor arguments raise an error that points to it.

Models hold configuration only

  • Constructors no longer take paradigm, data, parameters, weights or omega, and models have no such attributes. Pass them to each method: model.predict(paradigm, parameters).

  • Fitters no longer write to the model. ResidualFitter used to overwrite model.parameters and model.weights, and StimulusFitter model.omega and model.dof, so a model reused across cross-validation folds could silently decode with the last fold’s parameters. That can no longer happen: leaving out parameters raises ValueError.

  • get_stimulus_pdf needs omega or noise_model, and never reads a stored dof.

  • init_pseudoWWT + get_pseudoWWT() become get_pseudoWWT(stimulus_range, parameters), which returns the matrix. ResidualFitter.fit takes stimulus_range= or WWT=.

  • get_WWT(weights) and get_rf(parameters, ...) take their inputs.

  • to_linear_model(parameters) returns (model, parameters, weights), and to_xy_model(parameters) returns (model, parameters).

  • RegressionGaussianPRF and friends take design_data= (it only defines the design) and build their design matrices from the paradigm of each call. set_paradigm is gone.

  • CustomStimulusFitter and BarStimulusFitter take parameters= and weights=.

  • HRFModel is no longer changed by the model using it: unique_hrfs and set_unique_hrfs are gone, and the HRF’s shape decides how it is applied.

  • GaussianPRF2D needs grid_coordinates. It used to guess them from a 3D paradigm.

  • Removed: apply_mask, and to_discrete_model, which could not run. DiscreteModel takes stimulus_values.

Fitters keep their results as attributes (fitter.r2, fitter.estimated_parameters, fitter.r2_history_). A fitter represents one fit; a model is reusable.

ParameterFitter.fit

  • New default r2_atol=1e-4 (was 1e-6). On large real data, 1e-6 was unreachable within 10,000 iterations, and 1e-4 was about 3x faster for under 0.001 of R² in the paper benchmark. Pass r2_atol=1e-6 for a tighter fit.

  • noise_model stays 'ssq' by default, contrary to what 0.6 announced. New tests do not support the stated reason for switching. Adam scales each parameter’s steps by its own gradient history, so a constant per-voxel rescaling of the loss changes almost nothing: a sum-of-R² loss follows the SSQ path. From a good grid start 'gaussian' gave the same fit at about 25% more time per iteration. From a poor start it did reach the optimum in fewer iterations (about 2-5x smaller remaining R² gap at 3,000 iterations), but as much with equal noise across voxels as with unequal noise. The explanation in the 0.6 notes, that it balances noisy voxels, is not correct.

Other changes

  • Available on PyPI: pip install "braincoder[tensorflow]", [jax] or [torch].

  • Torch on Apple GPUs (MPS): the GP prior and safe_cholesky with float64 input now work. MPS has no float64, so those steps run on the CPU and the rest stays on the GPU.

  • fit() without init_pars no longer crashes in GaussianPRF.get_init_pars, and a fit with a regression model no longer crashes in its logging.

  • Models with a stimulus amplitude no longer fail on a 2-column numpy paradigm.

0.6.2 (2026-11-02)

Bug-fix release: inputs that gave plausible-looking wrong results now give the right result or a clear error. Some of these change what existing scripts do, so read the heads-up below.

  • get_rsq raises ValueError when row or column labels differ. Without overlapping rows, it returned R² = 1.0 for every voxel, because a sum skips the NaN that pandas filled in. If your cvR² came from frames with different indices, recompute it. A residual that is entirely NaN now gives NaN.

  • ParameterFitter pairs data and paradigm by position throughout. fit always did, but refine_baseline_and_amplitude and get_rsq paired by label, so an off-by-one index compared shifted timeseries: refined amplitudes were wrong, with no error. The paradigm now takes the index of the data, with a warning if a labelled index differed. Refit if this applied to you. A different number of rows raises ValueError.

  • Voxels with any NaN, or zero variance, now return NaN (parameters and fitter.r2), with a warning, instead of all-zero parameters and r2 == -1000. fitter.r2.mean() therefore stays meaningful. Such voxels also no longer poison shared_pars.

  • get_stimulus_pdf and predict_stimulus_grid raise ValueError on non-finite parameters. A single such row used to make every posterior NaN.

  • Decoding with *WithHRF models now ignores the HRF, with a warning. Each candidate stimulus was treated as a one-sample timeseries, which scaled the tuning curve by the first HRF samples: about 1/17 at a TR of 1.6 s, making posteriors about 5× too wide in a test. Re-decode if you decoded with a *WithHRF model.

  • get_fisher_information and get_expected_uncertainty raise NotImplementedError on *WithHRF models, which would convolve the stimuli as one timeseries.

  • get_stimulus_pdf uses model.dof when it also uses model.omega. It previously fell back to a Gaussian likelihood. With an explicit omega=, dof=None still means Gaussian.

  • ResidualFitter pairs residuals by position, reorders voxels if needed, and gives clear errors for NaN residuals, an empty voxel selection or different voxels.

  • WeightFitter.fit(fit_intercept=True) fits a per-voxel intercept and returns (weights, intercept). WeightFitter with LinearModelWithBaseline now subtracts the known baseline first: an all-positive feature otherwise absorbed the offset, and decoding could fall to r≈0.

  • DN with a negative rf_amplitude: the denominator used the signed amplitude, so it shrank and could cross zero, giving poles in the prediction. It now uses |rf_amplitude|, as the TensorFlow-era line did and as Aqil et al. (2021) define it. Positive amplitudes are unchanged. Refit DN models where negative amplitudes occurred.

  • refine_baseline_and_amplitude: clear error for zero amplitudes (TF raised “not invertible”, JAX returned junk); n_iterations > 1 keeps positive_amplitude and l2_alpha.

  • get_rf(parameters=...) no longer ignores its argument.

  • to_linear_model() on *WithHRF models raised TypeError. It now works, and LinearModelWithBaselineHRF adds the baseline after convolution, so it matches the PRF model.

  • A flexible-HRF model given parameters= in its constructor raised KeyError.

  • LinearModel.simulate() without parameters raised AttributeError.

  • Passing omega= to a constructor uses safe_cholesky, as decoding does, instead of raising LinAlgError on a slightly non-PSD matrix.

  • A missing TensorFlow or TFP now gives an explanatory ImportError for StimulusFitter, and from braincoder.optimize import * no longer fails.

  • Torch on MPS: fixed device errors in get_rf and the DN *WithHRF model.

  • Docs: braincoder is not on PyPI, so the install page now uses tagged git URLs. Added citation, license, related software (prfmodel) and the Claude Code skill. .zenodo.json: corrected ORCIDs and no longer describes the package as TensorFlow-based.

0.6.1 (2026-11-02)

Bug-fix release.

  • DivisiveNormalizationGaussianPRF2DWithHRF with flexible_hrf_parameters=True: the forward parameter transform passed bold_baseline and hrf_delay to the HRF model instead of hrf_delay and hrf_dispersion. The fitted HRF delay was therefore a fixed function of the BOLD baseline (delay = range·sigmoid(bold_baseline) + min) and the dispersion was driven by the raw delay; backward/forward did not round-trip. Refit any DN model fitted with a flexible HRF.

  • DifferenceOfGaussiansPRF2D: had no transforms of its own, so it inherited the 5-column Gaussian ones and dropped srf_amplitude / srf_size. It now transforms all 7 columns (srf_amplitude > 0, srf_size > 1).

  • New rf_normalization option on GaussianPRF2D and all subclasses: 'legacy' (default, unchanged: Gaussian divided by σ·√(2π)/pixel_area), 'peak' (peak 1, as prfpy’s normalize_RFs=False) and 'area' (integral 1). The three are exact reparameterisations of the amplitudes; existing fits are unaffected.

  • Tests: parameter-transform round trips for all *WithHRF 2D PRF models; normalisation scales.

0.6.0 (2026-10-25)

The headline of 0.6 is a new per-voxel Gaussian likelihood option in ParameterFitter, opt-in here and the default in 0.7. Same fixed points as the existing sum-of-squares loss, much faster convergence under heteroskedastic noise — which is to say, on every real fMRI dataset.

The second headline is calibrated decoding: braincoder.noise.LowRankNoise (low-rank + diagonal noise covariance with cross-validated rank and likelihood temperature) and braincoder.utils.calibration.

The rest of 0.6 is a substantial set of stability fixes, a new GP-prior fitter, and a per-fold voxel-selection helper.

Default fitter changes (heads-up for downstream projects)

  • ParameterFitter(noise_model={'ssq', 'gaussian'}) — new knob.

    • 'ssq' (default in 0.6): unweighted sum-of-squared-residuals. Equivalent to MLE under homoscedastic Gaussian noise. Same as 0.5.x.

    • 'gaussian' (new): per-voxel Gaussian negative log-likelihood with a free per-voxel σ²ᵥ. The θ-gradient is (1/σ²ᵥ)·∂SSQᵥ/∂θᵥ, so each voxel makes comparable progress under the shared Adam optimizer regardless of its noise level. Converges to the same per-voxel θ at high iterations — but does so much faster in practice on real data, where noise varies wildly across voxels.

  • Synthetic verification: at max_n_iterations=20_000 both modes agree on per-voxel θ to <1e-3 normalized RMSE. At 2_000 iters Gaussian mode is at its asymptote; SSQ mode is still ~5× further out. See gp_prior_fmri/notes/analyses/classical_vs_ml_convergence/ for the full convergence study.

  • 0.7 will flip the default to 'gaussian'. If you need exact reproduction of pre-0.6 fits, pin noise_model='ssq' explicitly.

  • ParameterFitter.r2_history_ / loss_history_ — the R² and loss trajectories of the last fit() call are now stored on the fitter.

Calibrated decoding: low-rank noise model with CV rank + temperature

  • braincoder.noise.LowRankNoise (also braincoder.LowRankNoise) — noise covariance Ω = D (F Fᵀ + Ψ) D: k principal factors of the residual correlation plus diagonal uniquenesses (floored), Student-t (ν by ML) or Gaussian. Stored and evaluated in factored form (Woodbury + determinant lemma; no dense V × V inverse), so it scales to thousands of voxels.

  • LowRankNoise.fit(model, data, paradigm, parameters, stimulus_range=grid, groups=runs) chooses the rank k and a likelihood temperature T (posterior ∝ likelihood^(1/T)) jointly by nested, group-wise CV within the training data on the decoding objective (held-out log posterior of the true stimulus). Fixed k= / temperature= also accepted. Encoding parameters are held fixed in the inner folds by default; inner_parameters= takes per-group parameters (dict) or a refit callable. noise.summary() / noise.cv_scores_ report the choice.

  • get_stimulus_pdf(..., noise_model=, temperature=) — new optional arguments (also on EncodingRegressionModel). Defaults unchanged: without them the output is identical to 0.5.x. temperature also works with a dense omega=. New helper EncodingModel.predict_stimulus_grid.

  • braincoder.noise.fit_lowrank_omega(residuals, k) → dense (omega, dof) for code that passes omega= / dof=.

  • braincoder.utils.calibration — randomised PIT, HPD level of the truth, HDI coverage, log score vs uniform, marginalize, calibration_summary, plot_calibration; works on any get_stimulus_pdf DataFrame.

  • Docs: new page docs/noise_models.rst, example examples/01_decoding_pipeline/04_lowrank_noise_calibration.py.

  • Warnings documented there (from 7T single-trial numerosity data): ResidualFitter’s one-factor Ω underestimates held-out noise (Mahalanobis ~4× too large; posteriors overconfident, all 38 participant × ROI worse than flat); lambd shrinkage is unsafe when voxels > trials; the pseudo-WWᵀ from init_pseudoWWT is uncentred (dominated by the common-mode response). ResidualFitter itself is unchanged.

  • Tests: tests/test_noise_models.py (Woodbury vs dense, CV recovery of k, calibrated coverage, T ≈ 1 when correct and > 1 when tuning is misspecified, backward compatibility, all backends).

Hierarchical Bayesian / GP prior

A new hierarchical-Bayesian fitter for any encoding model, with a Gaussian-Process prior over cortical geodesic distance.

  • GeodesicGPPrior (braincoder.optimize.gp_prior): RBF kernel over a precomputed pairwise distance matrix. Adaptive jitter for Cholesky stability; classical MDS embedding so the kernel is PSD even on non-Euclidean graph distances (Schoenberg 1938); Cholesky and triangular solves in float64.

  • BayesianParameterFitter (braincoder.optimize.bayesian_fitter): three-stage empirical-Bayes (classical → hyperparams via MLE → MAP), with options for type-II joint MAP (joint_hyperparams=True, co-fits hyperparameters in stage 3), shared lengthscale across priors (shared_lengthscale=True), and frozen Cholesky in MAP to keep TF’s CholeskyGrad out of the backward graph.

Voxel selection / FDR utilities

  • fit_r2_mixture / r2_fdr_threshold (braincoder.utils.stats) — 2-Gaussian mixture on logit(R²) with a tail-FDR threshold for empirical-null voxel selection.

  • r2_posterior_signal / r2_p_signal_threshold — per-voxel posterior P(signal | R²) and the R² at which it crosses a chosen probability. More forgiving than tail-FDR on small/degenerate ROIs.

  • plot_r2_mixture — diagnostic plot of the mixture fit + threshold.

Fisher information & expected uncertainty

  • Analytical Fisher information for multivariate Student-t noise. EncodingModel.get_fisher_information(..., analytical=True) now accepts dof and applies the closed-form prefactor (ν + p) / (ν + p + 2) · Jᵀ Ω⁻¹ J. Previously this combination raised ValueError and forced users to the Monte-Carlo path; MC was both noisier (~12% RMS at n=200) and prone to int32 overflow in UnsortedSegmentSum at n × n_vox × n_stim ≈ 5e7. The analytical path is now exact for any ν and recovers the Gaussian formula as ν → ∞.

  • EncodingModel.get_expected_uncertainty(stimuli, omega, dof, ...) — new convenience wrapper. Simulates n_simulations noisy responses per stimulus from (parameters, omega, dof), decodes each via get_stimulus_pdf, and returns a DataFrame indexed by stimulus value with mean_E, var_E, mean_error, mean_abs_error, n_sims. batch_stimuli lets you bound memory at large grid sizes.

  • Tests: tests/test_fisher_information.py (9 tests): Student-t prefactor, dof → ∞ recovery of Gaussian, MC ↔ analytical agreement, and the FI ↔ 1/var_E relationship.

  • Docs: new docs/fisher_information.rst page with the two-API story, the “is spikiness real?” diagnostic, and a worked example.

Cortical surface helpers

  • braincoder.utils.cortex.geodesic_distance_matrix — Dijkstra-based pairwise geodesic distance on a triangulated mesh, restricted to a set of source vertices (typical use: project EPI-mask centroids to nearest vertex then run Dijkstra on the matched set).

Robustness fixes

  • safe_cholesky(M, jitter=1e-4) (braincoder.utils.backend) — symmetrise + adaptive-jitter wrapper for ops.cholesky with a retry-on-NaN at 10× jitter. Wired into get_stimulus_pdf, Fisher information, both _simulate noise paths, and the residual fitter likelihood. Eliminates the Cholesky : Tensor had NaN values class of crashes that hit ~10–20% of subjects on production fits.

  • ResidualFitter.fit(use_wwt=True) — when False, strips the σ²·WᵀW tuning-similarity term from Ω. Diagnostic; default unchanged.

  • BayesianParameterFitter.fit_map uses a manual NaN-safe global- norm gradient clip instead of keras.optimizers.Adam(clipnorm=...), which under PyTorch would poison Adam’s moment buffers with NaN if any single gradient went non-finite.

  • ResidualFitter.fit no longer swallows every exception. It used to catch any exception, record cost=inf, back off the learning rate and carry on, so a fit that failed at every step (e.g. the old _lgamma under JAX) returned the initial Ω and dof as if it had converged. Now: programming errors (TypeError, which includes JAX tracer-conversion errors, plus AttributeError, NameError, …) are re-raised immediately; numerical failures (exceptions such as a Cholesky failure, non-finite cost or gradients) are still rolled back with a 10% learning-rate cut, but max_consecutive_failures=50 in a row raises RuntimeError, and so does a fit that never reaches a finite cost. A step with non-finite gradients is no longer applied (previously NaN gradients could poison the variables). Failed steps emit a RuntimeWarning and are counted in fitter.n_failed_steps. The stored best values now correspond to the parameters at which the best cost was evaluated (previously the post-update values were stored, one Adam step past the best cost).

Backend layer fixes (TF / JAX / torch parity)

  • TF compute_jacobian uses tf.while_loop instead of pfor, which overflowed int32 indexing on large (trials × voxels × parameters) problems.

  • Monte-Carlo Fisher information sums the log-probability before taking the gradient, so analytical=False works under JAX / torch (previously it raised on the non-scalar loss; TF summed it silently).

  • JAX compute_gradients runs inside a StatelessScope so keras.Variable reads inside value_and_grad don’t leak tracers.

  • sample_mvt / sample_student_t derive independent sub-seeds for the χ² and normal components.

  • _lgamma routes through differentiable backend-native lgamma (tf.math.lgamma / jax.scipy.special.gammaln / torch.lgamma) instead of the non-differentiable scipy fallback. Downstream impact: Student-t dof fitted on TF before this fix is biased low (the gradient was missing 0.5[ψ((ν+k)/2) − ψ(ν/2)] per observation); on JAX the residual fit silently never ran. Refit Ω/dof for any decoding results that used method='t' with an older checkout.

  • torch compute_gradients uses torch.autograd.grad instead of reading .grad off each variable.

  • get_stimulus_pdf converts user data arrays to tensors before _likelihood (avoids numpy-on-MPS device-mismatch errors).

  • safe_cholesky explicitly checks for NaN in the output, since some backends return NaN silently rather than raising.

Tests & CI

  • New test files: test_gp_prior.py (+360 lines), test_safe_cholesky.py (+174), test_backend_multibackend.py (+376), additions to test_utils.py (+168).

  • scikit-learn now declared as a runtime dep (used by fit_r2_mixture).

  • TFP-dependent import test is skipped when tensorflow_probability is not installed.

Compatibility

  • numpy.trapz (deprecated in NumPy 2.0) replaced with numpy.trapezoid via a shim.


0.5.1 (2026-05-04)

  • Fix invalid isRelatedTo relation in .zenodo.json (Zenodo schema requires references instead). The 0.5.0 GitHub release failed to deposit on Zenodo because of this; 0.5.1 contains no code changes, only the metadata fix.

0.5.0 (2026-05-04)

The headline change is a full Keras 3 port: braincoder is now backend-agnostic and runs on TensorFlow, JAX, or PyTorch (including Apple Silicon MPS). The codebase has been refactored into subpackages, the test suite has grown from a handful of integration tests to 170 passing tests across all three backends, and a long list of bugs has been fixed.

Backend & infrastructure

  • Keras 3 multi-backend port: all core code now uses keras.ops.* instead of TensorFlow primitives. TF, JAX, and PyTorch backends are all CI-tested.

  • Subpackage refactor: the monolithic models.py and optimize.py are split into braincoder/models/ (base, linear, prf_1d, prf_2d) and braincoder/optimize/ (parameter_fitter, weight_fitter, residual_fitter, stimulus_fitter).

  • GitHub Actions CI runs the full suite on every push.

  • Test suite expanded to 170 tests covering models, HRFs, optimizers, stimuli, and utilities.

  • NumPy 2.0 / pandas 3.x compatibility: np.trapz → np.trapezoid, Series[:, np.newaxis] workaround, groupby(axis=1) removed.

New models

  • AxialVonMisesPRF — π-periodic von Mises PRF for orientation data.

  • Gaussian Mixture PRFs (GaussianMixturePRF2D).

  • Difference-of-Gaussians PRFs (DifferenceOfGaussiansPRF2D, DifferenceOfGaussiansPRF2DWithHRF).

  • Divisive Normalization PRFs (DivisiveNormalizationGaussianPRF2D, DivisiveNormalizationGaussianPRF2DWithHRF).

New features

  • subtract_baseline=True option in GaussianPRF.init_pseudoWWT removes per-voxel baseline contamination from the WWT covariance.

  • lambd (convex blending between parametric and empirical covariance) is now actually wired into ResidualFitter.fit() (previously stored but ignored).

  • shared_pars / fixed_pars keep parameters constant across voxels — useful for hard-to-estimate parameters and future attention-field models.

  • Multi-dimensional stimulus support, correlated_response option, multiple repeats in simulate(), configurable HRF parameter ranges.

Bug fixes

  • ResidualFitter.lambd was silently ignored (closure called the wrong helper).

  • ResidualFitter λ=1 edge case: zero-gradient parametric vars; switched to dof-only short-circuit + adaptive jitter (1e-4 × mean_diag + 1e-9) for Cholesky stability.

  • get_stimulus_pdf: pass Cholesky of omega, not omega itself, to _likelihood.

  • get_fisher_information: add diagonal jitter before Cholesky.

  • VonMisesPRF._get_stimulus and GaussianPRFWithHRF MRO init bugs.

  • HRF: convolution uses ops.flip (MPS-compatible); upsample to highres_dt for creation; SPM HRF defaults fixed.

  • Various amplitude/baseline rescaling, aggressive_softplus for RegressionGaussianPRF, DN HRF formula correction.

Cleanup

  • Removed dead modules: braincoder/estimators.py, braincoder/tests/, stub CustomHRFModel.

  • Removed 5 legacy test files that referenced removed classes.

  • Switched from pkg_resources to importlib.

Migration notes

  • Most user-facing imports are unchanged; subpackage refactor is internal.

  • If you were using the old-style monolithic braincoder.models module path (e.g. from braincoder.models import GaussianPRF), this still works — the names are re-exported.

  • For PyTorch on Apple Silicon, set PYTORCH_ENABLE_MPS_FALLBACK=1 (required by ops.lstsq / ops.solve).