Skip to content

About

EEG source localization pipeline for mouse models using the Antwerp Mouse Brain Atlas. Supports multiple BEM head models, inverse methods (sLORETA, dSPM, MNE, beamformers), and multi-subject batch processing.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Mouse EEG Source Localization Package

Created: 2025-11-26 Last Updated: 2026-11-20 Version: 0.9.13 Status: Alpha

A Python pipeline for mouse EEG source localization: a 30-channel scalp recording in, per-ROI source time series and whole-brain source estimates out. Ships with several registered brain parcellations (Antwerp and Allen CCFv3 derived), multi-subject batch processing, MNE-based spectral and connectivity analysis, a dipole-simulation validation framework, and figure utilities.

The version and status above come from pyproject.toml and are checked by tests/test_readme_consistency.py, as are the atlas and preset tables below. If this file and the code disagree, the code is right and the test is broken.


Table of Contents


Overview

📖 Documentation site: docs/ — guides (adding an atlas, electrode setup, Monte Carlo source sampling) and known issues you should read before interpreting output. Preview locally with uv run --no-project --with "mkdocs-material>=9.5,<10" mkdocs serve.

Source localization solves the EEG inverse problem: given electrode measurements on the scalp, estimate the locations and strengths of neural activity inside the brain. This package does that for mouse recordings from a fixed 30-channel array, and reports the result over an atlas parcellation so that it can feed ROI-level statistics.

It is a research codebase under active development. The inverse problem is ill-posed and 30 sensors cap the effective rank of any solution at 30 whatever the source count, so read Validation and the known issues before treating a per-ROI number as a claim about anatomy.


Features

Core Pipeline

  • 8 pipeline presets covering 2 BEM types and 3 source-space families (the surface presets were withdrawn in 0.9.10; see the known issue)
  • 2 BEM types: a three-shell sphere (numerical by default; bem.sphere.numerical: false for the analytic Berg-Scherg form) and an ellipsoid (numerical, fitted to the brain mask)
  • 3 source-space families, all volumetric:
    • ROI-based: sources placed inside each atlas parcel (the default preset's)
    • Cartesian: 3D volumetric grid
    • Shell: concentric geometry-matched shells
  • Inverse methods: custom MNE, dSPM, sLORETA and eLORETA with mouse-scale regularization; stock MNE-Python LCMV and DICS beamformers (see known issues for the beamformer caveat)
  • Orientation: free (three components per source). Fixed and loose were withdrawn with the surface in 0.9.10
  • Registered atlases selectable with --atlas (see Atlas Selection)
  • 30-channel electrode array coordinates included, with the canonical six electrode regions (Left/Right Frontal, Medial, Posterior) in data/electrodes/mouse_array_regions.yaml; copy that block into a study's electrode_categories

Multi-Subject Study Processing

  • BIDS-inspired folder hierarchy, YAML study configuration
  • Batch processing with parallel jobs, status reporting, QC
  • Group-level result collection

MNE-Based Analysis

  • Band power per ROI using MNE's Welch PSD
  • Connectivity via MNE-Connectivity (coherence, PLV, wPLI, imcoh)
  • Automatic epoching of continuous data for connectivity

ROI Extraction

  • The pipeline's ROI step assigns each source to a parcel (by the source space's own parcel labels where it has them, otherwise nearest labeled voxel) and takes the unweighted mean of the sources in each parcel.
  • Two variants exist: magnitude (always positive) and signed. Which are written is outputs.output_variants (signed, magnitude or both; default both). Every preset sets signed, so a preset run writes no magnitude .set unless you set it to both in a --config file or through the API (Pipeline.from_preset(..., **{'outputs.output_variants': 'both'})). The signed value is, by default, the component with the largest variance within each epoch. Neither is an SVD. With inverse.signed_orientation: leadfield it is instead the projection onto each source's fixed leadfield direction, signs aligned within each parcel; see "What the outputs are".
  • Depth-weighted extraction exists in source_analysis.roi_analysis but is not part of the pipeline; the earlier claim that it was has been removed.

Visualizations

  • Per-step QC figures and an HTML report from every run
  • Interpolated heatmaps, ROI parcellation overlays, connectivity matrices and chord diagrams in source_analysis

Installation

Prerequisites

  • Python >= 3.9 and < 3.14
  • Virtual environment manager (uv recommended)

Using uv (Recommended)

# Install uv if needed
curl -LsSf https://astral.sh/uv/install.sh | sh

# Clone and install
git clone https://github.com/alexedmon1/source-localization.git
cd source-localization
uv venv && source .venv/bin/activate
uv pip install -e .

# For connectivity analysis (optional)
uv pip install -e ".[connectivity]"

# For the study's localization summary in the shared results format (optional, Python 3.10+)
uv pip install -e ".[results]"

Reproducing a published analysis

A plain install resolves whatever versions are current, which is not what produced any published result — MNE in particular resolves to 1.12.1 rather than the 1.11.0 used throughout. Install against a lockfile instead:

uv venv .venv
uv pip install --python .venv -r <lockfile>
uv pip install --python .venv --no-deps "source-localization @ git+https://github.com/alexedmon1/source-localization.git@<tag>"

--no-deps is deliberate: the lockfile is the authority on versions, and letting the package re-resolve its own dependencies is what drifts the environment.

Release tags used by published work:

tag what it is
v0.2.1 the reconstruction cited by the Fmr1 KO vs WT manuscript
v0.2.3 v0.2.1 plus one line of packaging metadata — declares scikit-learn, which source_space/roi_based.py imports but v0.2.1 never declared. git diff v0.2.1 v0.2.3 touches pyproject.toml and nothing else, so every analysis path is byte-identical. Install this; cite v0.2.1
v0.4.1 corrected brain mask — sources are placed inside the brain rather than the meningeal rim
v0.4.2 v0.4.1 plus the same packaging fix. Install this; cite v0.4.1

Every tag before v0.9.0 solves surface BEMs in the wrong surface order (see History, 0.9.0): forward models from the ellipsoid presets and the numerical sphere are physically inconsistent and wrong in amplitude by orders of magnitude. The analytic sphere is unaffected. Reproduce an older result with its tag, but rerun anything new on v0.9.0 or later.

Every tag before v0.9.1 computes free-orientation sLORETA and dSPM per component (see History, 0.9.1): each x, y and z component was scaled separately, so results depend on the head model's axes and sLORETA does not place a single noise-free source exactly. Fixed-orientation (anatomical surface and hybrid, both since withdrawn) and Monte Carlo runs are unaffected. inverse.standardisation: legacy_per_component reproduces the old form.

Every tag before v0.9.2 does three things that change results (see History, 0.9.2):

  • it keeps interpolated channels as if they were real sensors;
  • it collapses each free Monte Carlo pool source to one direction;
  • it weights free-orientation eLORETA with a scalar per source, which misplaces even a noise-free single source.

Rerun recordings with interpolated channels, free-pool Monte Carlo runs, and free-orientation eLORETA runs on v0.9.2 or later. forward.interpolated_channels: keep, monte_carlo.directions: dominant and inverse.eloreta_weights: legacy_scalar reproduce the old forms. study qc flags old eLORETA runs as a faulty inverse.

Note that versions before 0.5.1 did not reorder EEG channels to match the electrode registration. Recordings stored in a channel order other than E1..E30 were silently misaligned with the leadfield. Check epochs.ch_names on your input files before relying on an older tag.

Verify Installation

source-localization --help
source-localization study --help
python -c "import source_localization; print(source_localization.__version__)"

Quick Start

Single Subject

# ROI-based sources, ellipsoid BEM, Allen32 parcels (the default preset; what the FORGE study used)
source-localization run --preset roi_based_ellipsoid --atlas allen32 --eeg /path/to/data.set --output ./results

# View results
open results/pipeline_report.html

roi_based_ellipsoid is the default preset because one has to be; it is not a ranking (see Which Preset Should I Use?). Every preset defaults to the Antwerp atlas when --atlas is omitted. Prefer --atlas allen32 for anything that ends in a per-ROI claim; see Atlas Selection.

Multi-Subject Study

# 1. Initialize study from a folder of EEG files (writes atlas: allen32 since 0.9.12; --atlas to choose)
source-localization study init /path/to/eeg_data --name "MyStudy"

# 2. Process all subjects (4 parallel jobs)
source-localization study run study_config.yaml --jobs 4

# 3. Run spectral and connectivity analysis (on the study file's bands:, else the defaults)
source-localization study analyze study_config.yaml --verbose

# 4. Check status
source-localization study status study_config.yaml

Multi-Subject Study Processing

The study module provides a BIDS-inspired framework for organizing and processing multi-subject EEG studies.

Folder Hierarchy

study_folder/
├── study_config.yaml           # Study configuration
├── sourcedata/                 # Raw EEG files (or symlinks)
│   ├── sub-001.set
│   └── sub-002.set
├── participants.csv            # Subject metadata (optional)
└── derivatives/
    └── source_localization/
        ├── sub-001/
        │   ├── pipeline/       # Source localization outputs
        │   ├── roi_timeseries/ # ROI time series (.set files)
        │   └── analysis/       # Band power, connectivity
        └── group/
            ├── subjects.csv            # written by `study collect`
            ├── group_band_power.csv    # written by `study analyze`
            └── connectivity_*.csv

CLI Commands

# Initialize study from folder (default preset: roi_based_ellipsoid; default atlas: allen32, written into
# the study file since 0.9.12; a study file without an atlas runs on the preset's Antwerp paths)
source-localization study init /path/to/data --name "MyStudy" --preset roi_based_ellipsoid --atlas allen32

# Run source localization pipeline
source-localization study run study_config.yaml --jobs 4 --verbose

# Run spectral/connectivity analysis (uses MNE) on all of the study's bands, or pick some of
# them with `--bands` by the names the study file gives (e.g. "Low Gamma" in a FORGE-style file)
source-localization study analyze study_config.yaml --connectivity coherence

# Check processing status
source-localization study status study_config.yaml

# Collect the per-subject table into group/subjects.csv
source-localization study collect study_config.yaml

# Quality control report
source-localization study qc study_config.yaml

The study's localization summary

With the optional results extra installed (Lumière, the results specification shared with source-analytics and neurofaune), study qc also writes the study's localization as one diagnostic analysis in qc/, beside qc_report.html, so a study gallery or any reader can show how the recordings were localized without this package:

file what it holds
analysis.json role: diagnostic, domain: localization, the atlas, and caveats: recordings that failed or are missing, a recipe that differs between recordings, parcels the montage cannot resolve, QC outliers
recordings.csv (+ .json) one row per recording in the study config: subject, session, recording, group, its output folder, status (and the logged error), the paths of its pipeline_report.html, electrode-registration check and step figures, the version that localized it, its QC metrics and, under Monte Carlo sampling, its lowest coverage and gain and its count of collinear and undersampled parcels
parcel_coverage.csv (+ .json) Monte Carlo only: one row per parcel over the recordings: coverage, gain, its highest collinearity and the parcel it is most often collinear with, and reliable (never collinear at r >= 0.99, never below 0.5 coverage)
provenance.json the localization recipe (preset, atlas, BEM, source space, sampling, inverse) and whether every recording used the same one

Paths are relative to qc/, and each recording is named by its fields, so a reader never parses folder names such as sub-801_ses-01. Check it with lumiere check qc/. Without the extra, study qc is unchanged.

Python API

from source_localization.study import (
    StudyConfig,
    process_study,
    create_study_from_folder,
    analyze_study
)

# Create study from folder
config = create_study_from_folder(
    folder='/path/to/eeg_data',
    name='MyStudy',
    preset='roi_based_ellipsoid'
)

# Process all subjects
result = process_study(config, n_jobs=4)
print(f"Processed {result.n_successful} subjects, {result.n_failed} failed")

# Run analysis
df = analyze_study(
    config,
    bands={'low_gamma': (30, 55), 'theta': (4, 10)},
    connectivity_methods=['coherence', 'plv'],
    n_jobs=4
)

Spectral and Connectivity Analysis

The analysis module wraps MNE-Python and MNE-Connectivity for batch analysis of processed subjects.

Band Power Analysis

Computes power spectral density per ROI using Welch's method. study analyze and analyze_study use the study file's bands: (since 0.9.12; before, they were ignored and DEFAULT_BANDS always used), else DEFAULT_BANDS. Each subject's analysis/bands.json records the limits its files were computed with, and files computed with other limits are recomputed, with a warning, rather than reused. analyze_subject takes the bands directly:

from source_localization.study import analyze_subject, DEFAULT_BANDS

# DEFAULT_BANDS: delta, theta, alpha, beta, low_gamma, high_gamma
result = analyze_subject(
    subject_dir='derivatives/source_localization/sub-001',
    bands=DEFAULT_BANDS,
    overwrite=False
)

# Output: analysis/band_power.csv
# Columns: roi, band, fmin, fmax, power, power_db

There is no band called gamma in the defaults: they split it into low_gamma (30-55 Hz) and high_gamma (65-100 Hz). Unknown band names are rejected. A study file's band names may contain spaces (FORGE's "Low Gamma"); band_power.csv keeps the name as written, and file names use a safe stem (connectivity_coherence_low_gamma.csv), which collect_connectivity_matrices accepts either way.

Connectivity Analysis

Computes ROI-to-ROI connectivity using MNE-Connectivity:

# Requires: pip install mne-connectivity
result = analyze_subject(
    subject_dir='derivatives/source_localization/sub-001',
    connectivity_methods=['coherence', 'plv', 'wpli'],
    connectivity_bands=['low_gamma', 'theta'],
    epoch_length=2.0  # For continuous data, create 2s epochs
)

# Output: analysis/connectivity_coherence_low_gamma.csv (n_roi x n_roi matrix)

Available Methods

Method Description Use Case
coherence Magnitude-squared coherence Default, linear relationships
plv Phase-locking value Phase synchronization
wpli Weighted phase-lag index Volume conduction robust
imcoh Imaginary coherence Zero-lag artifact removal

CLI Usage

# `--bands` picks among the study's bands (all of them by default); a name the study file does not define
# is an error that lists the ones it does
source-localization study analyze study_config.yaml \
    --connectivity coherence plv \
    --epoch-length 2.0 \
    --jobs 4 \
    --verbose

Configuration Presets

Available Presets (7 total)

Source counts were measured on 2026-09-03 with the Allen32 atlas, except roi_based_ellipsoid, re-measured on 2026-11-18 under the 0.9.8 placement rule (exactly 200 on Allen32 and on Antwerp). ROI-based counts before 0.9.8 depended on the atlas. roi_based_sphere was withdrawn in 0.9.12 (its brain-centred sphere puts the electrodes inside the brain layer; see History). Presets in src/source_localization/config/presets/ are the source of truth for every setting; the CLI lists them under --preset.

Preset BEM Source space Sources Notes
roi_based_ellipsoid Ellipsoid ROI-based 200 Default. Sources inside each parcel. Used by the FORGE study with --atlas allen32
shell_ellipsoid Ellipsoid Shell 187 Concentric shells; see shell coverage known issue
shell_ellipsoid_extended Ellipsoid (extended) Shell 115 Conductor extended over the olfactory bulbs
shell_sphere Sphere Shell 89 Fast shell-based; centred under the electrodes (0.9.12)
ellipsoid_cartesian Ellipsoid Cartesian grid 141 Volumetric grid, auto spacing
ellipsoid_cartesian_extended Ellipsoid (extended) Cartesian grid 150 Conductor extended over the olfactory bulbs
sphere_cartesian Sphere Cartesian grid 80 Volumetric grid, auto spacing

"Extended" ellipsoids shift the centre anteriorly and lengthen the Y semi-axis so the olfactory bulbs fall inside the conductor. Without that, MNE drops bulb sources from the forward. Since 0.5.1 the forward step reports any dropped sources and restricts every per-source array to the survivors, so a drop can no longer misalign downstream indexing, but it still discards anatomy.

Head-model layers: with or without scalp

Every preset's ellipsoid is brain, skull (0.5 mm) and scalp (0.3 mm), the head model every release has built and MS1 used. It stays the default. For an array that sits on the bone, bem.ellipsoid.layers: brain_skull drops the scalp:

bem:
  ellipsoid:
    layers: brain_skull          # default brain_skull_scalp
    n_layers: 2
    conductivities: [0.33, 0.0042]   # brain, bone
    skull_thickness_mm: 0.25     # all of the bone (default 0.5); no scalp_thickness_mm

MNE's solver takes one or three surfaces, so the bone is built as two half-thickness shells at bone conductivity; an interface with the same conductivity on both sides adds nothing. The BEM cache is still bem_cache/ellipsoid_3layer.pkl, and head-model ensembles (locate, validation) scale every bone shell together. Only the ellipsoid has the option; a no-scalp sphere is bem.sphere.conductivities: [brain, bone, bone].

Why it exists (pilot Stage A2, one mouse, simulation on 0.9.0): in a realistic head with no scalp, the preset ellipsoid localised thalamic sources with a median error of 2.84 mm at 10 dB, a no-scalp ellipsoid with 0.25 mm of bone 0.90 mm, the mouse's own realistic head 0.77 mm. Against simulated heads that do have a scalp it reverses: the no-scalp models were worse at 10 and 20 dB. Which should be the default is not decided; no preset uses it yet.

Source Space Types

Type Description Orientation
ROI-based Sources placed inside each atlas parcel Free
Cartesian 3D volumetric grid Free
Shell Concentric geometry-matched shells Free

Listed without ranking: which one suits which question on this array has not been measured. Every per-type setting and its default: docs/guides/source_space_options.md.

Surface source spaces

Withdrawn in 0.9.10. source_type: surface (the anatomical cortical mid-ribbon and the icosphere), the presets ellipsoid_surface, ellipsoid_surface_anatomical and sphere_surface, and inverse.orientation: fixed / loose are refused when a configuration is built. A surface has no deep parcels, and on the dorsal array every deep scalp pattern has a cortical look-alike, so a surface reports deep activity as cortical. In simulation it put 56-76% of thalamic, subcortical, hypothalamic and hippocampal sources in a cortical parcel at every noise level. Why there is no surface method, the numbers, and what this does not claim about the volumetric spaces: docs/known-issues/SURFACE_WITHDRAWN.md. Finished surface runs still load, and study qc marks them withdrawn.

Hybrid source space

Withdrawn in 0.9.3, never published. source_type: hybrid put cortex, cerebellum and olfactory bulb on the anatomical surface (fixed along the normal) and the deep categories on a Cartesian grid, under pool sampling only (Monte Carlo or parcel-subspace). It was built because a cortex-only space puts deep activity on the nearest cortex. A config naming it is now refused when it is built, with the reason and the alternatives; the ellipsoid_hybrid preset is removed.

Why. On the dorsal MEA30 array a deep source is about as strong as a cortical one: thalamus 0.84x, hippocampus 0.95x, hypothalamus 0.65x of the median cortical source. Its scalp pattern also has a cortical look-alike. The best match with one surface source has median |cos| 0.993-0.996, above 0.95 for essentially every deep source. The reverse holds too: median 0.996 from cortex to one deep source. Two cortical sources 2 mm apart are less alike (0.987). So the data cannot split activity between the two parts, and the model's structure decided it: three free directions in the volume against one normal on the surface. In simulation (4,000 truths, head-model error, allen32), every cortical, cerebellar and olfactory truth came out largest in a deep parcel, even with cortical truths oriented exactly along the surface normals. No per-parcel rescaling fixed that. Rescaling lowered top-1 accuracy, on the Cartesian pool as well.

In a human head, deep structures are far deeper relative to the cortex, which is why a cortex-only model is a safe default there and not here.

Runs made with the hybrid still load (source_space/hybrid.py keeps the reader the planted-network validation uses). Compare a hybrid parcel only with itself across recordings, never with other parcels.

Which source space suits deep generators on this array has not been measured yet. The available ones are listed by source-localization list --methods.

Parcel-Subspace Sampling (withdrawn in 0.9.12)

Withdrawn in 0.9.12. A config naming source_sampling: parcel_subspace is refused. It collapses each free-orientation pool source to one direction, and on the free pools that remain (Cartesian, shell) it is near chance: 6-9% of simulated sources won their own parcel, against 3-4% chance (options inventory section D, D9). On the surface (withdrawn in 0.9.10) it was not better overall either (13.7-15.1% against 16.3-21.4% for fixed sampling); only its cortical top-1 was higher (45-50%). It returns if it gets a three-direction mode. The code stays, so finished runs can be read; study qc marks them withdrawn. The description below is kept for those runs.

source_sampling: parcel_subspace builds the same dense pool as Monte Carlo, but instead of averaging many sparse draws it represents each parcel by the top n_patterns patterns of its pool leadfield and solves one inverse over all of them. Deterministic: no draws, seed or sign alignment. Works with the Cartesian and shell source spaces; roi_based has no dense pool and is refused, as under Monte Carlo. A free-orientation pool source (Cartesian, shell) is collapsed to its dominant leadfield direction before the patterns are taken: unlike Monte Carlo since 0.9.2, parcel-subspace has no three-direction mode.

source_space:
  source_sampling: parcel_subspace
  parcel_subspace:
    n_patterns: 3        # patterns per parcel
    method: MNE          # MNE | sLORETA
    pool_spacing_mm: 0.2

Measured in simulation on the 30-electrode mouse array (one head model, 10 dB), as MS1's peak displacement over 15 cortical parcels: the deployed Monte Carlo operator (48 x 100, sLORETA) 3.05 mm, ROI-based 1.85, this operator (r = 3, MNE) 1.95; the floor set by the exact Bayesian posterior was 0.98. MNE localizes better than sLORETA here; per component the two have the same filter and differ only in scale, so ITC, phase and within-parcel effect sizes are identical under either. More than 3 patterns helped the large dorsal parcels and cost the rest.

Output per parcel: the dominant pattern's series as signed, the root-sum-square over components as magnitude (provisional), and every component (step6_roi_components.pkl) and the operator (parcel_subspace_operator.npz). Implementation: source_space/parcel_subspace.py, steps/parcel_subspace_roi.py; tests in tests/test_parcel_subspace.py.

Which Preset Should I Use?

No preset is recommended over another yet: the 0.9.x source-space comparison has not been measured. What is known:

  • ROI statistics on an existing design: roi_based_ellipsoid --atlas allen32 (the default, and what FORGE used).
  • Whole-brain parametric mapping: shell_ellipsoid, with the coverage caveat linked above.
  • Fast iteration: the sphere presets build quickest. shell_sphere is centred under the electrodes since 0.9.12; before, it was centred on the brain and the electrodes sat inside its brain layer (as on roi_based_sphere, withdrawn in 0.9.12).
  • Cortical activity specifically: there is no cortex-only option. On this array deep and cortical patterns are near-identical (see Surface source spaces), and every source space here can report activity from one in the other.

All inverse methods can be set per preset or with --method. sLORETA is the default in every preset and the most robust to mouse-scale leadfields (see the regularization known issue).


Atlas Selection

Atlases are declared in src/source_localization/data/atlas/registry.yaml and selected with --atlas on the CLI or atlas= in the Python API. All of them share one voxel grid and one coordinate space, so BEM geometry and electrode positions are identical across atlases; only the label volume and the ROI mapping change.

Atlas Parcels Description
antwerp 46 UAntwerpen C57BL/6 MRI atlas: 46 named structures plus background. Labels only ~31% of the brain mask, so nearest-label assignment can move a source up to 2.6 mm. Default for presets that do not carry their own atlas
allen32 32 Allen CCFv3 registered into Antwerp space, 16 parcels per hemisphere (ids 1-16 left, 17-32 right). Tiles grey matter. Each parcel carries a tier and category. Prefer this for per-ROI claims
allen 32 Alias of allen32 (identical files)
allen64 64 Finer Allen parcellation, 32 per hemisphere. No roi_categories file
allen26 26 Allen32 with six bilateral pairs merged that the 30-channel array cannot separate
coarse22 22 The 46 Antwerp structures regrouped into 22 regions. Inherits Antwerp's sparse coverage. Accepted as coarse_22roi by the validation CLI
# CLI
source-localization run --preset shell_ellipsoid --atlas allen32 --eeg data.set --output results/

# Python API
pipeline = Pipeline.from_preset('shell_ellipsoid', atlas='allen32')

Every preset works with every registered atlas.


Usage

Command Line Interface

# Run pipeline with preset
source-localization run --preset roi_based_ellipsoid --atlas allen32 --eeg data.set --output ./results

# Override parameters
source-localization run --preset roi_based_ellipsoid --atlas allen32 --eeg data.set \
    --snr 5.0 --method sLORETA --output ./results

# Include optional post-processing
source-localization run --preset roi_based_ellipsoid --atlas allen32 --eeg data.set \
    --spectral --visualize --output ./results

--method on the CLI accepts all six methods (source-localization list --methods). LCMV and DICS are experimental (0.9.12): outside the 1.0.0 supported set, and a config naming either gets a warning. LCMV is applied to the average of all epochs, so it gives one evoked time course rather than a series per epoch, and DICS gives one power value per source. Neither is covered by the mouse-scale regularization fix. One test each (since 0.9.11) runs them through Pipeline.run on a single source and checks the peak lands on it; that is a smoke test, not a validation. Both have been run through the shipped step only on single, uncorrelated simulated sources, which is a beamformer's best case. There they ran without error on the volumetric presets, but on epoch-averaged data, so not like-for-like with sLORETA (options inventory, section D12, 2026-11-18). Nothing is known about them with correlated sources, such as bilateral pairs or the cortical/deep look-alikes. Monte Carlo sampling builds sLORETA operators and refuses another --method.

Python API

from source_localization import Pipeline

# Create and run pipeline
pipeline = Pipeline.from_preset('roi_based_ellipsoid', atlas='allen32')
results = pipeline.run(eeg_file='data.set', output_dir='./results')

# Access outputs
stc = results['inverse_solution']['stc_signed']          # mne.VolSourceEstimate
roi_timeseries = results['roi_extraction']['roi_stcs_signed']  # dict: roi name -> array

# With parameter overrides (dotted keys)
pipeline = Pipeline.from_preset(
    'roi_based_ellipsoid', atlas='allen32',
    **{'inverse.snr': 5.0, 'inverse.method': 'sLORETA'}
)

Input requirements

The EEG file must be an EEGLAB .set (epoched or continuous) whose channel names are the electrode labels in data/electrodes/mouse_array_coords.csv (E1..E30). Channel order in the file does not matter: the EEG step reorders channels to match the electrode registration and refuses a file that lacks a registered electrode. Channels not in the registration are dropped with a message.

Output Files

results/
├── data/
│   ├── roi_timeseries_signed.set     # ROI time series (for connectivity)
│   ├── roi_timeseries_magnitude.set  # Absolute values (for power); only when
│   │                                 #   outputs.output_variants includes magnitude (no preset does)
│   ├── step6_roi_timeseries_*.pkl    # The ROI series as pickles (always written)
│   ├── step5_source_summary.json     # Source amplitude summary (study qc reads it)
│   ├── step[1-4]_*.pkl               # Intermediate results (save_intermediate)
│   └── step5_stc_*.pkl, source_timeseries_*.set
│                                     # Per-source series: only with outputs.save_source_series
│                                     #   (or --save-source-series), for debugging (0.9.9)
├── figures/
│   └── *.png                         # Per-step QC figures
└── pipeline_report.html              # Summary report

Load in MNE:

import mne
epochs = mne.io.read_epochs_eeglab('results/data/roi_timeseries_signed.set')
# Or for continuous data:
raw = mne.io.read_raw_eeglab('results/data/roi_timeseries_signed.set')

What the outputs are

  • Magnitude is the L2 norm across orientation components per source, averaged over the sources in each parcel. Use it for power.
  • Signed keeps polarity. It is, by default, the max-variance component per epoch, whose sign is arbitrary between epochs and sources; use it for within-epoch connectivity, not for polarity claims.
  • The default free-orientation signed series costs phase locking. A source can switch axis between epochs, and where its components have opposite signs each switch flips its series by 180 degrees. On real mouse 40 Hz ASSR recordings this happened in 15% of epochs and lowered ROI-based inter-trial coherence (wild-type mean 0.563 against 0.671). For phase-based measures (ITC, phase, phase connectivity) set inverse.signed_orientation: leadfield: every epoch is projected onto each source's fixed leadfield direction (steps.inverse_solution.leadfield_directions), with signs aligned within each parcel. It depends on the head model only, so it is the same for every recording. The default is unchanged so existing results reproduce. Monte Carlo and parcel-subspace outputs are not affected.
  • Monte Carlo runs with free-orientation sources (shell, Cartesian) keep three directions per source from 0.9.2 and write each parcel's x/y/z series (step6_roi_timeseries_vector.pkl), its magnitude (norm per sample) and a signed series read along the parcel's dominant leadfield direction. Use the vector series for band power. source_space.monte_carlo.directions: dominant restores the earlier one-direction operator. See docs/guides/monte_carlo_sampling.md.
  • DICS produces a single band-power value per source, not a time series. The pipeline writes it as roi_power_*.csv and source_power_*.csv rather than .set files, which cannot hold one sample.
  • ROIs with no assigned source are omitted from the outputs rather than written as zeros. The run log lists them.

Visualizations

Source Map Visualization

from source_localization.source_analysis import (
    SourceMapVisualizer, PRESETS, apply_style
)

apply_style('publication')
viz = SourceMapVisualizer(source_coords, brain_surface)
fig = viz.plot_surface_heatmap_smooth(
    gamma_power,
    view='dorsal',
    cmap='hot_black',
    show_all_sources=True
)

Connectivity Visualization

from source_localization.source_analysis import (
    ConnectivityVisualizer, extract_mne_connectivity
)
from mne_connectivity import spectral_connectivity_epochs

conn = spectral_connectivity_epochs(epochs, method='coh', fmin=30, fmax=55)
matrix = extract_mne_connectivity(conn, freq_band=(30, 55))
viz = ConnectivityVisualizer(roi_labels=epochs.ch_names)
fig = viz.plot_connectivity_matrix(matrix, cluster_order=True)
fig = viz.plot_chord_diagram(matrix, threshold_percentile=90)

ROI Visualization

from source_localization.source_analysis import ROIVisualizer

roi_viz = ROIVisualizer(atlas_path, roi_mapping_path)
fig = roi_viz.plot_roi_map(roi_values, show_boundaries=True, show_labels=True)

ROIVisualizer, AtlasLookup, and CorticalSourceSpace read label volumes through utils.atlas.get_true_affine(), which detects whether a file's header is 10x inflated. Do not scale affines by hand; see CLAUDE.md for which bundled files are in which convention.


Model catalogue

Every probability model the package uses to say where a signal comes from (the location posteriors, the priors they rest on, and the calibrations applied to their maps) is declared once in source_localization/methods.py, with a stable id, a version, its priors and values, and the domain where its calibration holds. The list is in docs/methods/CATALOGUE.md, generated from that declaration; source-localization list --catalogue prints the same. Results name the ids and versions that produced them. tests/test_catalogue.py fails if the page is stale, an id repeats, a prior is not catalogued or an implementation does not import.

Validation

Full guide: docs/validation/README.md. It covers which tool answers which question, validating a new atlas step by step, what to report, and which earlier results not to quote. Planned changes are in docs/validation/DESIGN_validation_upgrade.md.

The package includes a dipole simulation framework for validating source localization accuracy without EEG data.

How Validation Works

Validation uses forward-inverse testing: a known dipole is placed at a specific location, its scalp EEG is simulated using the forward model, then the inverse solution attempts to recover the original location. Metrics include:

  • Localization error (mm): Euclidean distance between true and estimated positions
  • ROI accuracy (%): whether the estimated source is in the correct parcel
  • Depth-stratified analysis: performance by source depth from electrodes

Every run states its regime (validation.regime, or --regime):

  • realistic (default from 0.6.0): truths at the requested positions through head models drawn from a prior (registration shift, skull conductivity), recorded background noise when validation.background is set, and a noise-only control.
  • legacy: the v0.5.x assumptions (the inversion's own forward model at grid-snapped positions, the "inverse crime"; generated noise; no noise-only control). Kept only to reproduce pre-0.6.0 numbers, which are best-case and not comparable with realistic ones. Results go to <config>_legacy/.

metrics.json records the regime under validation_regime. The validation guide defines both regimes and their options.

Setting Up a Validation Study

my_validation/
├── configs/                          # Your validation configs
│   ├── ellipsoid_shell_sLORETA.yaml
│   ├── sphere_cartesian_MNE.yaml
│   └── ...
└── results/                          # Created automatically
    └── ellipsoid_shell_sLORETA/
        ├── metrics.json
        ├── validation_report.html
        └── figures/

Validation Config Format

Validation configs are standard pipeline configs with an optional validation section:

pipeline:
  name: ellipsoid_shell_sLORETA
  bem_type: ellipsoid       # sphere or ellipsoid
  source_type: shell        # shell, cartesian or roi_based

inputs:
  brain_volume: data/atlas/Atlas_3DRois.nii
  brain_labels: data/atlas/allen/allen_labels.nii.gz
  roi_mapping: data/atlas/allen/roi_mapping.json
  electrodes_csv: data/electrodes/mouse_array_coords.csv
  eeg_file: null  # Not needed for validation

inverse:
  method: sLORETA           # MNE, sLORETA, dSPM, eLORETA, LCMV, DICS
  snr: 1.0                  # the default since D4 (3 before)
  depth_weighting: 0.8      # read by method MNE only

bem:
  ellipsoid:
    n_layers: 3
    conductivities: [0.33, 0.0042, 0.33]  # brain, skull, scalp
    ellipsoid_method: axis_aligned
    ellipsoid_margin: 1.23
    use_cache: true

source_space:
  shell:
    n_shells: 3
    min_points_per_shell: 20
    max_points_per_shell: 100
    distribution: fibonacci
    filter_exterior: true

validation:
  snr_levels: [10]          # SNR levels to test (dB)
  n_trials: 25              # Trials per test position
  test_mode: combined       # combined (recommended), roi_centroids, or uniform_grid
  grid_spacing_mm: 1.0
  grid_margin_mm: 0.2
  scale_factor: 1.0
  dipole:
    amplitude_nAm: 50.0
    duration_s: 1.0
    sfreq: 500.0

outputs:
  dir: null                 # Auto-set by validation runner
  save_intermediate: true   # false: no step 1-5 pickles, figures or source .set files; the ROI
                            # series and the run's records are always written (0.9.4)
  save_source_series: false # true: also write the per-source series (step5_stc_*.pkl and
                            # source_timeseries_*.set; ~80% of a run's disk). For debugging (0.9.9)
  figure_format: png
  figure_dpi: 100

Running Validation via CLI

# List available configs
source-localization validate --test-dir ./my_validation --config configs/ --list

# Run all configs
source-localization validate --test-dir ./my_validation --config configs/ --all

# Run specific config
source-localization validate --test-dir ./my_validation --config configs/ellipsoid_shell_sLORETA.yaml

# Quick test mode (5 ROIs, 1 trial, SNR=10)
source-localization validate --test-dir ./my_validation --config configs/ --all --quick

# Override SNR and trials
source-localization validate --test-dir ./my_validation --config configs/ --all \
    --snr 5 10 20 --trials 50

# Choose the test mode
source-localization validate --test-dir ./my_validation --config configs/ --all \
    --test-mode combined

# Choose the atlas (registry names; `full` and `coarse_22roi` are accepted legacy aliases)
source-localization validate --test-dir ./my_validation --config configs/ --all \
    --atlas allen32

# Summarize existing results
source-localization validate --summarize ./my_validation/results/

# Compare multiple configs
source-localization validate --compare \
    ./my_validation/results/config1/ \
    ./my_validation/results/config2/

The validation CLI defaults to the Antwerp atlas. Selecting anything else suffixes the output directory with the atlas name.

Test Modes

Mode Description Use Case
roi_centroids Test at parcel centroid positions ROI accuracy
uniform_grid Test on a uniform 3D grid across the brain Localization error, depth analysis
combined Both: ROI accuracy from centroids, localization error from the grid Recommended

Understanding Results

results/config_name/
├── metrics.json              # Full metrics (JSON)
├── validation_report.html    # Interactive HTML report
├── data/                     # Intermediate pipeline outputs
└── figures/
    ├── localization_error_map_snr10.png
    └── depth_error_snr10.png

metrics.json holds, per SNR level, localization error statistics, ROI accuracy (exact hits over test positions), and depth-stratified error.

What the validation numbers mean

Earlier versions of this file quoted a single headline accuracy for the recommended preset. Those figures came from one configuration on the Antwerp atlas under the default inverse crime, and the shallowest depth bin was being reported as if it were the whole brain. Accuracy depends strongly on depth, atlas, and source space, so run the validation for the configuration you intend to use and report the depth-stratified result. The Monte Carlo sampling guide describes how to integrate over source-grid placement. validation.displacement scores any parcel operator by peak displacement, the expected distance in mm between the parcel a source is in and the parcel it is credited to (the statistic of the published resting-state paper, reproduced exactly against its table).

Python API for Validation

from source_localization.validation import ValidationRunner, run_validation
from pathlib import Path

# Run multiple configs
results = run_validation(
    test_dir='/path/to/my_validation',
    config_files=[Path('configs/config1.yaml'), Path('configs/config2.yaml')],
    snr_levels=[5, 10, 20],
    n_trials=25,
    test_mode='uniform_grid',
    verbose=True
)

# Run a single config with more control
runner = ValidationRunner(
    config_path='configs/ellipsoid_shell_sLORETA.yaml',
    output_dir='results/ellipsoid_shell_sLORETA',
    verbose=True
)
runner.setup()
metrics = runner.run(snr_levels=[10], n_trials=25)
runner.save_results(metrics)

Pipeline Architecture

1. Electrode Registration  → MNE Info with 30 channel positions
2. EEG Data Loading       → EEGLAB .set → epochs, channels reordered to the registration
3. BEM Model              → Sphere (numerical; analytic optional) or Ellipsoid (numerical)
4. Source Space           → ROI-based / Cartesian / Shell
5. Forward Solution       → Leadfield G; per-source arrays restricted to kept sources
6. Inverse Solution       → MNE / dSPM / sLORETA / eLORETA / LCMV / DICS
7. ROI Extraction         → One time series per parcel with at least one source

Optional (--spectral, --visualize; --visualize runs the spectral step too):
8. Spectral Analysis      → Band power per ROI
9. Visualization          → Figures and HTML report (no source snapshot under Monte Carlo or
                            parcel-subspace sampling, which solve no single grid)

Troubleshooting

Checking what the inverse did, source by source

  • Since 0.9.9 the per-source series is not written by default; it was ~80% of a run's disk. Only the source-analytics-vertex plugin and source-analytics' no-step6 fallback read it. Re-run with --save-source-series (or outputs.save_source_series: true) to get step5_stc_*.pkl and source_timeseries_*.set. skip_roi_extraction runs always write it.

"recording lacks N registered electrode(s)"

  • The .set file is missing channels that the electrode CSV registers. The forward is built for all 30, so the data cannot be aligned. Check the file's channel names.

"source_type 'surface' ... was withdrawn in 0.9.10" (or inverse.orientation 'fixed')

  • The surface source spaces and the fixed and loose orientations were withdrawn; see docs/known-issues/SURFACE_WITHDRAWN.md. Use another preset, or check out 0.9.9 to reproduce a finished surface run.

"BEM CONTAINMENT: N sources fall outside the inner skull"

  • The conductor is smaller than the source space. Downstream indexing stays correct, but those sources are gone. Use an "extended" preset or a larger ellipsoid margin.

"Intensity projection puts N electrode(s) more than X mm above the brain mask"

  • The intensity threshold did not find the skull in this image. Use electrode.projection_method: brain_mask with skull_offset_mm set to the skull height, or none with measured positions. The limit is electrode.max_surface_above_brain_mask_mm.

"MNE's Berg-Scherg fit for this sphere failed"

  • Only the analytic sphere (numerical: false) fits this. Use the numerical sphere or change the radii slightly.

"mne-connectivity not found"

  • Install with: pip install mne-connectivity

"Module not found"

source .venv/bin/activate
uv pip install -e .

Citation

@software{mouse_eeg_source_localization,
  author = {Edmondson, Alex and Pedapati, Ernest},
  title = {Mouse EEG Source Localization Package},
  year = {2025},
  publisher = {GitHub},
  url = {https://github.com/alexedmon1/source-localization}
}

Package Structure

source_localization/
├── src/source_localization/
│   ├── pipeline.py              # Main orchestrator
│   ├── cli.py                   # CLI entry point
│   ├── config.py                # Configuration and atlas registry
│   ├── steps/                   # Pipeline step implementations
│   ├── bem/                     # BEM models (sphere, ellipsoid)
│   ├── source_space/            # Source space types
│   ├── study/                   # Multi-subject processing
│   │   ├── config.py            # StudyConfig class
│   │   ├── batch.py             # Batch processing
│   │   └── analysis.py          # MNE wrapper analysis
│   ├── source_analysis/         # Figures, atlas lookup, depth-weighted ROI utilities
│   ├── methods.py               # Method vocabulary and the model catalogue (docs/methods/CATALOGUE.md)
│   ├── locate/                  # Location posteriors, head-model ensembles, whitening, regions
│   ├── field/                   # Field templates and field definitions (the field method)
│   ├── validation/              # Dipole simulation validation
│   ├── utils/atlas.py           # Affine-convention detection; always go through this
│   ├── config/presets/          # 11 YAML presets
│   └── data/                    # Atlas and electrode files
└── pyproject.toml

History

The package version is 0.9.13. Earlier revisions of this README carried a separate 1.x numbering that never corresponded to a package release; it has been dropped. Release tags are listed under Reproducing a published analysis, and git log is the changelog.

Notable changes in 0.9.13 (2026-11-20): the Monte Carlo magnitude readout is the mean of the members' own norms (built 2026-11-19, Esprit cc57; made the default by Alex 2026-11-20 after the group test below), and an optional debiased parcel power for evoked data. This changes every three-direction Monte Carlo run's magnitude series (shell and Cartesian pools; the signed and vector series do not change). Its measured benefit is at inverse.snr 1 (the default since 0.9.12); at inverse.snr 3 it gains only +0.3 to +1.5 points. Every measurement below was made with 0.9.11's code, so on the 642-vertex head-model mesh, not 0.9.12's 2562. Each with a test (tests/test_mc_readout.py).

  • source_space.monte_carlo.readout: mean_of_norms (default). A three-direction parcel's magnitude per sample is the mean over Monte Carlo draws of the mean over its drawn members of each member's own |W_m y|. Since 0.9.2 it was the norm of the averaged parcel 3-vector (vector_mean); in spread-out parcels the members' differently oriented estimates partly cancel in that mean, so cortical and cerebellar parcels read low against compact deep ones (reports/no_scalp_2026-11/diag/README.md, sections 2, 4, 4b and 4c; single dipoles on perturbed heads, allen32, sLORETA, 160 per draw, SNR 3 per sample, 1,000 truths). Below, R is the number of independent recorded-noise repetitions each truth's readout is averaged over (the evoked-average situation), not the number of Monte Carlo draws, which is 100 throughout. Top-1 parcel, new readout minus shipped:
    • inverse.snr 1, sub-914's noise, shell and Cartesian (4b), at R = 1 / 5 / 20 / 100: preset head +0.4 to +3.1 points, no-scalp head +10.2 to +16.6.
    • inverse.snr 1, three more subjects' noise (801, 829, 962), both pools and both heads (4c): it matches or beats the shipped readout in 46 of 48 cells (the two exceptions -0.3 and -0.1, inside the ~2.5-point paired chance range); at R = 100 preset +3.2 to +4.9, no scalp +12.3 to +17.4, and within 1.9 points of debiased power.
    • inverse.snr 3 (the default before 0.9.12), preset head, sub-914: only +0.3 to +1.5 (shell +0.7 / +0.7 / +1.4 / +1.0, Cartesian +0.3 / +0.7 / +1.5 / +0.4 at R = 1 / 5 / 20 / 100): there a norm's noise floor offsets most of the gain.
    • It trades deep parcels for cortex (inverse.snr 1, preset head, R = 100, the three subjects' range): cortex 34-36 -> 46-49% and cerebellum 52-79 -> 86-90% on both pools; on the shell thalamus 66-70 -> 53-57%, hypothalamic 49-63 -> 21-51% and brainstem 68-74 -> 43-53%; on Cartesian brainstem 63-65 -> 40-47% and hypothalamic 65-84 -> 63-72%, while thalamus rises slightly, 30-34 -> 34-40%. (On sub-914's Cartesian run thalamus is unchanged at R = 100 but falls 19.1 -> 12.8% at R = 1.) Category cells are small (47 thalamic truths, 43 hypothalamic).
    • Its noise floor is more cortical (4c): on noise alone it names a cortical parcel 83-86% of the time on every pool and head at inverse.snr 1, against 40-72% for the shipped readout (cortical parcels are 43.8% of allen32). A norm of noise is positive and largest where noise projects most, under the array. So where a parcel's magnitude is mostly noise (weak or distributed activity, resting-state magnitude compared between parcels) it leans further toward cortex than the shipped readout. A parcel compared with itself between conditions or groups carries the floor on both sides, and it cancels only if the noise is the same.
    • Within-parcel group differences in dB: no practical difference (reports/readout_groupdiff_2026-11-20/, git-ignored; 24 pseudo-subjects from FORGE 801/829/914/962 recordings plus simulated theta activity, a difference of 0-6 dB in one allen32 parcel at a time, all 32 as targets, shell and Cartesian, head with scalp). The new readout's Hedges' g at the target is at most 0.05 below the shipped one's (cortical targets, weak signal), with the same detection rate, dB difference and false-positive rate (1-7% with no difference). Two findings from the same test hold for every readout: a difference placed in one parcel makes most other parcels significant (the target has the largest effect in only 1-29% of experiments), and a true 6 dB difference reads as about 2 dB for a weak signal and 4.7 dB for a strong one. The signed series loses up to half the effect size when a parcel's sources are coherent (D6, not in this release). It is nonlinear, so each draw is applied to the data (in chunks of 1,000 samples) instead of the averaged operator, so it is slower: on one FORGE recording (420,000 samples, 100 draws, BLAS on 2 threads) the Monte Carlo step takes 38 s instead of 4 s on the shell pool and 61 s instead of 16 s on the Cartesian pool, about 35-45 s more per recording (readout: vector_mean keeps the old speed). Measured while two other measurement jobs (2 BLAS threads each) shared the CPU, as was the first implementation's 157 s / 177 s. Divided by the number of draws, as the operator is, so coverage scaling is unchanged. readout: vector_mean reproduces 0.9.12 byte for byte. Not affected: one-direction runs (directions: dominant, or a pool with no free source) have no separate magnitude series: the step returns the signed series as roi_stcs_magnitude and writes no magnitude file, as before. In a three-direction run a one-direction parcel (normal-fixed members only, which no current pool has) keeps the absolute value of its single row applied to the data. Recorded as magnitude_readout in data/step6_mc_directions.json and readout in monte_carlo_report.json; config_resolved.yaml records readout and debiased_power.enabled for Monte Carlo runs. study qc: column mc_readout (mean_of_norms, vector_mean, vector_mean (pre-readout) for three-direction runs made before the option, none without three-direction parcels, unknown). The study recipe compares each run's effective readout, so a study mixing readouts shows as mixed, and a 0.9.12 run and a new vector_mean run do not differ in it. source-analytics and study qc's roi_amp_mean / roi_amp_std read step6_roi_timeseries_magnitude.pkl without checking the readout: in a study mixing readouts their values are not comparable, and mc_readout is the column that shows it.
  • source_space.monte_carlo.debiased_power: {enabled: true, baseline: [tmin, tmax]}, evoked data only (off by default). Per parcel and time sample, the mean over epochs of [mean over draws of mean over members of |W_m y|^2 - tr(W_m C W_m')], C the second moment of all epochs' baseline samples (in the referenced, channel- aligned data the operators are applied to). Its noise term has expectation zero, so averaged over epochs it tends to the sources' own power, with neither the cancellation nor a noise floor. Measured (diag sections 4 and 4b) with C the whole recording's covariance, which is exact there because the simulated recording's noise is that recording; a baseline-estimated C, as the option uses, was not measured. There, at R = 100: inverse.snr 3, shell 52.3% vs the shipped 46.3%, Cartesian 50.6% vs 44.2%; inverse.snr 1, shell 52.3% vs 47.5%, Cartesian 51.4% vs 47.8%. Written as data/step6_roi_power_debiased.pkl with step6_roi_power_debiased.json (units, baseline, epochs, baseline samples). A power, not a time series of activity (single samples can be negative), and not defined for resting state, which has no noise-only segment. Refused for continuous recordings, a baseline after the stimulus (tmax > 0) or outside the epochs, fewer than 10 baseline samples per channel in total, and outside Monte Carlo sampling. It cannot tell an epoched resting-state .set with tmin < 0 from evoked data: enable it only for stimulus-locked epochs, whose baseline holds no stimulus-locked signal.
  • Not changed: the vector series (step6_roi_timeseries_vector.pkl) is still the vector mean, so a band power summed from its three components inherits the cancellation. A band power from each member's own power is not implemented.

To reproduce a 0.9.12 Monte Carlo run: source_space.monte_carlo.readout: vector_mean; for a 0.9.11 run, add the settings at the end of the 0.9.12 entry.

Notable changes in 0.9.12 (2026-11-20): the decisions of 2026-11-19, in three parts: the supported set, the head model, and the inverse.snr default. Every run's results change (the head model's mesh and the regularisation both move them); finished runs' numbers do not, and study qc tells the two apart. To reproduce a 0.9.11 run, see the end of this entry.

Supported set (decisions that need no measurement and change no supported result: two options withdrawn, a head model that never existed refused, the beamformers labelled experimental, a study's own bands honoured, and one new QC column; tests/test_supported_set_0912.py). One output changes: study analyze on a study file with its own bands: now computes those bands, under those names (FORGE's and Autifony's study files define High Gamma as 65-80 Hz plus an 80-100 Hz Epsilon band, and FORGE names them Low Gamma, High Gamma, ...), where it used to compute the six defaults whatever the file said.

  • roi_based_sphere withdrawn, and with it any sphere head model with the roi_based source space. Its sphere is centred on the brain, so the electrodes sit inside the brain layer (median 0.76, p5-p95 0.61-0.91, of the outer radius; section D, D1) and the numerical solver moves them outward onto the scalp. Centred under the electrodes it keeps only 129 of its 178 sources (Antwerp), and it already dropped sources outside its sphere (it was the one expected failure of tests/test_preset_containment.py). Naming it (--preset, Config.from_preset, --bem sphere --source roi_based), or building any config with bem_type: sphere and source_type: roi_based (a --config file, overrides), gives that reason. The copy in configs/ is deleted. 7 presets remain.
  • source_sampling: parcel_subspace withdrawn. Near chance on free-orientation pools (6-9%; Cartesian allen32 6.2% against 3.1% chance, section D, D9), because it collapses each free source to one direction, and every remaining source space is free. Refused when a config is built, and by Pipeline.run; no longer offered by --source-sampling. The code stays for finished runs and direct tests; study qc marks such runs source_space_status: withdrawn.
  • pipeline.bem_type is checked. An unknown head model used to pass the config and fail inside the BEM step; tissue, documented once and never built, gets its own reason. bem.tissue sections in old records are still accepted with a warning.
  • LCMV and DICS are experimental, outside the 1.0.0 supported set until the like-for-like comparison (audit 17c): source-localization list --methods says so and a config naming either warns.
  • study analyze uses the study's own bands. A study file's bands: were parsed and ignored: the defaults were always used. Now they are the default, and --bands selects among them (an unknown name is an error that lists the study's bands). paths.analytics / paths.results are source-analytics keys and stay accepted. StudyConfig.to_yaml writes bands: and no longer writes analysis: / output:, which nothing acts on; reading a file that has them warns, naming the keys (an older file's analysis.frequency_bands is used as its bands when it has no bands:).
  • study analyze no longer reuses files computed with other bands. band_power.csv and connectivity_*.csv were reused whenever they existed, keyed by band name only, so a study analysed once kept its first bands. Each subject's analysis/bands.json now records the limits; files without a record are taken to have the old defaults (what study analyze always used), and any that do not match the bands asked for are recomputed with a warning. Band file names use a safe stem ("Low Gamma" -> low_gamma), so collect_connectivity_matrices(band='low_gamma') finds a FORGE-style study's files; the display name stays in band_power.csv. Connectivity files written before 0.9.12 under a name with spaces are recomputed, not read.
  • Malformed bands stop a study at load. A study file whose bands: (or analysis.frequency_bands) entry is not [low, high] with 0 <= low < high now raises when the study is read, so study run, study qc and study analyze all stop there; before, the bands were not checked and only study analyze could trip on them.
  • Study files written by study init / StudyConfig.to_yaml before 0.9.12 now warn about their analysis: and output: sections when read (nothing acts on them); delete the sections to silence it.
  • study init writes atlas: allen32 (--atlas to choose; StudyConfig.from_folder(atlas=...) and create_study_from_folder(atlas=...), where atlas=None leaves it to the preset). Existing study files without an atlas still run on the preset's Antwerp paths.
  • The batch validator's preset and method lists: roi_based_sphere is gone from --all-presets, and LCMV, which it listed but refused (it has no beamformer path), is refused at the command line with that reason.
  • The sphere head model with the roi_based source space is refused everywhere (Config._validate), not only by preset name, so a --config file or pipeline.bem_type / source_type overrides cannot rebuild it.
  • study qc has a placement column for roi_based runs: legacy when the record says so or the run's source_localization_version is before 0.9.8, contained when it says so or the version is 0.9.8 or later (some 0.9.8-0.9.11 records omit the key; config_resolved.yaml now always records it), unknown with neither; n/a otherwise. Information, not a fault: what the rule changes is being measured (audit 15). QC lists legacy-placement subjects. Checked against the 101 roi_based run records on the E drive (2026-11-19): 93 legacy (0.4.0-0.7.0), 6 legacy and 2 contained by their recorded rule (0.9.9).
  • study qc recognises parcel-subspace runs from their configuration or, without one, their parcel_subspace_operator.npz, and advises a different sampling mode for them, not a different source space.
  • The beamformer warning is given once per configuration built (it repeated: twice from from_preset with overrides, up to four times in ValidationRunner.setup).

Head model (options inventory section D, D1-D3; tests/test_head_model_0912.py). These change every numerical-BEM run's leadfields, so results made before differ from results made after; study qc tells them apart.

  • BEM mesh: 2562 vertices per surface by default (bem.ellipsoid.n_vertices, bem.sphere.n_vertices: 642, 2562 or 10242). Every release before used a hard-coded 642, which left ellipsoid leadfields 11% (shell) to 15% (surface sources) low at the median against a 10,242-vertex reference, up to 23-35% at p95, with |cos| down to 0.985 at p5 (section D, D2). 2562 cuts the median error to 3-4%. Measured on shell_ellipsoid: 2562 / 642 column norm median 1.083 (p5-p95 0.98-1.20), |cos| p5 0.9956. Amplitudes move by about 7-15%; localization barely, since patterns change little. The head model takes longer to build (shell_ellipsoid steps 1-4: 9 s at 642, 97 s at 2562, measured on a loaded machine), paid once per output directory because it is cached. A 3-layer BEM solution matrix is about 470 MB at 2562 (30 MB at 642, 7.5 GB at 10242); the validation and field-locator truth forwards (TruthForward, locate.geometry, validation.head_ensemble) keep up to 4, so up to about 1.9 GB each on a run built at 2562. The setting is part of the BEM cache key, so a 642 cache (including one written before 0.9.12) is rebuilt rather than served.
  • The analytic sphere evaluates the potential on its outer sphere (bem.sphere.analytic_electrodes: projected, default; numerical: false only). MNE's BEM path projects every electrode onto the outer surface; its analytic sphere used the raw positions, which on a brain-centred sphere are inside the head (median 0.67 of the outer radius). On brain-centred shell_sphere the raw analytic leadfield was 2.19x the numerical one (|cos| 0.974); projected it is 1.017x (|cos| 0.9999), against the 2562-vertex numerical sphere. validation.head_models.TruthForward follows it (the analytic model carries the setting).
  • shell_sphere is centred under the electrodes (bem.sphere.electrode_centered: true), as sphere_cartesian already was. Centred on the brain, the electrodes sat inside its brain layer and the numerical solver moved each one outward by 1.4-3.4 mm (section D, D1). It keeps 89 sources against 91.
  • study qc: bem_mesh_vertices and analytic_electrodes columns (with head_model_form_basis), from the run record or else the BEM cache: a record without the setting predates it and reads 642 (pre-0.9.12) / raw (pre-0.9.12). Information, not a fault. The study recipe compares them and electrode_centered, so a study mixing meshes shows as mixed.

inverse.snr defaults to 1, not 3 (decision D4), in every preset and wherever a configuration leaves the key out (config.INVERSE_SNR_DEFAULT, read by the fixed inverse step, Monte Carlo, parcel-subspace, both validation runners and the run record). This changes every run's results (lambda2 1 instead of 1/9: nine times more regularisation). Measured with recorded noise from 4 FORGE recordings (four noise backgrounds and channel sets on one template head, not four heads) through the shipped steps (audit 17a, reports/measurements_2026-11-19/README.md, allen32 top-1, sLORETA): against 3, +6 to +9 points at single-sample SNR 3 (roi_based +8.6, shell +6.8, Cartesian +5.9; peak 0.5 mm closer), +2 to +3 at SNR 10, -0.7 to +1.1 noise-free. Beyond that it levels off (inverse.snr 0.3-0.5 add 1-2 points at SNR 3; noise-free they cost about 0.5 points more on roi_based and gain 0.3-0.7 on shell and Cartesian). Measured on single-sample, evoked-style data only: epoch-averaged evoked data and resting-state band power are not measured, and all of it on the 642-vertex mesh, before the head-model change above. Monte Carlo keeps 160 sources per draw (D5). Each with a test (tests/test_inverse_snr_default.py).

  • The keyword defaults of apply_inverse_custom_* and compute_inverse_operator (snr=1.0) and of the pool operators build_roi_operator / build_subspace_operator (lambda2=1.0) follow, so the package has one default. Every pipeline caller passes the value explicitly, so this changes only direct calls that leave it out.
  • Not changed: validation.robustness.RobustnessTest(inverse_snr=3.0) and validation.roi_certainty.sloreta_attributor(snr=3.0), whose SNR is an argument of the analysis rather than read from a run; and validation.networks.nodes, which reads finished runs (a record without the key was run at 3).
  • scripts/run_roi_certainty.py's deployed arm models what a user gets, so it follows the pipeline default (now 1) and records the value in its output (deployed_inverse_snr); the published ROI-certainty results were computed at 3 (docs/validation/methods/ROI_CERTAINTY_VALIDATION.md).
  • study qc: snr is already in the study recipe, so a study mixing runs at 3 and 1 shows as mixed.
  • inverse.snr: null with no lambda2 is refused when the configuration is read. It used to pass validation and crash every step (.get('snr', default) returns the null, not the default); leave the key out for the default. With lambda2 set it still runs, as before.

To reproduce a 0.9.11 run: inverse.snr: 3, bem.<type>.n_vertices: 642, bem.sphere.analytic_electrodes: raw, and for shell_sphere bem.sphere.electrode_centered: false. Byte for byte: the head model in tests/test_head_model_0912.py; fixed, Monte Carlo and parcel-subspace runs end to end in tests/test_inverse_snr_default.py. A withdrawn option (roi_based_sphere, parcel_subspace) cannot be rerun.

Not in 0.9.12: the Monte Carlo magnitude readout (mean of member norms), built and reviewed but held until its effect on within-parcel group comparisons in dB is measured; the signed-series default (signed_orientation: leadfield) and band power from summed component power (D6). Measured and written up since 0.9.11 (reports/measurements_2026-11-19/README.md, git-ignored): the per-draw count (D5: Monte Carlo keeps 160 sources per draw), the inverse conductivity sweep (17b) and the like-for-like beamformer comparison (17c, which keeps LCMV and DICS experimental). Parcel-subspace sampling is withdrawn rather than given a three-direction mode. source-analytics and the pilot are to be told: study-file changes (bands honoured, analysis: / output: no longer written, band file stems), inverse.snr 1, the 2562 mesh.

Notable changes in 0.9.11 (2026-11-19): fixes from the audit of work left unfinished since 0.9.0. Defects found during earlier testing and left unfixed, now fixed, with a test each (tests/test_found_in_testing.py, tests/test_config_schema.py, tests/test_audit_inventory.py). No preset's results change. A run writes one new record (data/step6_roi_coverage.json), its config_resolved.yaml records more defaults, and the two Cartesian presets' default output folder (used only without --output) is outputs/<preset name> instead of the old *_volumetric.

  • Unknown configuration keys are refused. Any key used to be accepted, so a typo such as inverse.snrr (or a misspelt override) silently left the default in force. A key that no step reads now raises, naming the nearest known key (source_localization/config_schema.py). Keys older presets carried that no step reads (bem.ellipsoid.radii_ratios, shell.filter_above_electrodes, ...) are still accepted, with a warning that they have no effect. roi_based_sphere.yaml no longer carries bem.sphere.r0, which nothing read (same head model; its cached BEM is rebuilt once, since the cache key covers the section). Checked against every preset and the 307 finished runs' config_resolved.yaml on the lab's E drive: no unknown keys. A study file's pipeline: section refuses unknown keys too (presett: used to run the default preset). Its other sections are shared with source-analytics and are not checked.
  • --config FILE ignored every override flag: --snr, --method, --source-sampling, --interpolated-channels, --save-source-series, --recreate-bem, --no-bem-cache and --spacing. Only --preset and --bem/--source applied them. Now all three apply them. Found while writing the missing test for the BEM cache flags. Passing a run's config_resolved.yaml as --config now says it is a run record.
  • Cartesian auto spacing used the template's brain volume even when inputs.brain_mask named the subject's own mask. It now uses the run's mask. Presets name the packaged mask, so their spacing is unchanged (to 1e-12).
  • shell.distribution: latlon returned 60-76% of the requested points (1,200 -> 918). It now returns exactly the number asked for, spread over latitude bands in proportion to cos(latitude). No preset uses latlon; a configuration that did gets more sources.
  • The electrode ray-cast cross-check searched only the top 10 slices of the volume, and reported the top slice when it found nothing there, so its "methods agree" flag measured little. It now searches the whole column and counts electrodes with no brain below them. The cross-check is reported only; electrode positions are unchanged.
  • The electrode CSV loader dropped only a row labelled exactly Bregma. BREGMA or bregma became a 31st electrode. Matched case- and space-insensitively now, as the bregma cross-check already did.
  • bem.sphere.electrode_centered without electrode positions fell back to a brain-centred sphere without a word. It raises now. The pipeline always passes the positions; only direct calls were affected.
  • The shell source space kept every source when its mask filter failed. Any error there (a missing or unreadable inputs.source_brain_mask) was printed as a warning and the run went on with the sources outside the brain. It raises now, as does a mask no source falls in. A relative inputs.source_brain_mask is read against the package directory, like every other inputs: path (it was read against the working directory).
  • The validation runners did not validate what the pipeline runs. ValidationRunner ignored the config's depth_weighting (MNE always got 0.8; the pipeline's default is 0.0), standardisation and eloreta_weights, and ran its own beamformers (an LCMV that retried 12 covariance and regularisation strategies at reg 0.1, a DICS over 8-30 Hz). It now uses the pipeline's settings and beamformer functions (reg 0.05, the primary band, 30-55 Hz). The batch runner ran every method at SNR 3 whatever the preset said, MNE at depth 0.8, and any other method, LCMV included, silently as sLORETA; it now reads the preset and refuses beamformers. Validation numbers for MNE and for the beamformers change (every preset uses SNR 3, so that part changes none).
  • Checked when a configuration is built, instead of failing later or not at all: inverse.lambda2 and inverse.snr must be numbers > 0 (lambda2: 0 was used as 0 by fixed sampling and replaced by 1/snr² under Monte Carlo and parcel-subspace); spectral.primary_band must name a band and each band must have fmin < fmax (a wrong name raised after the band power was computed); the forward: section and its eeg, meg and mindist are required (they raised KeyError in a step); the electrode: section may be left out. A study's atlas and overrides are checked once when the study is validated, not by every subject in turn.
  • roi_based placement_strategy: random and stratified now mirror left to right under placement_rule: contained, as pca does; they ignored enforce_lr_symmetry with a printed note. legacy is unchanged. No preset uses either.
  • Records: a relative --eeg is recorded at the path it was read from (it was recorded against the package directory, as a file that did not exist). config_resolved.yaml records the defaults steps used for keys a configuration leaves out (BEM layers, margins and thicknesses, sphere numerical, signed_orientation, depth_weighting, interpolation_residual_max). Parcels with no sources, which the output leaves out, are listed in data/step6_roi_coverage.json. The study summary compares forward.average_reference, electrode.projection_method and electrode.skull_offset_mm across recordings.
  • Found when these fixes were verified (2026-11-19), and fixed too:
    • The unknown-key check refused the validation: block, so every documented validation config failed in ValidationRunner.setup(). The block is now passed through unchecked, and a test runs setup().
    • Validation MNE at depth_weighting > 0 was still not the pipeline's MNE: the function the runners call weighted depth by column norm, the form before 0.9.1, whatever inverse.standardisation said. It now uses each source's spectral norm, as the pipeline does, and a test compares the numbers of all four methods with the pipeline's operator. RobustnessTest (and ResolutionAnalysis, SeparabilityAnalysis) always ran MNE at depth 0.8 and λ² = 1/snr². They now take the run's lambda2, depth_weighting and standardisation. Validation numbers for MNE at depth > 0 change.
    • A run with its own inputs.brain_mask and no inputs.source_brain_mask placed its sources in the packaged template's mask; they now go in its own mask. Presets name the packaged mask, so nothing changes for them.
    • A missing or unreadable inputs.roi_mapping turned roi_based's left-right mirroring off without a word; it raises now. inputs: and outputs: are required sections. Without inverse.snr the fixed path raised KeyError where the pool steps used 3; it uses 3 too.
    • config_resolved.yaml also records the source-space, sampling, beamformer, standardisation, electrode, ROI and figure defaults. The study summary also compares lambda2, depth_weighting, standardisation, the head model's layers and conductivities, and the Cartesian spacing.
    • --snr 0 was ignored; it is refused now.
  • CLI: --atlas takes the legacy names full and coarse_22roi the API and the validation CLI accept, and records the canonical name. The HTML report shows combine, merge_bilateral and include_categories.
  • Tests added: dSPM and MNE run() checked against the operator applied to the file read by hand, plus common-mode invariance and linearity; the BEM cache flags through the CLI and the BEM step; LCMV and DICS through Pipeline.run (one source: the peak is on it); the continuous-.set fallback; the electrode-distance filter on a volumetric space; study init discovery and the study analyze and study qc flags. tests/test_psd_sanity.py --eeg-file works: the option was declared where pytest never reads it. The check also multiplied the recording's channels in file order by an operator in E1..E30 order; it now reorders and references them as the pipeline does.
  • Documentation corrected: four validation method documents now say that they were measured before the 0.9.0 head-model fix and not re-measured. The 0.9.9 note on the per-source series was wrong (see below). The beamformer sentence is updated. FIELD_LOCATION.md notes the 41 duplicated midline vertices and the unexplained gap between real and simulated map sizes. Preset comments no longer quote pre-fix accuracy as validated, and no longer recommend sLORETA as "best". The ellipsoid_cartesian / sphere_cartesian comments give the measured 141 / 80 sources, not "~210". pytest from the repo root no longer collects scripts/. source-localization list describes roi_based as it is (sources by parcel volume, not one per parcel). Preset comments say depth_weighting is read by MNE only. The electrode loader no longer ranks the projection methods, and the electrode guide no longer suggests rbf for a wrong surface. FIELD_TEMPLATES.md says the field mode ignores both forward.* EEG settings. New docs/guides/source_space_options.md lists every source-space key and its default. CLAUDE.md's parcel-coverage figures are re-counted on the current 187 shell sources.

Notable changes in 0.9.10 (2026-11-19). The surface source spaces are withdrawn, with fixed and loose orientation. Every run that used them changes; nothing else does.

  • source_type: surface (anatomical mid-ribbon and icosphere) is refused when a configuration is built, as the hybrid was in 0.9.3. The presets ellipsoid_surface, ellipsoid_surface_anatomical and sphere_surface are removed, and naming one gives the reason. inverse.orientation: fixed and loose are refused too: only the surface had normals. loose was also faulty (penalty on the wrong components, pooled normaliser), and it is withdrawn rather than fixed.
  • Why: a surface has no deep parcels, and on the dorsal MEA30 array every deep scalp pattern has a cortical look-alike (median |cos| 0.993-0.996), so a surface reports deep activity as cortical. Measured in section D of the options inventory: 56-76% of thalamic, subcortical, hypothalamic and hippocampal truths were reported in a cortical parcel, at every noise level. docs/known-issues/SURFACE_WITHDRAWN.md has the numbers, and what this does not claim about the volumetric source spaces.
  • The default preset in the README and CLI examples is roi_based_ellipsoid, as study init already used. It is a default, not a ranking.
  • study qc marks surface runs source_space_status: withdrawn and lists them. Finished surface runs still load. Check out 0.9.9 to reproduce one.
  • --preset with a withdrawn name gives the reason, not only "invalid choice". The batch validator's --all-presets list and the coverage-figure script no longer name the removed presets (the batch list now includes the two _extended presets it had missed).
  • --spacing now applies to the Cartesian grid only. source_space/surface*.py stay for their tests and for the geometry of finished runs, but the pipeline no longer reaches them.
  • The field locator's surface positions are kept behind an explicit assumption: LocationSpace(..., labelling_kind="surface") needs assume_cortical_source=True, otherwise it raises CorticalSourceAssumptionError, and the provenance records the assumption. With truths anywhere in the brain, the surface map put every deep truth in cortex or cerebellum, and in 94-99% of those maps at least half the mass sat on one wrong parcel. calibration.volumetric held 94-95% at the 90% level for every kind of truth (docs/methods/FIELD_LOCATION.md).

Notable changes in 0.9.9 (2026-11-18). The per-source series is no longer written by default. No result changes.

  • step5_stc_*.pkl and source_timeseries_*.set were about 80% of a fixed-sampling run's disk (FORGE 829: 251 of 312 MB; 1.09 TB across the lab's E drive against 0.37 TB of ROI output). source-analytics' own analyses work from the ROI series, and study qc took five amplitude numbers from them. Corrected 2026-11-18: this note first said nothing downstream read them. The source-analytics-vertex plugin does (all eight of its vertex analyses), and source-analytics falls back to them when a run has no step6 files. Runs made with 0.9.9 or later need --save-source-series for either.
  • outputs.save_source_series: true (CLI --save-source-series) writes them, for debugging. skip_roi_extraction turns it on, because the series is then the run's only output.
  • New data/step5_source_summary.json: the five amplitude numbers (min, max, mean, SD, median of the magnitude series). study qc reads it, and the pickles for runs made before 0.9.9.
  • The ROI outputs, figures, Python API (results['inverse_solution']['stc']) and spectral step are unchanged.

Notable changes in 0.9.8 (2026-11-17). The seven bugs the 0.9.7 option tests found. Five are in settings no preset uses (every preset's electrode and source positions are identical to 0.9.7):

  • Cartesian sources under bem.ellipsoid.ellipsoid_method: pca entered the ellipsoid frame with the transposed rotation, so the inset was applied to a differently tilted ellipsoid and sources reached 0.85 of the brain surface against the 0.80 inset.
  • bem.sphere.electrode_centered with brain_radius_mm: auto_ellipsoid raised; it now takes the same radius as the brain-centred sphere (geometric mean of the fitted semi-axes).
  • electrode.projection_method: rbf now runs the intensity-surface guard, as intensity does.
  • Shell scale_by_area: false silently dropped every shell in shell_scales beyond n_shells.
  • Shell filter_exterior scaled the mask's affine by hand; it now goes through get_true_affine(), so a mask stored in true units no longer loses every source.

Changes roi_based results (both roi_based presets, every atlas; source_space.roi_based.placement_rule, default contained; legacy reproduces 0.9.7 byte for byte, written to config_resolved.yaml):

  • The adaptive budget is split exactly (largest remainder, at least one source per ROI, an L/R pair counted as two). Re-rounding used to overshoot: 206 sources for max_total_sources: 200 on Antwerp, 204 on allen32. The presets now get 200.
  • A source whose voxel is not its own parcel's is moved to the nearest voxel that is, and a mirrored L/R pair moves together, so it stays mirrored. pca put sources in other parcels' voxels (Antwerp 1 of 206, allen32 19 of 204, allen26 23 of 201) and in unlabelled ones (4, 21, 16), and roi_extraction credited their signal to the declared parcel. Now none.
  • MS1 and other finished roi_based runs reproduce with placement_rule: legacy.

Notable changes in 0.9.7 (2026-11-17). Test gaps (options inventory, section E). No result changes.

  • tests/test_step_runs.py checks the step run() functions for their numbers, not only that files appear: a noise-free source per epoch, from a .set stored in reverse channel order, is placed exactly by sLORETA and eLORETA through Pipeline.run; ROI extraction agrees with the label volume, the per-parcel mean and its .set, and merge_bilateral and include_categories run the real loop; band power is the integrated Welch PSD (A²/2 for a sine); the parcel_subspace_roi step's saved operator reproduces its series.
  • compute_band_power's docstring said "mean power"; it is the integral over the band.
  • The non-default options now have tests that check what each one means: tests/test_source_space_options.py (roi_based, Cartesian, shell), tests/test_bem_options.py (analytic sphere, pca, margins, thicknesses, scale_factor, the BEM cache switches) and tests/test_electrode_roi_options.py (rbf/none, skull_offset_mm, bregma/lambda, the surface and interpolation thresholds, use_proximity, pool sampling with skip_roi_extraction). Seven bugs they found are pinned as strict xfails, not yet fixed:
    • Cartesian sources under ellipsoid_method: pca use the transposed rotation and pass the 0.80 inset.
    • electrode_centered with brain_radius_mm: auto_ellipsoid raises.
    • rbf electrode projection skips the intensity-surface guard.
    • roi_based max_total_sources is exceeded (200 gives 204 on allen32).
    • roi_based pca puts 9-11% of allen32/allen26 sources in another parcel's voxel (Antwerp 1 of 206).
    • Shell scale_by_area: false drops shells beyond n_shells.
    • Shell filter_exterior scales the mask affine by hand, so a true-unit mask removes every source.

Notable changes in 0.9.6 (2026-11-17). A no-scalp head model next to the three-layer one. No result changes: the default and every preset are unchanged.

  • bem.ellipsoid.layers: brain_skull builds brain and bone only, for an array on the bone; see Head-model layers. brain_skull_scalp stays the default, so MS1's results reproduce.
  • Head-model ensembles scale all of the bone. locate.geometry, validation.head_ensemble and validation.head_models took the skull as the one lowest-conductivity surface; on a no-scalp head (two bone shells) skull_factor would have scaled half of it. Three-layer heads are unaffected.

Notable changes in 0.9.5 (2026-11-17). Documentation that was wrong (options inventory, section C). No result changes. Removing dead keys changes the head-model cache signature of the ellipsoid presets and sphere_surface, so an existing output directory rebuilds its head model once, identically.

  • The sphere is numerical, not analytic. bem.sphere.numerical defaults to true and no preset sets it false; the docs, list and two presets called it analytical. The "~35x larger leadfield" quoted for the analytic form was the numerical solve's inner-first fault (0.9.0): measured now, the median analytic/numerical leadfield norm is 1.11 on sphere_surface and sphere_cartesian. On shell_sphere (and roi_based_sphere), whose sphere is centred on the brain rather than under the electrodes, the two differ 2.4x; centred, 1.1x. Which solver is right there is not yet measured.
  • fit_to_electrodes was never read by any version; the README and CLAUDE.md told users to set it. Removed, with the troubleshooting entry for an error the package never raises; the entries now quote messages it does raise.
  • Preset runs write the signed .set only. Every preset sets outputs.output_variants: signed, but the docs and output trees listed a magnitude .set too.
  • The ellipsoid's "~1.5 mm localization error" predates 0.9.0 and is no longer quoted.
  • CLAUDE.md now describes parcel_subspace sampling and lists all five registered atlases. Both docs now say parcel-subspace collapses a free pool source to its dominant direction.
  • Dead keys removed from the presets and the validation-config generator: filter_above_electrodes, electrode_margin_mm, cartesian.pos_mm, bem.ellipsoid.radii_ratios, bem.sphere.compute_method. Not changed: tissue and the unread study keys (analysis.*, bands, output.*, ...) wait on the supported-set decision, as does rejecting unknown keys.

Notable changes in 0.9.4 (2026-11-17). Options that crashed or could not be used (options inventory, section B). None changes the result of a run that completed before, except roi_based with placement_strategy: random, which is now seeded.

  • outputs.save_intermediate: false keeps the run's product. It also suppressed the ROI .set and step6_* files and the run's records (step2_interpolated_channels.json, the Monte Carlo and parcel-subspace reports). Now it gates only the step 1-5 pickles, the figures and the source-level .set files.
  • A missing output directory is a clear error. Six presets leave outputs.dir unset; run without --output, they raised a TypeError.
  • --spectral and --visualize work under Monte Carlo and parcel-subspace sampling, which have no source estimate: the sampling frequency comes from the recording, and the source snapshot is skipped. --visualize runs the spectral step itself (it raised without --spectral). run_spectral_analysis() and run_visualization() accept those runs, which they used to send back to run(). The visualization step raises on a source-count mismatch instead of front-slicing the coordinates.
  • roi_based without sources_per_roi (and without adaptive_sources: true) says what it needs, instead of a KeyError. placement_strategy: random takes roi_based.seed (default 0); it was unseeded.
  • Head-model layer counts are checked when the config is built. The ellipsoid and the numerical sphere need three conductivities, and n_layers must match their number. Other counts failed mid-run.
  • Not changed: bem_type: tissue still raises (it has no builder); whether it stays documented is part of the supported-set decision. roi_extraction.combine by dotted override already worked from 0.9.2.

Notable changes in 0.9.3 (2026-11-17).

  • The hybrid source space is withdrawn (it was never published). source_type: hybrid is refused when a config is built, and the ellipsoid_hybrid preset is removed. On the dorsal array every deep scalp pattern has a cortical look-alike, and the reverse, so the model's structure, not the data, decided which part got the activity. No rescaling fixed it. See Hybrid source space. Finished hybrid runs still load. Measurements: reports/fix_0.9.3/ (git-ignored).
  • study qc flags hybrid runs. A new source_space_status column (current, withdrawn or unknown, from the run's configuration or else its Monte Carlo report) is in recordings.csv, and the QC warnings list the subjects whose runs used a withdrawn source space.

Notable changes in 0.9.2 (2026-11-17). Three changes move results with the presets as shipped, so rerun the affected runs. Rerun every run on a recording with interpolated channels. Rerun every Monte Carlo run whose pool has free-orientation sources (shell, Cartesian, and the volume part of the hybrid). Rerun every free-orientation eLORETA run. Runs on a subject's own MRI and mask change too, and so do Monte Carlo runs that relied on the pool-density defaults (see below). Each change below has an option that restores the old behaviour, for reproducing old runs only. Each run records which form it used. Study qc's recordings.csv reports the interpolated-channel and Monte Carlo direction forms.

  • Interpolated channels are dropped from the inverse (forward.interpolated_channels: drop, default). eeg-preprocess restores removed channels by spherical-spline interpolation. A restored channel carries no information of its own, but it got a leadfield row at its own position. A channel is dropped only when all three agree:

    • it is listed in EEG.chaninfo.removedchans;
    • it is back in chanlocs;
    • it fits as an affine combination of the unlisted channels (relative residual < 1e-3).

    The channel is removed from the data before the average reference and from the leadfield's rows. The head model and source space still use all 30 electrodes. FORGE: 26 of 61 recordings, 1-3 channels each, unevenly by group (KO_HD_ICV 0/8, KO_VEH 12/18). In the Monte Carlo re-measure on FORGE 801, 829, 914 and 962, dropping brought each subject back to its no-interpolation accuracy. Keeping cost up to 6 points. Recorded in data/step2_interpolated_channels.json and in study qc's recordings.csv. keep reproduces earlier runs byte for byte.

  • Monte Carlo pools keep three directions per free source (monte_carlo.directions: three, default). Each free pool source used to be collapsed to its dominant leadfield direction. Now each draw solves all three columns with the 3x3 sLORETA block, and a parcel is the vector mean in the head frame. Re-measured on FORGE 801, 829, 914 and 962 with head-model error and realistic noise (top-1 correct parcel, chance 3.8%): 43% against 9% without noise, 21-26% against 7-8% at SNR 3, and both near chance at SNR 1. New outputs:

    • step6_roi_timeseries_vector.pkl (x/y/z);
    • magnitude (.pkl, and .set when outputs.output_variants includes it);
    • data/step6_mc_directions.json.

    The signed series is taken along each parcel's dominant leadfield direction. Normal-fixed pools (the anatomical surface) are unchanged. Surface parcels in the hybrid move slightly (r ≥ 0.98), because they share the solve. dominant reproduces earlier runs byte for byte.

  • Free-orientation eLORETA takes a 3x3 weight per source and no normaliser (inverse.eloreta_weights: block, default; Pascual-Marqui's form). On the FORGE shell forward it places every one of 500 noise-free single sources exactly, against 0 of 500 for the old form (median 3.48 mm). Fixed and loose orientation are unchanged. So is the validation runner's apply_inverse_custom_eLORETA, which follows it, so eLORETA validation numbers change too. legacy_scalar reproduces the old form bit for bit. sLORETA, dSPM and MNE are bit-identical to 0.9.1. The record gains eloreta_weights. study qc now reports free-orientation eLORETA runs from before 0.9.2 (and legacy_scalar ones) as inverse_status: faulty, where it used to say not affected.

  • The head model honours inputs.brain_mask. The ellipsoid and sphere builders always loaded the packaged template mask, so a run on a subject's own MRI got a head model fitted to the template brain. A mask that is named but missing now raises. The BEM cache records the mask's checksum and rebuilds when it changes. DipolePosterior.from_pipeline_dir restricts its grid to the run's mask too. Every preset resolves to the packaged mask, so preset head models are unchanged.

  • Electrode projection onto a subject's MRI. electrode.projection_method: brain_mask places each electrode skull_offset_mm above the top of the brain mask. On the pilot mouse that is 0.064 mm median from the measured positions, where the intensity projection was 2.1 mm off. intensity now raises when its surface sits more than electrode.max_surface_above_brain_mask_mm (1.5 mm) above the mask. Presets keep intensity, and their electrode positions are bit-identical.

  • config_resolved.yaml pins the files a run read. input_files: records the absolute path, size and sha256 of every input. The EEG file is recorded by path only. source_tree: records the package's git commit and whether it had uncommitted changes. The package-relative inputs: paths name whatever the working tree holds now, not what the run read. Downstream readers (source-analytics' roi_categories) should use these records, not the live tree.

  • study run --output-dir creates a missing directory instead of refusing it.

    Settings that gave wrong results without an error (found by the options inventory, 2026-11-17):

  • The head-model cache compares every head-model setting. It used to compare only conductivities and the layer count, so a rerun into the same output directory with a different margin, offset, axis extension, thickness, radius or numerical setting reused the old head model while config_resolved.yaml recorded the new one. Caches without the new signature rebuild once.

  • Monte Carlo parcel labels follow the sources the forward kept. They were read from the source space as built and cut to length, so one dropped pool source would shift every later label by one. No current preset pool drops a source, at the old or the new defaults, so existing runs were not affected.

  • study run --force replaces the ROI series it copies into roi_timeseries/. It kept the existing copy, which study analyze/collect/status read, so a forced rerun left the old series in place.

  • --bem X --source Y runs the preset with that pair. It read default_config.yaml, whose defaults had drifted from every preset: --bem ellipsoid --source surface gave free-orientation dSPM on the anatomical surface. The file is removed. Dotted overrides now create sections a preset lacks, which used to raise KeyError.

  • --spacing reaches the spacing the source space reads: the Cartesian grid or the anatomical surface. Before, it wrote a key nothing read. Other source spaces and pool sampling raise.

  • Monte Carlo and parcel-subspace sampling refuse settings they would ignore: another inverse.method (Monte Carlo always builds sLORETA), the fixed-sampling ROI options (roi.use_proximity, include_categories, merge_bilateral), roi_based, and the icosphere surface (never built dense).

  • Monte Carlo pool defaults are the documented ones: 24 shells × 1200 points, and 0.20 mm for the Cartesian grid, as in the guide and the measured FORGE runs. The code defaults were 12 × 400 and 0.5 mm, about a sixth of the pool. Monte Carlo runs that relied on the defaults change. Runs that set the keys do not.

  • EEG loading reports the real error. A problem in an epoched file after it was read, such as a missing electrode, was replaced by the raw reader's unrelated error.

  • The electrode guide and loader docstring said the coordinates CSV is 1-indexed; it is 0-indexed (b486d09). run_status read an analytic sphere's BEM cache as numerical. LCMV's caveat now says it is applied to the epoch average.

  • The hybrid source space is experimental. Its surface and volume parcels are on different scales, so the largest output is almost always a deep parcel. This was found while validating three directions end to end. The bias was present before 0.9.2 too (about 2.5x), and three directions widens it to 4-9x. See Hybrid source space.

  • Validated as shipped: three-direction Monte Carlo on shell and Cartesian pools. The pipeline's operator equals the prototype's exactly. End to end, from a .set file with its channels reordered, it gives 43.6 / 43.7% top-1 against the prototype's 43.4 / 43.5% (no noise), and 24.2 / 24.4% against 24.1 / 24.6% (recorded noise, SNR 3).

  • Not changed: the atlas mirror axis stays at X = 0. See ATLAS_PERENS_ANTWERP_REVIEW.md §1d.

Notable changes in 0.9.1 (2026-11-16). Free-orientation sLORETA, dSPM and MNE change, so results from the free-orientation fixed-sampling presets (roi_based_*, shell_*, *_cartesian*, sphere_surface) should be rerun:

  • sLORETA standardises each source by its 3x3 resolution block (R_ii^-1/2, Pascual-Marqui's definition) instead of each x/y/z component by its own diagonal. A single noise-free source is now placed exactly: on FORGE sub-801 rest_shell the median peak error goes from 2.08 mm (20% exact) to 0. With white sensor noise the gain narrows (SNR 3: 2.74 against 2.84 mm). Found by pilot-eeg-mri.
  • dSPM pools its noise normaliser per source, and MNE's depth weight uses each source's spectral norm, both as MNE-Python does. The old forms depended on the head model's axes: rotating x/y/z for the same physical dipoles moved 85% of sLORETA peaks and 82% of dSPM peaks. All three are now axis-invariant (tests/test_inverse_standardisation.py).
  • Fixed orientation is unchanged (one component), loose keeps its per-source pooling, eLORETA is unchanged, and Monte Carlo runs are unaffected (one direction per pool source). The custom functions validation uses (apply_inverse_custom_sLORETA, apply_inverse_custom_dSPM) change with them.
  • The form is recorded: data/step5_inverse_standardisation.json (per-source-v1); a run without it predates 0.9.1. inverse.standardisation: legacy_per_component restores the old form, off by default.

Notable changes in 0.9.0 (2026-11-14). Every forward model from a surface BEM changes, so results from earlier versions are not reproduced and should be rerun:

  • Surface BEMs are solved outermost surface first (bem/solution.py). mne.make_bem_solution takes surfaces in list order and puts zero conductivity outside the first; the ellipsoid and numerical-sphere builders produce them inner first, and every earlier version passed them on in that order, so each surface BEM was a physically inconsistent model. Against an exact multi-shell series solution the corrected solve is within mesh error (preset sphere ico-4: topography error 0.004, amplitude 0.98) and the old one is not (1.41, 0.007). Affects the ellipsoid presets and the numerical sphere (the default); the analytic sphere (numerical: false) is unchanged. Builders keep their inner-first order.
  • Surface nesting is checked before every solve: ids that disagree with the geometry (caches from before 2026-08-14) or descending sphere radii raise instead of being solved in the wrong order.
  • A failed analytic-sphere fit is refused (bem.sphere.check_sphere_fit) instead of returning NaN leadfields. tests/test_bem_order.py checks the surface BEM against the exact series.
  • Every forward model records its solver, and saved ones without a current tag are refused (StaleForwardError): load_forward, the validation readers, study qc (warns and skips), cached operators (DipolePosterior.load) and head-ensemble exports (export version 2). study batch neither skips nor overwrites a subject whose outputs predate the tag; use a new output directory or --force.
  • The probability-atlas Phase 9/10 reproduction tests are expected to fail until those references are rebuilt with the corrected solve.
  • The results extra pins Lumière (formerly neurobox-dev).

Notable changes in 0.8.1 (2026-11-10):

  • Hippocampus_Ant / Hippocampus_Post names corrected in allen32 (IDs 7/23 vs 8/24) and allen26 (4/14 vs 5/15). The split put "Ant" at Y < split as if y grew caudally; in this volume it grows rostrally. Names and descriptions are swapped in the mappings; IDs and voxels are unchanged. Outputs written before 0.8.1 name the opposite half. tests/test_atlas_registry.py pins the direction (ATLAS_PERENS_ANTWERP_REVIEW.md §1a).
  • Bundled atlases now ship in the wheel. data/atlas/* did not recurse, so a non-editable install had no Allen files at all. tests/test_package_data.py checks every file under data/atlas.
  • Head-model ensemble and noise whitening (validation/head_ensemble.py, validation/whitening.py), ported from probability-atlas.
  • Pool workers cap their BLAS/OpenMP threads (utils/parallel.py; threadpoolctl is now a declared dependency). n workers on n cores used to run about n² threads. The last bits of a float result can change.
  • Canonical electrode regions for the 30-site array in data/electrodes/mouse_array_regions.yaml (Left/Right Frontal, Medial, Posterior), checked against the coordinates.

Notable changes in 0.8.0 (2026-11-09; the field method, bayes-sl reports/2026-11-09_field_method_library_plan.md). No existing output changes: source mode is untouched, and every new step reproduces the study code it replaces:

  • Head-model-ensemble location posteriors (merged from feat/bayes-group): EnsemblePosterior, SourceSetPosterior, MirrorPairPosterior and the map calibrations VOLUMETRIC and SURFACE, in validation/ensemble_posterior.py
  • Model catalogue. Every location posterior, prior and calibration is declared in methods.py with an id, a version, its priors and values and its validity domain; docs/methods/CATALOGUE.md is generated from it, and source-localization list --catalogue prints it
  • source_localization.locate (phase F1): the location posteriors moved here from validation/ (the old import path still works); the head-model prior and named ensembles (ENSEMBLE_PA_PHASE2: nominal + 32 draws, seeded), ensemble leadfields with their cache, the head geometry, noise whitening (four catalogued estimators), region labelling and LocationSpace, which bundles them for one study's head and records which ensemble and labelling it used. Ported from probability-atlas, which is no longer needed: draws, whiteners and labels are identical, and the 33 leadfields equal its cached ensemble to a relative 2e-16
  • source_localization.field (phase F2): field templates (schema source_localization.field_template/1: maps, channel order, sign rules, catalogued definitions, sha256; freeze never overwrites; templates written before the schema load unchanged) and field definitions from group data (field.response_svd, .phase_aligned, .phase_free, .csd_leading). Re-defining surface-evoked's frozen Sentinel fields from their defining data reproduces all four exactly. See docs/methods/FIELD_TEMPLATES.md
  • Field mode (phase F3): pipeline.mode: field and source-localization field project project epoched recordings onto a frozen template (field.project_inner, the default, or field.project_joint), writing one virtual channel per field in the layout source-analytics reads, the residual's trial average, and field_run.json (template sha256, projection id and version). field show validates a template. Source mode is unchanged. For all 192 held-out Sentinel recordings the series equal surface-evoked's to a relative 6e-16
  • Locating a field (phase F4): calibrations carry the domain they were measured in (array, ensemble, grid, positions; the MEA30 array as data/calibration/mea30_sentinel.json), and locate.field_model.FieldLocator refuses a space outside it. The locator fits the whitener and the single-source and mirror-pair posteriors, reads calibrated maps, evidence and P(pair), and chooses the location (locate.field_choice); summarize and report_response_svd_field report it. Reproduces surface-evoked's location report of the frozen chirp fields exactly. FieldModel (locate.field_model_map) gives the located mass over resamples of the subjects for evoked, steady-state and ongoing data, and model_filter_pair (field.model_filter_pair) the filter of a located pair; both reproduce their study counterparts with no difference. locate.calibrate measures a calibration for a new space (calibration.procedure; it re-chooses the catalogued settings from their original scores). region_fields / field region-values (phase F5) give each located region's field and each subject's band power along it (field.region_field, field.region_power_db), reproducing bayes-sl L3's tables to 3e-14 dB. See docs/methods/FIELD_LOCATION.md

Notable changes in 0.7.0:

  • One reference for the leadfield and the data (X57). The forward step average-references the EEG leadfield (sol and _orig_sol), and the EEG step applies the average-reference projector it adds, which until now was added and never applied. Before this, every hand-rolled inverse was built from an unreferenced leadfield (channel mean a median 0.75-0.84 of each column's RMS) and applied to data in whatever reference the file carried
  • Every number changes. ROI and source outputs from earlier versions are not comparable with 0.7.0 ones; re-run rather than mix. study batches skip subjects whose outputs exist, so clear old outputs first
  • forward.average_reference: false restores the earlier behaviour, to reproduce old runs only. Each run's config_resolved.yaml records the setting

Notable changes in 0.6.0:

  • Validation regime. The validation runner defaults to the realistic regime: truths at the requested positions through head models drawn from a prior (registration shift, skull conductivity), recorded background noise when configured, and a noise-only control. legacy (--regime legacy) reproduces the v0.5.x assumptions for old numbers only; its results go to <config>_legacy/. See docs/validation/README.md and source_localization.validation.regime
  • Validation numbers change: realistic-regime results are not comparable with earlier ones
  • validate --batch and RobustnessTest follow the regime too (the sweep scripts take --regime); the posterior and ROI-certainty scripts write a noise-only control
  • Planted-network validation (validation.networks, validate --networks spec.yaml): which networks a montage, source model and atlas can resolve, with your own connectivity metrics injected; optional directed stage. validation.connectivity (no ground truth) is deprecated

Notable changes in 0.5.1 (v0.5.1):

  • EEG channels reordered to the electrode registration; the inverse refuses a mismatched order. Runs on files stored in a non-E1..E30 order before this release were silently misaligned
  • Forward step restricts per-source arrays to the sources MNE kept, instead of downstream steps front-slicing them
  • Anatomical-surface presets carry the Allen32 atlas
  • DICS written as power tables; eLORETA in the validation runner; unknown band names are errors; source_analysis reads affines through utils.atlas
  • README rebuilt from the code and tested against it

Notable changes in 0.5.0:

  • Anatomical cortical mid-ribbon surface source space with fixed orientation
  • Atlas registry (registry.yaml) driving both CLIs; allen26 added
  • Monte Carlo ROI operator

License

MIT License

Authors

Alex Edmondson - Primary Developer Ernest Pedapati, MD - Principal Investigator

Cincinnati Children's Hospital Medical Center

About

EEG source localization pipeline for mouse models using the Antwerp Mouse Brain Atlas. Supports multiple BEM head models, inverse methods (sLORETA, dSPM, MNE, beamformers), and multi-subject batch processing.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages