Skip to content

Phase 2: PMI core metric and component reordering - #154

Merged
neuromechanist merged 6 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-135-phase2-pmi-metric
Jul 16, 2026
Merged

neuromechanist merged 6 commits into
feature/issue-133-epic-mir-pmi-metricsfrom
feature/issue-135-phase2-pmi-metric

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Adds a clean-room implementation of Pairwise Mutual Information (PMI) between AMICA components, plus a greedy block-diagonal reordering, as pyAMICA.metrics.pairwise_mi(sources, nbins=None) -> np.ndarray and pyAMICA.metrics.block_diagonal_order(mi_matrix) -> np.ndarray.

This is deliberately NOT a port. The historical MATLAB reference (minfojp.m/get_mi.m/arrminf2.m in sccn/postAmicaUtility) is GPL-2.0-or-later, incompatible with a direct port into this BSD-3-Clause project. Per the epic's licensing decision, this implementation was derived solely from the algorithm description in issue #135 (binned marginal/joint entropy with a Miller-Madow bias correction; a greedy block-diagonal reordering) and standard statistics/algorithms -- the GPL source was never fetched or read at any point in this implementation.

pairwise_mi computes each pair's joint 2D histogram and derives both marginals by summing that same histogram (rather than independently rebinning), keeping the entropy terms self-consistent; entropy uses a proper Miller-Madow correction ((m_occupied - 1)/(2N)), distinct from MIR's fixed (nbins-1)/(2N) term. block_diagonal_order is a standard greedy nearest-neighbor chain seriation, matching the issue's own "greedy" framing.

Also includes a small phase-1 follow-up: extracted the shared input-validation logic (non-finite check, constant-channel check, nbins resolution) from mir.py into a new private pyAMICA/metrics/_common.py, reused by both modules -- a pure refactor, the 11 existing MIR tests pass unchanged. Also added the delorme2012independent citation (already in this repo's paper.bib) to mir.py's docstring, which the epic's own background section ties MIR to but the phase 1 docstring omitted.

Closes #135
Part of epic #133

Test plan

  • pyAMICA/tests/test_metrics_pmi.py (new, 8 tests): symmetry, diagonal-matches-self-entropy, the real scientific claim that ICA sources have lower pairwise MI than raw channels (real fitted pyresults/W.npy/sphere.npy vs raw real channels), valid-permutation and adjacent-weight-improvement checks for the reordering, and the same non-finite/constant-channel error-path tests as phase 1.
  • uv run pytest pyAMICA/tests/test_metrics_mir.py pyAMICA/tests/test_metrics_pmi.py -v: 19 passed (11 MIR unchanged + 8 new PMI).
  • uv run pytest pyAMICA/tests/ -q -m "not slow": 205 passed, 9 skipped, 6 deselected, 1 xfailed (pre-existing) -- no regressions.
  • uv run ruff check / uv run ruff format / uv run ty check: all clean.

@neuromechanist

Copy link
Copy Markdown
Member Author

Review summary (4 parallel Sonnet reviewers: code, tests, comments, silent-failures)

code-reviewer: no issues. Confirmed clean-room compliance explicitly (docstring accurately discloses the provenance, code reads as genuinely original NumPy -- not a mechanical MATLAB translation, no GPL content anywhere in the diff), and hand-traced the Miller-Madow correction, joint/marginal histogram consistency, and greedy chain algorithm as correct. Also confirmed the _common.py extraction didn't change mir.py behavior.

silent-failure-hunter (2 critical + 1 high, all confirmed by executing the code):

  • block_diagonal_order had zero input validation. A non-square matrix either silently truncated the caller's data and returned a plausible-looking wrong permutation, or crashed with a raw, unhelpful IndexError. NaN/Inf entries were silently mishandled four different ways (partial NaN quietly treated as "worse than everything" and ignored; all-NaN crashed with a bare KeyError: -1; Inf silently dominated the ordering; asymmetric matrices were accepted with no warning). Fixed: block_diagonal_order now validates square/finite/symmetric via a new _common.validate_mi_matrix, raising ValueError with a clear message.
  • Oversized nbins fabricated large bogus MI values from pure noise -- empirically confirmed: independent-Gaussian data with true MI=0 gave a fabricated 4.25 nats at nbins=1000. Fixed: pairwise_mi now raises ValueError when nbins**2 > n_samples (too many joint-histogram cells for the sample count).

pr-test-analyzer (no critical gaps, but independently found the same block_diagonal_order validation gap, plus): nbins passthrough untested at the public pairwise_mi API, resolve_nbins's ValueError branch untested for pairwise_mi, no n=1/n=2 coverage, greedy tie-breaking untested (and relies on Python set iteration order). Added: an nbins-passthrough test mirroring MIR's, tests for the new validation errors (non-square/non-finite/asymmetric mi_matrix, sparse nbins, invalid nbins), n=1/n=2 tests, and a hand-built tie-breaking test confirming the greedy algorithm still returns a valid permutation under ties.

comment-analyzer (no critical issues): verified the delorme2012independent citation is accurate in both mir.py and pmi.py (matches the real paper's actual PMI/MIR methodology), and the Balkan/Palmer/Miyakoshi acknowledgment is appropriately name-only, no fabricated bibliographic details. Suggested lifting some PR-description rationale into inline comments -- done: _binned_entropy_from_counts and pairwise_mi now have comments explaining the occupied-bin Miller-Madow term (vs mir.py's fixed-nbins term) and the joint-histogram-derived-marginals design choice. Also tightened mir()'s docstring, which imprecisely implied unmixing is validated directly (it's only caught indirectly via the transformed data) -- a pre-existing phase-1 imprecision, fixed while touching this area.

Tests: 28/28 (up from 19), full suite 214 passed / 9 skipped / 6 deselected / 1 xfailed (pre-existing) -- no regressions. ruff/ty clean.

@neuromechanist
neuromechanist merged commit 79f5758 into feature/issue-133-epic-mir-pmi-metrics Jul 16, 2026
6 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-135-phase2-pmi-metric branch July 16, 2026 19:25
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