Skip to content

Fix loadmodout byte order for W/sbeta/rho (#159) - #163

Merged
neuromechanist merged 5 commits into
mainfrom
fix/issue-159-loadmodout-byte-order
Jul 17, 2026
Merged

neuromechanist merged 5 commits into
mainfrom
fix/issue-159-loadmodout-byte-order

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

loadmodout read the Fortran/EEGLAB interop files W, sbeta and rho in C order while the writer, genuine Fortran output, and EEGLAB's loadmodout15.m all use column-major (F order). The result: AmicaOutput.W came back transposed, silently corrupting genuine Fortran output and everything derived from it (A = pinv(W@S), svar, origord), and sbeta/rho were scrambled whenever num_mix > 1 (the default). A write-then-read round trip cancels the error, so no self-consistency test could catch it, which is why prior gates (#92, #155) missed it.

Closes #159.

What changed

  • Reader (loadmodout): W, sbeta, rho now read order="F", matching the writer, genuine Fortran, and loadmodout15.m. This also corrects the derived A/svar/origord.
  • Writer (write_amicaout): the 3D W is written model-axis-slowest (transpose(2, 0, 1)) so multi-model output is genuine Fortran and EEGLAB-readable. Single-model output is byte-identical to before (verified), preserving Drop-in EEGLAB AMICA replacement: equivalent output, no extra interpretation #92.
  • load_results: reads the same genuine-Fortran bytes and transposes back to the internal-backend convention it returns for the NumPy viz helpers (identical output for single-model; fixes latent multi-model breakage).
  • AmicaOutput.sources(X, model=0): new supported accessor (loaded-fit counterpart of the live model's transform), so downstream source derivation no longer hand-rolls the sphere/unmixing composition, the error class that spawned this issue.
  • compare_with_fortran (uncalled diagnostic): transposes one side so it stays apples-to-apples.

Why it is correct (two external oracles)

  1. LL recomputation: recomputing the bundled fixture's own reported converged LL (-3.4018730) from what loadmodout reads gives -3.4018468 (5 sig figs); the shipped C-order read gave -3.5167 (off by 0.11). LL is not transpose-symmetric, so unlike A@W==I it discriminates orientation.
  2. MATLAB gate: EEGLAB's real loadmodout15.m vs Python loadmodout for W/A/sbeta/rho, on the genuine single-model fixture and a pyAMICA 2-model output, agree to <=1.3e-13 (.context/issue-159/matlab_interop_verification.md). This is the only test that pins direction 2 of the interop contract.

Test plan

  • New regression tests (all sabotage-validated to fail on the buggy read):
    • test_loadmodout_reproduces_fortran_reported_ll (LL oracle, real fixture)
    • test_loadmodout_sources_reproduce_live_transform_multimodel (2-model round trip: sources matches live transform at |corr| > 0.999 per model; was 0/32 before)
    • test_amicaoutput_sources_contract_and_c_subtraction
    • test_load_results_returns_internal_w_multimodel
  • Full non-slow suite: 275 passed, 9 skipped, 1 xfailed, no collection drop.
  • test_sample_data_cli (strict xfail, 2000-iter) still xfails (the W flip did not turn it into an XPASS).
  • ruff, ty, mkdocs build --strict clean.

Follow-up

plot_topo_pdf (deferred out of #136) is now unblocked and can build on AmicaOutput.sources.

@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 76.19048% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.95%. Comparing base (1fc704b) to head (88d209c).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pyAMICA/numpy_impl/load.py 77.77% 2 Missing and 2 partials ⚠️
pyAMICA/torch_impl/utils.py 0.00% 1 Missing ⚠️
❗ 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     #163      +/-   ##
==========================================
+ Coverage   82.68%   82.95%   +0.27%     
==========================================
  Files          19       19              
  Lines        2420     2435      +15     
  Branches      408      412       +4     
==========================================
+ Hits         2001     2020      +19     
+ Misses        306      299       -7     
- Partials      113      116       +3     
Files with missing lines Coverage Δ
pyAMICA/numpy_impl/core.py 85.80% <ø> (+1.27%) ⬆️
pyAMICA/numpy_impl/data.py 67.44% <100.00%> (+0.38%) ⬆️
pyAMICA/torch_impl/utils.py 59.30% <0.00%> (ø)
pyAMICA/numpy_impl/load.py 75.44% <77.77%> (-0.27%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@neuromechanist

Copy link
Copy Markdown
Member Author

PR review (4 Sonnet reviewers: code, tests, comments, silent-failure)

All findings addressed. Highlights:

Critical (found independently by the comment and code reviewers, empirically confirmed): compare_with_fortran's added .T was backwards. The real caller (examples/torch_example.py:79) passes get_unmixing_matrix(0), which is already the true/Fortran convention; since the #159 loader fix makes out.W the same convention, the two compare directly. My .T re-broke it (direct match |corr|=1.000 vs 0.985 with .T). Reverted; comment corrected. Note this function is uncalled in tests, so CI did not catch it.

Test quality (test-analyzer, empirically verified against reconstructed main):

  • test_loadmodout_reproduces_fortran_reported_ll and test_loadmodout_sources_reproduce_live_transform_multimodel confirmed genuine (fail on pre-fix code).
  • test_load_results_returns_internal_w_multimodel was shown to pass identically on main (it guards writer↔reader lockstep, not the original bug). Docstring corrected, and a new direct byte-layout test (test_written_w_bytes_are_genuine_fortran_layout) now pins the writer's genuine-Fortran multi-model layout in CI, independent of any reader.
  • Overstated "0/32" figure in a docstring softened to what's reproducible.
  • Added share_comps multi-model round-trip test and the missing sources() validation branches (negative model, 1-D X).

Silent-failure:

  • Legacy multi-model directories: a format-version stamp is infeasible (genuine Fortran output has no marker and must be read with the new convention, so unmarked can't be refused). Added a changelog migration note instead; pre-fix multi-model W was never in the correct convention regardless.
  • Added writer shape validation (W must be 3-D; model axis must match gm).
  • Stale _write_results docstring (core.py) and the "each array" overreach in write_amicaout corrected.

Out of scope, filed separately: #164 (pre-existing fit() crash on do_approx_sphere=False + pcakeep, the only genuine num_pcs < data_dim path).

MATLAB gate unchanged (writer bytes unchanged): W/A/sbeta/rho agree with loadmodout15.m to ≤1.3e-13 single- and multi-model.

@neuromechanist
neuromechanist merged commit 1bb6ec2 into main Jul 17, 2026
6 checks passed
@neuromechanist
neuromechanist deleted the fix/issue-159-loadmodout-byte-order branch July 17, 2026 16:13
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.

loadmodout reads W, sbeta and rho in the wrong byte order (corrupts genuine Fortran output)

2 participants