Skip to content

[ICA] Add eeg_mir, the mutual information reduction of a decomposition - #698

Merged
neuromechanist merged 7 commits into
developfrom
feature/eeg-mir
Nov 26, 2026
Merged

neuromechanist merged 7 commits into
developfrom
feature/eeg-mir

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

eeg_mir(EEG) returns the mutual information that icaweights removes from icasphere @ data, in nats, and the variance of that estimate. It ports getMIR.m's binned entropy estimator, as pamica.metrics.mir does, with a fixed 256 bins so that MIR does not drift with recording length, reads the data in blocks so that its extra memory stays bounded, and needs no optional dependency. The port's Apache-2.0 attribution ships in a new THIRD_PARTY_NOTICES.md.

Part of #20

eeg_mir(EEG) returns the MIR of icaweights measured against icasphere @ data,
in nats, and its variance, with getMIR.m's binned entropy estimator (as
pamica.metrics.mir ports it) at a fixed 256 bins. Pure NumPy, no extra.
Tested: closed form 1 - ln 2, identity, scaling/permutation/sign
invariance, equality with pamica.metrics.mir, and the refusals.
eeg_mir ports getMIR.m by Nima Bigdely-Shamlo (bigdelys/pre_ICA_cleaning),
which is Apache-2.0. Add the attribution, the changes made, and the
Apache-2.0 text, ship the file in the wheel and sdist license files, and
point to it from the eeg_mir docstring. Checked with uv build: the file is
in dist-info/licenses and at the sdist root.
eeg_mir held the selected channels, the sphered data and the components
at full length, about 5.25 times the float32 data in extra memory. It
now reads the data twice in blocks of 8192 samples (ranges, then bin
counts), checks finiteness per block, and indexes channels only for a
true subset, so the extra memory no longer grows with the recording
(32 x 1M float32: 641 MiB to 18 MiB peak, tracemalloc). The pAMICA
test now allows last-bit rounding. Tested: tests/test_eeg_mir.py.
Without pAMICA: icachansind that leaves out a flat and a noise channel
gives the MIR of the other four, and including the flat channel raises
the constant-row error; the variance equals getent4's on a hand-binned
two-row array. Also covers an icasphere whose rows do not match
icaweights and NaN or inf in either matrix. Each new test fails under
its fault (ignored icachansind, doubled variance).
Delorme et al. (2012, eq. 17) measure MIR from the recorded channels
with the full unmixing, in kbits/s, and eeg_nemar_dataqual.m passes the
channel data with icaweights @ icasphere, so their values include
sphering's reduction. The docstring and the API page now say that
eeg_mir measures from the sphered data and is not comparable with
them. Documentation only.
The module docstring now opens with the Apache-2.0 section 4(b) notice
that it is a modified port of getMIR.m. THIRD_PARTY_NOTICES.md states
that pAMICA's copyright holder contributes the code derived from
pAMICA's port under eegprep's BSD 2-Clause License, and lists block
reading among eegprep's changes. Documentation only.
Data shaped (channels, 0) raised a reshape ValueError and (channels,
pnts, 0) a ZeroDivisionError. eeg_mir now raises ValueError('EEG data
holds no samples; eeg_mir needs data.') for both, with a refusal case
for each. The pAMICA test comment also bounds the chance that last-bit
rounding moves a sample across a bin boundary. Tested:
tests/test_eeg_mir.py, 18 passed.
@neuromechanist

Copy link
Copy Markdown
Member Author

Summary. eeg_mir is in src/eegprep/functions/popfunc/eeg_mir.py and is exported from the package root, with tests in tests/test_eeg_mir.py, a section and an autosummary entry in docs/source/api/ica_and_components.rst, and a changelog line. THIRD_PARTY_NOTICES.md credits getMIR.m to Nima Bigdely-Shamlo, lists eegprep's changes, reproduces the Apache License 2.0, and states that pAMICA's copyright holder contributes the code derived from pAMICA's port under eegprep's BSD 2-Clause License; [tool.setuptools] license-files ships it in the wheel (dist-info/licenses) and the sdist. No existing function changes.

Motivation. NEMAR computes per-recording quality metrics in reviewed plugins that call eegprep's public functions rather than reimplementing them: nemar-quality counts classes with eeg_icalabelstat over eeg_pvaf shares, and nemar-spectrum calls compute_spectra (#603, #689; epic nemarOrg/nemar-cli#2324). The mutual information reduction (MIR) of the independent component analysis (ICA) decomposition is the next one. EEGLAB has no MIR function; the MATLAB reference is getMIR.m by Nima Bigdely-Shamlo in bigdelys/pre_ICA_cleaning (Apache-2.0), which pAMICA 0.4.0 ports as pamica.metrics.mir. Importing pamica imports torch, so calling it would put a NumPy metric behind the pamica extra and out of the browser build; eeg_mir is a NumPy port instead, and a test holds it equal to pAMICA's.

Definition. With W = icaweights, x = icasphere @ data and y = W @ x, MIR = log|det W| + sum_i h(x_i) - sum_i h(y_i), where h is a marginal differential entropy and log|det W| is the sum of log|eigenvalues|, as in getMIR.m. Identity weights give 0; rescaling, reordering and sign flips of components leave it unchanged; larger is better. This is equation 17 of Delorme et al. (2012, doi:10.1371/journal.pone.0030135) with x taken after sphering, so MIR rates what the unmixing adds to the decorrelation that sphering does. The paper measures MIR from the recorded channels with the full unmixing (sphering alone is one of the 22 decompositions it compares by MIR) and reports kbits/s, and the commented-out mir() of sccn/NEMAR-pipeline's eeg_nemar_dataqual.m passes the channel data with icaweights @ icasphere. Their values include the reduction that sphering achieves, so they are not comparable with eeg_mir's. Epochs are concatenated, icachansind selects the channels, and icaact is not read: the components are recomputed from data. icasphere may have fewer rows than channels, as after AMICA's pcakeep, and MIR is then measured in that subspace. icaweights must be square, so a runica decomposition reduced by PCA (which keeps the reduction in icaweights and an identity sphere) raises ValueError, as do a missing decomposition, an icasphere whose rows or columns do not match icaweights or icachansind, a singular icaweights or icasphere, NaN or infinite values in the data or either matrix, data with no samples, and a constant sphered row or component.

Bin rule. Each entropy uses getent4's estimator: equal bins between a row's minimum and maximum, the Miller-Madow correction and the log bin width. getMIR.m takes round(3 * log2(1 + N / 10)) bins for N samples, which grows with the recording, so the same decomposition scores differently on a shorter or longer segment. eeg_mir fixes the count at 256 (MIR_NBINS). On two unit-variance uniform sources rotated by 45 degrees, whose MIR is 1 - ln 2 = 0.3069 nats, the length-based count reads 0.046 nats low at 5,000 samples and 0.026 low at 1.2 million (mean of 20 seeds); 256 bins read 0.0052 to 0.0055 low at every length. That offset is the estimator's end bins, which are half as wide as the others, so a uniform row reads ln 2 / (nbins - 1) too high: 2 ln 2 / 255 = 0.0054. On two unit-variance Laplace sources (closed form 0.0968 nats) the length-based count reads 0.014 to 0.016 low and 256 bins stay within 0.0014. On the 32 components of sample_data/eeglab_data_epochs_ica.set (30,720 samples), 35 bins (the length-based count) give 0.851 nats, 100 give 0.982, 256 give 0.993 and 512 give 0.994. 512 bins gain about 0.001 there and are noisier below about 20,000 samples, so 256 it is.

Memory. eeg_mir reads the data twice in blocks of 8,192 samples, once for each row's range and once for its bin counts, checks finiteness per block, and indexes channels only when icachansind is a true subset. Peak memory beyond the dataset, from tracemalloc with float32 data and random full-rank matrices: 32 channels by 1 million samples, 641 MiB (5.25 times the data) before and 18 MiB after; the same samples as 1,000 epochs of 1,000 points, 641 MiB before and 19 MiB after; 128 channels by 1 million samples, 2,563 MiB before and 73 MiB after; 32 channels by 4 million samples, 18 MiB after. The extra memory now depends on the number of components and stays the same as the recording grows; run times are about the same (0.3 s, 0.4 s and 1.7 s for the first three cases, against 0.3 s, 0.3 s and 2.2 s before).

Key code. The second pass and the entropy of each histogram row (src/eegprep/functions/popfunc/eeg_mir.py), with rows 0 to n-1 of each block holding x and rows n to 2n-1 holding y:

counts = np.zeros((2 * components, MIR_NBINS), dtype=np.int64)
offsets = np.arange(2 * components)[:, np.newaxis] * MIR_NBINS
for block in _projected_blocks(data, selection, sphere, weights):
    bins = np.round((MIR_NBINS - 1) * (block - low[:, np.newaxis]) / (high - low)[:, np.newaxis]).astype(np.intp)
    counts += np.bincount((bins + offsets).ravel(), minlength=counts.size).reshape(counts.shape)

entropies, variances = _binned_entropies(counts, high - low, samples)
log_jacobian = np.sum(np.log(np.abs(np.linalg.eigvals(weights))))
mir = float(log_jacobian + np.sum(entropies[:components]) - np.sum(entropies[components:]))
variance = float((np.sum(variances[:components]) + np.sum(variances[components:])) / samples)

def _binned_entropies(counts, widths, samples):
    entropies = np.empty(counts.shape[0])
    variances = np.empty(counts.shape[0])
    for index, row in enumerate(counts):
        probability = row[row > 0] / samples
        plugin = -np.sum(probability * np.log(probability))
        variances[index] = np.sum(probability * np.log(probability) ** 2) - plugin**2
        entropies[index] = plugin + (MIR_NBINS - 1) / (2 * samples) + np.log(widths[index] / MIR_NBINS)
    return entropies, variances

Tests. tests/test_eeg_mir.py computes everything for real, with no mocks; 18 tests. Two uniform sources rotated by 45 degrees (200,000 samples) give 1 - ln 2 within 0.0094 nats: the 0.0054 end-bin offset of 256 bins plus four standard deviations of the estimate over seeds. Identity weights give exactly 0. Rescaling (by 2.5, -0.3, 7 and -1), reordering and sign flips of icaweights leave MIR and its variance unchanged within 1e-12. icachansind that leaves out a flat and a noise channel gives the MIR of the other four channels, and including the flat channel under an identity sphere raises the constant-row error. On a two-row array whose bins are known by hand (p = 3/4 and 1/4 in each row), the variance equals getent4's, 0.2263. On epoched data with 6 of 8 channels and a 4-row sphere, (mir, variance) equals pamica.metrics.mir(icaweights, icasphere @ data, nbins=256) within 1e-12: eeg_mir multiplies a block at a time and pAMICA in one product, so a BLAS may round a product differently in the last bit, which moves a row's minimum, maximum and log bin width by about 1e-16 (on this macOS host and on the sample dataset the two are bit-identical, 0.9933166970944427 nats). A last-bit difference could in principle also move one sample across a bin boundary, changing an entropy by about 1/N, but that needs a sample within one rounding step of a boundary, a probability below about 1e-8 for that test's 30,000 samples. That test skips when pamica is not installed, and CI installs it. A parametrized test checks each of twelve refusal cases, including data with no samples as (channels, 0) and as (channels, pnts, 0). Each guarded line was mutated once: dropping the log-Jacobian fails the invariance and pAMICA tests; getMIR's length-based count (43 bins at 200,000 samples) fails the closed-form test; dropping the log bin width fails three tests; ignoring icachansind fails the channel-selection and pAMICA tests; doubling the variance fails the getent4 and pAMICA tests.

Packaging. [tool.setuptools] license-files is the key that works beside the existing license = { file = "LICENSE" } table: project.license-files with that table fails the build. Current setuptools (84.2.1) warns that the key is deprecated, with the same 2027-02-18 deadline as its existing warning about the license table, and moving to an SPDX license string with project.license-files would clear both in a separate change. The key builds with setuptools 68.0.0, 70.0.0 and 84.2.1; the declared floor, setuptools 61, does not build eegprep on Python 3.12 at all (pkgutil.ImpImporter is gone), with or without this change.

Checks. ruff check ., ruff format --check ., uv lock --check and ./pre-commit.py --changed-from origin/develop pass, and uv build puts THIRD_PARTY_NOTICES.md in eegprep-0.5.0.dist-info/licenses and at the sdist root. ty check reports only the three unresolved onnx imports in tools/iclabel that appear without the torch extra. pytest tests/test_eeg_mir.py: 18 passed; with tests/test_package_exports.py, tests/test_package_help.py and tests/test_optional_extras.py added, 50 passed. Before the block rewrite, tests/test_console_workspace.py and tests/test_pop_runica_pamica.py without slow tests gave 157 passed and 1 failed, test_gui_pop_action_warning_output_follows_echoed_command for pop_reref, which fails the same way on this macOS host with the eeg_mir export removed; the rewrite touches neither. The EEGLAB reference suite was not run: no EEGLAB-ported function changes. The full suite was not run locally; CI runs it.

Agentic AI tools were used. Workflows follow the Research Skills (doi:10.5281/zenodo.20696515). The author assumes full responsibility for this content and associated changes.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

@claude

claude Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @neuromechanist's task in 1m 2s —— View job


Code review

  • Overall assessment: Looks good. I found no correctness, data-structure or AGENTS.md problems in eeg_mir.
  • Highest-risk area: The two-pass binning in _projected_blocks/eeg_mir. It relies on pass 2 computing the same blocks as pass 1. Both passes take the same slices through the same finite_matmul calls, so the blocks match. Even a 1-ulp drift would still round to a bin inside 0..255, so no sample lands in a neighbouring row's bins.
  • Merge recommendation: Safe to merge.

Blocking

None.

Important

None.

Nits

  • docs/source/changelog.rst: "so MIR no longer drifts with recording length" reads as if an earlier EEGPrep MIR drifted, but this is the function's first release. Suggest "so MIR does not drift with recording length (unlike getMIR.m's sample-dependent bin count)".

Test gaps

None. The tests cover the closed-form uniform/45° case, identity weights, invariance to scaling, reordering and sign flips, icachansind subsetting, the exact getent4 variance, epoched data with a reduced sphere compared against pAMICA, and each refusal path.

EEGLAB parity notes

None. EEGLAB has no MIR function, so there is no .m file to compare against. The PR adds a new function and changes no existing ported processing code, so it does not need a MATLAB reference-suite run under AGENTS.md. The docs say that the sphered-space definition is not comparable with the paper's or NEMAR's values.

What I checked:

  • icachansind handling goes through the existing 0-based _ica_channel_indices.
  • 3-D epoched data are concatenated, including when pnts > 8192, where blocks are cut inside each epoch.
  • Bin indices stay inside 0..255.
  • log|det W| is computed as the sum of log|eig|.
  • The Miller-Madow term uses nbins - 1.
  • Placement follows the popfunc conventions, and the lazy export is in place.
  • license-files sits under [tool.setuptools], which works with the current setuptools>=61 requirement.

I couldn't run tests/test_eeg_mir.py because this job's Bash permissions blocked it. Please rely on CI for the test results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant