Skip to content

Phase 4: MIR/PMI visualizations (PMI heatmap + model-probability timeline) - #158

Merged
neuromechanist merged 11 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-136-phase4-visualizations
Jul 17, 2026
Merged

neuromechanist merged 11 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-136-phase4-visualizations

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Adds pyAMICA/viz.py: plot_pmi_heatmap, plot_model_probability, plot_topo_pdf. New top-level, backend-agnostic module consuming AmicaOutput from loadmodout (the path already verified bit-exact against loadmodout15.m in #155), so it works for any backend's output directory. Functions return a Figure and accept an optional ax/axes, unlike the legacy numpy_impl/viz.py which returns None and 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.m and pop_modPMI.m carry explicit GPL-2.0-or-later headers (Copyright Ozgur Baklan, SCCN, INC, UCSD); modprobplot.m, minfojp.m, LLt2v.m, smooth_amica_prob.m sit in the same GPL plugin. pyAMICA is BSD-3-Clause, which is why Phase 2's PMI was clean-room.

No postAmicaUtility .m source was read at any point. The behavioural spec came only from MATLAB help text (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.m is 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

Quantity Oracle Result
mir() getMIR.m (Apache-2.0) 1.7e-15 relative
P(model | data) LLt2v 1.4e-14 vs our softmax(Lht)
v (log10 model odds) loadmodout15.m:284 bit-exact
Hanning-smoothed probability smooth_amica_prob r = 0.988577 (1 s), 0.959376 (5 s)
pairwise_mi minfojp (GPL, black box) r = 0.9887 off-diagonal, identical signals

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.png and cmp_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 own EEG.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. Since Lht ~= -108 is 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)

  • Smoothing endpoints: MATLAB pins the first/last sample to the raw unsmoothed value (a smooth() idiom). We return a locally averaged value. Ours is arguably more correct, and matching exactly would require reading GPL source.
  • MI diagonal: MATLAB zeroes it; ours is self-entropy (~2.83 vs off-diagonal ~0.06), so mask_diagonal=True by default. Unmasked it destroys the colour scale.
  • Negative MI: MATLAB's bias correction goes slightly negative; ours is strictly positive. Expected estimator difference.

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, the ValueError and ImportError paths), not pixels and not merely "did not crash".

  • pytest pyAMICA/tests/test_viz.py -> 35 passed
  • Full suite -> 260 passed, 9 skipped (MLX absent), 1 pre-existing xfail. Up exactly 35 from the 225 baseline, no regressions.
  • ruff check, ruff format --check, ty check all clean
  • mkdocs build --strict passes with the new docs/api/viz.md

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.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review summary

Four 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 plot_topo_pdf's out.W[:, :, model] @ sphered as wrong, citing trap 3 of .context/issue-136/matlab_viz_verification.md, which claimed the "canonical" formula was W[:, :, m].T @ (sphere @ (X-mean) - c[:, m]). That trap entry was wrong, I wrote it, and the reviewer escalated it in good faith. Acting on it would have broken working code.

The rule, now corrected in the doc:

  • AmicaOutput.W (from loadmodout) is the EEGLAB convention: ROWS are components, so out.W @ sphere @ (X - mean) is correct.
  • AMICATorchNG.W (the live model) is the internal convention: COLUMNS are components, so its transform needs the transpose.

They are transposes of each other; neither formula ports to the other object. load.py proves the row convention: it normalises A by columns but W by rows (W[i, :] *= na), alongside mu *= na and sbeta /= na — mutually consistent only under the row reading, and exactly what plot_topo_pdf needs since it draws A's column beside that component's activation and its mu/sbeta mixture.

The bad reasoning is recorded too, because it was seductive: best-match correlation against transform() ranked the wrong formula higher (0.988 vs 0.982 — both high, because loadmodout normalises and reorders), and the std(s_i) = ||W[:, i]|| identity is true but proves nothing about intent. What settles it is consistency with A: A @ (W @ sphered) reconstructs the centred data to 0.000000 relative error, the transpose form to 0.894.

The real bug (c502b44) — pre-existing, shipped

numpy_impl/pdf.py: compute_pdf used special.gammaln where the generalized Gaussian needs special.gamma:

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.py has its own log-space _compute_log_pdf mirroring the Fortran and never imports .pdf. Parity is untouched.
  • The pre-existing numpy_impl/viz.py: plot_pdf_fits has been drawing wrong curves; this fixes it too.
  • It survived because the only tests calling compute_pdf used 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.994 read as a stale copy of the doc's 0.9886 — they are different quantities (smoothed log-likelihood vs the resulting probabilities), both correct, and the ambiguity misled a reviewer.
  • The mask_diagonal divergence 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.
@neuromechanist

Copy link
Copy Markdown
Member Author

Scope change: plot_topo_pdf cut, deferred to #159

Two plots ship (plot_pmi_heatmap, plot_model_probability), both fully pinned to MATLAB with the visual gate accepted. plot_topo_pdf is removed and tracked in #159.

Why

It derives source activations from a loaded AmicaOutput, and that rests 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 for a single-model fit where c is identically zero (verified ||out.c|| = 0.000000):

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:

  1. Activation mean vs fitted mixture mean — degenerate. The fitted mixture is near-symmetric (sum(alpha*mu) ~= 0.01), so with E[sphered]=0 the no-c formula matches trivially (0 ~= 0) regardless of correctness.
  2. Best-match correlation vs transform() — cannot see c at all: Pearson correlation is shift-invariant, returning bit-identical numbers with and without it (0.849780 both).
  3. Histogram-vs-PDF L1 — too insensitive: it ranked no-c better (0.297 vs 0.326), but omitting c shifts each component by ~20% of its spread (|wc|/std mean 0.197, max 0.535), which should produce a far larger gap. Likely dominated by the unconverged fit. It was also silently invalid until the gammaln fix.

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.

@neuromechanist neuromechanist changed the title Phase 4: MIR/PMI visualizations Phase 4: MIR/PMI visualizations (PMI heatmap + model-probability timeline) Jul 17, 2026
@neuromechanist
neuromechanist merged commit c77de91 into feature/issue-133-epic-mir-pmi-metrics Jul 17, 2026
6 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-136-phase4-visualizations branch July 17, 2026 03:19
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