Skip to content

Phase 3: DIPFIT and source-localization standalone parity #160

Closed

Description

@suraj-ranganath

🤖 Phase 3 completes DIPFIT/source-localization workflows that are part of EEGPrep's bundled plugin surface.

Summary

Deliver standalone, tested DIPFIT/source-localization parity for the workflows EEG researchers actually use: head model setup, electrode realignment, coordinate transforms, grid/nonlinear fitting, dipole plotting, rejection, batch/manual flows, and STUDY/source integration boundaries.

Scope

  • Low-level DIPFIT helpers where user workflows need them: dipfit_gridsearch, dipfit_nonlinear, dipfit_reject, dipplot, headcoordinates, electroderealign, load_afni_atlas, mni2tal, sph2spm, transform helpers, and private warp/rigid-body helpers.
  • User-facing wrappers: pop_dipfit_batch, pop_dipfit_manual, and any currently shallow pop_dipfit_* workflows.
  • Native Python handling for head models, coordinate transforms, atlases, and plotting assets packaged with EEGPrep or clearly requested by the user.
  • FieldTrip conversion boundaries: implement practical standalone conversions where feasible; otherwise provide explicit optional-dependency messaging.

Acceptance Criteria

  • DIPFIT GUI workflows match EEGLAB visual layout and state for settings, manual, batch, grid, nonlinear, and plotting dialogs.
  • Source localization outputs are deterministic enough for MATLAB parity tests or have documented numerical tolerances.
  • Missing optional assets fail clearly and helpfully.
  • STUDY/source-localization hooks have stable contracts for Phase 4.
  • Console/history commands are replayable and GUI/session state stays synchronized.

Required References

  • AGENTS.md
  • src/eegprep/eeglab/plugins/dipfit/
  • src/eegprep/plugins/dipfit/
  • sample_data/
  • .agents/skills/eegprep-feature-development/SKILL.md
  • .agents/skills/eeglab-gui-visual-parity/SKILL.md
  • .agents/skills/gui-agent-flow-qa/SKILL.md

/goal

/goal Complete EEGPrep DIPFIT/source-localization standalone parity for the audit-approved workflows. Inspect EEGLAB DIPFIT source first, implement practical Python-native coordinate/head-model/dipole-fit/plot/manual/batch behavior, keep optional FieldTrip or atlas dependencies explicit, preserve GUI/API/console history semantics, add MATLAB parity or tolerance-backed tests, sample_data workflows, visual parity screenshots, GUI Agent QA, ruff/format/ty, non-slow pytest, and pre-commit. Avoid fake source-localization outputs and do not depend on the vendored EEGLAB tree at runtime.

Activity

  1. added
    phase
    on Jun 7, 2026
  2. claude commented on Jun 7, 2026

    @claude
    Contributor

    🤖 Plan:

    Research

    Phase 3 epic, not a bug. Current src/eegprep/plugins/dipfit/ is ~1.3k LOC: real pop_dipfit_settings (stores EEGLAB EEG.dipfit fields, applies BESA/BEM templates, builds chansel), a standalone matplotlib pop_dipplot (3-D scatter only — no MRI overlay, no dipplot flags wired through), a packaged MNI MRI viewer asset (_mri.py + resources/dipfit/standard_BEM/standard_mri_mni.npz), and EEGLAB-shaped placeholder dialogs for pop_dipfit_headmodel, pop_dipfit_gridsearch, pop_dipfit_nonlinear, pop_multifit, pop_leadfield, pop_dipfit_loreta that validate prerequisites, render the dialog, then raise DIPFITUnavailableError (_fieldtrip_workflows.py). Coverage is in tests/test_dipfit_workflows.py.

    Every other item in the issue scope is absent: no headcoordinates, no electroderealign, no mni2tal, no sph2spm, no load_afni_atlas, no dipfit_reject, no pop_dipfit_batch, no pop_dipfit_manual, no warp/rigid-body or transform helpers, no LORETA/leadfield computation, no atlas assets, no MRI mesh/head-model loading, no FieldTrip conversion boundary. The vendored EEGLAB reference tree at src/eegprep/eeglab/ is empty in this checkout — the issue lists src/eegprep/eeglab/plugins/dipfit/ as a required reference, so source porting needs that tree restored or a pinned external sccn/eeglab reference. Per epic #157, Phase 1 (#158, still open) is the gating phase that defines the optional-dependency contract and audit matrix; Phase 3 should not begin in isolation.

    Relevant code

    Proposed Approach (design phase — needs human review before code)

    This is multi-thousand-line plugin work spanning MRI mesh loading, BEM/sphere forward models, dipole fitting math, atlas IO, coordinate transforms, head-coregistration GUI, and source-localization plotting. It is the wrong shape for one agent PR. The decomposition below is proposed; please confirm scope/ordering before I open implementation issues.

    Block 0 — prerequisites (resolve before any Phase 3 code). Confirm Phase 1 (#158) defines the optional-dependency policy (FieldTrip/MNE-Python/Brainstorm) and the "missing optional asset fails clearly" UX. Decide where the EEGLAB DIPFIT MATLAB source lives for parity oracling: restore src/eegprep/eeglab/plugins/dipfit/ or document an external pinned reference. Decide which assets (standard_BEM/standard_vol.mat, standard_1005.elc, standard_mri.mat, AFNI TTatlas+tlrc) ship in resources/dipfit/ as EEGPrep-converted NPZ/NPY and which require optional install.

    Block 1 — coordinate/atlas/MRI primitives (sub-PR, ~600–900 LOC). Native Python mni2tal (Matthew Brett affine — pure-numpy port), sph2spm (spherical-to-SPM frame), headcoordinates (compute neuromag/CTF/ALS basis from nasion/LPA/RPA), private warp_apply/warp_optim and rigid-body affine helpers, load_afni_atlas (NIfTI/HEAD/BRIK via nibabel as optional dep), MRI mesh/vol loader for standard_BEM/standard_vol.mat (scipy.io). Numerical parity tests against EEGLAB MATLAB scripts under tests/matlab/ for mni2tal, sph2spm, headcoordinates, warp; tolerance < 1e-6 mm.

    Block 2 — forward model + fitting (sub-PR, ~800–1200 LOC). This is the hard part: EEGLAB delegates to FieldTrip ft_dipolefitting. Two viable paths — (a) port a minimal three-shell-spherical + BEM-precomputed-leadfield path inline; (b) make MNE-Python an explicit optional dependency for BEM forward (mne.make_bem_solution, mne.fit_dipole). I recommend (b) for BEM (sphere model still ported natively): single tested adapter, no reimplementation of FieldTrip's BEM, fits "explicit optional dependency" criterion. Needs confirmation. Implements dipfit_gridsearch (linspace coarse grid → leadfield projection → RV per location), dipfit_nonlinear (Nelder–Mead/L-BFGS over (pos, mom)), dipfit_reject (RV-threshold + outside-head purge), pop_dipfit_batch (multi-component grid+nonlinear), pop_dipfit_manual (single-component interactive). Writes EEGLAB-shaped EEG.dipfit.model[i] = {posxyz, momxyz, rv, diffmap, areadk, ...}.

    Block 3 — leadfield + LORETA (sub-PR, ~400–600 LOC). pop_leadfield with the four EEGLAB source-model choices (Colin27/ICBM152 surface, LORETA-KEY volumetric, AFNI volumetric, custom). pop_dipfit_loreta calling either native eLORETA (closed-form matrix-inverse formula — feasible in pure numpy from precomputed leadfield) or an optional mne.minimum_norm adapter. Tolerance-backed correlation against MATLAB outputs on sample IC.

    Block 4 — electroderealign + headmodel-from-MRI (sub-PR, ~400–700 LOC). electroderealign (Procrustes onto fiducials, optional ICP nonlinear), pop_dipfit_headmodel (FieldTrip ft_prepare_mesh + ft_prepare_headmodel equivalent — needs explicit optional MNE-Python or scoped doc note). Includes GUI: fiducial pick dialog matching EEGLAB layout.

    Block 5 — real pop_dipplot (sub-PR, ~300–500 LOC). Wire the EEGLAB flags currently ignored: MRI background (use packaged NPZ + _mri.py slice helpers already present), summary/projection/edges/pointout/normlen modes, RV range filter. Side-by-side EEGLAB/EEGPrep PNGs via tools/visual_parity/ (cases must be added — none exist for dipfit today).

    Block 6 — STUDY/source-localization boundary + console+history end-to-end (sub-PR, ~200–400 LOC). Stable Phase-4 contract for STUDY.dipfit/STUDY.cluster source fields, session sync per AGENTS.md GUI-console rules, history replay for batch/manual flows, viewprops integration. Visual-parity captures and GUI Agent QA pass.

    Open questions for the issue author.

    1. Phase 1 Phase 1: Remaining-work audit expansion, runtime contract, and docs architecture #158 is open — does Phase 3 wait, or proceed with an interim optional-dependency policy?
    2. Restore vendored src/eegprep/eeglab/plugins/dipfit/ or use an external pinned EEGLAB reference for parity oracling?
    3. MNE-Python as the named optional dependency for BEM forward / eLORETA / dipole optimization, vs porting FieldTrip internals natively? My recommendation: optional MNE for BEM/BEM-forward, native pure-numpy for sphere model, coarse grid, eLORETA closed form, warp/affine helpers, atlas IO.
    4. Which assets ship bundled (Colin27, ICBM152, LORETA-KEY, AFNI atlas) vs optional install? File sizes matter for wheel.
    5. Acceptance for "deterministic enough" — fix a tolerance (e.g. dipole position ≤ 2 mm, RV ≤ 1% absolute) against a frozen MATLAB run on sample_data/eeglab_data_epochs_ica.set?

    If you confirm direction on 1–5, I will open Block 0 as a follow-up issue and Block 1 as the first implementation PR against the epic branch feature/eeglab-full-standalone-completion.

  3. suraj-ranganath commented on Jun 7, 2026

    @suraj-ranganath
    MemberAuthor

    🤖 Phase PR for this issue has merged into feature/eeglab-full-standalone-completion and integration checks are passing on the epic branch. Closing this phase issue as completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    phase

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions