BrainMaze - EEG#
BrainMaze: Brain Electrophysiology, Behavior and Dynamics Analysis Toolbox - EEG#
This toolbox provides tools for processing of intracranial EEG recordings. See below and documentation for specific sections. This tool was separated from the BrainMaze toolbox to support a convenient and lightweight sharing of these tools across projects.
This project was originally developed as a part of the BEhavioral STate Analysis Toolbox (BEST) project. However, the development has transferred to the BrainMaze project.
Documentation#
Documentation is available at https://bnelair.github.io/brainmaze-eeg/.
Runnable examples are in the demo/ folder (see demo/README.md).
Installation#
pip install brainmaze-eeg
Plotting in brainmaze_eeg.hypnogram (plot_hypnogram, score_night(plot=True))
needs matplotlib, which is an optional extra:
pip install "brainmaze-eeg[plot]"
The trained models (seizure probability on iEEG, OpenSpindleNet sleep-spindle detection) are
in a separate package, brainmaze-eeg-models
(documentation). They run on ONNX Runtime
and do not need PyTorch. The models extra installs that package next to brainmaze-eeg:
pip install "brainmaze-eeg[models]" # same as: pip install brainmaze-eeg brainmaze-eeg-models
pip install "brainmaze-eeg[plot,models]"
The models are imported from their own package (import brainmaze_eeg_models), not from
brainmaze_eeg, which works the same with or without them. For an NVIDIA GPU, follow
NVIDIA GPU
in the brainmaze-eeg-models documentation (there is deliberately no GPU extra). Note that
after that swap, any later pip install "brainmaze-eeg[models]" (not only -U)
installs the CPU onnxruntime again, which then shadows the GPU build; repeat the swap
afterwards.
Unreleased#
fitof the KDE classifiers (KDEBayesianModeland its subclasses,KDEBayesianModelNC),features.utils.balance_classesandMapper.fit_mapaccept plain lists/tuples forX/y(a list of labels raisedAttributeErrorup to 3.1.0). Results and return types for ndarray and pandas input are unchanged.New
modelsextra:pip install "brainmaze-eeg[models]"also installs brainmaze-eeg-models (see Installation).Packaging:
python-dateutil>=2.8.2,<3. python-dateutil 3.0.0 (2026-10-21) is not compatible with pandas <= 3.1.0 (pandas GH#71459). With it, annotation times that carry adateutil.tz.gettz()zone with DST transitions (e.g.gettz('America/Chicago')) break every hypnogram scoring call: pandas 3.x raisesAttributeError: 'NoneType' object has no attribute 'total_seconds', and on pandas 2.x scalar timezone conversions can silently return tz-naive UTC times. Fixed-offset zones andzoneinfozones are not affected. No code or result changes with dateutil 2.x. If you need dateutil 3, usezoneinfo.ZoneInfo('America/Chicago')instead ofgettz(...): scores are identical (the hypnogram test suite passes unchanged with it), but the column dtype showsAmerica/Chicagoinstead oftzfile(...), and a wall-clock time inside a DST gap (nonexistent local time) maps to a different UTC instant. The bound will be lifted only together with a pandas floor that contains the fix (expected pandas 3.1.1).
What’s new in 3.1.0#
A minor release: no default output changes (the Janca detector with default arguments is bit-identical to 3.0.0 and to the eeg_forge reference).
Reference baseline for the Janca detector:
JancaBaselinemeasures the background (log-envelopemu/sdper channel) on a quiet or pre-injury recording, with gaps and constant dropouts excluded, and saves it as JSON.detect_spikes_janca(..., baseline=..., combine='reference'|'min'|'max')andJancaDetector(baseline=...)then use that fixed threshold instead of, or combined with, the local one. For channels that spike permanently: on synthetic iEEG with 1 / 3 / 5 spikes/s the local model finds 93 / 42 / 0.5 % of the spikes, the reference baseline 97 / 97 / 96 %, with no false detections. The signal-path parameters must match the baseline’s (checked), and so must the channel order when both sides have channel names (checked); the amplitude unit, gain and montage must too (not checkable; warnings flag a ×10 level mismatch on a channel and a ×3 mismatch of the montage’s background level).Long Janca windows on data with drops:
gap_aware_stats=Truecomputes the local statistics over valid samples only (O(n) for any window, e.g.window_s=3600on 24 h) and never detects on samples left out of them (dropouts and their edges);GapAwareSpikeDetectorpasses its gap mask so filled samples never enter them.
See Reference baseline in the spike detectors README for when to use it, what must match, and the limitations.
What’s new in 3.0.0#
brainmaze-eeg 3.0.0 is a major release: default outputs change (list below). It requires
brainmaze-utils>=3.0.0, which resamples correctly at every sampling rate and DC level and
provides brainmaze_utils.gaps (its numerical changes are listed on the
utils changes page). Full list of
merged pull requests: release notes.
New
detect_spikes_janca/JancaDetector(Janca et al. 2015, eeg_forge formulation, with presets'spike'and'ripple'; the ripple preset is not validated on real ripples) andGapAwareSpikeDetector, a wrapper that makes any spike detector safe for data with NaN gaps or constant-value dropouts and reports the valid time per channel. In 1.0.0 the package had onlySpikeDetectorHilbertanddetect_spikes_barkmeier. The raw detectors require finite input. See the Spike detectors page and the detailed README.WaveDetectorfeaturesWAVE_SLOPE_MEDIANandANALYSABLE_RATE(appended at the end, so the 1.0.0 feature names and positions are unchanged), thetrough='paper'mode (Carvalho et al. 2024 Methods), NaN gaps handled, and 7.5-9x faster. The samevalues, names = detector(x)interface as the other feature extractors. See the WaveDetector and slow-wave project pages.Out-of-distribution epochs in the sleep classifiers (
brainmaze_eeg.classifiers) are labelled'UNKNOWN'(NaN probabilities) instead of getting a confident label. The floor is not an artifact detector. See the Classifiers page.Demos for all three: demo/.
Changes in default output, and the way back
Where |
What changes |
1.0.0 behaviour |
|---|---|---|
Sleep classifiers (KDE family, MultiChannel) |
|
|
|
the default state label is |
was |
|
Butterworth band-pass instead of the ringing FFT filter: the mean downslopes change by
about -4 to -7 % (demo: slow oscillation 186.0 to 173.9 uV/s). |
|
|
the paper’s 1-35 Hz broad band (was 1-80 Hz) and one-minute blocks ( |
|
|
the Chebyshev band-pass is now 10-60 Hz as specified (it was effectively 18-48 Hz), so
detections change; the hum notch has the same width at every sampling rate; the ambiguous
class ( |
|
|
reworked so every public function returns correct numbers or raises: REM periods counted
per bout, data rate over multi-day spans, awakening/onset rules (N1 counts as sleep),
|
no switch: the 1.0.0/2.0.0 results were wrong or the functions failed |
How to contribute#
The project has 2 main protected branches main that contains official software releases and dev that contains the latest feature implementations shared with developers. To implement a new feature a new branch should be created from the dev branch with name pattern of developer_identifier/feature_name.
After the feature is implemented, a pull request can be created to merge the feature branch into the dev branch with. Pull requests need to be reviewed by a maintainer.
Releasing#
Releases are automated and go through a reviewed pull request. To cut a release, a maintainer runs the Prepare release GitHub Action (Actions tab, workflow_dispatch) and selects the bump (patch / minor / major). This opens a small Release vX.Y.Z pull request that bumps [project].version in pyproject.toml on a release/bump-* branch off main. A reviewer checks that it changes only that line and squash-merges it into main; the merge triggers the Release workflow, which tests, builds, publishes to PyPI (Trusted Publishing), and then tags the version and creates the GitHub release. The build reads the version from pyproject.toml, which remains the single source of truth.
Promotion of features from dev to main is independent of releases and must not change [project].version – a Version guard CI check flags any pull request outside the release flow that edits it (the check is advisory, so reviewers must not merge a flagged pull request). The version line is owned solely by the release automation on main; this is what keeps dev -> main merges free of version conflicts under the squash-merge policy (a version edited on both branches would otherwise conflict every release cycle).
The Prepare release action requires the repository/organization setting Allow GitHub Actions to create and approve pull requests to be enabled, so it can open the bump pull request. See RELEASING.md and the family guide bnelair/brainmaze-sphinx (including what to do if a release fails part-way).
New functions need to be implemented with Sphinx compatible docstrings. The documentation is automatically generated from the docstrings using Sphinx.
Building Documentation#
To build the documentation locally:
Install documentation dependencies:
pip install -e ".[docs]"
Alternatively, you can install from the requirements file:
pip install -r docs_src/requirements.txt
Build the documentation:
sphinx-build -b html docs_src/source docs
The generated HTML documentation will be in the docs/ directory. Note that the docs/ directory is excluded from version control via .gitignore and should not be committed to the repository.
License#
This software is licensed under the BSD 3-Clause license. For details see the LICENSE file in the root directory of this project.
Acknowledgment#
This code was developed and originally published for the first time by (Mivalt 2022, and Sladky 2022). Additionally, codes related to individual projects available in this repository are stated below. When using this toolbox, we appreciate you citing the papers related to the utilized functionality. Please, see the sections below for references to individual submodules.
F. Mivalt et V. Kremen et al., “Electrical brain stimulation and continuous behavioral state tracking in ambulatory humans,” J. Neural Eng., vol. 19, no. 1, p. 016019, Feb. 2022, doi: 10.1088/1741-2552/ac4bfd.V. Sladky et al., “Distributed brain co-processor for tracking spikes, seizures and behaviour during electrical brain stimulation,” Brain Commun., vol. 4, no. 3, May 2022, doi: 10.1093/braincomms/fcac115.
Sleep classification and feature extraction#
F. Mivalt et V. Kremen et al., “Electrical brain stimulation and continuous behavioral state tracking in ambulatory humans,” J. Neural Eng., vol. 19, no. 1, p. 016019, Feb. 2022, doi: 10.1088/1741-2552/ac4bfd.F. Mivalt et V. Sladky et al., “Automated sleep classification with chronic neural implants in freely behaving canines,” J. Neural Eng., vol. 20, no. 4, p. 046025, Aug. 2023, doi: 10.1088/1741-2552/aced21.
The work was based on the following references:
Gerla, V., Kremen, V., Macas, M., Dudysova, D., Mladek, A., Sos, P., & Lhotska, L. (2019). Iterative expert-in-the-loop classification of sleep PSG recordings using a hierarchical clustering. Journal of Neuroscience Methods, 317(February), 61–70. https://doi.org/10.1016/j.jneumeth.2019.01.013Kremen, V., Brinkmann, B. H., Van Gompel, J. J., Stead, S. (Matt) M., St Louis, E. K., & Worrell, G. A. (2018). Automated Unsupervised Behavioral State Classification using Intracranial Electrophysiology. Journal of Neural Engineering. https://doi.org/10.1088/1741-2552/aae5abKremen, V., Duque, J. J., Brinkmann, B. H., Berry, B. M., Kucewicz, M. T., Khadjevand, F., G.A. Worrell, G. A. (2017). Behavioral state classification in epileptic brain using intracranial electrophysiology. Journal of Neural Engineering, 14(2), 026001. https://doi.org/10.1088/1741-2552/aa5688
Evoked Response Potential Analysis#
K. J. Miller et al., “Canonical Response Parameterization: Quantifying the structure of responses to single-pulse intracranial electrical brain stimulation,” PLOS Comput. Biol., vol. 19, no. 5, p. e1011105, May 2023, doi: 10.1371/journal.pcbi.1011105.
EEG Slow Wave Detection and Analysis#
Carvalho DZ, Kremen V, Mivalt F, St Louis EK, McCarter SJ, Bukartyk J, Przybelski SA, Kamykowski MG, Spychalla AJ, Machulda MM, Boeve BF, Petersen RC, Jack CR Jr, Lowe VJ, Graff-Radford J, Worrell GA, Somers VK, Varga AW, Vemuri P. Non-rapid eye movement sleep slow-wave activity features are associated with amyloid accumulation in older adults with obstructive sleep apnoea. Brain Commun. 2024 Oct 7;6(5):fcae354. doi: 10.1093/braincomms/fcae354. PMID: 39429245; PMCID: PMC11487750.
The slow-wave detection project is documented on the EEG Slow Wave Detection and Analysis page; the runnable example is demo/eeg_wave_detection. The original project readme from the BEST toolbox: projects/slow_wave_detection/readme.rst.
Funding#
Individual sections of this code were developed under different projects including:
NIH Brain Initiative UH2&3 NS095495 - Neurophysiologically-Based Brain State Tracking & Modulation in Focal Epilepsy,
NIH U01-NS128612 - An Ecosystem of Technology and Protocols for Adaptive Neuromodulation Research in Humans,
DARPA - HR0011-20-2-0028 Manipulating and Optimizing Brain Rhythms for Enhancement of Sleep (Morpheus).
FEKT-K-22-7649 realized within the project Quality Internal Grants of the Brno University of Technology (KInG BUT), Reg. No. CZ.02.2.69/0.0/0.0/19_073/0016948, which is financed from the OP RDE.
Projects and demos
Modules
- Classifiers
KDEBayesianCausalModelKDEBayesianModelKDEBayesianModelNCMVGaussBayesianCausalModelMVGaussBayesianModelMapperMultiChannelMVGaussBayesClassifierMultiChannelMVGaussBayesClassifier.extract_features()MultiChannelMVGaussBayesClassifier.extract_features_bulk()MultiChannelMVGaussBayesClassifier.fit()MultiChannelMVGaussBayesClassifier.max_log_likelihood()MultiChannelMVGaussBayesClassifier.scores()MultiChannelMVGaussBayesClassifier.transform()
SleepClassifierWrapperSleepStageProbabilityMarkovChainFilterSleepStageProbabilityMarkovChainFilter.correct_certainty()SleepStageProbabilityMarkovChainFilter.fit()SleepStageProbabilityMarkovChainFilter.fit_optimize()SleepStageProbabilityMarkovChainFilter.get_changing_state_posteriors()SleepStageProbabilityMarkovChainFilter.get_changing_state_priors()SleepStageProbabilityMarkovChainFilter.get_changing_state_probabilities()SleepStageProbabilityMarkovChainFilter.get_prob_to_change()SleepStageProbabilityMarkovChainFilter.get_state_change_posterior()SleepStageProbabilityMarkovChainFilter.get_state_change_prior()SleepStageProbabilityMarkovChainFilter.get_state_idx()SleepStageProbabilityMarkovChainFilter.get_state_priors()SleepStageProbabilityMarkovChainFilter.predict()SleepStageProbabilityMarkovChainFilter.remove_class()SleepStageProbabilityMarkovChainFilter.reset_probabilities()SleepStageProbabilityMarkovChainFilter.weight_probabilities()
SleepStructureClassifierUNKNOWN_LABELmultivariate_normal_
- CRP
- Epochs
- Features
- Hypnogram
AROUSAL_TAGSLABEL_ALIASEScorrect_hypnogram()correct_rem()do_median_filtration()fill_nonrem_voids()fill_same_voids()fill_sleep_voids()fill_wakerem_voids()get_awakening_time()get_fell_asleep_time()get_hypnogram_datarate()get_number_of_awakenings()get_number_of_sleep_stages()get_rem_latency()get_stage_times()get_stage_times_dataset()get_time_by_key()get_transition_counts()get_transition_matrix()get_transition_matrix_dataset()is_sleep_complete()plot_hypnogram()print_sleep_score()score_night()transition_matrix_to_change_matrix()valid_dataset_index_by_duration()
- Montages
- Preprocessing
- Scikit Modules
- Selection statistics
- Spectral (multitaper)
- Spike detectors
- Detectors
- Janca
- Janca (Hilbert-envelope) interictal spike detectors
BASELINE_LEVEL_WARN_RATIOCOMBINE_MODESDECISION_PARAMSDEFAULT_MIN_VALID_FRACTIONDEFAULT_STATS_MARGIN_SJANCA_PRESETSJancaDetectorMAX_RESAMPLER_LOSS_DBMONTAGE_LEVEL_QUANTILEMONTAGE_LEVEL_WARN_RATIOSIGNAL_PATH_PARAMSSpikeDetectorHilbertdesign_janca_filters()detect_spikes_janca()janca_decimation_factor()janca_params()janca_resampling()janca_threshold()resampler_gain_db()
- Janca reference baseline (3.1.0)
- Barkmeier
- Gap handling
- Filter design