Repository navigation
Implement NumPy do_reject outlier rejection via good_idx (#123) - #126
Merged
Conversation
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 Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
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.
Member
Author
/review-pr summary (4 Sonnet reviewers: code, tests, silent-failure, comments)Reviewers found real issues (2 verified experimentally against live Critical (fixed)
Important (fixed)
Minor (fixed)
Follow-up (filed, not this PR)
Validation: |
neuromechanist
deleted the
123-numpy_impl-do_reject-outlier-rejection-is-non-functional-data_mask-never-initializedconsumed
branch
July 14, 2026 15:53
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #123. Implements outlier rejection (
do_reject) on the NumPy backend byporting
AMICATorchNG'sgood_idxmechanism. The feature was previously dead:_reject_outliersthresholded the scalar total LL (not per-sample),self.data_maskwas never consumed by the E-step, andnum_good_sampleswasused before assignment (
do_reject=Truecrashed mid-fit; #124 gated it with atemporary
NotImplementedError).Changes
good_idx: an index array of the currently-kept samples, initialized toall indices in
_initialize_parametersand only ever shrinking, withnum_good_samplestracking its size (mirrors the torch backend exactly)._get_updates_and_likelihood: restricts the E-step todata[:, good_idx]under
do_reject, and captures the pre-update per-sample LL (ingood_idxorder) so the reject keep-mask maps straight back onto
good_idx._get_block_updates: exposes the per-sample LL vector (ll_samples) underdo_reject;updates["ll"]isnp.sumof the same vector (unchanged)._reject_outliers: thresholds that per-sample LL atmean - rejsig*std(population std), shrinks
good_idx, and raises a clearValueErrorif everysample would drop -- byte-for-byte the torch backend's logic.
_update_parameters:gmnormalizes bynum_good_samplesunderdo_reject(the count the E-step actually summed over).rejint/rejsig/maxrej(matchingAMICATorchNG), sorejint=0/rejsig<=0fail up front instead of as anopaque
ZeroDivisionError/ empty-good-set crash deep in the loop.NotImplementedErrorgate and the deaddata_maskattribute.do_reject=Falseis bit-identicalEvery addition is guarded by
if self.do_reject, anddata_useisself.data(no copy) on the default path; the
llcomputation isnp.sumof the exact sameexpression 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_idxstays aunique in-range subset,
num_good_samplestracks it, W/LL finite.test_gm_normalizes_by_good_count_after_rejection: multi-model (n_models=2),gmstays 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<=0raise at construction.test_do_reject_false_leaves_good_idx_unset: default path never touches themachinery (
good_idx is None).test_do_reject_refused_on_numpy_backend(the Fix ty type-check diagnostics repo-wide (496 -> 0) #124refusal test).
Validation
uv run ty check .-> All checks passed! (0 diagnostics)uv run ruff check/ruff format --checkcleantest_numpy_reject.py,test_pyAMICA.py)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_rejectoracle (the torch backend's rejectionis 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.