Skip to content

Shape MATLAB outputs at the transport boundary - #657

Merged
suraj-ranganath merged 5 commits into
developfrom
cursor/output-transport-xfails-c726
Nov 19, 2026
Merged

suraj-ranganath merged 5 commits into
developfrom
cursor/output-transport-xfails-c726

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

Python vector results stay one-dimensional. MATLAB row, column, and 1-by-1 shapes are applied in the output transport used by the Python backend, and the matching xfail markers stay removed. pop_comments returns the history command only when return_com is set. Dataset struct arrays and several multi-output returns still differ and stay xfailed. MATLAB is not installed, so the reference suite was not run.

Refs #430

Open in Web Open in Cursor 

Numeric, cell, and character results that the Python backend compares
against EEGLAB now use row, column, 1-by-1, and container shapes.

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

@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.

@cursor

cursor Bot commented Nov 19, 2026

Copy link
Copy Markdown

🤖 Specification

Problem: after the MATLAB input adapters, 69 Python-backend xfails still failed because results left EEGPrep as Python scalars, 1-D arrays, lists, or too few outputs. Comparisons require MATLAB rows, columns, 1-by-1 arrays, or cell and character containers.

Approach: matlab_outputs.as_row, as_column, and empty_matrix wrap the numeric returns of the functions those tests call. finputcheck numeric fields are 1-by-1 and expose a second unrecognized-cell output. pop_comments always returns (text, command), and cell comments stay a padded character matrix. pop_chancenter returns locations, center, and command for a bare location list, and omitted channels stay in the cart2all conversion. kmeanscluster labels are 1-based, so the extra +1 in pop_clust and robust_kmeans is gone. eeg_matchchans keeps every source index; EEGLAB clears bglocs(1).bigchan inside the match loop.

Tests: the 69 markers are removed and those cases pass with --eeglab-backend python. A unit test locks the eeg_matchchans behavior. Tolerances, golden files, and parity JSON are unchanged. MATLAB is not installed, so the reference suite has not been run.

Left xfailed: dataset and location struct arrays (eeg_store, eeg_retrieve, mergechan, mergelocs, convertlocs, readlocs readers, newset, selectevent, importevent), multi-output wrappers (openbdf, runica via varsort/zica, readelp, rmbase, pop_rmbase, pop_rejchan, pop_rejtrend), forcelocs x/y, and hungarian when several assignments share the minimum cost.

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes. Making shapes match MATLAB is reasonable for [tests] Run EEGLAB-ported tests in CI via the Python backend lane #430, but some functions now return a different type, and callers inside the package weren't updated to match.
  • Highest-risk area: in-package callers of functions whose return shape or type changed (kmeanscluster, eeg_getepochevent, pop_comments, finputcheck).
  • Merge recommendation: needs changes.

Blocking

1. pop_clust crashes with algorithm="kmeanscluster" and a finite outlier threshold. src/eegprep/functions/studyfunc/robust_kmeans.py:43

  • kmeanscluster now returns as_column(labels + 1), which has shape (k, 1).
  • robust_kmeans then runs labels[active] = active_labels, writing that into a 1-D (n,) array. numpy raises ValueError: could not broadcast input array from shape (k,1) into shape (k,).
  • _outlier_rows also runs sorted(set(labels.tolist())), which fails on the nested lists.
  • pop_clust takes this path whenever outliers is finite (pop_clust.py#L75-L85), and no test covers it.
  • Fix: add active_labels = active_labels.ravel() after the call. Add a pop_clust(..., algorithm="kmeanscluster", clus_num=4, outliers=3) test in tests/test_study_clustering.py.
  • Fix this →

Important

2. The new (1, N) cell output of eeg_getepochevent breaks both of its callers. src/eegprep/functions/popfunc/eeg_getepochevent.py:95-99

Both callers iterate the second output as a list of per-epoch lists. Iterating a (1, N) object array yields one row, not N epochs.

  • pop_eventstat.event_values (L94-L104):
    • Each item is now one epoch's (1, k) array. When k > 1, float(...squeeze()) raises TypeError, the except catches it, and that epoch is silently dropped.
    • Continuous data puts every event in epoch 1, so pop_eventstat returns no values once more than one event matches.
  • pop_erpimage._sorting_variable (L373-L377):
    • The "multiple event latencies found in epochs 1" warning now fires for any multi-trial dataset, and the epoch list it gives is wrong.

Fix: in both callers, iterate np.asarray(grouped, dtype=object).ravel() and use np.ravel(item) for each epoch's values.

3. pop_comments now always returns (output, command). src/eegprep/functions/popfunc/pop_comments.py:40,63

  • EEG = pop_comments(EEG, '', 'note') now sets EEG to a tuple.
  • This contradicts the packaged help (pop_comments.md#L5-L7) and the AGENTS.md return_com contract that every other pop_* follows.
  • The test edits that add [0] / , _command hide the regression instead of catching it.
  • Fix: restore (output, command) if return_com else output on both lines and revert those test edits. For the two-output reference-suite form, have the transport pass return_com=True, or use the matlab_outputs attribute pattern this PR already uses in pop_chancenter.

4. _CheckedArguments breaks dict.values(). src/eegprep/functions/guifunc/finputcheck.py:90 (inline comment posted)

  • self.values = self replaces the inherited method on the instance.
  • finputcheck(...).values() now raises TypeError: '_CheckedArguments' object is not callable.
  • Fix: expose the first output under a name that isn't a dict method (for example "g"), or have tests/eeglab_tests/backend.py treat the first output as the object itself.

Nits

  • pop_chancenter._ChanCenterResult.__init__: the isinstance(chans, dict) branch can never run, because locs always comes from chanlocs_as_list.
  • eeg_matchchans._location_struct: records[0] raises IndexError when the small montage has no channels.

Test gaps

  • No test runs robust_kmeans / pop_clust with kmeanscluster and outliers (finding 1).
  • No pop_eventstat test has more than one matching event per epoch or uses continuous data (finding 2). The existing test_pop_eventstat_extracts_sample_event_latencies only checks size > 0.

EEGLAB parity notes

  • pcsquash no longer calls canonicalize_signs. That changes eigenvector signs, which the PR description doesn't mention. Eigenvector signs from eigh are arbitrary, so callers can now get different signs from run to run. Please state this in the PR description, or keep the canonicalization if parity doesn't need it removed.
  • eeg_matchchans now returns 1-based indices and a (1, n) numpy structured array instead of the list of chanloc dicts used throughout the rest of EEGPrep. That makes it the only chanlocs output in a different container, which conflicts with AGENTS.md "Preserve EEG dict semantics". Consider keeping the list of dicts and converting in the test transport. Keeping bigchan on the first-channel match is a documented, tested deviation from eeg_matchchans.m, so it is fine.
  • The PR changes core ported functions (eegrej, eegthresh, matsel, kmeanscluster, uniquef, perminv, and others), several of them from 0-based to 1-based. Per AGENTS.md, it needs the MATLAB reference-suite run (eeglab-reference.yml) and human approval before merge. The description says MATLAB wasn't run.

I couldn't run local tests in this environment (command approval was denied), so these findings come from reading the code and its callers. CI Tests was still running at review time.

@@ -41,7 +41,6 @@ def robust_kmeans(
)
elif method.lower() == "kmeanscluster":
active_labels, centers, _previous, _matrix = kmeanscluster(values[active], cluster_count)

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.

Blocking: pop_clust(..., algorithm="kmeanscluster", outliers=<finite>) now crashes.

kmeanscluster returns as_column(labels + 1), which has shape (k, 1). Two lines below, labels[active] = active_labels writes it into a 1-D (n,) array, and numpy raises ValueError: could not broadcast input array from shape (k,1) into shape (k,). Even with a working broadcast, _outlier_rows runs sorted(set(labels.tolist())), which fails on nested lists with TypeError: unhashable type: 'list'.

This is the robust_kmeans path that pop_clust uses when an outlier threshold is set (pop_clust.py#L75-L85), and no test covers it.

Fix: flatten here, and add a pop_clust(study, alleeg, algorithm="kmeanscluster", clus_num=4, outliers=3) test in tests/test_study_clustering.py.

Suggested change
active_labels, centers, _previous, _matrix = kmeanscluster(values[active], cluster_count)
active_labels, centers, _previous, _matrix = kmeanscluster(values[active], cluster_count)
active_labels = active_labels.ravel()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Cluster labels from kmeanscluster stay a one-dimensional 1-based vector, so robust_kmeans can assign them and _outlier_rows can read them. pop_clust(..., algorithm='kmeanscluster', clus_num=4, outliers=3) is covered in tests/test_study_clustering.py. The MATLAB column shape is applied in tests/eeglab_tests/matlab_output_transport.py when the result leaves through call_python.

Comment on lines +95 to +99
cells = np.empty((1, len(all_epoch_values)), dtype=object)
for index, item in enumerate(all_epoch_values):
array = np.asarray(item)
cells[0, index] = array.reshape(1, -1) if array.ndim < 2 else array
return output_values, cells

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 new (1, N) cell output breaks both in-package callers.

Both callers iterate the second output as a list of per-epoch lists. Iterating a (1, N) object array yields one row, not N epochs.

  • pop_eventstat.event_values: group is now the whole row, so each item is one epoch's (1, k) array. When k > 1, float(np.asarray(item).squeeze()) raises TypeError, the except catches it, and that epoch's values are silently dropped. Continuous data puts every event in epoch 1, so pop_eventstat gets no values as soon as more than one event matches. Epoched data with several matching events per epoch loses those epochs.
  • pop_erpimage._sorting_variable: enumerate(all_values) yields a single item of length N. The "multiple event latencies found in epochs 1" warning then fires for any multi-trial dataset and never names the right epochs.

Fix: update both callers to iterate np.asarray(grouped, dtype=object).ravel() and to use np.ravel(item) for each epoch's values. Add a pop_eventstat test on continuous data with several matching events, asserting the value count.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 eeg_getepochevent again returns a one-dimensional latency vector, or one list of latencies per epoch, so pop_eventstat and pop_erpimage see every matching event. tests/test_phase4_timefreq_statistics.py checks a continuous recording with three matching events. The reference comparison wraps that vector as a row in the output transport.

else:
output = new_text
return (output, command) if return_com else output
return output, command

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: pop_comments now always returns a tuple, which breaks the documented Python API.

EEG = pop_comments(EEG, '', 'note') now binds EEG to (EEG, ''), as does the cancel path on L40. That contradicts the packaged help (pop_comments.md#L5-L7). It also breaks the repo-wide return_com contract in AGENTS.md: "User-facing pop_* functions should support return_com=True and return EEGLAB-style history commands." Every other pop_* returns a bare result unless return_com=True. The test edits that add [0] / , _command hide the regression instead of catching it.

If the two-output form is only for the reference-suite transport, the transport should pass return_com=True, or use the matlab_outputs attribute pattern this PR already uses for pop_chancenter. The public function should not change.

Suggested change
return output, command
return (output, command) if return_com else output

(L40 needs the matching return (original, "") if return_com else original, and the test edits need reverting.)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Both the success path and the GUI cancel path return (output, command) if return_com else output. The unit tests call pop_comments without return_com again. The MATLAB backend passes return_com=True when nargout is greater than one.


def __init__(self, values: dict[str, Any], unrecognized: list[Any]):
super().__init__(values)
self.values = self

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: self.values = self shadows dict.values().

_CheckedArguments subclasses dict. An instance attribute named values takes precedence over the inherited dict.values method, so g = finputcheck(...); g.values() now raises TypeError: '_CheckedArguments' object is not callable. Any caller that iterates over the validated options with .values() breaks.

Fix: the transport only needs matlab_outputs to resolve to attributes. Expose the first output under a name that is not a dict method, for example matlab_outputs = ("g", "unrecognized") with self.g = self, or have backend.py map the first output to the object itself.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 The first MATLAB output is now g, the name EEGLAB assigns, so dict.values() stays the method. nargout=2 still returns the checked dict and the unrecognized cell.

cursoragent and others added 3 commits November 19, 2026 01:23
The MATLAB output name is g, so the checked-arguments dict no longer
shadows the values method.

Co-authored-by: Suraj Ranganath <[email protected]>
MATLAB row and column shapes are applied in the output transport used by
the Python backend, and pop_comments returns a command only when asked.

Co-authored-by: Suraj Ranganath <[email protected]>
Keep both sides' Python-backend xfail removals. MATLAB row and column shapes stay in the output transport, and nargout still requests the history command for pop_comments, pop_copyset, and pop_editeventfield.

Co-authored-by: Suraj Ranganath <[email protected]>
@cursor cursor Bot changed the title Return MATLAB shapes from processing outputs Shape MATLAB outputs at the transport boundary Nov 19, 2026
Channel matches, comment cells, and present-mode flags stay Python scalars and strings. The transport adds the struct, character matrix, and 1-by-1 shapes. pcsquash follows eig and does not flip eigenvector signs.

Co-authored-by: Suraj Ranganath <[email protected]>
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.

2 participants