Repository navigation
Epic: MIR and PMI separation-quality metrics - #162
Conversation
* 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 Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
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.
Integration reviewThree reviewers over the cumulative Fortran parity: PASSES on the integrated branchThe check that actually matters for this repo, and it does not run in CI: All three end-to-end Fortran-parity tests pass, including Fixed: three claims the
|
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
mir(mutual information reduction), ported from Apache-2.0getMIR.mpairwise_mi+block_diagonal_order, clean-room from a GPL referenceLLtposterior output parity with Fortran (both backends)plot_pmi_heatmap,plot_model_probabilitymodel.mir(X)/model.pmi(X)+mir_stepwaypointsLicensing
pyAMICA is BSD-3-Clause, and the two references have incompatible licences, so they were handled differently and deliberately:
getMIR.m(Apache-2.0, bigdelys/pre_ICA_cleaning), pinned to a commit SHA, with the full licence vendored inTHIRD_PARTY_NOTICES.mdto satisfy Apache-2.0 section 4(a).minfojp.m/get_mi.m/arrminf2.min postAmicaUtility) is GPL-2.0-or-later; that source was never fetched or read, and a reviewer independently checked for leakage.pop_topohistplot.m/pop_modPMI.mcarry explicit GPL headers, so they were run and observed, never read:helptext, 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:
mir()getMIR.m(Apache-2.0)LLtreader/writerloadmodout15.m, MATLAB R2025bP(model | data)LLt2vv(log10 model odds)loadmodout15.msmooth_amica_probpairwise_miminfojp(GPL, black box)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
do_rejectLLt parity (Phase 3: posterior-probability (LLt) output parity with Fortran #156): both backends wrote real log-likelihoods where Fortran writes exactly0.0. Those zeros are load-bearing, not padding: Fortran'sload_rejreconstructs the rejection mask from them, so a Fortran run reading a pyAMICALLtwould have concluded nothing was rejected.gammalnforgammainnumpy_impl/pdf.py(Phase 4: MIR/PMI visualizations (PMI heatmap + model-probability timeline) #158): pre-existing and shipping. Made the generalized-Gaussian density negative for every rho outside the special-cased 1 and 2 — including the defaultrho0=1.5. It survived because the only tests calledcompute_pdfwith rho=1.0 and 2.0, exactly the two hard-coded-correct branches. The fit path was never affected (it has its own correct log-space implementation), but the shippedplot_pdf_fitswas drawing wrong curves.loadmodoutreshape order (Phase 3: posterior-probability (LLt) output parity with Fortran #156): read theLLtbytes C-order where the layout is column-major.Deliberate divergences, documented not silent
LLtis stale by one M-step relative to theW/Abeside it. We recompute post-update, so ours is self-consistent. That wart is not load-bearing, unlike thedo_rejectzero-sentinel, which we do match.Scope changes
plot_topo_pdfwas cut to loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output) #159. It needs source activations from a loadedAmicaOutput, which turned out to rest on a real loader bug (below). It was also the only plot with no MATLAB oracle, so nothing external could catch a wrong activation space.loadmodoutreadsW/sbeta/rhoin the wrong byte order — corrupts genuine Fortran output; found while chasing Phase 4: MIR/PMI visualizations (PMI heatmap + model-probability timeline) #158, proven by recomputing the Fortran's own reported LL), Test mir_history_ against the keep_best rollback and save/load #161 (two untestedmir_history_claims).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).-m slow) run on the integrated branchruff,ty,mkdocs build --strictcleanmax|diff| = 0.0across four real-data LL trajectories) rather than trusted to a green suite