diff --git a/src/ndi/gui/nav/datasets_pane.py b/src/ndi/gui/nav/datasets_pane.py index f25d1f89..6a7453b1 100644 --- a/src/ndi/gui/nav/datasets_pane.py +++ b/src/ndi/gui/nav/datasets_pane.py @@ -704,6 +704,15 @@ def _session_menu(self, node: Any) -> Any: session_root.addAction("Info...", lambda: self.show_session_info(node)) session_root.addAction("Ingest", lambda: self.ingest_session_node(node)) session_root.addAction("Ingestion Status", lambda: self.update_session_status(node)) + # "Tables" exposes the session summary tables of ndi.fun.doc_table + # (VH-Lab/NDI-matlab#1243); see ndi.gui.nav.session_table. + from .session_table import table_kinds + + tables_root = session_root.addMenu("Tables") + for info in table_kinds(): + tables_root.addAction( + info["Label"], lambda k=info["Kind"], n=node: self.show_session_table(n, k) + ) return menu def _unaffiliated_menu(self, node: Any) -> Any: @@ -908,6 +917,27 @@ def show_daq_systems(self, node: Any) -> Any: browser.show() return browser + def show_session_table(self, node: Any, kind: str) -> Any: + """Build one summary table of NODE's session and show it. + + KIND is a kind from :func:`ndi.gui.nav.session_table.table_kinds` + (``element``, ``epoch``, ``probe``, ``subject`` or ``treatment``). + """ + from .session_table import SessionTable, kind_info + + title = kind_info(kind)["Title"] + session = self._resolve_or_report(node, title) + if session is None: + return None + try: + window = SessionTable(session, kind) + except Exception as exc: # noqa: BLE001 + self._alert(str(exc), title, success=False) + return None + self.open_windows.append(window) + window.show() + return window + def assign_session_to_workspace(self, node: Any) -> str | None: """Put NODE's session in a workspace variable (default ``S``). diff --git a/src/ndi/gui/nav/session_table.py b/src/ndi/gui/nav/session_table.py new file mode 100644 index 00000000..a1e557c9 --- /dev/null +++ b/src/ndi/gui/nav/session_table.py @@ -0,0 +1,372 @@ +"""ndi.gui.nav.session_table - a window showing one summary table of a session. + +MATLAB counterpart: ``src/ndi/+ndi/+gui/+nav/sessionTable.m`` + +Builds one of the session summary tables of :mod:`ndi.fun.doc_table` and +shows it. The target of the navigator's per-session "Session > Tables" +submenu (VH-Lab/NDI-matlab#1243): + +============= ============================== +Menu item Builds +============= ============================== +Elements... ``ndi.fun.doc_table.element`` +Epochs... ``ndi.fun.doc_table.epoch`` +Probes... ``ndi.fun.doc_table.probe`` +Subjects... ``ndi.fun.doc_table.subject`` +Treatments... ``ndi.fun.doc_table.treatment`` +============= ============================== + +The window has a heading with the row count, "Assign to workspace..." (puts +the DataFrame in ``__main__``'s globals, the navigator's workspace) and +"Export CSV...", and the table itself with every cell shown as text. The +table is built once, at construction. The helpers that decide what is shown +are module functions, testable without a display. +""" + +from __future__ import annotations + +import importlib +import math +from typing import Any + +from ..cloud_colors import cloud_colors, rgb_to_hex + +__all__ = [ + "SessionTable", + "TABLE_KINDS", + "table_kinds", + "kind_info", + "compute_table", + "summary_text", + "table_cells", + "cell_text", + "session_ref", +] + +#: The session tables, in menu (alphabetical) order. Fields as in MATLAB's +#: tableKinds: Kind, Label, Title, VariableName, Function (the MATLAB +#: function); ``python_function`` is the doc_table function called here. +TABLE_KINDS: tuple[dict[str, str], ...] = ( + { + "Kind": "element", + "Label": "Elements...", + "Title": "Element table", + "VariableName": "elementTable", + "Function": "ndi.fun.docTable.element", + "python_function": "element", + }, + { + "Kind": "epoch", + "Label": "Epochs...", + "Title": "Epoch table", + "VariableName": "epochTable", + "Function": "ndi.fun.docTable.epoch", + "python_function": "epoch", + }, + { + "Kind": "probe", + "Label": "Probes...", + "Title": "Probe table", + "VariableName": "probeTable", + "Function": "ndi.fun.docTable.probe", + "python_function": "probe", + }, + { + "Kind": "subject", + "Label": "Subjects...", + "Title": "Subject table", + "VariableName": "subjectTable", + "Function": "ndi.fun.docTable.subject", + "python_function": "subject", + }, + { + "Kind": "treatment", + "Label": "Treatments...", + "Title": "Treatment table", + "VariableName": "treatmentTable", + "Function": "ndi.fun.docTable.treatment", + "python_function": "treatment", + }, +) + +UNNAMED_SESSION = "(unnamed session)" + + +def table_kinds() -> list[dict[str, str]]: + """The session tables, in menu order (copies, safe to modify).""" + return [dict(k) for k in TABLE_KINDS] + + +def kind_info(kind: str) -> dict[str, str]: + """The :data:`TABLE_KINDS` entry for KIND (case-insensitive).""" + for k in TABLE_KINDS: + if k["Kind"].lower() == str(kind).lower(): + return dict(k) + raise ValueError( + f'Unknown session table kind "{kind}". Expected one of: ' + + ", ".join(k["Kind"] for k in TABLE_KINDS) + + "." + ) + + +def compute_table(session: Any, kind: str) -> Any: + """Build the KIND table for SESSION. + + Calls the :mod:`ndi.fun.doc_table` function for KIND and returns its + table: a function that returns a tuple (``treatment``) gives its first + element, as MATLAB keeps its first output. Anything that is not a + DataFrame becomes an empty DataFrame. + """ + import pandas as pd + + info = kind_info(kind) + doc_table = importlib.import_module("ndi.fun.doc_table") + result = getattr(doc_table, info["python_function"])(session) + if isinstance(result, tuple): + result = result[0] if result else None + if not isinstance(result, pd.DataFrame): + result = pd.DataFrame() + return result + + +def summary_text(title: str, table: Any) -> str: + """Heading text, e.g. ``'Subject table (3 rows)'``.""" + try: + n = len(table.index) + except Exception: # noqa: BLE001 - not a DataFrame: no rows + n = 0 + return f"{title} (1 row)" if n == 1 else f"{title} ({n} rows)" + + +def _is_missing_scalar(v: Any) -> bool: + if v is None: + return True + try: + import pandas as pd + + if v is pd.NaT: + return True + except ImportError: # pragma: no cover - pandas is required by compute_table + pass + return isinstance(v, float) and math.isnan(v) + + +def _matlab_num(v: Any) -> str: + """A number the way MATLAB's num2str/mat2str writes it (3, not 3.0).""" + if isinstance(v, bool): + return "true" if v else "false" + if isinstance(v, float) and v.is_integer(): + return str(int(v)) + return f"{v:.5g}" if isinstance(v, float) else str(v) + + +def cell_text(v: Any) -> str: + """Format one table value as display text, as MATLAB's cellText does. + + str -> itself; None / NaN / NaT / empty -> ``''``; bool -> ``'true'`` / + ``'false'``; number -> as MATLAB's num2str writes it; a numeric + sequence or array -> MATLAB's ``'[1 2]'``; a list/tuple of other things + -> the elements' texts, blanks dropped, joined with ``', '``; dict -> + ``''``; datetimes and the rest -> ``str``. + """ + try: + import numpy as np + except ImportError: # pragma: no cover + np = None # type: ignore[assignment] + + if isinstance(v, str): + return v + if np is not None and isinstance(v, np.ndarray): + v = v.tolist() + if np is not None and isinstance(v, np.generic): + v = v.item() + if _is_missing_scalar(v): + return "" + if isinstance(v, bool): + return "true" if v else "false" + if isinstance(v, (int, float)): + return _matlab_num(v) + if isinstance(v, dict): + return "" + if isinstance(v, (list, tuple)): + if not v: + return "" + if all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in v): + if all(isinstance(x, float) and math.isnan(x) for x in v): + return "" + return "[" + " ".join(_matlab_num(x) for x in v) + "]" + parts = [cell_text(x) for x in v] + return ", ".join(p for p in parts if p) + return str(v) + + +def table_cells(table: Any) -> tuple[list[str], list[list[str]]]: + """Column names and an all-text grid of rows for display. + + An empty or non-DataFrame TABLE gives ``([], [])``. + """ + try: + names = [str(c) for c in table.columns] + except Exception: # noqa: BLE001 + return [], [] + if not names: + return [], [] + rows = [[cell_text(v) for v in row] for row in table.itertuples(index=False, name=None)] + return names, rows + + +def session_ref(session: Any) -> str: + """A session's reference for the window title, best effort.""" + try: + ref = str(session.reference or "") + except Exception: # noqa: BLE001 + ref = "" + return ref or UNNAMED_SESSION + + +class SessionTable: + """A window showing one summary table of a session. + + Constructing it builds the table (``self.table``, a DataFrame); + :meth:`build` creates the widgets. They are separate so the table can + be tested without a display. + """ + + def __init__(self, session: Any, kind: str, *, build: bool = True): + self.session = session + self.kind = kind_info(kind)["Kind"] + self.table = compute_table(session, self.kind) + self.figure: Any = None + self.ui_table: Any = None + if build: + self.build() + + # ------------------------------------------------------------------ + # actions (no Qt needed when a name / path is given) + # ------------------------------------------------------------------ + def assign_to_workspace(self, name: str | None = None) -> str | None: + """Put the table in a workspace variable (``__main__``'s globals). + + Asks for a name (default e.g. ``subjectTable``) unless NAME is given. + Returns the name assigned, or None when nothing was. + """ + from . import datasets_model + from .datasets_text import workspace_name_error + + title = "Assign to workspace" + if name is None: + name = self._ask_text( + "Workspace variable name:", title, kind_info(self.kind)["VariableName"] + ) + if name is None: + return None + name = name.strip() + message = workspace_name_error(name) + if message: + self._alert(message, title) + return None + try: + datasets_model.assign_workspace_var(name, self.table) + except Exception as exc: # noqa: BLE001 + self._alert(str(exc), title) + return None + return name + + def export_csv(self, path: str | None = None) -> str | None: + """Write the table (as displayed text) to a CSV file. + + Asks for the file unless PATH is given. Returns the path written, + or None when nothing was. + """ + import pandas as pd + + if path is None: + path = self._ask_save_path(f"{kind_info(self.kind)['VariableName']}.csv") + if not path: + return None + try: + names, rows = table_cells(self.table) + pd.DataFrame(rows, columns=names).to_csv(path, index=False) + except Exception as exc: # noqa: BLE001 + self._alert(str(exc), "Export CSV") + return None + return path + + # ------------------------------------------------------------------ + # Qt + # ------------------------------------------------------------------ + def build(self) -> Any: + """Create the window and fill the table.""" + from .._qt_helpers import get_or_create_app, require_qt + + require_qt() + get_or_create_app() + from PySide6 import QtWidgets + + c = cloud_colors() + info = kind_info(self.kind) + + self.figure = QtWidgets.QWidget() + self.figure.setWindowTitle(f"{info['Title']}: {session_ref(self.session)}") + self.figure.setObjectName("ndiNavigatorSessionTable") + self.figure.resize(900, 520) + self.figure.setStyleSheet(f"background-color: {rgb_to_hex(c.dark_blue)};") + + layout = QtWidgets.QVBoxLayout(self.figure) + layout.setContentsMargins(10, 10, 10, 10) + layout.setSpacing(6) + + header = QtWidgets.QHBoxLayout() + label = QtWidgets.QLabel(summary_text(info["Title"], self.table)) + label.setStyleSheet(f"color: {rgb_to_hex(c.white)}; font-weight: bold;") + header.addWidget(label, 1) + assign = QtWidgets.QPushButton("Assign to workspace...") + assign.clicked.connect(lambda: self.assign_to_workspace()) + header.addWidget(assign) + export = QtWidgets.QPushButton("Export CSV...") + export.clicked.connect(lambda: self.export_csv()) + header.addWidget(export) + layout.addLayout(header) + + names, rows = table_cells(self.table) + table = QtWidgets.QTableWidget(len(rows), len(names)) + table.setHorizontalHeaderLabels(names) + table.verticalHeader().setVisible(False) + table.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.NoEditTriggers) + table.setStyleSheet( + f"background-color: {rgb_to_hex(c.white)}; color: {rgb_to_hex(c.dark_blue)};" + ) + for r, row in enumerate(rows): + for col, value in enumerate(row): + table.setItem(r, col, QtWidgets.QTableWidgetItem(value)) + layout.addWidget(table, 1) + self.ui_table = table + return self.figure + + def show(self) -> None: + if self.figure is not None: + self.figure.show() + + def _ask_text(self, prompt: str, title: str, default: str) -> str | None: + from PySide6 import QtWidgets + + text, ok = QtWidgets.QInputDialog.getText(self.figure, title, prompt, text=default) + return text if ok else None + + def _ask_save_path(self, default: str) -> str: + from PySide6 import QtWidgets + + path, _ = QtWidgets.QFileDialog.getSaveFileName( + self.figure, "Export CSV", default, "CSV files (*.csv)" + ) + return path + + def _alert(self, message: str, title: str) -> None: + if self.figure is None: + return + from PySide6 import QtWidgets + + QtWidgets.QMessageBox.warning(self.figure, title, message) + + def __repr__(self) -> str: + return f"SessionTable(session={session_ref(self.session)!r}, kind={self.kind!r})" diff --git a/src/ndi/gui/ndi_matlab_python_bridge.yaml b/src/ndi/gui/ndi_matlab_python_bridge.yaml index 07ad98c2..207d3820 100644 --- a/src/ndi/gui/ndi_matlab_python_bridge.yaml +++ b/src/ndi/gui/ndi_matlab_python_bridge.yaml @@ -870,7 +870,7 @@ ported_late: - name: datasetsPane matlab_path: "+ndi/+gui/+nav/datasetsPane.m" - matlab_last_sync_hash: "666a0ddfa" + matlab_last_sync_hash: "c5174ab" python_path: "ndi/gui/nav/datasets_pane.py" decision_log: > The navigator's elastic pane, ported across #103, #109, #110 and @@ -911,6 +911,12 @@ ported_late: the refresh symbol (rightWidth 108 -> 56; REFRESH_WIDTH follows). The attribute is refresh_btn because refresh_button is now the NavPane factory method. + 2026-11-13: NDI-matlab c5174ab (VH-Lab/NDI-matlab#1243): the session + menu's "Session" submenu gains "Tables" (Elements..., Epochs..., + Probes..., Subjects..., Treatments...), each opening a sessionTable + window (showSessionTable -> show_session_table). MATLAB shows an + indeterminate progress dialog while the table is built; Python, like + its ingest_session_node, builds it without one. - name: cloudComparison matlab_path: "+ndi/+gui/+nav/cloudComparison.m" @@ -980,6 +986,29 @@ ported_late: (VH-Lab/NDI-matlab#1058): DAQ systems are loaded with daqsystem_load() and no name regexp, which is slow on large databases. + - name: sessionTable + matlab_path: "+ndi/+gui/+nav/sessionTable.m" + matlab_last_sync_hash: "c96e86e" + python_path: "ndi/gui/nav/session_table.py" + decision_log: > + Added with VH-Lab/NDI-matlab#1243: the window behind the navigator's + "Session > Tables" submenu, showing one ndi.fun.docTable summary table + (element, epoch, probe, subject, treatment) with "Assign to + workspace..." and "Export CSV...". Class SessionTable; snake_case like + the rest of ndi.gui.nav. MATLAB's static helpers are module functions + (tableKinds -> table_kinds plus the TABLE_KINDS constant, kindInfo -> + kind_info, computeTable -> compute_table, summaryText -> summary_text, + tableCells -> table_cells, cellText -> cell_text, sessionRef -> + session_ref); properties Session/Kind/Table/Figure/UITable -> + session/kind/table/figure/ui_table, where table is a pandas DataFrame + from ndi.fun.doc_table. kind_info raises ValueError where MATLAB raises + ndi:gui:nav:sessionTable:unknownKind. The workspace is __main__'s + globals, as for datasetsPane's "Assign to workspace...". + assign_to_workspace and export_csv take an optional name / path so + they can run without dialogs, as MATLAB's public assignToWorkspace and + exportCsv do since NDI-matlab c96e86e (both return the name / path, or + MATLAB '' / Python None when nothing was done). + - name: daqSystemBrowser matlab_path: "+ndi/+gui/+nav/daqSystemBrowser.m" matlab_last_sync_hash: "663ccff" diff --git a/tests/test_gui_nav_datasets_pane.py b/tests/test_gui_nav_datasets_pane.py index f205fd92..77cd69e3 100644 --- a/tests/test_gui_nav_datasets_pane.py +++ b/tests/test_gui_nav_datasets_pane.py @@ -645,8 +645,38 @@ def test_the_session_menu_items_are_alphabetical(self): "Info...", "Ingest", "Ingestion Status", + "Tables", ] + def test_the_tables_submenu_lists_the_session_tables(self): + """VH-Lab/NDI-matlab#1243: Session > Tables exposes the doc tables.""" + _qt_or_skip() + nav, pane = _built_pane() + pane.user_sessions = [FakeSession("a", path="/s/a")] + pane.populate_tree() + menu = pane.build_node_menu(pane.tree.topLevelItem(0).child(0)) + session_menu = menu.actions()[2].menu() + tables = [a for a in session_menu.actions() if a.text() == "Tables"][0].menu() + assert [a.text() for a in tables.actions()] == [ + "Elements...", + "Epochs...", + "Probes...", + "Subjects...", + "Treatments...", + ] + + def test_a_session_table_that_fails_is_reported_not_raised(self, monkeypatch): + _qt_or_skip() + import ndi.gui.nav.session_table as st + + nav, pane = _built_pane() + pane.user_sessions = [FakeSession("a", path="/s/a")] + pane.populate_tree() + node = pane.tree.topLevelItem(0).child(0) + monkeypatch.setattr(st, "compute_table", _raise("no stimulators")) + assert pane.show_session_table(node, "epoch") is None + assert any("no stimulators" in m for m, _, _ in nav.alerts) + def test_a_dataset_node_gets_the_cloud_menu_in_matlabs_order(self): _qt_or_skip() nav, pane = _built_pane(user_datasets=[FakeDataset("d")]) diff --git a/tests/test_gui_nav_session_table.py b/tests/test_gui_nav_session_table.py new file mode 100644 index 00000000..8486ef08 --- /dev/null +++ b/tests/test_gui_nav_session_table.py @@ -0,0 +1,134 @@ +"""ndi.gui.nav.session_table against MATLAB's sessionTable. + +MATLAB counterpart: ``src/ndi/+ndi/+gui/+nav/sessionTable.m`` (tests: +``tests/+ndi/+unittest/+gui/+nav/sessionTable_test.m``) + +The helpers are plain Python and run everywhere; the window test builds it +under the offscreen platform and skips without PySide6. +""" + +from __future__ import annotations + +import math +import os + +import pytest + +pd = pytest.importorskip("pandas") + +import ndi.fun.doc_table as doc_table # noqa: E402 +import ndi.gui.nav.session_table as st # noqa: E402 + + +class TestKinds: + def test_table_kinds_order_and_functions(self): + kinds = st.table_kinds() + assert [k["Kind"] for k in kinds] == [ + "element", + "epoch", + "probe", + "subject", + "treatment", + ] + labels = [k["Label"] for k in kinds] + assert labels == [ + "Elements...", + "Epochs...", + "Probes...", + "Subjects...", + "Treatments...", + ] + assert sorted(labels) == labels + for k in kinds: + assert callable(getattr(doc_table, k["python_function"])) + assert k["VariableName"].isidentifier() + + def test_kind_info(self): + info = st.kind_info("Subject") + assert info["Kind"] == "subject" + assert info["Title"] == "Subject table" + with pytest.raises(ValueError, match="Unknown session table kind"): + st.kind_info("nope") + + +class TestFormatting: + def test_summary_text(self): + assert st.summary_text("Probe table", pd.DataFrame()) == "Probe table (0 rows)" + assert st.summary_text("Probe table", pd.DataFrame({"a": [1]})) == "Probe table (1 row)" + assert st.summary_text("Probe table", pd.DataFrame({"a": [1, 2]})) == "Probe table (2 rows)" + + def test_cell_text(self): + f = st.cell_text + assert f("abc") == "abc" + assert f("") == "" + assert f(["a", "b"]) == "a, b" + assert f(3) == "3" + assert f(3.0) == "3" + assert f(math.nan) == "" + assert f(None) == "" + assert f([1, 2]) == "[1 2]" + assert f(True) == "true" + assert f([]) == "" + assert f(["a", 2, ""]) == "a, 2" + assert f({"a": 1}) == "" + + def test_table_cells(self): + T = pd.DataFrame({"Name": ["s1", "s2"], "Value": [1, math.nan], "Pair": [[1, 2], [3, 4]]}) + names, rows = st.table_cells(T) + assert names == ["Name", "Value", "Pair"] + assert rows == [["s1", "1", "[1 2]"], ["s2", "", "[3 4]"]] + + def test_table_cells_empty(self): + assert st.table_cells(pd.DataFrame()) == ([], []) + + +class TestComputeAndActions: + def test_compute_table_keeps_the_first_output(self, monkeypatch): + df = pd.DataFrame({"a": [1]}) + monkeypatch.setattr(doc_table, "treatment", lambda s: (df, ["id"], ["dep"])) + assert st.compute_table(object(), "treatment") is df + + def test_compute_table_non_frame_is_empty(self, monkeypatch): + monkeypatch.setattr(doc_table, "element", lambda s: None) + assert st.compute_table(object(), "element").empty + + def test_assign_and_export(self, monkeypatch, tmp_path): + import __main__ + + df = pd.DataFrame({"Name": ["s1"], "Value": [2.0]}) + monkeypatch.setattr(doc_table, "subject", lambda s: df) + window = st.SessionTable(object(), "subject", build=False) + assert window.table is df + + monkeypatch.delattr(__main__, "subjectTableTest", raising=False) + assert window.assign_to_workspace("subjectTableTest") == "subjectTableTest" + assert __main__.__dict__["subjectTableTest"] is df + del __main__.__dict__["subjectTableTest"] + assert window.assign_to_workspace("1bad") is None + + out = tmp_path / "subjects.csv" + assert window.export_csv(str(out)) == str(out) + assert out.read_text().splitlines() == ["Name,Value", "s1,2"] + + +def test_window_shows_the_table(monkeypatch): + pytest.importorskip("PySide6") + os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + try: + from ndi.gui._qt_helpers import get_or_create_app + + get_or_create_app() + except Exception as exc: # noqa: BLE001 + pytest.skip(f"no usable Qt platform plugin: {exc}") + + df = pd.DataFrame({"probe_name": ["ctx", "lgn"], "probe_reference": [1, 2]}) + monkeypatch.setattr(doc_table, "probe", lambda s: df) + + class S: + reference = "exp1" + + window = st.SessionTable(S(), "probe") + assert window.figure.windowTitle() == "Probe table: exp1" + assert window.ui_table.rowCount() == 2 + assert window.ui_table.columnCount() == 2 + assert window.ui_table.item(1, 0).text() == "lgn"