Skip to content
JoshuaDuqPublic

About

Audited phase-tracked regression of periodic helium cryocooler comb artifacts in simultaneous EEG-fMRI, writing EEG-BIDS derivatives with sample-exact replay verification and provenance manifests.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

decomb

decomb logo

Python 3.11+ License: BSD-3-Clause BIDS Standard Ruff

Audited phase-tracked regression of periodic helium cryocooler comb artifacts in simultaneous EEG-fMRI.

decomb detects cryocooler harmonics or applies precomputed frozen harmonic models, estimates time-varying shared phase across spatial sensors, executes adaptive leave-one-cycle-out (LOCO) harmonic regression, writes standard EEG-BIDS derivatives, verifies sample-level numerical exactness via deterministic replay, and generates comprehensive diagnostic figures and provenance manifests.

Feature Specification
Target Artifact Quasi-periodic helium compressor pump comb ($\sim 1.2\text{ Hz}$ fundamental, 72 cycles/min)
Frequency Scope Comb harmonics from 10 to 110+ Hz (configurable across acquisition bandwidth)
Phase Engine Circular consensus with Huber robust weighting ($\delta = 0.7\text{ rad}$) on Hann SVD leading spatial modes
Fitting Engine Adaptive leave-one-cycle-out (LOCO) regression with Gaussian weighting ($\sigma = 20\text{ s}$) and SNR shrinkage
Input Format Continuous BrainVision EEG recordings structured as EEG-BIDS datasets
Verification Gate Deterministic sample-exact replay confirming zero maximum absolute deviation

Signal Architecture

flowchart LR
    A["Raw EEG-BIDS"] --> B["Harmonic Selection"]
    B --> C["Shared Phase Tracking"]
    C --> D["Adaptive LOCO Regression"]
    D --> E["BIDS Derivative"]
    E --> F["Replay Verification"]
    E --> G["Diagnostic Reports"]
Loading
  1. Harmonic Selection: Discovers prominent comb teeth via Welch power spectral density or loads a precomputed frozen harmonic manifest.
  2. Shared Phase Tracking: Decomposes overlapping Hann windows into spatial singular vectors, combining phase evidence across harmonics using Huber robust circular consensus.
  3. Adaptive LOCO Regression: Segments continuous data into cycles, fitting harmonic coefficients with local Gaussian weighting while excluding the predicted cycle to prevent overfitting.
  4. BIDS Derivative: Writes verified BrainVision float32 derivatives alongside cryptographic provenance manifests.
  5. Replay Verification: Replays the recorded regression against untouched source data to verify bitwise numerical exactness.
  6. Diagnostic Reporting: Outputs publication-ready spectral summaries, scalp topographies, and synthetic probe recovery benchmarks.

Install

Python 3.11 or newer is required.

python3 -m venv .venv
source .venv/bin/activate
pip install -e .

Run the pipeline

Create a configuration file decomb.yaml pointing to your EEG-BIDS dataset:

paths:
  bids_root: /path/to/bids-dataset

Execute the end-to-end pipeline (correction, verification, and diagnostic plots):

decomb run --config decomb.yaml

By default, the corrected derivative is written to <bids_root>_cryocoolerregressed and reports are saved to <bids_root>_decomb_reports/removal. Existing output directories are strictly rejected to prevent accidental overwriting.

Pipeline Stages

decomb provides modular commands for execution, testing, and inspection:

Command Primary Action Typical Output
decomb run --config decomb.yaml Complete sequential workflow (apply $\to$ verify $\to$ psd) Corrected dataset, verification table, figures
decomb apply --config decomb.yaml Estimates phase, regresses harmonics, writes BIDS derivative sub-*/[ses-*/]eeg/*_eeg.vhdr, manifest.json
decomb verify --config decomb.yaml Deterministic replay from source data verification_summary.tsv (exact parity check)
decomb psd --config decomb.yaml Computes Welch spectra and generates diagnostic plots Diagnostic PNG/PDF figures, spectral caches

run, apply, and verify process the complete dataset to guarantee dataset-level provenance integrity. psd can inspect specific participants via --subjects 01 02.

Harmonic Selection: Detection vs. Frozen Models

decomb supports two complementary selection workflows:

  • Automatic Detection (default / --detect): Discovers prominent comb harmonics directly from each recording's Welch power spectrum (prominence $&gt; 0.5\text{ dB}$, width $\le 4$ bins). This mode is self-contained and conservative.
  • Frozen Model (--model <path> or paths.model_manifest): Applies fixed harmonic sets defined in advance via a TSV/JSON manifest. A frozen model captures weaker teeth that fall below single-recording detection thresholds across a cohort.
# Automatic detection (default)
decomb run --config decomb.yaml --detect

# Precomputed frozen harmonic model
decomb run --config decomb.yaml --model /path/to/harmonics.tsv

Both modes execute the identical regression engine and produce the same provenance metadata replayed by verify. In a 126-recording cohort benchmark, the frozen set averaged 65.5 teeth per recording and automatic detection averaged 47.9 teeth, agreeing within 0.04 dB on harmonics selected by both methods. For format specifications, see frozen models; for empirical measurements, see the mode comparison.

Configuration Reference

All pipeline parameters can be configured in decomb.yaml. Relative paths resolve from the current working directory:

paths:
  bids_root: /path/to/bids-dataset               # Source EEG-BIDS root
  output_root: /path/to/corrected-dataset       # Corrected derivative root (optional)
  removal_dir: /path/to/reports                 # Diagnostic reports and figures (optional)
  task: rest                                    # Target task name, or "*" for all tasks
  # model_manifest: /path/to/harmonics.tsv     # Optional precomputed frozen harmonic model

removal:
  comb_fundamental_hz: 1.2                      # Declared hardware fundamental frequency (Hz)
  anchor_harmonics: [43, 45, 49, 51]            # Mandatory harmonics contributing to shared phase
  phase_tracking_window_s: 20.0                 # Hann window duration for phase SVD (s)
  regression_window_count: 3                    # Number of phase windows per support block (60 s total)
  phase_hop_s: 1.0                              # Temporal step between phase updates (s)
  phase_robust_cutoff_rad: 0.7                  # Huber robust loss threshold (radians)
  local_coefficient_sigma_s: 20.0               # Gaussian weighting scale for LOCO coefficients (s)
  estimation_window_s: 10.0                     # Welch window duration for harmonic screening (s)

The default configuration describes a 1.20 Hz cryocooler comb (72 cycles/min). The fundamental frequency is an explicit hardware parameter, not inferred from data. All selected teeth at or above the lowest anchor contribute to the shared phase estimate.


Python API

decomb provides programmatic access to its core regression engine for integration into custom scientific pipelines:

import mne
from decomb.cryocooler import CryocoolerRegressionSettings, regress_cryocooler

# Load continuous EEG data
raw = mne.io.read_raw_brainvision("sub-01_task-rest_eeg.vhdr", preload=True)
picks = mne.pick_types(raw.info, eeg=True, exclude="bads")
eeg_data = raw.get_data(picks=picks)
sampling_rate = raw.info["sfreq"]

# Define regression geometry and harmonic parameters
settings = CryocoolerRegressionSettings(
    fundamental_hz=1.2,
    harmonic_numbers=(8, 18, 43, 45, 49, 51),
    anchor_harmonic_numbers=(43, 45, 49, 51),
    segment_duration_s=20.0,
    regression_window_count=3,
    phase_hop_s=1.0,
    phase_robust_cutoff_rad=0.7,
    local_coefficient_sigma_s=20.0,
)

# Execute audited regression
result = regress_cryocooler(eeg_data, sampling_rate, settings)

# Access cleaned data, artifact estimate, and continuous phase trajectory
cleaned_eeg = result.cleaned_data      # ndarray of shape (n_channels, n_samples)
artifact_comb = result.artifact_data  # ndarray of shape (n_channels, n_samples)
tracked_phase = result.phase_radians  # ndarray of shape (n_samples,)

Automatic Diagnostics and Verification

Every complete pipeline run produces publication-ready summaries and signal-preservation benchmarks derived directly from the dataset:

Correction Diagnostics

Harmonic suppression across the frequency spectrum, detailed reduction indices on focused teeth, and a scalp map of comb prominence. Each tooth's reduction uses only recordings that modeled it; error bars represent sample standard deviations across recordings. The scalp map is projected from recorded sensor coordinates:

Correction summary

Spectral Change and Signal Recovery

Paired spectral change ($\text{corrected} - \text{source}$) alongside recovery performance for synthetic test probes. Probe gain and normalized RMS error are evaluated separately; the comb-locked removal control targets zero gain and 100% error to confirm target specificity:

Preservation summary

See figure conventions for averaging definitions, uncertainty representations, and interpretation guidelines.

Additional Diagnostic Artifacts

Alongside visual figures, each run generates structured provenance and validation tables:

  • Harmonic measurements table (harmonic_measurements.tsv): Recording-level suppression and baseline power per tooth.
  • Verification summary (verification_summary.tsv): Bitwise maximum sample deviations from deterministic replay.
  • Cryptographic provenance manifest (manifest.json): Schema-4 record containing algorithm digests, runtime parameters, and input file hashes.
  • Panel availability log (plot_availability.json): Explicit records of any omitted figures (e.g., absent sensor coordinates) to prevent silent fallback or approximation.

Method and Input Contract

Inputs must be continuous BrainVision EEG recordings structured as EEG-BIDS datasets. Reading uses MNE-BIDS; array computation uses MNE-Python, NumPy, and SciPy. Missing inputs, invalid models, and unsupported acquisition geometries raise immediate errors.

  • Target Scope: decomb specifically targets the periodic narrowband helium cryocooler comb artifact in continuous EEG.
  • Data Integrity: Source recordings are treated as strictly immutable. Bad EEG channels, auxiliary non-EEG channels (ECG, EOG), annotations, and sampling intervals are preserved without modification.
  • Regression Engine (robust_shared_phase_adaptive_loco_v1):
    • Robust shared phase is computed from overlapping 20-second Hann windows updated every second. Harmonics at or above the lowest anchor are spatially pooled via SVD, then combined using circular consensus with Huber robust weights (0.7-radian cutoff).
    • Coefficients are estimated within 60-second support blocks using adaptive leave-one-cycle-out (LOCO) regression with a 20-second Gaussian kernel and SNR shrinkage.
    • Automatic and frozen selection modes execute this identical engine.
  • Verification and Reproducibility: Every run writes a Schema-4 model manifest recording all method parameters and cryptographic digests. decomb verify replays the recorded regression sample-for-sample to confirm exact numerical reproduction.
  • Scientific Boundaries: Neural activity coherent with the cryocooler cannot be distinguished from the artifact by spectral regression alone. Synthetic probe recovery evaluates filter transparency, not unobserved endogenous neural dynamics. See methods and limitations.

Repository Structure

decomb/
├── src/decomb/                     # Core library: phase tracking, LOCO regression, BIDS I/O, verification
│   ├── cli.py                      # Command-line interface entry points
│   ├── cryocooler.py               # Core regression engine and settings
│   ├── shared_phase.py             # SVD and Huber robust consensus phase estimator
│   ├── defaults.yaml               # Baseline acquisition and algorithm configuration
│   └── figures/                    # Publication-grade plotting modules
├── docs/                           # Documentation: methods, models, plotting, references
│   ├── README.md                   # Documentation index and study records
│   ├── methods.md                  # Mathematical formulations, data boundary, limitations
│   ├── frozen-models.md            # Schema-4 frozen model specifications and export
│   ├── plotting.md                 # Diagnostic figures, metric definitions, caching
│   ├── tuning.md                   # Cold-head phase tracking window tuning guide
│   └── references.md               # Literature citations and software reference index
├── studies/cryocooler_2026/        # 2026 validation study: cohort models, assessments, reports
│   └── README.md                   # Study workflow and module map
├── experiments/                    # Exploratory studies outside production API (e.g., ventilation fans)
│   └── README.md                   # Non-production investigation index
├── tests/                          # Test suite: unit verification, pipeline integration, regressions
├── CITATION.cff                    # Machine-readable software citation metadata
├── CONTRIBUTING.md                 # Development workflows and verification commands
└── LICENSE                         # BSD 3-Clause License

For study workflows and module maps, see the 2026 cryocooler study. For development commands, see contributing.


Citing decomb

Until an archival DOI is assigned, cite the exact software release used in the analysis:

Duquette, J. (2026). decomb (version 0.5.0) [Computer software]. https://github.com/JoshuaDuq/decomb

@misc{duquette_decomb_2026,
  author = {Duquette, Joshua},
  title = {decomb},
  year = {2026},
  version = {0.5.0},
  url = {https://github.com/JoshuaDuq/decomb},
  note = {Computer software}
}

Canonical metadata is maintained in CITATION.cff. When referring to underlying methodologies or software libraries, cite the primary literature indexed in docs/references.md.


License

BSD 3-Clause License; see LICENSE.

About

Audited phase-tracked regression of periodic helium cryocooler comb artifacts in simultaneous EEG-fMRI, writing EEG-BIDS derivatives with sample-exact replay verification and provenance manifests.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages