Skip to content

[arch] Kill duplication, fix ownership & layering (Fable 5 Phase 4) - #204

Merged
suraj-ranganath merged 11 commits into
fable5/epicfrom
fable5/phase4-architecture
Jun 12, 2026
Merged

suraj-ranganath merged 11 commits into
fable5/epicfrom
fable5/phase4-architecture

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Behavior-preserving consolidations across studyfunc, timefreq, popfunc, GUI/CLI/extensions and the clean_rawdata/firfilt plugins: extract the k-means kernel so numerics import downward, route newtimef/newcrossf through canonical FDR and bootstrap helpers, remove duplicated is_on copies, serialize chanlocs through the one canonical helper, share the rejkurt/jointprob plumbing, split extension_catalog's manager and curation halves, and move firws/firwsord to the firfilt plugin. Existing tests pass unchanged. Findings that would change observable behavior, or need out-of-scope files, and the four large-file decompositions are deferred to Phase 4b.

Base is fable5/integration (Phases 1/2/3/5 stacked); merge after #200/#201/#202/#203 and rebase onto fix/fresh-uv-console once they land.

Part of #197

suraj-ranganath and others added 5 commits June 11, 2026 19:08
Part of the Fable 5 Findings epic (#193); addresses issue #198.

Standalone/runtime hygiene:
- Move developer/parity tooling out of the installed wheel into tools/:
  visual_capture.py -> tools/visual_parity/, stage_comparison.py ->
  tools/eeg_bids/, iclabel_net_load_py_measures.py -> tools/iclabel/
  (refactored to import the canonical ICLabelNet, removing the
  float64/float32 model drift). pop_reref_helper.py -> scripts/.
- Make eeglabcompat import side-effect-free (lazy temp dir), so importing
  core modules no longer creates a temp directory at import time.
- Resolve the packaged montages dir via importlib.resources instead of a
  __file__ dirname chain in pop_load_frombids.

Dependencies & docs:
- Drop the redundant eeglabio optional extra that duplicated the mandatory
  dependency. eeglabio stays required (used transitively via mne.export for
  .set writing); installation docs updated to match.
- Remove conda-forge install instructions for this unpublished pre-release;
  make the EEGobj example in contributing.rst actually runnable.
- Fix the README docs badge and correct CI branch triggers (main -> develop).

Dead code:
- Remove _currentset_list (menu_actions), _reject_unsupported_options
  (pop_newcrossf), the unused withindex parameter (pop_chansel), the
  custom_randperm no-op wrapper (runica; hoist `import time`), an unraisable
  except in eegrej, and the unread top-level STUDY['preclust'] seed
  (_study_utils).
Part of the Fable 5 Findings epic (#193); addresses issue #194.

- Remove assertion-swallowing try/except->skipTest wrappers across
  test_clean_artifacts, test_clean_drifts, test_eeg_picard,
  test_ICL_feature_extractor, and test_eeg_mne2eeg so assertions run
  instead of converting failures into skips. Genuine optional-dependency
  skips are kept as explicit @skipUnless guards.
- Deduplicate the per-module create_test_eeg fixtures onto the shared
  tests/fixtures.py fixture.
- Tighten the eeg_autocorr_fftw vs eeg_autocorr cross-check from
  rtol/atol=0.1 to 1e-4/1e-7 (documented: the only divergence is the
  single-precision FFT cast in eeg_autocorr).
- Add a real (unmocked) calc_projector test that runs the actual
  sphericalSplineInterpolate and validates channel mapping/assembly.
- Replace the ASR numpy-error-injection log-string tests with real
  degenerate-input tests asserting finite, sane cleaned output.
- Assert real clustering behavior (shared labels within tight pairs,
  far point isolated) in the study clustering helper test.

test_eeg_picard_different_random_states now xfails honestly: eeg_picard
converges identically regardless of random_state (tracked under the epic
for Phase 2/3); marked xfail rather than re-hidden.
…iants

Part of the Fable 5 Findings epic (#193); addresses issue #195.

Make side-effect-free functions actually side-effect-free by copying at
entry, and fix the ICA sign-normalization invariant break.

- Deep-copy EEG at entry in eeg_runica, eeg_amica, load_amica_model,
  eeg_picard, pop_select, pop_headplot, pop_clean_rawdata, clean_windows and
  clean_asr; copy the data array at entry in runica and clean_asr; build
  pop_saveset's MATLAB structures from copies so the caller keeps 0-based
  urchan/urevent; deep-copy the clean_artifacts high-pass snapshot.
- eeg_rpsd no longer reseeds the global NumPy RNG (uses a local RandomState).
- coords_to_mm / coords_RAS_to_ALS no longer mutate the caller's array.
- eeg_from_data no longer silently transposes a tall 2-D array on a
  shape>shape guess; it raises and asks for nbchan when orientation is
  ambiguous.
- posact sign-flips now negate the matching icaweights row and icawinv
  column directly instead of recomputing icaweights via pinv(icawinv), which
  had folded the non-identity sphere into the weights; icasphere is left
  untouched, preserving icawinv == pinv(icaweights @ icasphere) and
  icaact == icaweights @ icasphere @ data. eeg_amica and eeg_picard now
  flatten epoched data in Fortran order to match eeg_runica and EEGLAB.
- Adds regression tests asserting inputs are unchanged and the ICA
  invariants hold.
Part of the Fable 5 Findings epic (#193); addresses issue #196.

Replace silent fallbacks with real dispatch, make ignored options take
effect or fail loudly, and fix index/boundary errors — each with a test
that reproduces the bug first.

- Loading: pop_loadset dispatches HDF5 vs scipy by the actual file instead
  of swallowing every error into an HDF5 retry; pop_fileio dispatches .mat
  by content instead of silently importing a broken .set as a raw array;
  pop_loadset_h5 drops the hard-coded emoji fixture and decodes by one rule.
- Indexing/events: pop_select chantype selection no longer crashes
  (eeg_decodechan return unpacked) and the console zero-bases pop_select
  numeric channels so 1-based history replays correctly; eeg_eegrej no
  longer drops first/last events by latency; pop_editeventvals epoched
  latency display/edit is symmetric (ms<->points) and no longer raises.
- sigproc: epoch() boundary check fixed (no negative-index slice); eegrej()
  shifts boundary latencies by base region spans; runamica() cleans its
  temp dir on failure without swallowing the error.
- Session: console CURRENTSET reassignment guarded by a regression test;
  IMPLEMENTED_ACTIONS now has a test enforcing it matches dispatch routing;
  GUI dataset commit applies history only after the abort check; the
  headplot menu action commits its spline edit through the session.
- CLI: pipeline gains the negative-edge filter guard the subcommand has;
  --quiet/--verbose/--no-progress are wired; the self-describing schema
  covers all required params and stops marking --output required under
  --overwrite; bids dispatches by format and propagates exit codes.
- ASR/clean: clean_flatlines walrus precedence fixed; asr_calibrate raises
  on unsupported sample rates; clean_artifacts/clean_asr/asr_process no
  longer swallow failures and re-insert ignored channels per EEGLAB.
- Other: newtimef _is_on uses correct whitelist semantics and its dead
  params fail loudly; compute_pac passes through title/vert/newfig;
  std_precomp recompute and std_makedesign delfiles take effect; EEGobj
  raises on unknown attributes; gen_derived_fpath honors ${root}; ICLabel
  validates icawinv before dereferencing it.
The mutation regression test snapshotted icaweights via list(), which breaks
when the shared tests/fixtures.py fixture (Phase 1) provides a pre-ICA dataset
with icaweights=None. Assert the caller's ICA fields are the exact same objects
after the call instead, which is what 'does not mutate' means and works for both
a None and an array-valued icaweights.
@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Specification (PR >500 LOC; full per-finding detail in #197, epic #193)

Stacking. This PR is based on fable5/integration (Phases 1/2/3/5 merged) so the refactors operate on the already-corrected code — e.g. the ICA dedups preserve Phase 2's posact invariant fix and the is_on consolidation aligns to the whitelist semantics Phase 3 set. GitHub shows only the Phase 4 diff against that base. Merge order: 1/2/3/5 first, then rebase this onto fix/fresh-uv-console.

Problem. 45 duplication/ownership/layering findings — the loudest maintainability theme in the review. The highest-value, well-isolated ones are fixed here.

Approach (behavior-preserving — existing tests pass unchanged). One canonical helper imported downward; parallel branches collapsed; logic moved to the owning module. Key moves: k-means kernel → studyfunc/_cluster_kmeans.py; firws/firwsord → the firfilt plugin; extension_catalog.py split into manager + extension_catalog_validation.py; is_on/python_literal/chanlocs serialization / lowpass / FDR / bootstrap consolidated onto their canonical implementations; pop_rejkurt↔pop_jointprob and the _eegplot_rejection↔pop_eegplot plumbing shared.

Honest scope (this is dedup work, so "duplicates" that have diverged cannot be merged without a behavior decision). ~23 findings fully done, ~8 partial (canonical helper added + some call sites converted; remaining call sites live in out-of-allowlist files), ~10 deferred because consolidation would change observable behavior (figure titles/legends, history strings, the cluster partition + STUDY.cluster.algorithm provenance, error-message strings, or the mask-vs-None return protocol) or required files outside the cluster's allowlist. Each is annotated in the per-cluster report.

Deferred to Phase 4b (high-risk, low-reward; better as focused standalone work): the four large-file decompositions — pop_load_frombids.py (1200L), statistics/_core.py (1036L), pop_prop_extended.py (1376L), and the QtDialogRenderer class-as-namespace in qt.py.

Tests. All affected suites green (640+ passed, MATLAB-gated skips only, 1 pre-existing xfail); ruff/pre-commit clean. Three independent reviewers confirmed zero allowlist violations and no behavior changes beyond the intended canonical convergences (each test-locked).

@claude

claude Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 7m 47s —— View job


Code review — PR #204 (Fable 5 Phase 4)

  • Overall assessment: Safe to merge. The refactor is genuinely behavior-preserving across the extracted modules and rewired call sites.
  • Highest-risk area: FDR consolidation in newtimef._significance_mask (non-finite p-value handling).
  • Merge recommendation: Safe to merge; one important-but-low-reachability note worth a follow-up, plus a couple of nits.

I read the full diff against origin/fable5/integration and cross-checked every extracted helper, rewired call site, and removed block against the surviving source. The dedup is real (single canonical copies, no diverging twins left behind), removed helpers are dropped from their old __all__/imports, the function-local imports added (extension_catalog_validation ↔ extension_catalog, menu_actions → console) are justified cycle-breaks, and the "numerics import downward" layering holds (_cluster_kmeans, firfilt/firws+firwsord, _rejection→_plot_utils).

Blocking

None.

Important

FDR canonical helper no longer strips non-finite p-values — functions/statistics/_core.py:fdr (used by newtimef._significance_mask / newcrossf after this PR replaced the local _fdr_threshold).

The removed _fdr_threshold filtered to finite values first and used that finite count as the Benjamini-Hochberg denominator:

values = values[np.isfinite(values)]        # removed helper
accepted = values <= alpha * ranks / values.size

The canonical fdr() uses the full size including any non-finite entries:

flat = np.sort(values.reshape(-1)); count = flat.size   # _core.py:140-144
accepted = flat <= indices / count * q_value / correction

Two consequences when pvalues contains non-finite values:

  • NaNs sort to the end and are never accepted (the mask is unaffected), but they inflate count, making the BH condition more conservative → a different significance mask than before.
  • An inf p-value now trips if np.any((values < 0) | (values > 1)) and raises ValueError, where the old helper tolerated it.

Why it matters: this is the FDR multiple-comparison correction for ERSP/ITC significance, and the removed helper's NaN-stripping matched EEGLAB's fdr.m (which does pvals(isnan(pvals)) = []), so the canonical helper now diverges from both the prior code and EEGLAB. Reachability is low — exact_p_values builds p-values via nanmean over boolean comparisons and rarely emits NaN/inf — so this is a correctness/parity note rather than a blocker.

Concrete fix: strip non-finite in fdr() before computing count (sort, drop ~isfinite, use that length as the denominator), restoring parity with the removed helper and fdr.m. Fix this →

Nits

  • newcrossf on/off parsing tightened from blacklist to whitelist — functions/timefreqfunc/newcrossf.py. The removed local _is_on was a blacklist (str(value).lower() not in {"0","false","off","no","none"} → True for unrecognized strings); the shared _pop_utils.is_on it now imports is a whitelist (True only for {"1","on","true","yes"}). For the actual defaults (plot/plotamp/plotphase = "on") behavior is identical, and newtimef was already on the whitelist form, so only newcrossf changes and only for atypical truthy strings (e.g. plot="display" flips True→False). The new test asserts this intentionally. The whitelist is the more correct EEGLAB semantics — just worth calling out as a tightening, since the PR is framed as behavior-preserving.

  • pop_saveset primary chanlocs: empty numeric coords now serialize as 0, not NaN — functions/popfunc/pop_saveset.py. Routing the primary chanlocs through the canonical _chanlocs_to_struct_array (previously only used for chaninfo.removedchans) is the right consolidation and correctly fixes the dropped unit field (new test covers it). Side effect: the old inline serializer left None in float fields (numpy → NaN), the canonical converter substitutes 0 (0 if np.issubdtype(t, np.number) else ''). Only affects partially-empty numeric chanloc fields; EEGLAB stores empty coords as [], so neither value is a perfect match. Edge-case, low impact.

  • pop_topochansel resolves the selection even on the GUI path — functions/popfunc/pop_topochansel.py:25. pop_chansel_resolve(chanlocs, select) now runs unconditionally; on the gui branch resolved is discarded (chanlist comes from pop_chansel). Wasted work, plus an invalid explicit select label would now raise before the GUI runs. pop_chansel would raise on the same label anyway, so it's not a correctness regression — optional to skip the resolve when gui is taken.

Test gaps

Coverage is adequate and the new tests are meaningful (not tautological) — test_component_activations_dedup_contract (negated stored icaact proving the use_stored split), test_kmeans_kernel_is_shared_by_clustering_callers, test_firws_and_firwsord_are_owned_by_firfilt_plugin (runs firwsord→firws, checks linear-phase symmetry), and test_chanlocs_serialized_through_single_converter (round-trips through loadmat, asserts unit survives) all exercise the consolidated paths with real assertions.

  • (nit) If you address the FDR item above, add a regression test for fdr() / _significance_mask with NaN-containing p-values asserting the finite-count denominator.
  • (nit) std_pacplot's delegation to the shared default_measure_target(..., "pacdata", ...) has no direct test for the "pacdata" field-name path (channels-vs-cluster-1 default). Optional hardening: call with channels=clusters=components=None and a STUDY whose changrp[0] caches pacdata, assert ("channels", None); without it assert (None, 1).

EEGLAB parity notes

  • Verified faithful: the rejkurt/jointprob shared run_epoched_rejection preserves per-method stats routing (kurtE/kurt vs icakurtE/icakurt, jp equivalents), 1-based rejected = flatnonzero(marks)+1, and the history-command closure receiving the normalized (1-based) elecrange.
  • The bootstrap_threshold consolidation in newtimef/newcrossf pools surrogates to the same per-frequency population (transpose(0,2,1).reshape(-1,nfreq)) and uses the identical tail_count = max(1, round(N·alpha)) tail-mean, including the single-frequency shape case.
  • The one parity divergence is the FDR non-finite handling above (canonical fdr() vs EEGLAB fdr.m's NaN-strip).
    · branch fable5/phase4-architecture

clean_asr now returns a fresh dataset; reword the three comments that still
described it mutating EEG in place (AGENTS.md: delete stale comments in
touched code).
# Conflicts:
#	tests/test_utils_asr.py
…ing)

Part of the Fable 5 Findings epic (#193); addresses issue #197. Built on the
integration of Phases 1/2/3/5 so the deduped code keeps those fixes.

Behavior-preserving consolidations (existing tests pass unchanged):
- studyfunc: extract the k-means kernel into _cluster_kmeans.py so pop_clust,
  optimal_kmeans and robust_kmeans import it downward (layering inversion
  fixed); share unique_preserving_order, trialinfo_rows, default_measure_target
  and the MEASURE_DATA_FIELDS map.
- timefreq: newtimef/newcrossf use the canonical statistics.fdr and the shared
  bootstrap/threshold helpers instead of forked copies; _is_on imports the
  canonical whitelist predicate.
- popfunc: remove the duplicated _is_on copies (import _pop_utils.is_on),
  pop_topoplot reuses the shared python_literal, pop_topochansel delegates to
  pop_chansel, pop_comperp collapses the repeated lowpass calls, pop_saveset
  serializes chanlocs through the single _chanlocs_to_struct_array, and the
  near-identical pop_rejkurt/pop_jointprob share their rejection plumbing.
- gui/cli/extensions: menu_actions collapses the per-name dispatch branches;
  the pop-result interpretation contract is shared; the dead run_main() is
  removed; extension_catalog splits its manager and curation halves
  (extension_catalog_validation.py) and reuses the canonical entry-point
  helpers; plugin_menu derives bundled metadata from the registry.
- plugins: firws/firwsord move to the firfilt plugin (correct ownership) with
  clean_rawdata importing them.

Findings that would change observable behavior (figure titles, history
strings, cluster partition/provenance, error strings) or need files outside
this scope are intentionally left for a follow-up, as are the four large-file
decompositions (pop_load_frombids, statistics/_core, pop_prop_extended,
QtDialogRenderer) — those are tracked as Phase 4b.
@suraj-ranganath
suraj-ranganath force-pushed the fable5/phase4-architecture branch from bfb4638 to df33f83 Compare June 12, 2026 04:46
@suraj-ranganath
suraj-ranganath changed the base branch from fable5/integration to fable5/epic June 12, 2026 04:46
@suraj-ranganath
suraj-ranganath merged commit d20caa6 into fable5/epic Jun 12, 2026
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