Skip to content

Show component properties and the remaining DIPFIT dialogs - #591

Merged
suraj-ranganath merged 29 commits into
developfrom
cursor/stream-8-iclabel-dipfit-03be
Nov 18, 2026
Merged

suraj-ranganath merged 29 commits into
developfrom
cursor/stream-8-iclabel-dipfit-03be

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Component property dashboards open for channels and components, and a map click opens that component. The head-model menu fills the file fields and enables Browse for a custom model. An empty EEG.dipfit array is missing settings, LORETA-KEY builds a 20 mm in-head grid, and autofit accepts 'normlen' 'on'. ICLabel was dropped because #386 covers it. The BESA volume and missing standard_vol.mat path were dropped because #610 and #611 cover them.

Fixes #553

Open in Web Open in Cursor 

Make ICLabel, extended properties, and DIPFIT usable from the menus: install PyTorch with the GUI, replay flag history, show the property windows, and store the four-shell BESA volume the spherical fitter can use.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 06:45

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 2m 31s —— View job


Code review

  • Overall assessment: Needs changes. One test-layout issue and three nits. I found no correctness bugs in the fitting, ICLabel guards, history replay or Qt callbacks.
  • Highest-risk area: DIPFIT settings checks (ensure_dipfit_settings) and the new pop_viewprops component path (grid + dashboard + click-to-open).
  • Merge recommendation: Needs changes. Separately, the pinned MATLAB EEGLAB reference run is still required before a maintainer approves.

Blocking

None.

Important

  • The new tests go in a stream-named file, and two of them only check constants. File: tests/test_stream8_iclabel_dipfit.py.
    • File placement: AGENTS.md says "Test files generally mirror source module names" and "Search existing test files before creating new ones. Extend the closest existing test first." Closer files already exist: tests/test_dipfit_workflows.py, tests/test_gui_pop_icflag.py and tests/test_gui_pop_iclabel.py.
      • Fix: move the DIPFIT tests into test_dipfit_workflows.py and the pop_icflag history/F7 tests into test_gui_pop_icflag.py. Put the pop_viewprops tests next to the existing viewprops coverage.
    • Constant-only tests: test_f53_gui_and_dev_installs_include_pytorch_for_iclabel reads pyproject.toml and checks its strings. test_f6_plot_menu_keeps_extended_property_entries checks menu labels and action names. AGENTS.md says "Do not write tautological tests that only assert types, constants, or implementation details." Neither test runs any behavior.
      • Fix: delete both. If F53 needs a guard, the existing tests/test_optional_extras.py is the place for it.

Nits

  • ensure_dipfit_settings edits the caller's EEG (src/eegprep/plugins/dipfit/_utils.py:211-212). It writes EEG.dipfit.vol into the caller's dict, and callers such as pop_dipfit_gridsearch (_fieldtrip_workflows.py:85) pass the input EEG before copying it. In eegprep-console, a dataset configured before this PR picks up dipfit.vol with no history entry.
    • Fix: keep the check pure and add the BESA vol on the copy.
  • Duplicate ICA-presence checks. iclabel._require_ica repeats the existing pop_iclabel._require_ica. pop_icflag and pop_viewprops._has_ica_weights add two more checks, each with a slightly different rule. AGENTS.md lists "Parallel implementations of existing helpers" as a failure pattern.
    • Fix: use one shared helper in the ICLabel plugin.
  • Discarded return value in pop_viewprops._plot_props (src/eegprep/plugins/ICLabel/pop_viewprops.py:138-139). has_component_classifier(...) runs only so it can raise on mismatched rows. A reader could delete the line as dead code and lose the F7 guard.
    • Fix: call the validating function under a name that says it validates.

Test gaps

None beyond the test placement above. Behavior tests already cover: F55 replay through exec, F7 refusal of mismatched rows, the BESA radii and conductivities, BEM-without-volume raising, the LORETA-KEY grid staying within the 75 mm radius, the 'normlen' 'on' parsing, and both Qt callbacks.

EEGLAB parity notes

  • src/eegprep/eeglab/ is not vendored in this checkout, so I could not compare the .m files line by line. The intentional differences are documented in eeglab_migration.rst:
    • BESA default instead of MNI
    • Python keyword history
    • None instead of NaN in flag history
    • the LORETA-KEY 20 mm grid instead of the FieldTrip atlas
    • the component grid opening together with the dashboard
  • This PR changes ported processing code: the DIPFIT volume conductor and the ICLabel/icflag guards. Per AGENTS.md, the MATLAB reference suite (eeglab-reference.yml or a local --eeglab-backend=matlab run) has to run on the final branch before human approval. The PR body says it has not run yet.

I checked correctness, EEGLAB parity, EEG dict handling, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance. I posted three inline comments, one for each nit.

Comment thread src/eegprep/plugins/dipfit/_utils.py Outdated
Comment on lines +211 to +212
if kind == "besa" and _shell_radii(dipfit.get("vol")).size == 0:
dipfit["vol"] = besa_four_shell_volume()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this changes the caller's EEG in place. dipfit_record returns the caller's own EEG["dipfit"] dict, so this line edits it directly. pop_dipfit_gridsearch, pop_dipfit_nonlinear, pop_multifit and pop_dipfit_loreta all call ensure_dipfit_settings on the input EEG before copy_eeg. Example: a dataset whose settings name standard_BESA.mat but have no vol (any dataset configured before this PR, since apply_template only now stores vol). Running a coarse fit on it in eegprep-console adds EEG.dipfit.vol to the user's workspace EEG, and no history entry records the change.

Suggested fix: keep ensure_dipfit_settings as a pure check, and fill in the BESA vol on the copy inside the fitting path. Alternatively, call ensure_dipfit_settings only after copy_eeg in the callers. AGENTS.md asks for "explicit inputs and return values".

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 ensure_dipfit_settings no longer writes vol. dipfit_gridsearch, dipfit_nonlinear, and pop_leadfield copy the dataset first and call fill_missing_besa_volume on that copy. test_besa_fit_stores_a_missing_volume_on_the_result_only checks that a coarse fit and a missing-leadfield LORETA call leave the input without vol, and that the fit result stores radii 71, 72, 79, and 85 mm.

Comment thread src/eegprep/plugins/ICLabel/iclabel.py Outdated
Comment on lines +110 to +113
def _require_ica(EEG, feature: str) -> None:
weights = np.asarray(EEG.get("icaweights", [])) if isinstance(EEG, dict) else np.asarray([])
if getattr(weights, "ndim", 0) != 2 or weights.size == 0:
raise ValueError(f"{feature} needs an ICA decomposition in EEG.icaweights. Run pop_runica first.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this duplicates an existing helper. pop_iclabel.py:72 already defines _require_ica with the same purpose and the same "Run pop_runica first" message. This PR adds two more variants nearby: an inline check in pop_icflag._require_iclabel and pop_viewprops._has_ica_weights. That makes three slightly different rules for "has ICA" in one plugin: ndim == 2, len(w[0]) > 0, and size > 0.

AGENTS.md lists "Parallel implementations of existing helpers" as a failure pattern. Suggested fix: move one require_ica(EEG, caller) helper into the ICLabel plugin (for example _prop_numerics.py) and call it from iclabel, pop_iclabel, pop_icflag and pop_viewprops.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 require_ica_weights in _prop_numerics.py is now the only check: EEG.icaweights must be a non-empty 2-D matrix. iclabel, pop_iclabel, pop_icflag, and pop_viewprops call it. pop_icflag still checks that the classification row count matches that matrix.

Comment on lines +138 to +139
if not typecomp:
has_component_classifier(EEG, classifier_name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the return value is thrown away. This call runs only so that resolve_classifier_data raises when the rows don't match. A reader will see a discarded boolean and could delete the line as dead code, which would silently undo the F7 guard. Suggested fix: name the intent, for example call resolve_classifier_data(EEG, classifier_name, component_total=component_count(EEG), require=False) directly. A small validate_component_classifier helper would also work.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 _plot_props now calls validate_component_classifier. That helper raises when stored classifier rows do not match the current ICA component count, so the F7 guard is not a discarded boolean.

ensure_dipfit_settings no longer writes EEG.dipfit.vol into the caller's
dataset. Fitting stores the four-shell sphere on its copy. ICLabel uses one
icaweights check, and component properties validate classifier rows by name.
Behavior tests now live next to the DIPFIT, icflag, and viewprops suites.

Co-authored-by: Suraj Ranganath <[email protected]>
@cursor

cursor Bot commented Nov 11, 2026

Copy link
Copy Markdown

🤖 Review notes are addressed on 267961f.

The DIPFIT behavior tests moved into tests/test_dipfit_workflows.py. The pop_icflag history replay and stale-label tests moved into tests/test_gui_pop_icflag.py. The pop_viewprops display, click, and missing-ICA tests moved into tests/test_rejection_workflows.py, next to the existing viewprops history test. tests/test_stream8_iclabel_dipfit.py is deleted. The pyproject string check and the Plot-menu label check are gone.

The three nits are fixed in the same commit: the BESA volume is written only on the fit copy, ICA presence uses require_ica_weights, and component properties call validate_component_classifier. Inline replies are on those threads.

The MATLAB reference suite is still not run here. Pins remain EEGLAB d0963be9d81acc5b66e84f8d3d7c89e3ce127cc4 and eeglab_tests fec88f9ffe7c225eb1de8924db8b6a3e0d53a4d9.

cursoragent and others added 15 commits November 11, 2026 07:01
Keep the new component-property tests and the average-reference channel
rejection test that landed on develop.

Co-authored-by: Suraj Ranganath <[email protected]>
The dataset dialog timer was handling the same window on the next tick and
consuming the following action. That failed the merge and edit-dataset GUI
tests on the slower CI runners.

Co-authored-by: Suraj Ranganath <[email protected]>
Keep the Stream 8 changelog notes and the BIDS channel-coordinate note that landed on develop.

Co-authored-by: Suraj Ranganath <[email protected]>
Accept and reject process Qt events, so the dialog timer could run again
before the first handler returned and take the next action.

Co-authored-by: Suraj Ranganath <[email protected]>
Co-authored-by: Suraj Ranganath <[email protected]>

# Conflicts:
#	docs/source/changelog.rst
Accept processes Qt events before the window closes. Remember the window
by its Qt object, including across a momentary gap with no modal, and
still answer a different window that opens during accept.

Co-authored-by: Suraj Ranganath <[email protected]>
Accept can hide the active modal for a timer tick and then show the same
window again. Keep that window out of the next handler until its Qt object
is gone.

Co-authored-by: Suraj Ranganath <[email protected]>
The dialog timer was taking the next action for a window it had already
answered. Remember the window name, and when a handler refuses a window
close it without dropping the handler.

Co-authored-by: Suraj Ranganath <[email protected]>
Merging opens the dataset dialog from inside the merge dialog's OK
button. The timer has to claim that dataset handler before OK runs.

Co-authored-by: Suraj Ranganath <[email protected]>
A dataset dialog can appear before its title is ready. Keep the handler
and try that window again, and close the window only after it keeps
refusing the handler.

Co-authored-by: Suraj Ranganath <[email protected]>
A click can make a control the active modal while its dialog is still
open. The timer was treating that control as the next dialog.

Co-authored-by: Suraj Ranganath <[email protected]>
The merge window stayed active after OK and the timer answered it again
with the dataset handler. A window title already claimed is left alone.

Co-authored-by: Suraj Ranganath <[email protected]>
A window left open by an earlier test was taking the merge OK handler.
The merge handler now checks the window title and leaves that earlier
window to be closed.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 13:41
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 13:41
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 2m 58s —— View job


Code review

  • Overall assessment: Needs changes. The three nits from the last review are fixed (BESA vol is now written only on the fit copy, one ICA-presence check, validate_component_classifier) and the tests are in the right files. One new correctness issue remains: switching the head model can leave the old BESA sphere behind.
  • Highest-risk area: the stored EEG.dipfit.vol in pop_dipfit_settings and the BEM guard in ensure_dipfit_settings.
  • Merge recommendation: Needs changes. Separately, the pinned MATLAB EEGLAB reference run is still missing, and AGENTS.md requires it before a maintainer approves.

Blocking

None.

Important

  • An old BESA vol survives a head-model change, so a fit can silently use the wrong model (src/eegprep/plugins/dipfit/_utils.py:222, pop_dipfit_settings._apply_settings).
    • Cause: This PR stores dipfit["vol"] for the BESA template. _apply_settings starts from a copy of the existing dipfit and removes vol only through apply_template, which runs only when a model= option is passed. The F114 guard raises only when there is no shell volume.
    • Trigger: pop_dipfit_settings(EEG, model="standardBESA") followed by pop_dipfit_settings(EEG, hdmfile="standard_BEM/standard_vol.mat", coordformat="MNI"). Choosing "Custom model" in the dialog does the same.
    • Result: pop_dipfit_gridsearch raises nothing and fits the 85 mm BESA sphere while the settings name a BEM file (or a custom file) in MNI coordinates. In EEGLAB, vol always comes from hdmfile, so the two cannot disagree.
    • Fix: In _apply_settings, when options sets hdmfile, drop vol unless the new file names the BESA template. fill_missing_besa_volume restores it for BESA at fit time.
    • Details are in the inline comment. Fix this →

Nits

None.

Test gaps

  • Add the regression test for the case above in tests/test_dipfit_workflows.py. Steps: store BESA settings, then call pop_dipfit_settings again with only hdmfile="standard_BEM/standard_vol.mat" and coordformat="MNI". Then assert that pop_dipfit_gridsearch raises "standard_vol.mat is not bundled" and that out["dipfit"] has no vol.

EEGLAB parity notes

  • src/eegprep/eeglab/ is not vendored in this checkout, so I could not compare the .m files line by line. The intended differences are documented in eeglab_migration.rst and covered by tests:
    • BESA default instead of MNI
    • Python keyword history
    • None instead of NaN in flag history
    • the LORETA-KEY 20 mm grid
    • the component grid opening together with the dashboard
  • This PR changes ported processing code: the DIPFIT volume conductor and the ICLabel/icflag guards. The MATLAB reference suite (eeglab-reference.yml or a local --eeglab-backend=matlab run) still has to run on the final branch, and the PR body should record the counts.

I checked iclabel, pop_iclabel, pop_icflag (history replay, row-count guard) and pop_viewprops (dashboard, grid click wiring, missing-ICA guard). In DIPFIT I checked dipfit_record, the BESA volume fill on the copy, matlab_plot_options, the leadfield LORETA-KEY path, and both Qt callbacks (0-based indices match the template and text lists). I also considered whether EEG.dipfit.model from loaded .set files could crash the new or "" checks. It cannot, because loaded struct arrays become lists of dicts.

Comment thread src/eegprep/plugins/dipfit/_utils.py Outdated
"Run pop_dipfit_settings and choose Template Spherical Four-Shell (BESA)."
)
kind = _template_kind(dipfit)
if kind == "bem" and _shell_radii(dipfit.get("vol")).size == 0:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: an old BESA vol survives a head-model change, so this guard does not fire.

This guard raises only when there is no shell volume. This PR stores dipfit["vol"] for the BESA template. Later, _apply_settings in pop_dipfit_settings.py copies the existing dipfit. It removes vol only through apply_template, which runs only when a model= option is passed:

dipfit = dict(existing) if isinstance(existing, dict) else {}
if "model" in options and str(options["model"]).strip():
apply_template(dipfit, template_by_name(options["model"]))
for key in ("hdmfile", "mrifile", "chanfile", "coordformat"):
value = options.get(key)
if value not in (None, ""):
dipfit[key] = value

Passing just hdmfile (the usual EEGLAB script form) keeps the old sphere. So does choosing "Custom model" in the dialog, which has an empty shortname, so apply_template is skipped. _head_radius then reads the stale vol["r"] (_fitting.py:434-436).

Example:

EEG = pop_dipfit_settings(EEG, model="standardBESA", gui=False)       # stores BESA vol
EEG = pop_dipfit_settings(EEG, hdmfile="standard_BEM/standard_vol.mat",
                          coordformat="MNI", gui=False)               # vol kept
EEG = pop_dipfit_gridsearch(EEG, [1], gui=False)                      # no error; fits the 85 mm BESA sphere in "MNI" coords

A custom hdmfile gets the same silent fallback to the BESA sphere. In EEGLAB, vol always comes from hdmfile, so the two cannot disagree.

Fix: in _apply_settings, when options sets hdmfile, drop vol unless the new file names the BESA template. fill_missing_besa_volume restores it for BESA at fit time. Example: if options.get("hdmfile") and _template_kind(dipfit) != "besa": dipfit.pop("vol", None), after making _template_kind public. Add a regression test in tests/test_dipfit_workflows.py that runs the three calls above and expects the "standard_vol.mat is not bundled" error.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Valid. pop_dipfit_settings copied the existing DIPFIT record and only rebuilt vol when model= selected a template, so a later hdmfile= call kept the BESA sphere. The missing-volume check then saw a shell and the fit used the 85 mm radii.

The suggested model check would have missed this path: _template_kind treated a leftover standardBESA label as BESA before it looked at the new file, and fill_missing_besa_volume would have written the sphere back at fit time.

_apply_settings now syncs vol and model whenever this call sets hdmfile or model. The BESA file keeps the four-shell volume. Any other file drops vol. A boundary-element file is labeled standardBEM, and a custom file clears the model name. _template_kind classifies the file first, so a stale model name cannot restore the sphere.

test_replacing_the_besa_head_model_file_drops_the_stored_sphere runs the BESA settings call, then the standard_vol.mat call, then pop_dipfit_gridsearch, and expects standard_vol.mat is not bundled. The same test checks that a custom file does not keep the sphere. The original dataset is unchanged.

Settings copied the previous sphere onto a new head-model file, so a
later fit kept the 85 mm BESA shell. The stored volume now follows the
file, and the MNI boundary-element file still reports that it is missing.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 14:00
cursoragent and others added 2 commits November 11, 2026 21:05
GUI installs use onnxruntime. Torch stays the export-only extra.
The spherical fitter is documented as an infinite homogeneous medium,
and the BESA default stays until the MNI forward model lands.

Co-authored-by: Suraj Ranganath <[email protected]>
…label-dipfit-03be

Co-authored-by: Suraj Ranganath <[email protected]>

# Conflicts:
#	docs/source/changelog.rst
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:09
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:09
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 6s —— View job


Code review

  • Overall assessment: Needs changes. Commit 8765d51 is new since the last review. It moves ICLabel from PyTorch to the packaged ONNX network, which is a sound change. It also adds a browser/Pyodide backend that nothing calls. The develop merge (62f3c5f) brings in no conflicts with this stream's files that I could find.
  • Highest-risk area: the new ICLabel runtime path: iclabel.py, iclabel_net_onnx.py and iclabel_net_onnx_web.py.
  • Merge recommendation: Needs changes. Then re-run the ICLabel MATLAB reference on the final head (see the parity notes).

Blocking

None.

Important

  • The Pyodide/async ICLabel backend has no caller (iclabel_net_onnx.py:53-77, all of iclabel_net_onnx_web.py).
    • Why it matters:
      • iclabel() only calls the synchronous run_iclabel_net, and nothing imports run_iclabel_net_async. So under Emscripten, pop_iclabel always raises, and the error tells the user to await a function they can't reach through pop_iclabel.
      • MISSING_HOST_MESSAGE names tools/pyodide/iclabel_web_bridge.mjs, which is not in the branch.
      • No test runs this code.
      • AGENTS.md: "Do not add features beyond what was asked. No speculative configurability, future-proofing".
    • Fix: remove the web adapter and the IS_EMSCRIPTEN branches. Ship them in a separate PR with the JS bridge, a caller path from iclabel, and a test.
    • Fix this →

Nits

  • iclabel.py:25: the engine : str or None docstring line is now over-indented, so engine drops out of the rendered Parameters list. There is a suggestion inline.
  • The wheel now ships two copies of the network. iclabel.onnx (11.6 MB) is new, and netICL.mat (10.8 MB) plus the torch-only iclabel_net.py still ship through plugins/**/*.mat. Classification no longer reads netICL.mat; only tools/iclabel/export_iclabel_onnx.py and test_onnx_matches_torch_on_sample_data use it. Consider excluding it from package data so a plain install doesn't grow by about 11 MB. A follow-up issue is fine for this.

Test gaps

None. test_basic now runs ICLabel parity through onnxruntime. test_onnx_matches_torch_on_sample_data checks the exported artifact against the torch network. test_missing_onnxruntime_and_matlab_name_the_function_and_the_install checks the install message.

EEGLAB parity notes

  • The augmentation and averaging steps are unchanged; they only moved into prepare_network_inputs and postprocess_network_output. The NCHW permutes (3, 2, 0, 1) match the old torch permute(-1, 2, 0, 1).
  • The ICLabel MATLAB numbers in the PR body (max abs diff 3.28e-6, identical argmax, pop_icflag marking components 3 and 11) were measured at 0b00192a. That was before ICLabel ran on ONNX. AGENTS.md asks for the reference run on the final branch, so re-run the ICLabel/icflag subset with --eeglab-backend=matlab at the final head and update the counts in the body.

I checked the 8765d51 diff (ICLabel runtime, extras and install messages, pyproject extras, dev group, package data, export tool, docs and help text) and the DIPFIT text-only edits in that commit. I could not run pytest in this job.

Comment on lines +53 to +77
if IS_EMSCRIPTEN:
raise RuntimeError(
"ICLabel synchronous ONNX execution is unavailable under Emscripten; use await run_iclabel_net_async(...)."
)
session = _get_session()
inputs = {
INPUT_NAMES[0]: np.asarray(image, dtype=np.float32),
INPUT_NAMES[1]: np.asarray(psdmed, dtype=np.float32),
INPUT_NAMES[2]: np.asarray(autocorr, dtype=np.float32),
}
(output,) = session.run([OUTPUT_NAME], inputs)
return output


if IS_EMSCRIPTEN:
from eegprep.plugins.ICLabel.iclabel_net_onnx_web import run_iclabel_net_async as _run_iclabel_net_async
else:

async def _run_iclabel_net_async(image, psdmed, autocorr):
return run_iclabel_net(image, psdmed, autocorr)


async def run_iclabel_net_async(image, psdmed, autocorr):
"""Run the platform-selected ICLabel backend asynchronously."""
return await _run_iclabel_net_async(image, psdmed, autocorr)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: the Pyodide/async backend has no caller and points users to a file that does not exist.

  • run_iclabel_net_async and all of iclabel_net_onnx_web.py are unreachable. iclabel() only calls the synchronous run_iclabel_net (
    image, psdmed, autocorr = prepare_network_inputs(ICL_feature_extractor(EEG, True))
    output_np = postprocess_network_output(run_iclabel_net(image, psdmed, autocorr))
    ), and nothing else in src/, tests/ or docs/ imports the async function.
  • Under Emscripten, pop_iclabel therefore always raises this RuntimeError. The message tells the user to await run_iclabel_net_async(...), but a user can't do that through iclabel/pop_iclabel.
  • MISSING_HOST_MESSAGE in iclabel_net_onnx_web.py names tools/pyodide/iclabel_web_bridge.mjs and createIcLabelWebBridge(). That directory is not in this branch.
  • No test runs any of this code.

AGENTS.md says: "Do not add features beyond what was asked. No speculative configurability, future-proofing". This PR fixes the #553 menu findings. A browser runtime is not one of them.

Fix: delete iclabel_net_onnx_web.py, the IS_EMSCRIPTEN branch, and lines 67-77. Add the browser backend in its own PR, together with the JS bridge, a caller path from iclabel, and a test.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Valid. run_iclabel_net_async and iclabel_net_onnx_web.py had no caller, and the error text named tools/pyodide/iclabel_web_bridge.mjs, which is not in this branch. Under Emscripten that path would only tell someone to await a function iclabel never exposes.

Those files and the IS_EMSCRIPTEN branch are removed. iclabel still classifies through the synchronous run_iclabel_net session. The browser bridge can land with its JavaScript host, a caller from iclabel, and a test. The native pieces that match the epic stay: run_iclabel_net, prepare_network_inputs, postprocess_network_output, and the iclabel extra.

Comment thread src/eegprep/plugins/ICLabel/iclabel.py Outdated
Algorithm to use for classification, passed to the MATLAB/Octave implementation.
Default is 'default'.
engine : str or None
engine : str or None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this edit indented engine : str or None by four more spaces. The numpydoc parser now reads it as part of the algorithm description, so engine disappears from the rendered Parameters list.

Suggested change
engine : str or None
engine : str or None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Valid. engine was indented with the algorithm description, so it was not a Parameters entry. It is back at the same indent as algorithm.

The async ONNX path had no caller and named a JavaScript bridge that is
not in this branch. Classification stays on the synchronous onnxruntime
session.

Co-authored-by: Suraj Ranganath <[email protected]>
@cursor

cursor Bot commented Nov 11, 2026

Copy link
Copy Markdown

🤖 Agreed. netICL.mat should not ship in the plain wheel long term. It is still needed by tools/iclabel/export_iclabel_onnx.py and the ONNX-vs-torch cross-check, so the packaging split goes in a follow-up rather than this PR.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 21:35
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 21:35
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 33s —— View job


Code review

  • Confirm head SHA and review scope (da8c5f9486de0828be9b2cde8b38bbdda04b3ceb, matches the checkout)

  • Review the changes since the last review (da8c5f9) and the ONNX runtime path

  • Post findings

  • Overall assessment: Looks good. Commit da8c5f9 does what the last review asked. It deletes iclabel_net_onnx_web.py and removes the IS_EMSCRIPTEN branch and both run_iclabel_net_async definitions. It also fixes the over-indented engine docstring line in iclabel.py. Nothing outside the bundled EEGLAB reference and the separate eegprep-lean package still mentions iclabel_net_onnx_web, run_iclabel_net_async, Emscripten or missing_torch_message.

  • Highest-risk area: the ICLabel runtime path. That is iclabel() → prepare_network_inputs → run_iclabel_net (onnxruntime) → postprocess_network_output. It is unchanged from 8765d51, apart from removing the Emscripten branch.

  • Merge recommendation: Safe to merge once a human approves. The PR body now has the MATLAB reference results at 62f3c5f7:

    • --eeglab-backend=matlab: 174 passed, 1 skipped.
    • ICLabel compared with EEGLAB: max abs diff 2.1e-6, argmax identical.

    da8c5f9 only removes dead code, so those numerics still hold at the final head.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None.

  • test_basic covers ICLabel parity through onnxruntime.
  • test_onnx_matches_torch_on_sample_data checks the exported network against the torch model. It skips when torch is not installed.
  • test_missing_onnxruntime_and_matlab_name_the_function_and_the_install covers the error a user sees when onnxruntime is missing.

EEGLAB parity notes

None new.

  • The augmentation order, the NCHW (3, 2, 0, 1) transposes, and the four-way averaging match the previous torch path.
  • The documented differences are listed in eeglab_migration.rst: the interim BESA default, the homogeneous spherical fit (DIPFIT standardBESA: eegprep and EEGLAB dipole positions differ by 21 to 42 mm #600), None instead of NaN in flag history, and the LORETA-KEY grid.
  • Two follow-ups are already acknowledged and not blocking:
    • Excluding netICL.mat from the plain wheel.
    • The BESA autofit position gap.

Checked for correctness bugs, EEGLAB parity, data structure compatibility, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance. I did not run pytest; this review only read the code.

Keep component property windows and the DIPFIT dialog, leadfield, and plot behavior that the MNI boundary-element and four-shell pull requests do not cover.

Co-authored-by: Suraj Ranganath <[email protected]>
@cursor cursor Bot changed the title Stream 8: ICLabel, component properties, and DIPFIT Show component properties and the remaining DIPFIT dialogs Nov 18, 2026
Keep the component property windows, the head-model menu, empty DIPFIT settings, the LORETA-KEY grid, and autofit plot options.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 10:44
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 10:44

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Confirm the head SHA (88eb6f8, matches the checkout) and the review scope

  • Review the whole source diff against develop. The branch was rebased: ICLabel/ONNX and the BESA volume work now come from Epic: make EEGPrep browser-ready with Pyodide and ONNX ICLabel #386 and Fit DIPFIT dipoles with the packaged MNI boundary-element model #610.

  • Check callers of the changed helpers and the tests

  • Post findings

  • Overall assessment: Looks good. I found two nits and no correctness bugs. Since the rebase, the PR covers four things:

    • pop_viewprops: shows the dashboard in both modes, maps clicks on the grid to components, and refuses to run without ICA.
    • DIPFIT dialogs: the head-model template callback, Browse enabling, and the LORETA-KEY leadfield choice.
    • Settings guard: dipfit_record replaces the or {} checks.
    • matlab_plot_options: parses plot options for pop_multifit and pop_dipplot.
  • Highest-risk area: the new pop_viewprops component path. That is _plot_props, which builds the dashboard, the pop_topoplot grid and _attach_component_clicks, plus the unconditional show_figures in pop_prop_extended.

  • Merge recommendation: Safe to merge once a human approves and the reference-evidence question below is settled.

Blocking

None.

Important

None.

Nits

  • pop_dipfit_settings._run_gui:162-165: a try/except around the coordformat popup index. The popup always returns an int, so the guard covers a case that can't happen. AGENTS.md lists this as a failure pattern. I left a committable suggestion inline.
  • tests/test_stream11_datasets.py and tests/test_stream11_menus.py change the shared modal-dialog fixture, which is outside this PR's feature.
    • The fixture now dedupes dialogs by window identity or title and requeues a handler that fails.
    • The identity logic is copied into both files: _dialog_identity in one, and inlined in test_f121_failed_import_keeps_file_menu in the other.
    • Title-based dedupe also means a test that expects two dialogs with the same title will never see the second one.
    • Fix: if this hardening is needed, move it to its own small PR with a single shared helper. Otherwise drop it from this PR.

Test gaps

None that block. The new tests cover:

  • Channel and component dashboards being shown.
  • Clicking a grid map opening the right component (eegprep_open_property(2) → IC2).
  • The missing-ICA error and refusal of mismatched ICLabel rows.
  • The DIPFIT dialog, LORETA-KEY and plot-option paths in test_dipfit_workflows.py.

One gap is optional: component mode with no classifier is only exercised with plot=False. The help says that case still shows the grid and dashboard. _component_dashboard_data handles classifier is None, so I don't expect a failure. A one-line pop_viewprops(eeg_without_labels, 0, [1]) check would pin that claim.

EEGLAB parity notes

  • These differences are intentional and documented in eeglab_migration.rst, pop_viewprops.md, pop_leadfield.md and the changelog:

    • Component mode opens the dashboard together with the topography grid. EEGLAB opens only the grid, and a click opens pop_prop_extended.
    • Channel mode shows the dashboard.
    • LORETA-KEY uses a 20 mm grid inside a 75 mm radius instead of the FieldTrip atlas.
    • DIPFIT history is stored as Python keywords.
    • Co-register stays disabled.
  • In MNI/BEM coordinates, some LORETA-KEY grid points fall outside the brain mesh, for example (0, 60, -40). source_model_from_points already marks them through ft_inside_headmodel, so inside is correct.

  • MATLAB reference evidence: after the rebase, the PR body no longer records a --eeglab-backend=matlab run. The processing changes left are small:

    • ensure_dipfit_settings now goes through dipfit_record.
    • loreta_key_source_points is new.
    • The rest is GUI, help and history.

    Whether this needs a fresh reference run under AGENTS.md is the maintainer's call. If it does, record the counts in the body.

I did not run pytest because this job's permissions blocked the command. Checked: correctness, EEGLAB parity, EEG dict handling, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance.

Comment on lines +162 to +165
try:
coord_index = int(result.get("coordformat", state["coordformat"]) or state["coordformat"]) - 1
except (TypeError, ValueError):
coord_index = int(state["coordformat"]) - 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this try/except guards a case that can't happen. coordformat is a popupmenu, so inputgui always returns a 1-based int for it (

coord_formats = ("Spherical", "MNI", "Neuromag", "")
try:
coord_index = int(result.get("coordformat", state["coordformat"]) or state["coordformat"]) - 1
except (TypeError, ValueError):
coord_index = int(state["coordformat"]) - 1
options: dict[str, Any] = {
"model": template.shortname,
). AGENTS.md lists "Over-protective try/except blocks and defensive None checks for impossible states" as a failure pattern. If a renderer ever returns something else, the error should surface instead of silently falling back to the template's format.

Suggested change
try:
coord_index = int(result.get("coordformat", state["coordformat"]) or state["coordformat"]) - 1
except (TypeError, ValueError):
coord_index = int(state["coordformat"]) - 1
coord_index = int(result.get("coordformat", state["coordformat"])) - 1

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. The popup returns a 1-based int, so the try/except is defensive. It does not change fitting or leadfields. Leaving it for a follow-up.

Copy link
Copy Markdown
Member Author

Jamming at 88eb6f8 is clean. 44 tests in test_dipfit_bem.py, test_dipfit_four_shell.py, and test_dipfit_workflows.py passed, including test_bem_leadfield_and_multifit_match_fieldtrip and test_fieldtrip_leadfields_and_pop_multifit_positions_match_eeglab. 21 tests in the component-property files also passed. There is no test that compares the LORETA-KEY leadfield to MATLAB; test_loreta_key_leadfield_and_missing_source_analysis only checks the in-head grid and the missing-analysis error.

The two nits are non-blocking: the coordformat try/except does not change results, and the stream11 fixture changes are outside the DIPFIT and dashboard work.

Copy link
Copy Markdown
Member Author

CI is red on the Python 3.12/3.13 test matrix (ubuntu, macos, and windows). I am holding the merge.

On macos-latest and windows-latest, the async ICLabel menu-action test in tests/test_gui_main_window.py hit the 300s pytest timeout inside QtDialogRenderer.run at dialog.exec(), while opening the pop_iclabel dialog. Ubuntu 3.12 and 3.13 failed the same Run Python tests step with a similar runtime.

Jamming DIPFIT/BEM/component-property MATLAB-engine tests at 88eb6f8 were clean (44 + 21). This hanging GUI test still needs a fix before merge.

cursoragent and others added 2 commits November 18, 2026 13:08
The Update Marks warning was shown with QMessageBox's default application modality and no dialog loop. The async ICLabel menu test then accepted that leftover warning and waited forever in pop_iclabel's dialog.exec().

Co-authored-by: Suraj Ranganath <[email protected]>
The selected head model builds that leadfield. Match standardBEM and standardBESA against ft_compute_leadfield through the MATLAB engine, using the same relative bounds as the existing DIPFIT engine tests.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 13:11
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 13:11
…label-dipfit-03be

Co-authored-by: Suraj Ranganath <[email protected]>

# Conflicts:
#	docs/source/changelog.rst
@suraj-ranganath
suraj-ranganath merged commit d8cd314 into develop Nov 18, 2026
12 checks passed
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.

[Release readiness] Stream 8: ICLabel, component properties, DIPFIT

2 participants