Skip to content

Phase 1: MIR core metric (mutual information reduction) - #153

Merged
neuromechanist merged 6 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-134-phase1-mir-metric
Jul 16, 2026
Merged

neuromechanist merged 6 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-134-phase1-mir-metric

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Ports the MIR (Mutual Information Reduction) separation-quality metric from getMIR.m in bigdelys/pre_ICA_cleaning (Apache-2.0, permits a direct port with attribution). Adds pyAMICA.metrics.mir(unmixing, data, nbins=None) -> (mir_nats, variance) as a standalone, backend-agnostic function.

The _marginal_entropies helper (a port of getMIR.m's nested getent4) uses np.unique(binned, return_counts=True) rather than np.histogram, since the MATLAB source's run-length-of-sorted-values method only ever reports occupied bins, which is what keeps log(p) finite.

This does not port the 2023 NEMAR-pipeline mir(data, linT) adaptation directly, since that version has a real scope bug (its body references eig(W) and /N, neither of which are its own parameters, and only resolves via MATLAB's nested-function shared workspace) and depends on a GPL-licensed sphering routine out of scope for this BSD-3-Clause project. Instead, mir() takes an explicit unmixing matrix; composing pyAMICA's own sphere-then-unmixing pipeline into that matrix is deferred to the API-wiring phase (#137).

Not included in this phase: wiring mir() into the AMICA/AMICATorchNG classes (model.mir(X)) -- that's phase 4, issue #137.

Closes #134
Part of epic #133

Test plan

  • pyAMICA/tests/test_metrics_mir.py (new): 5 tests against the real bundled sample EEG data (no synthetic/mock data), including an exact closed-form check (scaled-identity unmixing gives MIR ~= 0 and a provably-exact variance) and an independent np.histogram-based re-derivation of the entropy estimator.
  • uv run pytest pyAMICA/tests/test_metrics_mir.py -v: 5 passed.
  • uv run pytest pyAMICA/tests/ -q -m "not slow": 191 passed, 9 skipped, 6 deselected, 1 xfailed (pre-existing) -- no regressions.
  • uv run ruff check / uv run ruff format / uv run ty check: all clean.

@codecov-commenter

codecov-commenter commented Jul 16, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 95.12195% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.40%. Comparing base (1cf287a) to head (afe3469).

Files with missing lines Patch % Lines
pyAMICA/metrics/mir.py 94.73% 1 Missing and 1 partial ⚠️
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files

Impacted file tree graph

@@                            Coverage Diff                             @@
##           feature/issue-133-epic-mir-pmi-metrics     #153      +/-   ##
==========================================================================
+ Coverage                                   80.11%   80.40%   +0.28%     
==========================================================================
  Files                                          14       16       +2     
  Lines                                        2102     2143      +41     
  Branches                                      357      363       +6     
==========================================================================
+ Hits                                         1684     1723      +39     
- Misses                                        303      304       +1     
- Partials                                      115      116       +1     
Files with missing lines Coverage Δ
pyAMICA/__init__.py 100.00% <100.00%> (ø)
pyAMICA/metrics/__init__.py 100.00% <100.00%> (ø)
pyAMICA/metrics/mir.py 94.73% <94.73%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@neuromechanist

Copy link
Copy Markdown
Member Author

Review summary (4 parallel Sonnet reviewers: code, tests, comments, silent-failures)

code-reviewer: no issues; confirmed algorithmic parity against the actual upstream getMIR.m/getent4 line-by-line, including the subtle variance-before-correction statement order.

silent-failure-hunter (3 critical, empirically verified by executing the code):

  • Singular/near-singular unmixing silently returned a wrong-but-finite MIR value (floating-point noise means eigvals rarely hits exact zero, so log|eigenvalue| stayed finite). Fixed: mir() now checks the smallest |eigenvalue| and raises ValueError below a 1e-10 threshold, matching this repo's existing logdet-singularity guard pattern in numpy_impl/core.py.
  • Constant channel silently produced nan in the aggregate output (defeats any downstream mir_val < threshold QC gate). Fixed: _marginal_entropies now raises ValueError naming the offending channel.
  • NaN/Inf in data silently propagated to nan with zero warnings. Fixed: _marginal_entropies now validates finiteness up front.
  • (Medium) nbins auto-formula could hit 0 for tiny sample counts; now validated and raises.

pr-test-analyzer (1 critical + several important):

  • No test exercised a real, non-trivial unmixing matrix (identity/scaled-identity can only ever give MIR ~= 0). Added test_mir_real_fitted_unmixing_is_large_and_positive, using the bundled real fitted pyresults/W.npy/sphere.npy -- confirms MIR ~= 3.8 for the real fit vs exactly 0 for identity.
  • Added: variance cross-check in the histogram-rederivation test, an nbins-passthrough test at the public mir() level, and tests locking in the four new error paths above (plus non-square unmixing, which already failed loudly via LinAlgError and now has a test confirming that contract).
  • Tightened the identity-unmixing tolerance to match the scaled-identity test (both are the same closed form) and added the missing variance assertion there.

comment-analyzer (1 critical + several precision fixes):

  • Apache-2.0 attribution named the license but didn't satisfy Section 4(a) (must give recipients a copy of the license itself). Added THIRD_PARTY_NOTICES.md vendoring the full Apache-2.0 text, and pinned the getMIR.m link to the exact commit it was ported from.
  • Softened the overgeneral docstring claim ("an orthogonal transform gives MIR near zero" -> qualified to identity/scalar multiples only, since a generic rotation of dependent non-Gaussian data need not).
  • Fixed two wording-precision issues: the dead NEMAR mir() code now correctly says it would raise an undefined-variable error if uncommented (not just "resolves via shared workspace"), and the GPL attribution now points at the actual GPL-licensed helper functions it calls (block_geometric_median, hlp_memfree) rather than robust_sphering_matrix itself.

Tests: 11/11 new (up from 5), full suite 197 passed / 9 skipped / 6 deselected / 1 xfailed (pre-existing) -- no regressions. ruff/ty clean.

@neuromechanist
neuromechanist merged commit e2ff460 into feature/issue-133-epic-mir-pmi-metrics Jul 16, 2026
6 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-134-phase1-mir-metric branch July 16, 2026 18:25
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.

2 participants