Skip to content

Add cart2topo coordinate conversion - #45

Closed
suraj-ranganath wants to merge 10 commits into
developfrom
feat/cart2topo-port
Closed

suraj-ranganath wants to merge 10 commits into
developfrom
feat/cart2topo-port

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented Apr 30, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR ports EEGLAB's current cart2topo coordinate conversion behavior to Python in EEGPREP.

Changes:

  • Adds eegprep.cart2topo.cart2topo for converting Cartesian channel coordinates to EEGLAB topoplot theta/radius coordinates.
  • Supports both N x 3 coordinate arrays and separate x, y, z coordinate vectors.
  • Exports cart2topo from the top-level eegprep namespace for compatibility with existing EEGPREP function patterns.
  • Adds unit coverage for cardinal points, shape handling, empty input, NaN propagation, and top-level export.
  • Adds MATLAB parity coverage comparing both theta and radius against EEGLAB's cart2topo.

Stacking / Merge Order

This is a stacked PR. The branch was created from feat/parity-harness-foundation and is blocked by PR #43. Review can happen now, but this should merge only after #43 lands or after this branch is rebased onto the default branch once #43 is merged.

Notes

Current EEGLAB cart2topo.m has deprecated documentation for GUI/squeeze/center options, but the active implementation rejects additional parameters and delegates to convertlocs(..., 'cart2all'). This Python port implements that active non-GUI behavior.

Validation

  • python -m pytest tests/test_cart2topo.py -q passed: 9 passed
  • python -m pytest tests/test_topoplot.py tests/test_cart2topo.py -q passed: 38 passed, 2 subtests passed

@claude

claude Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Code Review — PR #45: Add cart2topo coordinate conversion

Note: This is a draft PR stacked on #43. Review covers all new code, but the parity harness infrastructure is the larger change here; the cart2topo function itself is a small, clean addition.


Overview

This PR does two distinct things:

  1. Ports EEGLAB's cart2topo to Python (~67 lines, well-scoped)
  2. Introduces a full parity testing harness (eegprep.parity, ~900 lines across 4 modules + TOML resources)

Both are solid, but the parity harness is the bulk of the review surface.


src/eegprep/cart2topo.py ✅

The core implementation is clean and correct.

  • np.hypot is the right choice for numerical stability.
  • The zero-vector EEGLAB convention (theta=0, radius=0.5) is explicitly tested.
  • NaN propagation is implicit and correct (arctan2(nan, …) → nan).

Minor:

  • _coerce_xyz: the 1D-length-3 special case (xyz.ndim == 1 and xyz.size == 3) is ambiguous in the error path. If someone passes a 1D array of 2 elements, the fallthrough hits the N x 3 error rather than a "must be N×3 or [X, Y, Z]" message. Not a bug, just slightly confusing.

src/eegprep/parity/compare.py

Generally well-structured with good edge-case handling.

Issues:

  1. _is_numeric_array swallows all exceptions (line 531):

    except Exception:
        return False

    except (TypeError, ValueError) would be more precise and avoid masking bugs like MemoryError or programming errors.

  2. _compare_any text fallback (line 798) — the final else branch compares arbitrary values via their str() representations after whitespace normalization. This means comparing a numpy scalar, a Python int, and a string that happens to format the same will all be "equal." It's probably fine in practice, but a comment explaining this intent would prevent future surprises.

  3. compare_stage_outputs bare KeyError (line 864):

    data_result = compare_numeric(py_eeg["data"], mat_eeg["data"], ...)

    If either EEG dict is missing "data", this raises an unhelpful KeyError. A data_key_err guard with a descriptive message would help.

  4. zero_metrics logic (line 594) is complex and hard to follow at a glance. A comment describing what the sentinel None represents (i.e., "finite metric undefined when all differences are non-finite and the array is non-empty") would help reviewers.


src/eegprep/parity/oracle.py

Issues:

  1. Path.is_relative_to() requires Python ≥ 3.9 (line 1251). The project's pyproject.toml should declare a python_requires floor, or this needs a try/except fallback for 3.8. Worth confirming the minimum supported Python version.

  2. MatlabEngineOracle.__init__ starts the engine eagerly (lines 1197–1200). Starting MATLAB on every construction is expensive and surprising. Consider lazy initialization via a property or an explicit .start() method.

  3. resolve_oracle_backend with a preferred backend that is unavailable silently falls through to the artifact_root fallback or raises. This behavior is non-obvious — if the caller explicitly requested LIVE_MATLAB_ENGINE and it's not available, an early RuntimeError with a clear message would be friendlier than silent fallback.


src/eegprep/utils/stage_comparison.py — Breaking change risk

The old compare_eeg_data always returned real numpy shapes:

'shape_py': EEG_py['data'].shape,   # always a tuple
'shape_mat': EEG_mat['data'].shape,

The new implementation returns metrics from compare_numeric:

'shape_py': data_metrics.get('expected_shape'),  # None if shape-mismatch early return
'shape_mat': data_metrics.get('actual_shape'),

If compare_numeric returns early due to a shape mismatch, .get() falls through to raise_if_failed() or the ValueError above — but the old key names are still there and may be None. Any caller that does result['shape_py'][0] (indexing into the shape) will now get a TypeError: 'NoneType' object is not subscriptable instead of an AssertionError. The docstring for compare_eeg_data was not updated either. This should be documented or the return type made explicitly consistent.


Tests

tests/test_cart2topo.py:

  • Good coverage of the cardinal points, edge cases, NaN, and empty input.
  • The MATLAB parity class is properly skipped when MATLAB is unavailable.
  • _matlab_cart2topo uses delete=False + finally cleanup, which is correct.

tests/test_parity_harness.py:

  • Good. Covers comparator behavior, oracle selection, path traversal guard, and CLI exit code.
  • test_manifest_reports_expired_deviations hardcodes "2026-04-30" as the reference date — this is sensible for a parity test but worth noting this will drift relative to date.today().

Style inconsistency: test_cart2topo.py uses unittest.TestCase; test_parity_harness.py uses pure pytest. Since pytest.ini is now the top-level runner, new tests should consistently use pytest-native style (plain functions + assert). The test_cart2topo.py unittest class works under pytest but is inconsistent with the direction this PR sets.


Documentation & Configuration

  • HARNESS.md is thorough and useful. The MATLAB MCP section is developer-facing context; it's fine here.
  • AGENTS.md: Useful for AI-assisted development, but this is an unusual top-level file for a Python repo. Consider whether .claude/AGENTS.md or a note in CONTRIBUTING.md would be more appropriate. Leaving it at root means it shows up for all contributors regardless of context.
  • parity_known_deviations.toml — runica_component_permutation max_atol = 200.0: The reason text itself calls this a "broad guardrail" that should shrink. Agreed — this is a very large tolerance for what is ultimately an EEG signal comparison. Even as a temporary measure, it would be worth ensuring this only applies to component-axis dimensions rather than all of data.
  • pytest.ini testpaths = tests: Fine, but worth noting this excludes any tests that might live in src/. Double-check nothing is missed.

CI

  • unittest discover → pytest is a clean upgrade.
  • The new "Inspect parity manifest" step is a nice smoke test that the packaged TOML loads correctly before running any tests.
  • uv pip install --system -e .[all,tests] — the comment in pyproject.toml explaining why [tests] alone is insufficient is appreciated; consider adding the same note as an inline comment in the workflow YAML for future readers.

Summary

Category Severity Item
stage_comparison.py shape return type Medium shape_py/shape_mat can now be None; old callers may break silently
Python 3.8 compat Medium Path.is_relative_to() requires Python ≥ 3.9
Bare KeyError in compare_stage_outputs Low Missing "data" key gives an unhelpful error
except Exception in _is_numeric_array Low Too broad; masks bugs
Test style consistency Low Mix of unittest.TestCase and pytest-native in new code
AGENTS.md placement Nit Top-level is unusual; consider .claude/
ICA deviation max_atol=200.0 Nit Document intended shrinkage plan with a linked issue

The cart2topo function itself is ready to merge. The parity harness is well-designed — the main asks before merging are clarifying the stage_comparison.py return-type contract and confirming the Python floor for is_relative_to.

🤖 Generated with Claude Code

@suraj-ranganath

Copy link
Copy Markdown
Member Author

Closing because this PR is no longer relevant.

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