Repository navigation
Description
Surfaced while building Phase 4's plot_topo_pdf (#136), which needs per-component source activations derived from an AmicaOutput. Splitting it out rather than guessing, per the #155 precedent.
The observation
loadmodout's W does not reproduce the live model's own sources at high fidelity, under either orientation, even in the cleanest possible case.
Setup: real bundled sample EEG (32ch x 8192), AMICATorchNG(n_models=1, n_mix=3, seed=1), 30 iterations. Single model, so out.c is identically zero (verified: ||out.c|| = 0.000000), no gm model reordering, no component sharing. Ground truth is the model's own ng.transform(data). Compared per-component by best |corr|, which is invariant to the per-component scale, sign and permutation that loadmodout legitimately introduces (it normalises to unit-norm A columns and variance-reorders):
| candidate | mean |corr| | min | n > 0.999 |
|---|---|---|---|
out.W[:, :, 0] @ sphered |
0.877 | 0.47 | 0/32 |
out.W[:, :, 0].T @ sphered |
0.932 | 0.81 | 0/32 |
where sphered = out.S[:out.num_pcs] @ (data - out.data_mean[:, None]).
If out.W were simply a normalised, variance-reordered AMICATorchNG.W, one of these should hit |corr| ~ 1.000 for all 32 components, because correlation already quotients out exactly the transformations loadmodout applies. Neither does. 0.88/0.93 is "close but not it" (random would be ~0.1-0.2 in 32 dimensions), so this is not a permutation or scaling artefact.
Reproduced on a 2-model fit too (0.85 / 0.83 for model 0, 0.77 / 0.75 for model 1), with the gm model pairing explicitly checked and identity.
Why this is not obviously a bug
loadmodout is verified bit-exact against EEGLAB's real loadmodout15.m on the genuine Fortran fixture and on pyAMICA-written output, single- and multi-model (.context/issue-155/matlab_interop_verification.md, .context/issue-136/matlab_viz_verification.md). Issue #92 separately verified the mixture-parameter layout through a MATLAB round-trip. So out.W is correct in the EEGLAB sense. The A @ (out.W @ sphered) reconstruction identity also holds to ~1e-15.
So the question is not "is loadmodout broken" but: what exactly is out.W relative to AMICATorchNG.W, and what is the correct way to derive source activations from an AmicaOutput?
Why it matters
Anyone reconstructing sources from a loaded fit (rather than a live model) needs this: PMI/MIR on a saved fit, activation histograms, ERP-style analyses, any downstream EEGLAB interop. There is currently no supported accessor, so callers hand-roll it — and hand-rolling it is demonstrably error-prone (see below).
AMICATorchNG.transform (torch_impl/core.py:1909) does self.W[:, :, m].T @ (X_t - self.c[:, m]), matching the E-step at torch_impl/core.py:828 and the Fortran's b = W(x - c). That formula is correct for the live model. It does not port to AmicaOutput, and it is not currently known what does.
Relevant convention facts
loadmodoutnormalisesAby COLUMNS (A[:, i, h] /= na) butWby ROWS (W[i, :, h] *= na), withmu[:, i, h] *= na,sbeta[:, i, h] /= na(numpy_impl/load.py). It variance-reordersW's rows (W[:, :, h] = W[idx, :, h]) alongsideA/mu/sbeta/alpha/rhocolumns.A = pinv(W @ S)(load.py~332), which ignorescentirely. This makes theA @ (W @ sphered)reconstruction identity circular as evidence aboutc:AandW @ Sare inverse by construction.- Fortran
cis SPHERED-CHANNEL indexed, not component indexed. Established fromamica15.f90:1979:call DGEMV('N',nw,nw,1.0,W(:,:,h),nw,c(:,h),1,0.0,wc(:,h),1)computeswc = W @ c, andwc(i,h)is then consumed component-indexed (b(:,i,h) = -wc(i,h)). SoloadmodoutNOT reorderingcby the per-component variance index is correct. cis identically zero forn_models=1, so this only bites multi-model.
The open sub-question: should c be subtracted?
Unresolved. The fit centres (b = W(x - c)), so mu/sbeta describe the centred variable, which argues for subtracting. But the shift is material, not negligible: measured |wc| / std ~= 0.197 mean, 0.535 max (2-model, 40 iters), with |wc| (5.3) comparable to |mu| (13.6). Yet the fitted mixture mean sum(alpha*mu) ~= 0.01 ~= 0, whereas E[b] = -wc ~= -5.3 would be expected if mu described the centred variable. That inconsistency is itself unexplained and may be the same root cause.
Warning: three natural tests are all degenerate here
Recorded because each one 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 (
alpha=[0.32,0.393,0.287],mu=[-22.79,0.36,24.95]givessum(alpha*mu) ~= 0.01), so withE[sphered]=0the no-c formula matches trivially (0 ~= 0) regardless of correctness. - Best-match correlation vs
transform()— cannot discriminatecat all: Pearson correlation is shift-invariant, so it returns bit-identical numbers with and withoutc(0.849780 both). It only discriminates the transpose. - L1 between the activation histogram and the fitted PDF — too insensitive: it ranked no-c better (0.297 vs 0.326), but a 20%-of-spread shift should produce a far larger gap than 10%, so it is likely dominated by the unconverged fit rather than by the shift. (It was also silently invalid until the
gammalnfix, since the "density" integrated to -8.82.)
A discriminating test needs something the symmetry does not wash out: quantile/CDF comparison against the fitted mixture, a deliberately asymmetric source, or a direct algebraic derivation of out.W from AMICATorchNG.W through write_amicaout -> loadmodout.
Acceptance
- A definitive, derived (not guessed) statement of what
out.Wis relative toAMICATorchNG.W, including how the#24internal transpose interacts with the C-order write andloadmodout's row-normalise + variance-reorder. - A definitive answer on whether
cmust be subtracted when deriving activations from anAmicaOutput, and an explanation of thesum(alpha*mu) ~= 0vsE[b] = -wcdiscrepancy. - Ideally a supported accessor (e.g.
AmicaOutput.sources(X, model=0)) so nobody hand-rolls this again. Related: Phase 5: wire MIR/PMI into the AMICA API #137 (Phase 5) exposesmodel.mir()/model.pmi()for the live-model case; this is the loaded-fit counterpart. - A non-degenerate regression test locking it in.
Blocks plot_topo_pdf (scalp topography + generalized-Gaussian mixture PDF overlay), which was deferred out of #136 for exactly this reason. The other two Phase 4 plots are unaffected: they never touch raw data or sources.
Activity
Defer plot_topo_pdf to #159, ship verified plots
Record topo_pdf deferral in the gate documents
[-]Define how to derive source activations from an AmicaOutput (loadmodout W convention)[/-][+]loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output)[/+]neuromechanist commentedon Jul 17, 2026
RESOLVED as a real bug, with a non-circular oracle
The framing in the issue body ("what IS
out.W?") is now answered:loadmodoutreadsW,sbetaandrhoin the wrong byte order. The writer writes all of themorder="F"; the reader usesorder="F"foralpha/mubut C order forW(load.py:174),sbeta(:278) andrho(:292).The oracle that settles it
Every test I tried first was degenerate (see the issue body). The one that works: recompute the Fortran's own reported converged LL from its own written parameters. Log-likelihood is not transpose-symmetric, so unlike
A @ W == I(which both conventions satisfy, sinceA@W=IimpliesAᵀ@Wᵀ=I), it discriminates. On the genuine bundledsample_data/amicaout, whoseLLfile reports -3.4018730:F/F reproduces the Fortran's own number to 5 significant digits (residual is the Fortran's block truncation). The shipped combination does not.
Independently confirmed for the mixture params by a pairing test (
loaded[:, i] == live[:, origord[i]], which unlike a sorted-multiset comparison can see a permutation):alpha(reader usesorder="F"): True, max diff 0.0rho(reader omits it): False, max diff 0.969Two distinct bugs, different provenance
sbeta/rhoread C-order — new, undocumented, corrupts values. Drop-in EEGLAB AMICA replacement: equivalent output, no extra interpretation #92's MATLAB round-trip caught exactly this class foralpha/mu/c/comp_listand fixed them;sbeta/rhowere missed. Bites whenevernum_mix > 1(default 3).Wread C-order — known and documented in.context/scratch_history.mdas a deliberate out-of-scope quirk, on the stated premise that it "does NOT corrupt values ... and nothing consumes those fields for correctness". That premise no longer holds:A = pinv(W @ S)is derived from the wrong-orientationW, soout.A,out.svarandout.origordare wrong too, and Phase 4: MIR/PMI visualizations #136/Phase 5: wire MIR/PMI into the AMICA API #137 need exactly those fields to derive sources. Note the scratch_history claim conflates a writer fact (C-order bytes are Fortran-identical, and only fornum_models=1) with a reader consequence.write_amicaoutwritesWC-order (load.py:121), which is a valid Fortran dump only fornum_models=1. Not independently reverified here, but consistent with the above and worth checking as part of the fix.Why every gate missed it
Phase 3's MATLAB interop gate verified
Lht/Lt/v/mod_probbit-exactly against the realloadmodout15.m— it never comparedW/sbeta/rho. #92's round-trip covered the mixture params it knew about. And a pyAMICA-write -> pyAMICA-read round trip cancels the W error, so no self-consistency test can see it. It takes an external oracle (the Fortran's own LL, or MATLAB reading our bytes).Not affected
plot_pmi_heatmap,plot_model_probability): they use onlyout.Lht, which is readorder="F"and verified bit-exact vs MATLAB. Confirmed by grep:out.Lhtis the onlyAmicaOutputfieldviz.pytouches.Lht/Ltareorder="F"and MATLAB-verified.pyAMICA.metrics: operates on caller-supplied arrays.Acceptance (supersedes the issue body's)
W,sbeta,rhoreadorder="F"; writer's multi-modelWchecked.loadmodout's output must land within ~1e-4 of its ownLLfile. That is external, non-circular, and would have caught all of this.W/A/sbeta/rhoagainstloadmodout15.m, not justLht/Lt/v.plot_topo_pdf(Phase 4: MIR/PMI visualizations #136) can be built on it, with the histogram responsibility-weighted (the per-model mixture describes thev_h-weighted distribution, so a pooled histogram is misaligned even with a correctWandc).cSHOULD be subtracted when deriving activations (out.W @ (sphered - out.c[:, m])), andcis sphered-channel indexed, soloadmodoutnot variance-reordering it is correct. Both hold only once the loader is fixed.Phase 4: MIR/PMI visualizations (PMI heatmap + model-probability time…
Correct the W-convention claim again, and stop asserting one
Fix two claims the plot_topo_pdf cut invalidated
Fix loadmodout W/sbeta/rho byte order (#159)
Add #159 byte-order regression tests
Document #159 fix and MATLAB gate
Address #159 review: fix compare_with_fortran, add guards
Fix loadmodout byte order for W/sbeta/rho (#159) (#163)
Fix the EEGLAB guide's scalp-map example and multi-model note
Correct the API overview and backend pages
Phase 16: audit the documentation against the epic (#353)