Skip to content

Epic: MIR and PMI separation-quality metrics - #162

Merged
neuromechanist merged 9 commits into
mainfrom
feature/issue-133-epic-mir-pmi-metrics
Jul 17, 2026
Merged

neuromechanist merged 9 commits into
mainfrom
feature/issue-133-epic-mir-pmi-metrics

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Ports the MIR and PMI separation-quality metrics into pyAMICA, wires them into the model API, and adds two MATLAB-verified visualizations. Five phases, each individually reviewed and merged into this branch.

Closes #133

Phase PR What
1 #153 mir (mutual information reduction), ported from Apache-2.0 getMIR.m
2 #154 pairwise_mi + block_diagonal_order, clean-room from a GPL reference
3 #156 LLt posterior output parity with Fortran (both backends)
4 #158 plot_pmi_heatmap, plot_model_probability
5 #160 model.mir(X) / model.pmi(X) + mir_step waypoints

Licensing

pyAMICA is BSD-3-Clause, and the two references have incompatible licences, so they were handled differently and deliberately:

  • MIR is a permitted direct port of getMIR.m (Apache-2.0, bigdelys/pre_ICA_cleaning), pinned to a commit SHA, with the full licence vendored in THIRD_PARTY_NOTICES.md to satisfy Apache-2.0 section 4(a).
  • PMI is a clean-room reimplementation. Its reference (minfojp.m/get_mi.m/arrminf2.m in postAmicaUtility) is GPL-2.0-or-later; that source was never fetched or read, and a reviewer independently checked for leakage.
  • Phase 4's visualizations are a fresh design. postAmicaUtility's pop_topohistplot.m/pop_modPMI.m carry explicit GPL headers, so they were run and observed, never read: help text, rendered figures and black-box I/O only. That posture is what let us match observable behaviour without deriving from protected expression.

Verification against MATLAB

Every quantity that could be pinned to an external oracle was pinned:

Quantity Oracle Result
mir() getMIR.m (Apache-2.0) 1.7e-15 relative
LLt reader/writer real loadmodout15.m, MATLAB R2025b bit-exact, both directions
P(model | data) LLt2v 1.4e-14
v (log10 model odds) loadmodout15.m bit-exact
Smoothed model probability smooth_amica_prob r = 0.9886
pairwise_mi minfojp (GPL, black box) r = 0.9887

The MIR oracle closed a Phase 1 gap: MIR had only ever been validated against itself, while the Apache-2.0 original was available the whole time.

Bugs found and fixed along the way

Deliberate divergences, documented not silent

  • LLt staleness: Fortran's on-disk LLt is stale by one M-step relative to the W/A beside it. We recompute post-update, so ours is self-consistent. That wart is not load-bearing, unlike the do_reject zero-sentinel, which we do match.
  • Smoothing endpoints: MATLAB pins the first/last sample to the raw unsmoothed value; we return a locally averaged one.
  • MI diagonal: MATLAB zeroes it; ours is self-entropy, so the heatmap masks it rather than fabricating a zero.

Scope changes

Test plan

Real bundled sample EEG and the real Fortran fixture throughout; no synthetic data as the basis of any correctness claim (.rules/testing.md).

  • 270 passed, 9 skipped (MLX/mne absent), 1 pre-existing xfail on the integrated branch
  • Fortran-parity suite (-m slow) run on the integrated branch
  • ruff, ty, mkdocs build --strict clean
  • Phase 3's shared-forward-pass refactor touches the training path, so it was proven bit-identical against the pre-refactor commit (max|diff| = 0.0 across four real-data LL trajectories) rather than trusted to a green suite

* Add MIR mutual-information-reduction metric

* Wire metrics package into pyAMICA exports and packaging

* Add tests for MIR metric against real sample EEG

* Drop unused entropy return in scaled-identity test

* Raise on singular/non-finite MIR input, fix attribution

* Test MIR validation errors and a real fitted unmixing
* Extract shared validation into metrics/_common.py

* Add clean-room PMI pairwise mutual-information metric

* Wire pairwise_mi and block_diagonal_order into metrics package

* Add tests for PMI metric against real sample EEG

* Validate block_diagonal_order input, guard sparse nbins

* Test PMI validation errors and small-n edge cases
* Write LLt posterior output, fix reshape order

Fortran writes a per-timepoint, per-model log-likelihood file (LLt) on
every run; neither pyAMICA backend produced it, and loadmodout read the
bundled Fortran fixture with a C-order reshape where the layout is
column-major (verified against sample_data/amicaout/LLt: single-model
Lht != Lt for 87% of samples under order='C', exact equality under 'F').

Both backends now recompute the full-dataset per-sample log-likelihood
from their current parameters at write time, so the output is correct
after a keep_best rollback. Tested against real sample EEG.

* Zero rejected samples in LLt, share numpy forward pass

_compute_full_posterior_ll now scores only good_idx under do_reject
and scatters into zero-initialized arrays, matching Fortran's zero
sentinel that load_rej relies on for its rejection mask. The numpy
backend's forward pass (b/z/logV) is extracted into a shared
_forward_block used by both _get_block_updates and
_compute_full_posterior_ll, so a future fix cannot silently drift
between two copies. Also drops the dead data= parameter (the only
caller never passed one) and documents the deliberate one-M-step-
fresher divergence from Fortran plus the added per-writestep cost.

* Compute torch LLt once after keep-best, warn if omitted

Drops _X_t (which pinned the full sphered dataset on the model,
GPU included) in favor of computing LLt exactly once at the end of
fit(), strictly after any keep-best restore, storing only the
compact per-sample arrays. write_amica_output reads those stored
arrays directly and logs a warning instead of silently omitting
LLt for a model restored via from_state_dict (no training data to
recompute from). Under do_reject, only good_idx is scored and
scattered into zero-initialized arrays, matching Fortran's zero
sentinel. Documents the same deliberate divergence from Fortran's
one-M-step-stale LLt as the numpy backend.

* Document LLt in AMICA.write_amica_output docstring

* Raise on mismatched Lht/Lt in write_amicaout

Passing exactly one of Lht/Lt silently skipped the whole LLt file;
raise ValueError naming both params instead of a silent no-op.

* Add LLt regression tests: reject, multimodel, reorder

Covers the review findings: do_reject zeroing on both backends,
a numpy multi-model round-trip (only torch had one), a partial
final block on both backends (existing tests were all evenly
divisible by block_size), a from_state_dict model omitting LLt
with a warning, and a real non-identity gm_ord case proving
loadmodout permutes Lht in lockstep with W/mod_prob rather than
leaving it in on-disk order.
The LLt tests in #156 only pin one direction of the interop contract (we
read Fortran's output, via the real bundled fixture). They cannot pin the
other direction: a self-consistently-wrong writer/reader pair passes every
round-trip test. Issue #92 caught a real column-major bug exactly there, and
LLt is a new file that had never been through that gate.

Verified by hand against real loadmodout15.m under MATLAB R2025b: it reads
pyAMICA's LLt bit-exactly (single- and multi-model), and both readers agree
bit-exactly on the genuine Fortran fixture. MATLAB is not on CI, so this is
recorded rather than automated.
…line) (#158)

* Add read_eeglab_set_metadata to load.py

* Add pyAMICA.viz visualization module

* Add tests for pyAMICA.viz

* Add viz docs and changelog entry

* Record Phase 4 MATLAB viz gate

Plots have no byte contract, so the gate is two-level: pin every plotted
quantity to a MATLAB oracle, then compare rendered figures side by side.
All quantities pinned (mir 1.7e-15 vs Apache-2.0 getMIR.m; P(model|data)
1.4e-14 vs LLt2v; v bit-exact; smoothed probability r=0.9886; pairwise_mi
r=0.9887 vs the GPL minfojp as a black box). Visual gate accepted.

postAmicaUtility is GPL and pyAMICA is BSD-3-Clause, so no .m source was
read: help text, rendered output and black-box I/O only. MATLAB cannot run
in CI, so this is recorded rather than automated.

* Fix gammaln-for-gamma in generalized-Gaussian pdf

compute_pdf divided by log(Gamma(1+1/rho)) instead of Gamma(1+1/rho),
making the returned density NEGATIVE for every rho outside the
special-cased 1 and 2. At the default rho0=1.5 it integrated to -8.82.
The Fortran computes this in log space (- gamln(1+1/rho) - log(2),
amica15.f90:1305-1306) where log-gamma is correct; the port transcribed
that gamln into a linear-space expression.

The fit path was never affected: numpy_impl/core.py has its own log-space
_compute_log_pdf mirroring the Fortran and never imports .pdf. The
shipped numpy_impl/viz.py plot_pdf_fits was drawing wrong curves, as
would the new plot_topo_pdf.

It survived because the only tests calling compute_pdf used rho=1.0 and
rho=2.0, exactly the two special-cased branches that are correct. Guarded
now by a property test (density integrates to 1 for rho 1.0-3.0) and a
continuity test (rho=2 vs rho=2+1e-9 must agree across the branch
boundary). Both fail on the old code.

* Skip topo tests when optional mne is absent

CI installs the base env only (bare uv sync), so the 7 tests reaching
plot_topo_pdf's mne import failed there while passing locally where the
viz extra is installed.

Per-test skipif rather than a module-level importorskip on purpose: a
module-level skip would also drop the 28 tests here that need no mne,
leaving a green suite that never exercised the module. Verified by
simulating CI's env: 28 passed, 7 skipped (not 35 skipped).
test_plot_topo_pdf_raises_importerror_without_mne stays unmarked; it
asserts the guard fires precisely when mne is missing.

* Correct wrong W-convention claim in viz gate record

Trap 3 claimed W @ S @ (x-mean) was the wrong way to get sources from an
AmicaOutput and that the transpose was canonical. That is backwards, and
a PR reviewer reasonably escalated it as a critical bug in correct,
shipped code; acting on it would have broken plot_topo_pdf.

AmicaOutput.W (loadmodout) is EEGLAB convention, ROWS are components, so
out.W @ sphere @ (x-mean) is right. AMICATorchNG.W is internal
convention, COLUMNS are components, so its transform needs the transpose.
They are transposes of each other and neither formula ports to the other
object. load.py proves the row convention: it normalises A by columns but
W by rows, alongside mu *= na and sbeta /= na.

Records the bad reasoning too (best-match correlation is a weak
discriminator; the std==column-norm identity proves nothing) so it is not
repeated. Also labels which quantity the smoothing correlations describe,
since an unlabelled 0.994 read as a stale 0.9886, and strengthens the
mask_diagonal divergence note.

* Assert heatmap pixels, not just tick labels

Review demonstrated the gap by deleting the permutation outright: all nine
plot_pmi_heatmap tests still passed, because the tick labels are generated
from "order" independently of the array handed to imshow. A heatmap whose
axes advertise a reordering its pixels do not have would have shipped
silently. Same failure class as issue #136 trap 1, where MATLAB's
mInfoMatrix is stored already-reordered and comparing it raw reads as
r=-0.13, looking exactly like a broken PMI. The new test fails on that
sabotage.

Also validate mi_matrix unconditionally: the non-finite check previously
rode along inside block_diagonal_order, so passing an explicit "order"
skipped it entirely and NaN rendered as a blank cell, indistinguishable
from a genuine near-zero mutual information.

And raise in read_eeglab_set_metadata when chanlocs is empty, which the
existing np.any(np.isnan(...)) guard cannot catch on an empty array.

* Defer plot_topo_pdf to #159, ship verified plots

plot_topo_pdf derives source activations from a loaded AmicaOutput, which
depends on a W convention that turns out to be unsettled: loadmodout's W
does not reproduce the live model's transform() sources at high fidelity
under either orientation, even single-model with c identically zero
(W @ sphered gives mean |corr| 0.877, W.T @ sphered 0.932, 0/32 above
0.999, where a merely normalised and reordered W would give ~1.000 for
all 32 since correlation quotients out scale, sign and permutation).

Three natural tests to settle it were each degenerate: the activation
mean matches trivially because the fitted mixture is near-symmetric and
E[sphered]=0; best-match correlation is shift-invariant so it cannot see
c at all; and the histogram-vs-PDF L1 is too insensitive to a 20%-of-
spread shift. Review escalated this function twice on the strength of a
wrong claim in our own verification doc, which is itself a signal.

This is the one plot with no MATLAB oracle (pop_topohistplot is broken
upstream), so nothing external can catch a wrong activation space. Rather
than ship a scalp map that renders plausibly but cannot be verified,
defer it to #159 and ship the two plots that are fully pinned to MATLAB
(smoothed model probability r=0.9886 vs smooth_amica_prob; pairwise_mi
r=0.9887 vs minfojp) and touch neither raw data nor sources.

read_eeglab_set_metadata stays: plot_model_probability needs srate, which
pyAMICA has no other notion of.

* Record topo_pdf deferral in the gate documents

The verification record and scratch_history now state the Phase 4 outcome
(two plots shipped and MATLAB-pinned, plot_topo_pdf cut to #159) and warn
that three natural tests for the W/c convention are each degenerate:
the activation-mean test matches trivially because the fitted mixture is
near-symmetric and E[sphered]=0; best-match correlation is shift-invariant
so it cannot see c; and histogram-vs-PDF L1 is too insensitive to a
20%-of-spread shift. Each of those produced a confident wrong or useless
answer during triage.
The trap-3 entry in the Phase 4 gate record has now been wrong twice, in
opposite directions. v1 said W @ S @ (x-mean) was wrong and the transpose
canonical. v2 "corrected" it to say AmicaOutput.W is row-convention so
out.W @ sphered is right. Both were asserted from reasoning and
self-consistency checks, and a reviewer escalated v1 as a critical bug in
correct code.

The truth, from an external oracle: loadmodout reads W, sbeta and rho in
the wrong byte order (#159), so no formula on the shipped loader is
correct. Recomputing the bundled Fortran fixture's own reported LL from
its own written params, F-order W plus F-order mixture reproduces its
-3.4018730 to five significant digits while the shipped C-order read is
off by 0.10-0.15. Log-likelihood is not transpose-symmetric, which is why
it discriminates where A @ W == I cannot (both conventions satisfy it).

The entry now asserts no formula, points at #159, and records the five
tests that misled: the circular reconstruction identity (a random W passes
it), shift-invariant correlation, the degenerate mean test, the pooled L1,
and A @ W == I.

Also marks the #92 note's "nothing consumes those fields for correctness"
premise as expired, and records that #92 missed sbeta/rho in the reader.
* Add mir/pmi accessors and mir_step waypoints to AMICATorchNG

* Delegate mir/pmi and mir_step through AMICA wrapper

* Test mir/pmi wiring and mir_step waypoints

* Document mir/pmi API wiring in changelog (#137)

* Stop a failed MIR waypoint from killing the fit

The waypoint called self.mir(X) unprotected, so a raising waypoint
propagated straight out of fit() and destroyed the whole decomposition.
Verified by forcing the raise: the ValueError escaped fit() and the run
was lost.

This was reachable, not theoretical. metrics.mir raises on a
near-singular unmixing, and a near-singular W mid-fit is a transient the
natural gradient can pass through -- the training path only warns about
the same condition. So enabling a purely diagnostic flag could throw away
hours of training over something the optimiser was about to recover from.

Now caught at the waypoint: warn naming the iteration and cause, and
record (iter, nan, nan) so the gap stays visible in mir_history_ rather
than silently absent. A plotted trajectory shows a hole exactly where the
transient was. The fit itself is unaffected.

The new test fails on the unprotected version.

* Test model_idx and nbins passthrough, pin pca guard

Three review findings, each proven by sabotage rather than argued.

model_idx and nbins were never exercised: hardcoding either inside mir()
and pmi() left all nine tests passing, because the shared fixture is
single-model and every wiring test defaulted to model 0 and nbins=None on
both sides of the comparison. The new tests use a genuine 2-model fit and
a non-default nbins, and both fail on that sabotage.

The pca up-front test matched on "pcakeep", which is generic: mir()'s own
downstream guard says it too, so the test could not distinguish "rejected
before iteration 0" from "rejected during iteration 0" -- the entire claim
it exists to make. Now matches "Rejected up front", which is unique to
fit()'s guard.

Note the waypoint fix in the previous commit incidentally hardened this:
with the ValueError now caught at the waypoint, deleting the up-front
guard produces no error at all rather than a look-alike message. The
tighter match keeps the test honest independently of that.
@codecov-commenter

codecov-commenter commented Jul 17, 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 98.15951% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.01%. Comparing base (1cf287a) to head (b5323da).

Files with missing lines Patch % Lines
pyAMICA/numpy_impl/load.py 81.81% 2 Missing and 2 partials ⚠️
pyAMICA/torch_impl/core.py 96.22% 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             @@
##             main     #162      +/-   ##
==========================================
+ Coverage   80.11%   83.01%   +2.90%     
==========================================
  Files          14       19       +5     
  Lines        2102     2420     +318     
  Branches      357      408      +51     
==========================================
+ Hits         1684     2009     +325     
+ Misses        303      297       -6     
+ Partials      115      114       -1     
Files with missing lines Coverage Δ
pyAMICA/__init__.py 100.00% <100.00%> (ø)
pyAMICA/amica.py 92.68% <100.00%> (+0.71%) ⬆️
pyAMICA/metrics/__init__.py 100.00% <100.00%> (ø)
pyAMICA/metrics/_common.py 100.00% <100.00%> (ø)
pyAMICA/metrics/mir.py 100.00% <100.00%> (ø)
pyAMICA/metrics/pmi.py 100.00% <100.00%> (ø)
pyAMICA/numpy_impl/core.py 85.80% <100.00%> (+1.63%) ⬆️
pyAMICA/numpy_impl/pdf.py 33.33% <ø> (ø)
pyAMICA/viz.py 100.00% <100.00%> (ø)
pyAMICA/torch_impl/core.py 92.63% <96.22%> (+0.53%) ⬆️
... and 1 more
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Both are integration defects: correct when written, invalidated by a later
phase, and invisible to any per-phase review because each phase was only
ever reviewed against its own base.

viz.py's module docstring still announced "three plots" and described the
topography/PDF view, but the module defines two functions. The commit that
cut plot_topo_pdf missed the module docstring, so a confidently wrong claim
survived the exact commit that invalidated it. That is the failure mode
this epic was burned by twice already.

read_eeglab_set_metadata refused any file with an unlocalized channel,
because its only consumer was the scalp-topography plot that genuinely
could not use one. That plot is gone (#159), so the sole remaining
consumer wants srate and nothing else, and the guard blocked the sample
rate over a field nobody reads. EOG channels are commonly unlocalized, so
this would have hit real datasets. Unlocalized channels are now NaN, which
is visible rather than silently plausible, and the docstring tells callers
that use positions to check. The new test blanks one channel in a copy of
the real bundled .set, matching the repo's existing precedent for
degenerate edge cases, and fails if the old raising behaviour returns.
Three integration gaps, all invisible to a per-phase review because each
phase PR was only ever read against its own base.

The changelog covered phases 4 and 5 only. Phases 1, 2 and 3 added no
entry at all, so a user reading it would never learn that MIR, PMI, or the
LLt output shipped -- including a new on-disk file with a MATLAB-verified
EEGLAB round trip. Nobody saw the pattern because nobody had read the five
phases together.

docs/guides/eeglab.md's file table, the page a user integrating with
EEGLAB actually reads, still listed the pre-LLt set of files even though
write_amica_output now writes LLt after every fresh fit.

pyAMICA.metrics had no API page, violating .rules/documentation.md's own
one-page-per-module convention, while docs/api/viz.md already linked to
pyAMICA.metrics.pairwise_mi with nothing to resolve to. It is the
computational core phases 1 and 2 shipped.
@neuromechanist

Copy link
Copy Markdown
Member Author

Integration review

Three reviewers over the cumulative main...HEAD diff, each in its own isolated worktree, briefed to hunt for what the integration broke rather than to re-review the phases. That framing paid off: every finding below is invisible to a per-phase review, because each phase PR was only ever read against its own base.

Fortran parity: PASSES on the integrated branch

The check that actually matters for this repo, and it does not run in CI:

uv run pytest pyAMICA/tests/ -m "slow"
4 passed, 1 skipped, 2 xfailed in 1887.39s (0:31:27)
pyAMICA/tests/torch_tests/test_ng_backend.py ...  [100%]

All three end-to-end Fortran-parity tests pass, including test_full_fit_parity_numpy_vs_ng. This matters most because Phase 3 refactored the training path (extracting a shared _forward_block). Both xfails are pre-existing: git diff main...HEAD -- pyAMICA/tests/test_sample_data.py shows this epic made no xfail changes.

Fixed: three claims the plot_topo_pdf cut invalidated (0586ae0)

  1. viz.py's module docstring still announced "three plots" and described the topography view, while the module defines two. The commit that cut the plot missed the docstring, so a confidently wrong claim survived the exact commit that invalidated it. That is the third time this epic has been bitten by that pattern.
  2. read_eeglab_set_metadata refused any file with an unlocalized channel. That guard was correct when its only consumer was the scalp-topography plot, which genuinely could not use one. That plot is gone, so the guard blocked the sample rate (its one remaining purpose) over a field nothing reads. EOG channels are commonly unlocalized, so this would have hit real datasets. Now NaN with a documented contract, guarded by a test that blanks one channel in a copy of the real bundled .set and fails if the old behaviour returns.

Fixed: the changelog was missing three of five phases (b5323da)

Verified commit-by-commit: Phases 1, 2 and 3 added no changelog entry at all. Only Phases 4 and 5 did. A user reading it would never learn that MIR, PMI, or the LLt output shipped, the last of which is a new on-disk file with a MATLAB-verified EEGLAB round trip. Nobody noticed because nobody had read the five phases together. Also:

  • docs/guides/eeglab.md's output-file table, the page someone integrating with EEGLAB actually reads, still listed the pre-LLt file set.
  • pyAMICA.metrics had no API page, violating .rules/documentation.md's own one-page-per-module convention, while docs/api/viz.md already linked to pyAMICA.metrics.pairwise_mi with nothing to resolve to. It is the computational core Phases 1-2 shipped.

Verified clean

  • Collection is complete: 271 passed / 9 skipped / 1 pre-existing xfail, with per-file counts confirmed. This epic was bitten twice by tests silently not running (a stale base hiding 28 metrics tests; an optional dependency), so this was checked explicitly rather than assumed.
  • Zero deletions in any test file across the whole epic (--numstat): no assertion was weakened by a later phase.
  • The plot_topo_pdf cut is otherwise complete: no dangling imports, exports, nav entries, orphaned tests, or dead helpers.
  • The three previously-fixed structural-gap tests are still fixed in the integrated tree.
  • No code in this epic depends on loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output) #159's broken loader path: plot_pmi_heatmap takes a raw matrix, plot_model_probability touches only out.Lht, and mir()/pmi() read the live in-process model.
  • __all__ matches actual exports; pyproject.toml picked up pyAMICA.metrics (avoiding the Epic: Clean module naming and structure (drop amica_/pyAMICA/_torch/_v2 sprawl) #34 wheel-drop bug); mkdocs build --strict clean.

@neuromechanist
neuromechanist merged commit 1fc704b into main Jul 17, 2026
6 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-133-epic-mir-pmi-metrics branch July 17, 2026 07: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.

Epic: port MIR and PMI separation-quality metrics from postAmicaUtility/pre_ICA_cleaning

2 participants