Skip to content

Add cart2topo coordinate conversion - #44

Closed
suraj-ranganath wants to merge 1 commit into
feat/parity-harness-foundationfrom
feat/cart2topo-port
Closed

suraj-ranganath wants to merge 1 commit into
feat/parity-harness-foundationfrom
feat/cart2topo-port

Conversation

@suraj-ranganath

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.

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: Add cart2topo coordinate conversion

Overall: This is a clean, minimal port of EEGLAB's cart2topo with solid test coverage. A few nits below, but nothing blocking.


src/eegprep/cart2topo.py

Strengths

  • Implementation is correct — the math faithfully replicates EEGLAB's convertlocs('cart2all') pipeline (sph_theta → -theta, sph_phi → 0.5 - phi/180)
  • Input coercion is well-factored into _coerce_xyz, keeping the public function short and clear
  • Docstring follows the project's NumPy-style convention

Issues

  1. Redundant .astype(np.float64, copy=False) calls (cart2topo.py:57-58):
    _coerce_xyz already casts all inputs to dtype=np.float64, so all intermediate arrays are already float64. The .astype(..., copy=False) calls on the final return values are no-ops and add noise. They can be removed:

    # before
    return theta.astype(np.float64, copy=False), radius.astype(np.float64, copy=False)
    # after
    return theta, radius
  2. Zero-vector input is silently accepted (cart2topo.py:52-56):
    [0, 0, 0] produces theta=0, radius=0.5 via atan2(0,0)=0 in both NumPy and MATLAB, so parity is maintained — but the point has no well-defined spherical coordinates. This is an underspecified input that EEGLAB also handles silently. If it's in scope, a test asserting the current behavior (or a note in the docstring) would help future maintainers.

  3. Returns docstring is vague (cart2topo.py:56-58):

    theta, radius : ... EEGLAB topoplot angle in degrees and radius by topoplot convention.
    

    Consider adding the formula or at least the range: e.g. theta is in [-180, 180] degrees (negated azimuth), radius is 0.5 - elevation_deg / 180 (0 = top of head, 0.5 = equator, 1 = bottom).


src/eegprep/__init__.py

  1. Import ordering (line 50):
    All surrounding imports are eeg_* prefixed. cart2topo sorts before eeg_* alphabetically, so placing it in the middle of the eeg_* block looks inconsistent. Suggest grouping it either before the first eeg_* import or adding a blank line to signal intent.

tests/test_cart2topo.py

Strengths

  • Good breadth: cardinal points, single vector, matrix, separate vectors, empty, invalid shapes, NaN propagation, top-level re-export, and MATLAB parity
  • MATLAB tests are properly guarded with EEGPREP_SKIP_MATLAB
  • setUp with skipTest prevents hard failures in environments without MATLAB

Issues

  1. test_matrix_input validates against itself (test_cart2topo.py:41-48):
    The expected values are computed with the same formula as the implementation, so this test can only catch regressions, not original bugs. The MATLAB parity tests cover correctness, but it would be worth noting this or replacing the inline formula with a hand-verified constant:

    # [1,1,1]: azimuth=45°, elevation=35.26°
    np.testing.assert_allclose(theta[0], -45.0, atol=1e-10)
    np.testing.assert_allclose(radius[0], 0.5 - 35.264389682754654 / 180.0, atol=1e-10)
  2. MATLAB parity only covers matrix input (TestCart2TopoParity):
    A second parity test covering the separate x, y, z vector path would give confidence that _coerce_xyz doesn't silently reorder or reshape in that case.

  3. tempfile.NamedTemporaryFile objects not used as context managers (test_cart2topo.py:81-85):
    Minor style nit — using with tempfile.NamedTemporaryFile(..., delete=False) as f: f.name and then closing/deleting in finally is more idiomatic Python than calling .close() manually.


Summary

Category Finding
Correctness ✅ Math is accurate, NaN/empty/error paths work
Style Minor: import order, redundant cast, docstring range
Tests Good coverage; test_matrix_input tautological but parity tests compensate
Performance ✅ Fully vectorised, no Python loops
Security ✅ No concerns

This is ready to merge with the nits addressed or deferred as follow-ups — the implementation and test suite are sound.

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