Skip to content

Implement NumPy do_reject outlier rejection via good_idx (#123) - #126

Merged
neuromechanist merged 3 commits into
mainfrom
123-numpy_impl-do_reject-outlier-rejection-is-non-functional-data_mask-never-initializedconsumed
Jul 14, 2026
Merged

neuromechanist merged 3 commits into
mainfrom
123-numpy_impl-do_reject-outlier-rejection-is-non-functional-data_mask-never-initializedconsumed

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

Closes #123. Implements outlier rejection (do_reject) on the NumPy backend by
porting AMICATorchNG's good_idx mechanism. The feature was previously dead:
_reject_outliers thresholded the scalar total LL (not per-sample),
self.data_mask was never consumed by the E-step, and num_good_samples was
used before assignment (do_reject=True crashed mid-fit; #124 gated it with a
temporary NotImplementedError).

Changes

  • good_idx: an index array of the currently-kept samples, initialized to
    all indices in _initialize_parameters and only ever shrinking, with
    num_good_samples tracking its size (mirrors the torch backend exactly).
  • _get_updates_and_likelihood: restricts the E-step to data[:, good_idx]
    under do_reject, and captures the pre-update per-sample LL (in good_idx
    order) so the reject keep-mask maps straight back onto good_idx.
  • _get_block_updates: exposes the per-sample LL vector (ll_samples) under
    do_reject; updates["ll"] is np.sum of the same vector (unchanged).
  • _reject_outliers: thresholds that per-sample LL at mean - rejsig*std
    (population std), shrinks good_idx, and raises a clear ValueError if every
    sample would drop -- byte-for-byte the torch backend's logic.
  • _update_parameters: gm normalizes by num_good_samples under
    do_reject (the count the E-step actually summed over).
  • Construction-time validation of rejint/rejsig/maxrej (matching
    AMICATorchNG), so rejint=0 / rejsig<=0 fail up front instead of as an
    opaque ZeroDivisionError / empty-good-set crash deep in the loop.
  • Removes the Fix ty type-check diagnostics repo-wide (496 -> 0) #124 NotImplementedError gate and the dead data_mask attribute.

do_reject=False is bit-identical

Every addition is guarded by if self.do_reject, and data_use is self.data
(no copy) on the default path; the ll computation is np.sum of the exact same
expression as before. So the issue #24 single-model parity path is unchanged.

Tests (pyAMICA/tests/test_numpy_reject.py, real sample EEG -- no synthetic)

  • test_rejection_shrinks_good_sample_set: good set shrinks, good_idx stays a
    unique in-range subset, num_good_samples tracks it, W/LL finite.
  • test_gm_normalizes_by_good_count_after_rejection: multi-model (n_models=2),
    gm stays a valid finite distribution summing to 1 after rejection.
  • test_rejection_degenerate_ll_raises_clear_error: all-NaN per-sample LL ->
    ValueError("removed all ...").
  • test_reject_param_validation: rejint=0 / rejsig<=0 raise at construction.
  • test_do_reject_false_leaves_good_idx_unset: default path never touches the
    machinery (good_idx is None).
  • Drops the now-obsolete test_do_reject_refused_on_numpy_backend (the Fix ty type-check diagnostics repo-wide (496 -> 0) #124
    refusal test).

Validation

  • uv run ty check . -> All checks passed! (0 diagnostics)
  • uv run ruff check / ruff format --check clean
  • New + existing NumPy tests green (test_numpy_reject.py, test_pyAMICA.py)
  • Parity regression: test_amica.py + test_sample_data.py -> 10 passed,
    3 xfailed (pre-existing), 0 failed -- default path unregressed.

Note on parity

There is no bit-exact Fortran do_reject oracle (the torch backend's rejection
is itself behavior-validated, not bit-exact), so this is validated the same way:
the mechanism matches the torch port and behaves correctly on real data.

Port AMICATorchNG's outlier rejection to AMICA_NumPy, replacing the
non-functional data_mask stub. Previously do_reject was dead: _reject_outliers
thresholded the scalar total LL (not per-sample), self.data_mask was never
consumed by the E-step, and num_good_samples was used before assignment.

- good_idx: an index array of kept samples (init to all in _initialize_parameters,
  only ever shrinks), with num_good_samples tracking its size.
- _get_updates_and_likelihood restricts the E-step to data[:, good_idx] and
  captures the pre-update per-sample LL (in good_idx order) when do_reject.
- _reject_outliers thresholds that per-sample LL (mean - rejsig*std, population
  std), shrinks good_idx, and raises a clear ValueError if all samples drop
  (mirrors the torch backend exactly).
- gm/LL normalize by num_good_samples under do_reject.
- Validate rejint/rejsig/maxrej at construction (matching AMICATorchNG).

do_reject=False is bit-identical: every addition is guarded by self.do_reject
and the LL split is np.sum of the same expression. Removes the #124
NotImplementedError gate. New test_numpy_reject.py exercises the real sample
EEG (shrinks good set, gm stays a valid distribution, degenerate LL raises,
param validation); drops the now-obsolete refusal test.
Reverse the #124 caveats in AGENTS.md and docs/api/numpy-backend.md now
that outlier rejection is implemented on the NumPy backend.
@codecov-commenter

codecov-commenter commented Jul 14, 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 89.79592% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.34%. Comparing base (f821104) to head (763b971).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pyAMICA/numpy_impl/core.py 89.79% 3 Missing and 2 partials ⚠️
❗ 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     #126      +/-   ##
==========================================
+ Coverage   79.60%   80.34%   +0.74%     
==========================================
  Files          14       14              
  Lines        2064     2096      +32     
  Branches      345      355      +10     
==========================================
+ Hits         1643     1684      +41     
+ Misses        310      300      -10     
- Partials      111      112       +1     
Files with missing lines Coverage Δ
pyAMICA/numpy_impl/core.py 84.75% <89.79%> (+2.45%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Code review found the reject schedule missing Fortran/torch's max(1, ...)
clamp: Python's non-negative modulo let (iter-rejstart) % rejint hit 0 for
iter < rejstart, firing rejection before rejstart. Add the clamp (verified:
rejstart=3,rejint=2 now fires at [3,5,7], not [1,3,5]).

Silent-failure + comment review found my "num_good_samples drives the gm/LL
normalization" comments wrong: self.ll is a raw sum over the good set, never
normalized (this backend's convention for both modes). Correct the comments
to say only gm is normalized, and note that dropping the most-negative samples
raises the raw-sum LL, so the reject iteration is an increase and does not
spuriously trip the convergence checks (now covered by a test).

Also: expose self.numrej as an instance attribute (matching AMICATorchNG) so
the maxrej cap is testable; preserve good_idx/num_good_samples across a NaN
restart (Fortran startover keeps prior rejections); validate rejstart>=0; fix
the rejsig<=0 validation wording (at 0 it keeps ~half, not "every sample").

Tests: assert the numrej cap and c-finiteness under multi-model rejection
(dead-model dgm==0 guard), add an LL-sanity test across the reject event.
@neuromechanist

Copy link
Copy Markdown
Member Author

/review-pr summary (4 Sonnet reviewers: code, tests, silent-failure, comments)

Reviewers found real issues (2 verified experimentally against live AMICA_NumPy/AMICATorchNG). All addressed in commit 763b971.

Critical (fixed)

  1. Reject schedule missing the max(1, iter - rejstart) clamp (code review, verified). Python's non-negative modulo let (iter - rejstart) % rejint == 0 fire rejection before rejstart for non-default settings (e.g. rejstart=3, rejint=2 fired at [1,3,5] instead of [3,5]). This pre-existing schedule code was inert while do_reject was non-functional; my PR activated it. Added the clamp matching Fortran (amica17.f90:1142) + torch; verified it now fires at [3,5,7].
  2. Misleading LL-normalization comments (silent-failure + comment review, both independently). My good_idx comments claimed num_good_samples drives the gm/LL normalization, but self.ll is a raw sum, never normalized (this backend's convention for both modes). Corrected to say only gm is normalized, and documented that dropping the most-negative samples raises the raw-sum LL, so the reject iteration is an increase and does not spuriously trip convergence. Chose not to normalize self.ll: the do_reject=False path must stay bit-identical for Verify NG init-basin vs Newton bit-parity via Fortran load_* init-matching #24 parity (normalizing would shift min_dll timing). Added test_rejection_does_not_spuriously_stop_fit to lock the behavior.

Important (fixed)

  1. Restart reverts prior rejections (code review). _reinitialize_for_restart reset good_idx to the full set; Fortran's startover preserves rejections (amica17.f90:1121-1148). Now snapshots/restores good_idx/num_good_samples across the reinit.
  2. numrej was a local, maxrej cap untested (test review). Exposed self.numrej (matching torch, testable) and asserted the cap.
  3. Multi-model c finiteness untested (test review). Added test_multimodel_rejection_keeps_gm_and_c_finite exercising the dead-model dgm==0 guard.

Minor (fixed)

  • rejsig<=0 validation wording corrected (at 0 it keeps ~half, not "every sample"; comment review); added rejstart>=0 validation; docstrings made accurate ("exactly maxrej passes" now asserted).

Follow-up (filed, not this PR)

Validation: ty check . 0 diagnostics, ruff clean, all 6 do_reject tests pass, do_reject=False still bit-identical (#24 parity path untouched).

@neuromechanist
neuromechanist merged commit 9fdc76c into main Jul 14, 2026
6 checks passed
@neuromechanist
neuromechanist deleted the 123-numpy_impl-do_reject-outlier-rejection-is-non-functional-data_mask-never-initializedconsumed branch July 14, 2026 15:53
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.

numpy_impl: do_reject outlier rejection is non-functional (data_mask never initialized/consumed)

2 participants