Repository navigation
Phase 4: MIR/PMI visualizations (PMI heatmap + model-probability timeline) - #158
Conversation
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.
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.
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.
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.
Review summaryFour parallel reviewers plus a maintainer pass. The headline: the escalated "critical bug" was a false positive caused by a wrong entry in my own verification doc, but chasing it uncovered a real, pre-existing, shipped bug elsewhere. The false positive (and the doc that caused it)A reviewer flagged The rule, now corrected in the doc:
They are transposes of each other; neither formula ports to the other object. The bad reasoning is recorded too, because it was seductive: best-match correlation against The real bug (
|
| rho | before | after |
|---|---|---|
| 1.0, 2.0 (special-cased) | 1.000000 | 1.000000 |
1.5 (the default rho0) |
-8.82 | 1.000000 |
A density integrating to a negative number. Origin: 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 straight into a linear-space expression.
- The fit path was never affected.
numpy_impl/core.pyhas its own log-space_compute_log_pdfmirroring the Fortran and never imports.pdf. Parity is untouched. - The pre-existing
numpy_impl/viz.py: plot_pdf_fitshas been drawing wrong curves; this fixes it too. - It survived because the only tests calling
compute_pdfused rho=1.0 and rho=2.0 — precisely the two special-cased branches that are correct. The default 1.5 was never tested.
Now guarded by a property test (density integrates to 1 across rho 1.0–3.0, which no restatement of the formula could fake) and a continuity test (rho=2 vs rho=2+1e-9 must agree across the exact-equality branch boundary). Both fail on the old code; the pre-existing rho=1/rho=2 test passes on both, confirming it was structurally incapable of catching this.
CI fix (aa3017d)
7 topo tests failed in CI because mne is the optional viz extra and CI runs bare uv sync. Fixed with a per-test skipif, not a module-level importorskip: the latter would also drop the 28 tests needing no mne, leaving a green suite that never exercised the module. Verified by simulating CI's environment: 28 passed, 7 skipped (not 35 skipped).
Also addressed (3ab2544)
- The smoothing-correlation comment now names which quantity it describes. An unlabelled
0.994read as a stale copy of the doc's0.9886— they are different quantities (smoothed log-likelihood vs the resulting probabilities), both correct, and the ambiguity misled a reviewer. - The
mask_diagonaldivergence note now carries the same "do not align this with MATLAB" imperative its smoothing counterpart has. - Trap citation corrected (4 -> 5).
Verified fine
plot_model_probability raises a clear ValueError when out.Lht is None — tested against a real LLt-stripped output directory (the #155 restored-model case), not by reading code.
Suite: 262 passed, 9 skipped, 1 pre-existing xfail.
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.
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.
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.
Scope change:
|
| candidate | mean |corr| | n > 0.999 |
|---|---|---|
out.W @ sphered |
0.877 | 0/32 |
out.W.T @ sphered |
0.932 | 0/32 |
A merely normalised, variance-reordered W would give ~1.000 for all 32, because correlation already quotients out exactly the scale/sign/permutation loadmodout introduces. Neither does. loadmodout is separately bit-exact against EEGLAB's real loadmodout15.m, so this is not a simple bug; it is an unanswered question about what out.W is.
plot_topo_pdf is also the only plot with no MATLAB oracle (pop_topohistplot is broken upstream: Unrecognized function or variable 'showhist'), so nothing external could catch a wrong activation space. Shipping a scalp map that renders plausibly but cannot be verified is exactly the failure mode this epic keeps hitting, in a repo whose stated bar is numerical parity. Cut rather than documented-and-shipped.
The two plots that ship touch neither raw data nor sources, so they are unaffected.
Three tests that look decisive and are not
Recorded in #159 and the gate doc, because each produced a confident wrong or useless answer during triage and the next person will reach for them:
- Activation mean vs fitted mixture mean — degenerate. The fitted mixture is near-symmetric (
sum(alpha*mu) ~= 0.01), so withE[sphered]=0the no-c formula matches trivially (0 ~= 0) regardless of correctness. - Best-match correlation vs
transform()— cannot seecat all: Pearson correlation is shift-invariant, returning bit-identical numbers with and without it (0.849780 both). - Histogram-vs-PDF L1 — too insensitive: it ranked no-c better (0.297 vs 0.326), but omitting
cshifts each component by ~20% of its spread (|wc|/stdmean 0.197, max 0.535), which should produce a far larger gap. Likely dominated by the unconverged fit. It was also silently invalid until thegammalnfix.
Review escalated this function twice as a critical bug, both times on the strength of a wrong claim in our own verification doc (now corrected). I disproved the specific claim, but could not positively verify the function, and did not want to merge on "I couldn't prove it wrong."
The detour paid for itself
Chasing this is what surfaced the gammaln-for-gamma bug in numpy_impl/pdf.py (c502b44) — pre-existing, shipped, making the generalized-Gaussian density negative for every rho outside the special-cased 1 and 2, including the default rho0=1.5. That fix stays in this PR and repairs numpy_impl/viz.py: plot_pdf_fits too.
Suite: 258 passed, 9 skipped, 1 pre-existing xfail.
c77de91
into
feature/issue-133-epic-mir-pmi-metrics
Summary
Adds
pyAMICA/viz.py:plot_pmi_heatmap,plot_model_probability,plot_topo_pdf. New top-level, backend-agnostic module consumingAmicaOutputfromloadmodout(the path already verified bit-exact againstloadmodout15.min #155), so it works for any backend's output directory. Functions return aFigureand accept an optionalax/axes, unlike the legacynumpy_impl/viz.pywhich returnsNoneand mutates pyplot global state; that module is left untouched.Closes #136
Part of epic #133
Licensing: why this was built the way it was
pop_topohistplot.mandpop_modPMI.mcarry explicit GPL-2.0-or-later headers (Copyright Ozgur Baklan, SCCN, INC, UCSD);modprobplot.m,minfojp.m,LLt2v.m,smooth_amica_prob.msit in the same GPL plugin. pyAMICA is BSD-3-Clause, which is why Phase 2's PMI was clean-room.No postAmicaUtility
.msource was read at any point. The behavioural spec came only from MATLABhelptext (public API docs), rendered figures, and black-box input/output. Running the reference is what let us match observable behaviour without deriving from protected expression, so the MATLAB gate is not merely a check here, it is the mechanism that keeps the reimplementation clean.pre_ICA_cleaning/getMIR.mis Apache-2.0 and was legitimately read (Phase 1 ported it with attribution).MATLAB gate
Plots have no byte-level contract, so the gate is two-level: pin every plotted quantity to a MATLAB oracle, then compare rendered figures. Full record, traps and reproduction steps:
.context/issue-136/matlab_viz_verification.md.Data gate: every plotted quantity is pinned
mir()getMIR.m(Apache-2.0)LLt2vsoftmax(Lht)v(log10 model odds)loadmodout15.m:284smooth_amica_probpairwise_miminfojp(GPL, black box)The last two are correlations by design. Our PMI is a clean-room, genuinely different estimator, so equality would be suspicious; and near a model switch the probability is near-binary, so
max|diff|~ 1.0 is expected while mean abs diff is 0.014. These must not be tuned toward MATLAB — that would convert a clean-room reimplementation into a derivation.This also closed a Phase 1 gap: MIR had only ever been validated against itself. The Apache-2.0 original was always available and is now run.
Visual gate: accepted
.context/issue-136/cmp_modprob.pngandcmp_pmi.png(committed). The timeline reproduces MATLAB's two panels, switching times, LL trace and seconds axis. The heatmap is rendered on identical signals (MATLAB's ownEEG.icaact) so the comparison isolates estimator and ordering; both show the same dependent-subspace cluster and radiating cross pattern at the same MI scale. Accepted deliberate differences: viridis vs jet, we add a colorbar, 0-based labels, and a different (clean-room) ordering algorithm.Bug caught by the gate before it shipped
The obvious Hanning smooth,
np.convolve(row, w/w.sum(), mode="same"), zero-pads beyond the data. SinceLht ~= -108is nowhere near 0, that padding drags the first and last half-window toward zero: input[0] = -123.4701 became -60.39. After the softmax that produces confidently wrong model probabilities at both ends of every plot: plausible-looking and completely wrong, the worst failure mode. Fixed by dividing by the window overlap (a shrinking normalised window at the boundaries). Guarded by a test asserting the edges are not dragged toward zero.Deliberate divergences (documented in-code so nobody "fixes" them)
smooth()idiom). We return a locally averaged value. Ours is arguably more correct, and matching exactly would require reading GPL source.mask_diagonal=Trueby default. Unmasked it destroys the colour scale.Test plan
Real bundled sample EEG and a real short 2-model fit throughout; no synthetic data (
.rules/testing.md).matplotlib.use("Agg"). Tests assert on structure (axes count, labels, line count == n_models, probabilities summing to 1, tick labels equalling reordered component indices, masked diagonal, edge-not-dragged-to-zero, theValueErrorandImportErrorpaths), not pixels and not merely "did not crash".pytest pyAMICA/tests/test_viz.py-> 35 passedruff check,ruff format --check,ty checkall cleanmkdocs build --strictpasses with the newdocs/api/viz.md