diff --git a/changelog.d/ITL-1304.md b/changelog.d/ITL-1304.md new file mode 100644 index 000000000..e970e3258 --- /dev/null +++ b/changelog.d/ITL-1304.md @@ -0,0 +1,20 @@ +### Changed + +- The preview tells a plain tag from a data-tag (ITL-1304). A data-tag (one column that is + both a tag and the data column of the same name) is still shown once, among the tags, in + tag order, but with its own mark. In the notebook (HTML) preview the marks compose + (developer, November 21, 2026): a tag's header is bold in the accent colour (as before), + a data column's header is now underlined (at normal weight), and a data-tag's header has + both. The hidden column groups keep their look when shown: system tags are marked as + tags, as before; source-info, context, content-hash and meta (`__`) columns stay + unmarked. In the text preview a data-tag's name starts with `+` (a plain tag's with `*`; + data columns stay unmarked). The legend line names exactly the marks shown (of the + columns Polars renders, when it leaves some out of a wide table): "bold = tag; + underlined = data; bold underlined = data-tag (a tag that is also data)" in a notebook, + "* = tag; + = data-tag (tag and data)" as text, each part only when such a column is + shown. It holds for every view: `head()`, `tail()`, `sort_by_tags()`, `run()`, the + notebook preview and the text form, of a source, a stream, an operator or function pod + result and a job node, loaded jobs included. A `StreamView` has two new fields, + `data_tag_columns` and `data_columns`, taken from the stream's `keys()`. Only the + display is marked: the view's `table`, `as_table()`, the data frames and every schema, + hash and stored form are unchanged. diff --git a/docs/concepts/data-tags.md b/docs/concepts/data-tags.md index 501a24f58..fcb9ea022 100644 --- a/docs/concepts/data-tags.md +++ b/docs/concepts/data-tags.md @@ -37,8 +37,30 @@ not a declared tag is an error. A source built with all its tags plain is exactl source v0.3 built: same columns, same hashes. The column is stored once: `as_table()` shows it once, and every row's tag and data hold -the same value. The notebook preview shows it once, among the tags, marked as a tag -([Working in notebooks](notebooks.md#a-stream-at-the-end-of-a-cell)). +the same value. The preview shows it once, among the tags, marked as a data-tag. In a +notebook the marks compose: a tag's header is bold in an accent colour, a data column's is +underlined, and a data-tag's has both. As text a data-tag's name starts with `+` (a plain +tag's with `*`; a data column's is unmarked). The legend line names the marks shown +([Working in notebooks](notebooks.md#a-stream-at-the-end-of-a-cell)). Only the display is +marked: the view's table and `as_table()` keep the plain names. + +```python +mixed = op.sources.DictSource( + rows, tag_columns=["unit", "time"], tag_only_columns=["time"], source_id="spikes" +) +print(mixed.head()) +# DictSource[spikes] — all 2 rows +# * = tag; + = data-tag (tag and data) +# shape: (2, 3) +# ┌───────┬───────┬──────┐ +# │ +unit ┆ *time ┆ amp │ +# │ --- ┆ --- ┆ --- │ +# │ i64 ┆ i64 ┆ f64 │ +# ╞═══════╪═══════╪══════╡ +# │ 1 ┆ 10 ┆ 0.5 │ +# │ 2 ┆ 20 ┆ 0.25 │ +# └───────┴───────┴──────┘ +``` Data-tags come first among the data columns, in tag order, then the other data columns in their table order. Every stream, operator result and row follows this order, whatever the diff --git a/docs/concepts/notebooks.md b/docs/concepts/notebooks.md index f44532a04..010af6748 100644 --- a/docs/concepts/notebooks.md +++ b/docs/concepts/notebooks.md @@ -70,10 +70,16 @@ What it shows ([Looking at data](streams.md#looking-at-data) states each rule in here `first 10 of 64 rows, sorted by tags`. A source that reads only part of its table says so, as a [SpiralDB source](sources.md) does ("10 rows read, sorted by tags, of about 63,349"). -- **Tag columns** come first and are marked: in a notebook their headers are bold (in an - accent colour), a vertical rule separates them from the data columns and a line under the - header says "bold = tag". A [data-tag](data-tags.md) is one column: the notebook preview - shows it once, among the tags, marked as a tag. +- **Tag columns** come first and are marked, and so are data columns: in a notebook a tag's + header is bold (in an accent colour), a data column's is underlined, a vertical rule + separates the tags from the data columns, and a line under the header names the marks, + "bold = tag; underlined = data". A [data-tag](data-tags.md) is one column, a tag that is + also data: the preview shows it once, among the tags, with both marks (bold, in the + accent colour, and underlined), and the line adds + "bold underlined = data-tag (a tag that is also data)". The line names only the marks + shown: the tags of `units` are all plain. (The pictures were taken before data headers + were underlined.) When `columns` asks for the hidden column groups, system tags are + marked as tags and the source-info, context, content-hash and meta columns are left unmarked. - **Large cells** are summarised (an array as `ndarray float64 (2, 3)`, bytes as `bytes (300 B)`, long text and long lists shortened); `head().table` keeps the full values. @@ -83,8 +89,9 @@ what is held or stored, or make a bounded table read), never call your code (a f predicate, a side effect) and never write to a database. So a job node shown before the job has run has no rows: its header says `not run`, and the table shows its columns only. -In a terminal, `print(stream.head())` prints the same preview as text. There, each tag -column's name starts with `*` ("* = tag"): +In a terminal, `print(stream.head())` prints the same preview as text. There, each plain tag +column's name starts with `*` ("* = tag"), and each data-tag's with `+` +("+ = data-tag (tag and data)"): ```python print(units.head(3)) @@ -112,6 +119,30 @@ print(job.nodes["rates"].head()) # └─────────────┴──────────┴────────┴───────┴─────────┘ ``` +The same table read with `probe` and `unit` as data-tags (only `subject_id` and `session` +kept plain) marks the two kinds of tag apart: + +```python +units_by_probe = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], + tag_only_columns=["subject_id", "session"], + source_id="units", +) +print(units_by_probe.head(2)) +# CSVSource[units] — first 2 of 64 rows +# * = tag; + = data-tag (tag and data) +# shape: (2, 7) +# ┌─────────────┬──────────┬────────┬───────┬────────┬──────────┬──────────┐ +# │ *subject_id ┆ *session ┆ +probe ┆ +unit ┆ region ┆ depth_um ┆ n_spikes │ +# │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ +# │ str ┆ str ┆ str ┆ i64 ┆ str ┆ i64 ┆ i64 │ +# ╞═════════════╪══════════╪════════╪═══════╪════════╪══════════╪══════════╡ +# │ mouse_01 ┆ s1 ┆ imec0 ┆ 0 ┆ V1 ┆ 1580 ┆ 149 │ +# │ mouse_01 ┆ s1 ┆ imec0 ┆ 1 ┆ V1 ┆ 2560 ┆ 326 │ +# └─────────────┴──────────┴────────┴───────┴────────┴──────────┴──────────┘ +``` + (`head()` does not sort, so its header does not say `sorted by tags`; the preview asks for the sorted head.) What each kind of object shows before and after it is computed (a source, a computed stream, a job node, a side-effect node) is the table "What each kind of object diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 0e0eba670..38cdcecf6 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -293,10 +293,16 @@ the stream's results: each row is computed once and every read yields the same r feeds the stream. An upstream finishing its first computation during the read is not a change; a `clear_cache()` upstream between the reads is, and the next read starts again. -The display marks the tag columns, which come first: in a notebook their headers are bold -(in an accent colour), a vertical rule separates them from the data columns and a line under -the header says "bold = tag"; as text, each tag column's name starts with `*` ("* = tag"). -Only the display is marked: the view's table and `as_table()` keep the plain names. +The display marks each column's role, with the tag columns first, in tag order. In a +notebook the marks compose: a tag's header is bold (in an accent colour), a data column's is +underlined, and a [data-tag](data-tags.md), a tag that is also data, has both; a vertical +rule separates the tags from the data columns, and a line under the header names each mark +shown ("bold = tag; underlined = data; bold underlined = data-tag (a tag that is also +data)"). A data-tag is one column, shown once, among the tags. When `columns` asks for the hidden +column groups, system tags are marked as tags, and the source-info, context, +content-hash and meta (`__`) columns are left unmarked. As text, a plain tag's name starts with `*` ("* = tag") and a data-tag's +with `+` ("+ = data-tag (tag and data)"); a data column's is unmarked. Only the display is +marked: the view's table and `as_table()` keep the plain names. In the preview, large cells are summarised (an array as `ndarray float64 (2, 3)`, bytes as `bytes (300 B)`, long text and long lists shortened); `head().table` keeps the full values. diff --git a/src/orcapod/core/streams/view.py b/src/orcapod/core/streams/view.py index 9388afedd..cde4ba5ee 100644 --- a/src/orcapod/core/streams/view.py +++ b/src/orcapod/core/streams/view.py @@ -20,7 +20,7 @@ import dataclasses import html import importlib -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from dataclasses import dataclass from enum import Enum from html.parser import HTMLParser @@ -28,6 +28,7 @@ from typing_extensions import override +from orcapod.system_constants import constants from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: @@ -136,30 +137,54 @@ class ColumnRoleMark: html_style: Inline CSS of the column's header cell in the HTML display. text_legend: The legend line of the text display naming this mark, or empty. html_legend: The legend line of the HTML display naming this mark, or empty. + group: The group of columns the role is shown in: the HTML display draws its + rule between two groups, never between two roles of one group. """ text_prefix: str = "" html_style: str = "" text_legend: str = "" html_legend: str = "" + group: str = "" # The one place that says how the display marks each column role (developer, November 13, -# 2026, ITL-1081). Roles today: "tag" and "data". A new role (e.g. a data-tag) gets -# its own entry here; the renderers need no change. The accent colour has a contrast of -# about 4.3:1 on white and on #111; bold carries the meaning without the colour. +# 2026, ITL-1081; the data-tag, ITL-1304). Roles: "tag" (a plain tag), "data" (a data +# column of the stream), "data-tag" (a tag that is also the data column of the same name, +# shown once, among the tags) and "other" (a column shown that is neither a tag nor a +# data column of the stream: a source-info, context, content-hash or meta column, left +# unmarked; a system-tag column shown is a tag column of the view, marked as a tag). The renderers read +# only this table. In the HTML display the marks compose (developer, November 21, 2026): +# bold in the accent colour means a tag, an underline means data, and a data-tag has both. +# A data header is set to normal weight, since a header cell is bold by default. The accent +# colour has a contrast of about 4.3:1 on white and on #111; bold and the underline carry +# the meaning without the colour. The legend names the marks shown, in this table's order. COLUMN_ROLE_MARKS: dict[str, ColumnRoleMark] = { "tag": ColumnRoleMark( text_prefix="*", html_style="font-weight:bold;color:#2a7fb8", text_legend="* = tag", html_legend="bold = tag", + group="tags", ), - "data": ColumnRoleMark(), + "data": ColumnRoleMark( + html_style="font-weight:normal;text-decoration:underline", + html_legend="underlined = data", + group="data", + ), + "data-tag": ColumnRoleMark( + text_prefix="+", + html_style="font-weight:bold;text-decoration:underline;color:#2a7fb8", + text_legend="+ = data-tag (tag and data)", + html_legend="bold underlined = data-tag (a tag that is also data)", + group="tags", + ), + "other": ColumnRoleMark(group="data"), } -# The HTML display draws this rule after the last column of each role, on every row, so -# the table reads "tags | data". It takes the text colour, so it reads on any theme. +# The HTML display draws this rule after the last column of each group of roles, on every +# row, so the table reads "tags | data". It takes the text colour, so it reads on any +# theme. ROLE_BOUNDARY_STYLE = "border-right:2px solid currentColor" @@ -186,6 +211,11 @@ class StreamView: label: The name shown for it: its label, or for a source given no label its source id (``display_name``). Never used as an identity. tag_columns: The columns of ``table`` that are tags. + data_tag_columns: The columns of ``tag_columns`` that are data-tags: each is also + a data column of the stream (``data_roles_of``). Only the display marks them. + data_columns: The other columns of ``table`` that are data columns of the stream + (``data_roles_of``); any other column (a source-info, context, + content-hash or meta column) is shown unmarked. total_rows: The stream's row count when it is known without computing, else ``None``. For ``PARTIAL``, the number of rows computed so far. total_is_estimate: ``True`` when ``total_rows`` is a recorded estimate. @@ -219,6 +249,8 @@ class StreamView: kind: str label: str tag_columns: tuple[str, ...] = () + data_tag_columns: tuple[str, ...] = () + data_columns: tuple[str, ...] = () total_rows: int | None = None total_is_estimate: bool = False origin: str = "held" @@ -245,13 +277,18 @@ def of_rows( description: str | None = None, display_all_rows: bool = True, ) -> StreamView: - """Return a view with rows of ``stream``.""" + """Return a view with rows of ``stream``; its data-tags and data columns are + ``data_roles_of``.""" + tags = tuple(c for c in tag_columns if c in table.column_names) + data_tags, data = data_roles_of(stream, tags, table.column_names) return cls( table=table, status=status, kind=type(stream).__name__, label=display_name(stream), - tag_columns=tuple(c for c in tag_columns if c in table.column_names), + tag_columns=tags, + data_tag_columns=data_tags, + data_columns=data, total_rows=total_rows, total_is_estimate=total_is_estimate, origin=origin, @@ -270,13 +307,18 @@ def without_rows( tag_columns: tuple[str, ...], note: str | None = None, ) -> StreamView: - """Return a head of ``stream`` with no rows: ``table`` holds its columns only.""" + """Return a head of ``stream`` with no rows: ``table`` holds its columns only; + its data-tags and data columns are ``data_roles_of``.""" + tags = tuple(c for c in tag_columns if c in table.column_names) + data_tags, data = data_roles_of(stream, tags, table.column_names) return cls( table=table.slice(0, 0), status=status, kind=type(stream).__name__, label=display_name(stream), - tag_columns=tuple(c for c in tag_columns if c in table.column_names), + tag_columns=tags, + data_tag_columns=data_tags, + data_columns=data, note=note, ) @@ -492,20 +534,32 @@ def _describe_rows(self, shown: int) -> str: return f"first {shown:,} of {total:,} {noun}{suffix}" def _display_columns(self) -> list[tuple[str, str]]: - """Return the shown columns in display order, each with its role: tags first.""" + """Return the shown columns in display order, each with its role: the tags first, + in tag order, each a ``"data-tag"`` or a plain ``"tag"``, then the other columns + in table order, each ``"data"`` or ``"other"``. A data-tag is one column and is + shown once, among the tags.""" tags = [c for c in self.tag_columns if c in self.table.column_names] - return [(c, "tag") for c in tags] + [ - (c, "data") for c in self.table.column_names if c not in self.tag_columns + return [ + (c, "data-tag" if c in self.data_tag_columns else "tag") for c in tags + ] + [ + (c, "data" if c in self.data_columns else "other") + for c in self.table.column_names + if c not in self.tag_columns ] - def _legend(self, text: bool) -> str: - """Return the legend line of the marks the shown columns carry, or empty.""" - roles = dict.fromkeys(role for _, role in self._display_columns()) + def _legend(self, text: bool, roles: Iterable[str]) -> str: + """Return the legend line of the marks of ``roles``, the roles of the columns a + display rendered, in the order of ``COLUMN_ROLE_MARKS``, or empty. + + Args: + text: Whether the legend is the text display's (else the HTML display's). + roles: The role of each rendered column. + """ + shown = set(roles) legends = [ - COLUMN_ROLE_MARKS[role].text_legend - if text - else COLUMN_ROLE_MARKS[role].html_legend - for role in roles + mark.text_legend if text else mark.html_legend + for role, mark in COLUMN_ROLE_MARKS.items() + if role in shown ] return "; ".join(legend for legend in legends if legend) @@ -566,33 +620,62 @@ def _display_rows(self) -> int: def _repr_html_(self) -> str: """Return the notebook preview: header, legend and the rows (large cells - summarised), each column's header styled by its role (``COLUMN_ROLE_MARKS``).""" + summarised), each rendered column's header styled by its role + (``COLUMN_ROLE_MARKS``). The legend names the marks of the columns Polars + rendered (``_rendered_columns``): none when the header cannot be matched, since + no cell is then marked, and none when Polars renders no column.""" parts = [ f"
{html.escape(self.header(), quote=False)}
" ] - legend = self._legend(text=False) - if legend: - parts.append( - f"
{html.escape(legend, quote=False)}
" - ) + table_html = "" + roles: list[str] = [] if self.table.num_columns: # Polars shortens strings to its own default length; show up to _MAX_TEXT. with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): frame_html = self._display_frame()._repr_html_() - roles = [role for _, role in self._display_columns()] - parts.append(_mark_columns(frame_html, roles)) + columns = self._display_columns() + names = _HeaderNames() + names.feed(frame_html) + names.close() + rendered = _rendered_columns(names.cells, [name for name, _ in columns]) + table_html = _mark_columns(frame_html, columns, rendered) + if rendered is not None: + roles = [columns[i][1] for i in rendered if i is not None] + legend = self._legend(text=False, roles=roles) + if legend: + parts.append( + f"
{html.escape(legend, quote=False)}
" + ) + if table_html: + parts.append(table_html) return "\n".join(parts) def __str__(self) -> str: """Return the preview as text: header, legend and the rows, each column's - header prefixed by its role's mark (``*`` for a tag).""" + header prefixed by its role's mark (``*`` for a plain tag, ``+`` for a + data-tag). The legend names the marks of the columns Polars rendered + (``_rendered_columns``); when its header cannot be read, of every column.""" lines = [self.header()] - legend = self._legend(text=True) - if legend: - lines.append(legend) + frame_text = "" + roles: list[str] = [] if self.table.num_columns: with pl.Config(fmt_str_lengths=_MAX_TEXT, tbl_rows=self._display_rows()): - lines.append(str(self._display_frame(text=True))) + frame = self._display_frame(text=True) + frame_text = str(frame) + columns = self._display_columns() + rendered = _rendered_columns(_text_header_cells(frame_text), frame.columns) + if rendered is not None: + roles = [columns[i][1] for i in rendered if i is not None] + else: + # A header that cannot be read (a name Polars wraps over two lines, + # another table style): the marks are part of the names, so every + # column's role is named. + roles = [role for _, role in columns] + legend = self._legend(text=True, roles=roles) + if legend: + lines.append(legend) + if frame_text: + lines.append(frame_text) return "\n".join(lines) def __repr__(self) -> str: @@ -603,29 +686,129 @@ def __repr__(self) -> str: ) -def _mark_columns(frame_html: str, roles: Sequence[str]) -> str: +def _mark_columns( + frame_html: str, + columns: Sequence[tuple[str, str]], + rendered: Sequence[int | None] | None, +) -> str: """Return Polars' HTML table ``frame_html`` with its columns styled by role. - The cells are found by position, never by name, so a name that HTML escapes is - handled as Polars wrote it. The header cell of a column gets its role's - ``html_style``; every cell of the last column of a role followed by another role gets - ``ROLE_BOUNDARY_STYLE``. Everything else is passed on unchanged. + Polars may leave columns out of a wide table, showing the first and the last ones + around an ellipsis cell, so each rendered header cell is styled by the column + ``rendered`` matched it to by name (``_rendered_columns``), never by its position + among all the columns. The header cell of a column gets its role's ``html_style``; + every cell of the last column of a group of roles followed by another group gets + ``ROLE_BOUNDARY_STYLE`` (the ellipsis cell's when the boundary is among the columns + left out). The ellipsis cell gets no mark, and a header that could not be matched + leaves every cell unmarked: no mark is better than a wrong one. Everything else is + passed on unchanged. Args: - frame_html: The HTML of the display frame, one column per entry of ``roles``. - roles: The role of each column, in display order. + frame_html: The HTML of the display frame, one column per entry of ``columns``. + columns: The name and the role of each column, in display order. + rendered: For each rendered header cell, the index of its column in + ``columns``, or ``None`` for the ellipsis cell; ``None`` when the cells + could not be matched (``_rendered_columns``). """ - header = [COLUMN_ROLE_MARKS[role].html_style for role in roles] - boundary = [ - ROLE_BOUNDARY_STYLE if i + 1 < len(roles) and roles[i + 1] != roles[i] else "" - for i in range(len(roles)) + cells = [] if rendered is None else list(rendered) + roles = [role for _, role in columns] + header = [ + "" if column is None else COLUMN_ROLE_MARKS[roles[column]].html_style + for column in cells ] + boundary = [""] * len(cells) + groups = [COLUMN_ROLE_MARKS[role].group for role in roles] + if cells and any(column is not None for column in cells): + for last in range(len(groups) - 1): + if groups[last] != groups[last + 1]: + # The cell showing the last column of the group, or the ellipsis cell + # when that column is left out. + shown = [i for i, column in enumerate(cells) if column == last] + if not shown: + shown = [i for i, column in enumerate(cells) if column is None] + for i in shown: + boundary[i] = ROLE_BOUNDARY_STYLE marker = _ColumnMarker(header, boundary) marker.feed(frame_html) marker.close() return "".join(marker.out) +_ELLIPSIS = "…" + + +def _rendered_columns( + cells: Sequence[str], names: Sequence[str] +) -> list[int | None] | None: + """Return, for each rendered header cell, the index of its column in ``names``, or + ``None`` for the ellipsis cell; ``None`` instead of the list when the cells cannot be + matched to the columns. + + Polars renders either every column, or a first run and a last run of them around one + ellipsis cell; the match is checked by name on both sides of the ellipsis. The one + reading of which columns a display rendered: the HTML display's header marks and + legend, and the text display's legend, all use it. + + Args: + cells: The text of each cell of the first header row, as rendered. + names: The names of the columns of the display frame, in order. + """ + if list(cells) == list(names): + return list(range(len(names))) + left_out = len(names) - (len(cells) - 1) + if left_out > 0: + for i, cell in enumerate(cells): + if ( + cell == _ELLIPSIS + and list(cells[:i]) == list(names[:i]) + and list(cells[i + 1 :]) == list(names[i + left_out :]) + ): + return [*range(i), None, *range(i + left_out, len(names))] + return None + + +def _text_header_cells(frame_text: str) -> list[str]: + """Return the text of each cell of the first header line of Polars' text table, or + no cell when the table has no such line.""" + for line in frame_text.splitlines(): + if line.startswith("│"): + return [cell.strip() for cell in line.strip().strip("│").split("┆")] + return [] + + +class _HeaderNames(HTMLParser): + """Collects the text of each cell of the first header row of an HTML table.""" + + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.cells: list[str] = [] + self._rows: int = 0 + self._in_thead: bool = False + self._cell: list[str] | None = None + + @override + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag == "thead": + self._in_thead = True + elif tag == "tr" and self._in_thead: + self._rows += 1 + elif tag in ("th", "td") and self._in_thead and self._rows == 1: + self._cell = [] + + @override + def handle_endtag(self, tag: str) -> None: + if tag == "thead": + self._in_thead = False + elif tag in ("th", "td") and self._cell is not None: + self.cells.append("".join(self._cell)) + self._cell = None + + @override + def handle_data(self, data: str) -> None: + if self._cell is not None: + self._cell.append(data) + + class _ColumnMarker(HTMLParser): """Copies Polars' HTML table, adding inline styles to cells by column position.""" @@ -735,6 +918,44 @@ def display_name(stream: Any) -> str: return name +def data_roles_of( + stream: Any, tag_columns: Sequence[str], column_names: Sequence[str] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return which shown columns of ``stream`` are data-tags and which are data columns. + + The roles are read from the stream's public ``keys()``: a data-tag is one column in + both roles, a name among both its tag and its data keys; a data column is a name + among its data keys that is not a tag and not a meta column (``META_PREFIX``): a raw + ``ArrowTableStream`` lists its meta columns among its data keys, and a meta column + is shown unmarked. A view that shows columns has its stream's + schema already, so reading the keys computes, reads and polls nothing; a view with no + column (one whose schema would need a poll, ``schema_requires_io``) does not read + them. + + Args: + stream: The stream, source or node whose view is built. + tag_columns: The tag columns the view shows, in display order. + column_names: Every column the view shows, in table order. + + Returns: + The data-tags, in the order of ``tag_columns``, and the data columns, in the + order of ``column_names``. + """ + if not column_names: + return (), () + tags, data = stream.keys() + data_names = set(data) + data_tags = tuple(c for c in tag_columns if c in data_names and c in set(tags)) + data_columns = tuple( + c + for c in column_names + if c in data_names + and c not in tag_columns + and not c.startswith(constants.META_PREFIX) + ) + return data_tags, data_columns + + def preview_html(stream: Any) -> str: """Return the notebook preview of ``stream``: its head with the rows in tag order. @@ -759,8 +980,9 @@ def head_of( """Return ``head`` (another stream's) shown as ``stream``. A ``StreamView`` keeps every field. Any other result of ``head`` (a - ``StreamViewProtocol``) is adapted from what that protocol gives: its rows, status - and total. + ``StreamViewProtocol``) is adapted from what that protocol gives (its rows, status + and total), with the columns' roles read from ``stream``'s ``keys()``, as every other + view gets them (``data_roles_of``). Args: head: What another stream's ``head`` returned. @@ -769,11 +991,19 @@ def head_of( note: Another note, if given. """ if not isinstance(head, StreamView): + table: pa.Table = head.table + names = table.column_names + # A table with no column needs no keys (``data_roles_of``). + tags = tuple(c for c in stream.keys()[0] if c in names) if names else () + data_tags, data = data_roles_of(stream, tags, names) head = StreamView( - table=head.table, + table=table, status=ViewStatus(head.status), kind=type(stream).__name__, label=display_name(stream), + tag_columns=tags, + data_tag_columns=data_tags, + data_columns=data, total_rows=head.total_rows, ) return head.for_stream(stream, origin=origin, note=note) diff --git a/tests/test_core/streams/test_data_tag_preview.py b/tests/test_core/streams/test_data_tag_preview.py new file mode 100644 index 000000000..c733fba64 --- /dev/null +++ b/tests/test_core/streams/test_data_tag_preview.py @@ -0,0 +1,954 @@ +"""The preview tells a plain tag from a data-tag (ITL-1304). + +A data-tag is one column in both roles: a tag and the data column of the same name. Every +view of a stream knows which of its tag columns are data-tags (``data_tag_columns``, +taken from the stream's public ``keys()``), however the view is built, and only the +display marks them: never ``StreamView.table``, ``as_table()``, ``as_polars_df()`` or a +schema. Building such a view computes nothing, calls no user code and writes nothing. + +The streams here have two plain tags (``session``, ``trial``), two data-tags (``unit``, +``time``) and two data columns (``amp``, ``label``), in several tag orders and table +layouts. +""" + +from __future__ import annotations + +import csv +from html.parser import HTMLParser +from pathlib import Path +from typing import Any +from unittest import mock + +import pyarrow as pa +import pytest + +from orcapod import function_pod +from orcapod.core.operators import Join, SelectDataColumns +from orcapod.core.sources import CSVSource, DerivedSource, DictSource +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.job import PipelineJob +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.side_effects import SideEffectPod +from orcapod.streams import StreamView, ViewStatus + +PLAIN = ("session", "trial") +DATA_TAGS = ("unit", "time") +DATA = ("amp", "label") + +ROWS = [ + {"session": "s2", "unit": 5, "trial": 2, "time": 31, "amp": 0.125, "label": "n"}, + {"session": "s1", "unit": 3, "trial": 1, "time": 10, "amp": 0.5, "label": "s"}, + {"session": "s2", "unit": 3, "trial": 2, "time": 20, "amp": 0.75, "label": "s"}, + {"session": "s1", "unit": 4, "trial": 1, "time": 12, "amp": 0.25, "label": "b"}, +] + +# Tag orders: plain and data-tags interleaved, data-tags first, and reversed. +TAG_ORDERS = { + "interleaved": ("session", "unit", "trial", "time"), + "data_tags_first": ("time", "unit", "trial", "session"), + "plain_first": ("trial", "session", "unit", "time"), +} +# Table layouts: data before tags, and tags in another order than declared. +LAYOUTS = { + "data_first": ("label", "amp", "time", "trial", "unit", "session"), + "tags_first": ("unit", "session", "time", "trial", "amp", "label"), +} + +ORCHESTRATORS = { + "sync": SyncPipelineOrchestrator, + "async": AsyncPipelineOrchestrator, +} + +CALLS: list[float] = [] + + +@pytest.fixture(autouse=True) +def _reset_calls() -> None: + """Clear the record of function calls before each test.""" + CALLS.clear() + + +@function_pod(output_keys="scaled") +def scale(amp: float) -> float: + """Double ``amp``, recording the call.""" + CALLS.append(amp) + return 2 * amp + + +def _rows(layout: tuple[str, ...]) -> list[dict[str, Any]]: + return [{name: row[name] for name in layout} for row in ROWS] + + +def _source( + tag_order: tuple[str, ...] = TAG_ORDERS["interleaved"], + layout: tuple[str, ...] = LAYOUTS["data_first"], + plain: tuple[str, ...] = PLAIN, +) -> DictSource: + """Four rows with two plain tags, two data-tags and two data columns.""" + return DictSource( + _rows(layout), + tag_columns=list(tag_order), + tag_only_columns=list(plain), + source_id="spikes", + label="spikes", + ) + + +def _expected(tag_order: tuple[str, ...]) -> tuple[str, ...]: + """The data-tags of ``_source(tag_order)``, in tag order.""" + return tuple(c for c in tag_order if c in DATA_TAGS) + + +def _data_tags_of(stream: Any) -> tuple[str, ...]: + """The data-tags ``stream`` declares, in its own tag order; both of ``DATA_TAGS``.""" + tags, data = stream.keys() + found = tuple(c for c in tags if c in data) + assert sorted(found) == sorted(DATA_TAGS) + return found + + +def _in_view_order(view: StreamView) -> tuple[str, ...]: + """``DATA_TAGS`` in the order ``view`` shows its tags (which column order a view + shows is ITL-1305); checks the view shows both.""" + found = tuple(c for c in view.tag_columns if c in DATA_TAGS) + assert sorted(found) == sorted(DATA_TAGS) + return found + + +def _view(view: object) -> StreamView: + """``view`` as the ``StreamView`` every stream's ``head`` and ``run`` return.""" + assert isinstance(view, StreamView) + return view + + +def _views(view: object) -> dict[str, StreamView]: + """Every view a view builds of its own rows, and views of those views.""" + view = _view(view) + return { + "view": view, + "head": view.head(2), + "tail": view.tail(2), + "sorted": view.sort_by_tags(), + "head_of_tail": view.tail(3).head(1), + "sorted_head": view.head(3).sort_by_tags(), + } + + +# --------------------------------------------------------------------------- +# Every way a view is built knows the data-tags +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +@pytest.mark.parametrize("tag_order", list(TAG_ORDERS)) +def test_every_view_of_a_source_knows_its_data_tags( + tag_order: str, layout: str +) -> None: + """head, run and the view's own head, tail and sort all carry the data-tags.""" + source = _source(TAG_ORDERS[tag_order], LAYOUTS[layout]) + expected = _expected(TAG_ORDERS[tag_order]) + for built in ( + source.head(), + source.head(3), + source.head(columns={"sort_by_tags": True}), + source.run(), + ): + for name, view in _views(built).items(): + assert view.tag_columns == TAG_ORDERS[tag_order], name + assert view.data_tag_columns == expected, name + + +def test_a_raw_stream_view_knows_its_data_tags() -> None: + """A raw ``ArrowTableStream`` with ``data_tags`` marks exactly those.""" + table = pa.Table.from_pylist(_rows(LAYOUTS["tags_first"])) + for data_tags in (("unit", "time"), ("time", "unit")): + stream = ArrowTableStream( + table, tag_columns=list(TAG_ORDERS["interleaved"]), data_tags=data_tags + ) + assert stream.head().data_tag_columns == ("unit", "time") + assert stream.run().tail(1).data_tag_columns == ("unit", "time") + plain = ArrowTableStream(table, tag_columns=list(TAG_ORDERS["interleaved"])) + assert plain.head().data_tag_columns == () + + +def test_only_plain_tags_and_only_data_tags() -> None: + """All tags plain: no data-tag; no tag plain: every tag is a data-tag.""" + all_plain = _source(plain=PLAIN + DATA_TAGS) + assert all_plain.head().data_tag_columns == () + assert all_plain.run().sort_by_tags().data_tag_columns == () + none_plain = _source(plain=()) + assert none_plain.head().data_tag_columns == TAG_ORDERS["interleaved"] + assert none_plain.run().tail(2).data_tag_columns == TAG_ORDERS["interleaved"] + + +@pytest.mark.parametrize("tag_order", list(TAG_ORDERS)) +def test_operator_results_know_their_data_tags(tag_order: str) -> None: + """An operator's result, before and after it is computed, carries its data-tags, + for one input and for two inputs in both orders.""" + source = _source(TAG_ORDERS[tag_order]) + expected = _expected(TAG_ORDERS[tag_order]) + other = DictSource( + [{"trial": r["trial"], "session": r["session"], "w": 1.0} for r in ROWS[:2]], + tag_columns=["trial", "session"], + tag_only_columns=True, + source_id="other", + ) + for stream in ( + source.drop_data_columns(["label"]), + source.select_data_columns(["amp", "unit", "time"]), + Join()(source, other), + Join()(other, source), + ): + tags = stream.keys()[0] + expect = tuple(c for c in tags if c in expected) + assert stream.head().status is ViewStatus.NOT_COMPUTED + assert stream.head().data_tag_columns == expect + for name, view in _views(stream.run()).items(): + assert view.data_tag_columns == expect, name + + +def test_dropping_the_data_role_leaves_a_plain_tag() -> None: + """A data-tag whose data role is dropped is shown as a plain tag.""" + source = _source() + with pytest.warns(Warning, match="data-tag"): + stream = source.drop_data_columns(["time"]) + assert stream.run().data_tag_columns == ("unit",) + assert source.drop_tag_columns(["unit"]).run().data_tag_columns == ("time",) + + +def test_function_pod_results_know_their_data_tags() -> None: + """``pod(stream)`` lets data-tags fall through, and the view says so; + ``pod.process`` makes every output tag plain.""" + source = _source() + stream = scale.pod(source) + # The data-tags in the stream's own tag order (which column order a stream shows + # is ITL-1305). + expected = tuple(c for c in stream.keys()[0] if c in DATA_TAGS) + assert sorted(expected) == sorted(DATA_TAGS) + head = _view(stream.head()) + assert CALLS == [] + assert head.status is ViewStatus.NOT_COMPUTED + assert head.data_tag_columns == expected + for name, view in _views(stream.run()).items(): + assert view.data_tag_columns == expected, name + with pytest.warns(Warning, match="data-tag"): + selected = source.select_data_columns(["amp"]) + exact = scale.pod.process(selected) + assert _view(exact.run()).data_tag_columns == () + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_job_nodes_know_their_data_tags(orchestrator: str) -> None: + """Function and operator job nodes, before and after a run on either + orchestrator, and their stored view.""" + job = PipelineJob(name="itl1304", database=InMemoryArrowDatabase()) + with job: + scaled = scale.pod(_source(), label="scaled") + _ = SelectDataColumns(["unit", "time", "scaled"])(scaled, label="sel") + for label in ("scaled", "sel"): + head = job.nodes[label].head() + assert head.status is ViewStatus.NOT_COMPUTED + assert head.data_tag_columns == _data_tags_of(job.nodes[label]), label + assert CALLS == [] + _ = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + for label in ("scaled", "sel"): + node = job.nodes[label] + for name, view in _views(node.head()).items(): + assert view.data_tag_columns == _in_view_order(view), (label, name) + view = node.run() + assert view.data_tag_columns == _in_view_order(view), label + stored = job.nodes["scaled"].as_source() + assert stored.head().data_tag_columns == _data_tags_of(stored) + + +def test_a_loaded_job_knows_its_data_tags(tmp_path: Path) -> None: + """A loaded job's nodes, before and after a load-only run, and their stored view.""" + path = tmp_path / "spikes.csv" + with path.open("w", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=list(LAYOUTS["data_first"])) + writer.writeheader() + writer.writerows(_rows(LAYOUTS["data_first"])) + source = CSVSource( + str(path), + tag_columns=list(TAG_ORDERS["interleaved"]), + tag_only_columns=list(PLAIN), + source_id="spikes", + ) + job = PipelineJob(name="itl1304", database=DeltaTableDatabase(tmp_path / "store")) + with job: + _ = scale.pod(source, label="scaled") + _ = job.run() + saved = tmp_path / "job.json" + job.save(saved) + CALLS.clear() + + loaded = PipelineJob.load(str(saved)) + node = loaded.nodes["scaled"] + assert node.head().status is ViewStatus.NOT_COMPUTED + assert node.head().data_tag_columns == _data_tags_of(node) + stored = node.as_source().head() + assert stored.data_tag_columns == _in_view_order(stored) + _ = loaded.run(load_only=True) + assert CALLS == [] + for name, view in _views(node.head()).items(): + assert view.status is ViewStatus.LOADED_ONLY, name + assert view.data_tag_columns == _in_view_order(view), name + + +def test_a_derived_source_view_knows_its_data_tags() -> None: + """A derived source over a computed stream keeps the data-tags its keys name.""" + job = PipelineJob(name="itl1304", database=InMemoryArrowDatabase()) + with job: + _ = scale.pod(_source(), label="scaled") + _ = job.run() + derived = job.nodes["scaled"].as_source() + assert isinstance(derived, DerivedSource) + expected = _data_tags_of(derived) + assert derived.run().data_tag_columns == expected + assert derived.head().tail(1).data_tag_columns == expected + + +# --------------------------------------------------------------------------- +# Showing a stream with data-tags computes nothing (ITL-991) +# --------------------------------------------------------------------------- + + +def test_preview_of_a_function_pod_with_data_tags_calls_no_function() -> None: + """Neither head, the preview nor the text form calls the function.""" + stream: Any = scale.pod(_source()) + _ = stream.head() + _ = stream._repr_html_() + _ = str(stream.head()) + assert CALLS == [] + + +def test_preview_of_an_operator_with_data_tags_runs_no_operator() -> None: + """The preview of a join over data-tags never runs the join over rows.""" + other = DictSource( + [{"trial": 1, "session": "s1", "w": 1.0}], + tag_columns=["trial", "session"], + tag_only_columns=True, + source_id="other", + ) + stream = Join()(_source(), other) + original = Join.static_process + with mock.patch.object( + Join, "static_process", autospec=True, side_effect=original + ) as spy: + head = stream.head() + _ = stream._repr_html_() + _ = str(head) + over_rows = sum( + any(s.as_table().num_rows for s in call.args[1:]) + for call in spy.call_args_list + ) + assert over_rows == 0 + assert head.data_tag_columns == _in_view_order(head) + + +def test_preview_of_a_side_effect_with_data_tags_delivers_nothing() -> None: + """Showing a side-effect stream over data-tags delivers nothing.""" + delivered: list[float] = [] + + def deliver(amp: float) -> None: + """Record a delivery.""" + delivered.append(amp) + + # The side effect reads amp only; the data-tags stay tags (plain ones here). + with pytest.warns(Warning, match="data-tag"): + selected = _source().select_data_columns(["amp"]) + stream = SideEffectPod(deliver)(selected) + _ = stream.head() + _ = stream._repr_html_() + assert delivered == [] + + +def test_job_preview_with_data_tags_writes_nothing() -> None: + """Showing the nodes of a job that has not run writes nothing to its database.""" + store = InMemoryArrowDatabase() + job = PipelineJob(name="itl1304", database=store) + with job: + _ = scale.pod(_source(), label="scaled") + with ( + mock.patch.object( + InMemoryArrowDatabase, "add_records", side_effect=AssertionError("write") + ), + mock.patch.object( + InMemoryArrowDatabase, "add_record", side_effect=AssertionError("write") + ), + ): + _ = job.nodes["scaled"]._repr_html_() + _ = str(job.nodes["scaled"].head()) + assert CALLS == [] + + +# --------------------------------------------------------------------------- +# Only the display is marked +# --------------------------------------------------------------------------- + + +def test_only_the_display_is_marked() -> None: + """The view's table, as_table and the data frames carry no mark.""" + source = _source() + view = source.run() + names = list(source.as_table().column_names) + assert view.table.column_names == names + assert view.as_table().column_names == names + assert list(view.as_polars_df().columns) == names + assert source.keys() == ( + TAG_ORDERS["interleaved"], + ("unit", "time", "label", "amp"), + ) + + +class _Cells(HTMLParser): + """Collects every table row of an HTML display: each cell's text and style.""" + + def __init__(self) -> None: + super().__init__() + self.rows: list[list[tuple[str, str]]] = [] + self._cell: list[str] | None = None + self._style = "" + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag == "tr": + self.rows.append([]) + elif tag in ("th", "td"): + self._cell = [] + self._style = dict(attrs).get("style") or "" + + def handle_endtag(self, tag: str) -> None: + if tag in ("th", "td") and self._cell is not None: + self.rows[-1].append(("".join(self._cell), self._style)) + self._cell = None + + def handle_data(self, data: str) -> None: + if self._cell is not None: + self._cell.append(data) + + +def _cells(html_text: str) -> list[list[tuple[str, str]]]: + parser = _Cells() + parser.feed(html_text) + return parser.rows + + +BOLD = "font-weight:bold" +ACCENT = "color:#2a7fb8" +UNDERLINE = "text-decoration:underline" +TEXT_LEGEND = {"tag": "* = tag", "data-tag": "+ = data-tag (tag and data)"} +HTML_LEGEND = { + "tag": "bold = tag", + "data": "underlined = data", + "data-tag": "bold underlined = data-tag (a tag that is also data)", +} + + +def _check_display(shown: object) -> None: + """Both displays of ``shown`` (a view of the default columns) mark each plain tag, + each data-tag and each data column, with one rule after the tags, and a legend + naming exactly the marks shown: bold in the accent colour for a tag, an underline + for data, both for a data-tag.""" + view = _view(shown) + data_tags = set(view.data_tag_columns) + plain = [c for c in view.tag_columns if c not in data_tags] + others = [c for c in view.table.column_names if c not in view.tag_columns] + # A view of the default columns shows user columns only: every other one is data. + assert list(view.data_columns) == others + roles = [ + *(["tag"] if plain else []), + *(["data"] if others else []), + *(["data-tag"] if data_tags else []), + ] + + html_text = view._repr_html_() + legend = "; ".join(HTML_LEGEND[role] for role in roles) + if legend: + assert f"{legend}" in html_text + if view.table.num_columns: + rows = _cells(html_text) + header = rows[0] + assert [name for name, _ in header] == [*view.tag_columns, *others] + for name, style in header: + if name in data_tags: + assert BOLD in style and ACCENT in style and UNDERLINE in style, name + elif name in view.tag_columns: + assert BOLD in style and ACCENT in style, name + assert UNDERLINE not in style, name + else: + assert "font-weight:normal" in style and UNDERLINE in style, name + assert ACCENT not in style, name + # Only the first header row is marked: the type row and the rows of values + # carry no mark. + for row in rows[1:]: + assert all(UNDERLINE not in s and BOLD not in s for _, s in row) + if view.tag_columns and others: + for row in rows: + ruled = [i for i, (_, s) in enumerate(row) if "border-right" in s] + assert ruled == [len(view.tag_columns) - 1] + + lines = str(view).split("\n") + text_legend = "; ".join(TEXT_LEGEND[role] for role in roles if role in TEXT_LEGEND) + if text_legend: + assert lines[1] == text_legend + else: + assert "= tag" not in str(view) + if view.table.num_columns: + names_line = next(line for line in lines if line.startswith("│")) + names = [cell.strip() for cell in names_line.strip("│").split("┆")] + assert names == [ + *(("+" if c in data_tags else "*") + c for c in view.tag_columns), + *others, + ] + + +# --------------------------------------------------------------------------- +# The marks: a plain tag, a data-tag and a data column +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +@pytest.mark.parametrize("tag_order", list(TAG_ORDERS)) +def test_both_displays_mark_plain_tags_and_data_tags( + tag_order: str, layout: str +) -> None: + """Two plain tags, two data-tags and two data columns, in several tag orders and + table layouts: every view's displays mark each role and say so.""" + source = _source(TAG_ORDERS[tag_order], LAYOUTS[layout]) + for built in (source.head(), source.run()): + for name, view in _views(built).items(): + assert set(view.data_tag_columns) == set(DATA_TAGS), name + _check_display(view) + + +def test_the_marks_of_a_known_stream() -> None: + """The exact header styles, text names and legends of one stream: tags in tag order + (plain and data-tags interleaved), then two data columns.""" + view = _source(TAG_ORDERS["interleaved"], LAYOUTS["tags_first"]).run() + header = _cells(view._repr_html_())[0] + assert header == [ + ("session", "font-weight:bold;color:#2a7fb8"), + ("unit", "font-weight:bold;text-decoration:underline;color:#2a7fb8"), + ("trial", "font-weight:bold;color:#2a7fb8"), + ( + "time", + "font-weight:bold;text-decoration:underline;color:#2a7fb8;" + "border-right:2px solid currentColor", + ), + ("amp", "font-weight:normal;text-decoration:underline"), + ("label", "font-weight:normal;text-decoration:underline"), + ] + assert ( + "bold = tag; underlined = data; " + "bold underlined = data-tag (a tag that is also data)" + ) in view._repr_html_() + text = str(view) + assert text.split("\n")[1] == "* = tag; + = data-tag (tag and data)" + assert "*session ┆ +unit ┆ *trial ┆ +time ┆ amp" in text + # The legend's order is the marks' order, whatever the first column's role. + first = _source(TAG_ORDERS["data_tags_first"]).run() + assert str(first).split("\n")[1] == "* = tag; + = data-tag (tag and data)" + assert ( + "bold = tag; underlined = data; bold underlined = data-tag" + in first._repr_html_() + ) + + +def test_a_stream_with_only_plain_tags_shows_no_data_tag_mark() -> None: + """No data-tag: no header is both bold and underlined, and the legend names the + tag and data marks only.""" + view = _source(plain=PLAIN + DATA_TAGS).run() + _check_display(view) + assert all( + not ("font-weight:bold" in s and UNDERLINE in s) + for _, s in _cells(view._repr_html_())[0] + ) + assert "bold = tag; underlined = data" in view._repr_html_() + assert "data-tag" not in view._repr_html_() + assert str(view).split("\n")[1] == "* = tag" + + +def test_a_stream_with_only_data_tags_shows_no_plain_tag_mark() -> None: + """Every tag a data-tag: the legend names the data and data-tag marks only; with + no other data column, the data-tag mark only.""" + view = _source(plain=()).run() + _check_display(view) + assert "underlined = data; bold underlined = data-tag" in view._repr_html_() + assert str(view).split("\n")[1] == "+ = data-tag (tag and data)" + only = ( + _source(plain=()) + .select_data_columns(["session", "unit", "trial", "time"]) + .run() + ) + _check_display(only) + assert only.data_columns == () + assert ( + "bold underlined = data-tag (a tag that is also data)" + in only._repr_html_() + ) + + +def test_a_stream_without_tags_marks_its_data_only() -> None: + """No tag: every column is underlined and the legend names the data mark only.""" + view = ArrowTableStream(pa.table({"amp": [0.5, 0.25], "label": ["s", "b"]})).run() + _check_display(view) + assert "underlined = data" in view._repr_html_() + assert "= tag" not in str(view) + + +def test_hidden_column_groups_keep_their_look() -> None: + """With every column group shown, only the user data columns are underlined: + system-tag columns keep the tag mark they had (they are tag columns of the view), + and source-info, context and content-hash columns stay unmarked.""" + source = _source(TAG_ORDERS["interleaved"], LAYOUTS["data_first"]) + computed = scale.pod(source) + _ = computed.run() + for head in ( + _view(source.head(all_info=True)), + _view(computed.head(all_info=True)), + ): + user_tags = [c for c in head.tag_columns if not c.startswith("_")] + system_tags = [c for c in head.tag_columns if c.startswith("_tag")] + unmarked = [ + c + for c in head.table.column_names + if c not in head.tag_columns and c not in head.data_columns + ] + assert sorted(head.data_tag_columns) == sorted(DATA_TAGS) + assert len(system_tags) == 2 + assert any(c.startswith("_source_") for c in unmarked) + assert "_context_key" in unmarked + assert all(c.startswith("_") for c in unmarked) + assert not any(c.startswith("_") for c in head.data_columns) + header = dict(_cells(head._repr_html_())[0]) + for name in system_tags: + assert header[name].startswith("font-weight:bold;color:#2a7fb8"), name + assert UNDERLINE not in header[name], name + for name in user_tags: + assert BOLD in header[name], name + for name in head.data_columns: + assert header[name] == "font-weight:normal;text-decoration:underline" + for name in unmarked: + assert header[name] == "", name + # The rule still follows the last tag. + ruled = [name for name, style in header.items() if "border-right" in style] + assert ruled == [head.tag_columns[-1]] + + +def test_every_kind_of_stream_shows_the_marks() -> None: + """A raw stream, operator results, a function pod result and the preview.""" + source = _source() + other = DictSource( + [{"trial": r["trial"], "session": r["session"], "w": 1.0} for r in ROWS[:2]], + tag_columns=["trial", "session"], + tag_only_columns=True, + source_id="other", + ) + raw = ArrowTableStream( + pa.Table.from_pylist(_rows(LAYOUTS["data_first"])), + tag_columns=list(TAG_ORDERS["data_tags_first"]), + data_tags=["unit", "time"], + ) + streams: tuple[Any, ...] = ( + raw, + source.drop_data_columns(["label"]), + Join()(source, other), + Join()(other, source), + scale.pod(source), + ) + for stream in streams: + _check_display(stream.head()) + _check_display(stream.run()) + _check_display(stream.run().tail(2).sort_by_tags()) + preview = stream._repr_html_() + assert HTML_LEGEND["data-tag"] in preview + assert HTML_LEGEND["data"] in preview + + +@pytest.mark.parametrize("orchestrator", list(ORCHESTRATORS)) +def test_job_nodes_show_the_marks(orchestrator: str) -> None: + """A job's function and operator nodes, before and after a run, and their + stored view, show the marks.""" + job = PipelineJob(name="itl1304", database=InMemoryArrowDatabase()) + with job: + scaled = scale.pod(_source(), label="scaled") + _ = SelectDataColumns(["unit", "time", "scaled"])(scaled, label="sel") + for label in ("scaled", "sel"): + _check_display(job.nodes[label].head()) + _ = job.run(orchestrator=ORCHESTRATORS[orchestrator]()) + for label in ("scaled", "sel"): + node = job.nodes[label] + _check_display(node.head()) + _check_display(node.run()) + assert HTML_LEGEND["data-tag"] in node._repr_html_() + _check_display(job.nodes["scaled"].as_source().head()) + # Only the run called the function, once per row. + assert len(CALLS) == len(ROWS) + + +RAW_LAYOUTS = { + "meta_between": ("x", "__debug", "a", "y", "b", "__note"), + "meta_first": ("__note", "__debug", "b", "a", "y", "x"), +} + + +@pytest.mark.parametrize("tag_order", [("a", "b"), ("b", "a")], ids=["ab", "ba"]) +@pytest.mark.parametrize("layout", list(RAW_LAYOUTS)) +def test_meta_columns_of_a_raw_stream_stay_unmarked( + layout: str, tag_order: tuple[str, str] +) -> None: + """A raw stream lists its meta columns among its data keys; the display leaves + them unmarked and the legend counts them as nothing, while its data columns and + its data-tag keep their marks.""" + values = {"a": [1, 2], "b": [3, 4], "x": [5, 6], "y": [7, 8]} + values |= {"__debug": ["d1", "d2"], "__note": ["n1", "n2"]} + table = pa.table({name: values[name] for name in RAW_LAYOUTS[layout]}) + stream = ArrowTableStream(table, tag_columns=list(tag_order), data_tags=["b"]) + assert {"__debug", "__note"} <= set(stream.keys()[1]) + meta = [c for c in RAW_LAYOUTS[layout] if c.startswith("__")] + data = [c for c in RAW_LAYOUTS[layout] if c in ("x", "y")] + for shown in ( + stream.head(), + stream.head(columns={"meta": True}), + stream.run(), + stream.run().tail(1), + ): + view = _view(shown) + assert view.tag_columns == tag_order + assert view.data_tag_columns == ("b",) + assert list(view.data_columns) == data + html_text = view._repr_html_() + header = dict(_cells(html_text)[0]) + for name in meta: + assert header[name] == "", name + for name in data: + assert header[name] == "font-weight:normal;text-decoration:underline" + assert header["a"].startswith("font-weight:bold;color:#2a7fb8") + assert header["b"].startswith( + "font-weight:bold;text-decoration:underline;color:#2a7fb8" + ) + assert ( + "bold = tag; underlined = data; " + "bold underlined = data-tag (a tag that is also data)" + ) in html_text + lines = str(view).split("\n") + assert lines[1] == "* = tag; + = data-tag (tag and data)" + names_line = next(line for line in lines if line.startswith("│")) + names = [cell.strip() for cell in names_line.strip("│").split("┆")] + tags = [("+" if c == "b" else "*") + c for c in tag_order] + assert names == [*tags, *(c for c in RAW_LAYOUTS[layout] if c not in tag_order)] + + +STYLES = { + "tag": "font-weight:bold;color:#2a7fb8", + "data-tag": "font-weight:bold;text-decoration:underline;color:#2a7fb8", + "data": "font-weight:normal;text-decoration:underline", +} +RULE = "border-right:2px solid currentColor" + + +def _header_cells(html_text: str) -> list[tuple[str, str]]: + """The first header row of an HTML display: each cell's text and style.""" + return _cells(html_text)[0] + + +def _check_rendered_roles( + view: StreamView, role_of: dict[str, str], hidden_boundary: bool +) -> list[str]: + """Check every rendered header cell has its own column's mark, the ellipsis none, + and the rule after the last tag (on the ellipsis when that tag is left out). + Return the names of the rendered cells.""" + rows = _cells(view._repr_html_()) + header = rows[0] + names = [name for name, _ in header] + assert "…" in names, "the table is shown truncated" + for name, style in header: + if name == "…": + assert style == (RULE if hidden_boundary else ""), style + else: + expected = STYLES[role_of[name]] + assert style.removesuffix(";" + RULE) == expected, name + ruled = [name for name, style in header if RULE in style] + last_tag = view.tag_columns[-1] + assert ruled == (["…"] if hidden_boundary else [last_tag]) + for row in rows[1:]: + ruled_cells = [i for i, (_, style) in enumerate(row) if RULE in style] + assert ruled_cells == [names.index(ruled[0])] + return names + + +@pytest.mark.parametrize("layout", ["tags_first", "data_first"]) +def test_a_wide_table_marks_the_columns_polars_shows(layout: str) -> None: + """At Polars' default width a 100-column table is shown truncated: every shown + header keeps its own column's mark, never another column's.""" + plain = [f"p{i}" for i in range(5)] + data_tags = [f"t{i}" for i in range(85)] + data = [f"d{i}" for i in range(10)] + tags = plain + data_tags + columns = tags + data if layout == "tags_first" else data[::-1] + tags + source = DictSource( + [{name: i for i, name in enumerate(columns)}], + tag_columns=tags, + tag_only_columns=plain, + source_id="wide", + ) + role_of = { + **dict.fromkeys(plain, "tag"), + **dict.fromkeys(data_tags, "data-tag"), + **dict.fromkeys(data, "data"), + } + view = _view(source.run()) + names = _check_rendered_roles(view, role_of, hidden_boundary=False) + assert names[:5] == plain + assert any(role_of.get(name) == "data" for name in names) + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +def test_an_explicit_column_limit_marks_the_columns_polars_shows(layout: str) -> None: + """Under ``tbl_cols=4`` the six-column stream shows two columns either side of the + ellipsis: each keeps its own mark, the ellipsis none, and the rule moves onto the + ellipsis when the last tag is left out; the text form marks the same columns.""" + import polars as pl + + source = _source(TAG_ORDERS["interleaved"], LAYOUTS[layout]) + view = _view(source.run()) + role_of = {"session": "tag", "trial": "tag", "unit": "data-tag", "time": "data-tag"} + role_of |= {"amp": "data", "label": "data"} + with pl.Config(tbl_cols=4): + names = _check_rendered_roles(view, role_of, hidden_boundary=True) + text = str(view) + assert names[:2] == ["session", "unit"] + assert names[3:] == list(view.data_columns) + names_line = next(line for line in text.split("\n") if line.startswith("│")) + shown = [cell.strip() for cell in names_line.strip("│").split("┆")] + assert shown == ["*session", "+unit", "…", *view.data_columns] + # Showing more columns than the limit hides none: every mark, by position. + with pl.Config(tbl_cols=20): + header = _header_cells(view._repr_html_()) + assert "…" not in [name for name, _ in header] + for name, style in header: + assert style.removesuffix(";" + RULE) == STYLES[role_of[name]], name + + +def test_an_unmatched_header_marks_nothing() -> None: + """When the rendered header cannot be matched to the columns, no cell is marked.""" + from orcapod.core.streams.view import _mark_columns, _rendered_columns + + frame = ( + "" + "" + "
ab
i64i64
12
" + ) + assert _rendered_columns(["a", "b"], ["x", "y"]) is None + marked = _mark_columns(frame, [("x", "tag"), ("y", "data")], None) + assert "style=" not in marked + columns = [("a", "tag"), ("b", "data")] + matched = _mark_columns(frame, columns, _rendered_columns(["a", "b"], ["a", "b"])) + assert f'a' in matched + assert f'b' in matched + + +def test_an_unmatched_header_has_no_html_legend_and_a_full_text_legend( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A header that cannot be matched: the HTML marks nothing and so names no mark; + the text display, whose marks are part of the names, names every column's.""" + from orcapod.core.streams import view as view_module + + monkeypatch.setattr(view_module, "_rendered_columns", lambda cells, names: None) + view = _view(_source().run()) + html_text = view._repr_html_() + assert "" not in html_text.split("", 1)[1] + assert str(view).split("\n")[1] == "* = tag; + = data-tag (tag and data)" + + +def _legends(view: StreamView, columns: int | None) -> tuple[str, str]: + """The HTML and text legend lines of ``view`` under ``tbl_cols=columns`` (Polars' + default when ``None``), empty when there is none.""" + import polars as pl + + with pl.Config(tbl_cols=columns) if columns else pl.Config(): + html_text = view._repr_html_() + text = str(view) + html_legend = "" + if "
" in html_text: + html_legend = html_text.split("
", 1)[1].split("", 1)[0] + second = text.split("\n")[1] + return html_legend, "" if second.startswith("shape:") else second + + +TAGS_AND_DATA = "bold = tag; underlined = data" +DATA_AND_DATA_TAGS = ( + "underlined = data; bold underlined = data-tag (a tag that is also data)" +) +FULL = "bold = tag; " + DATA_AND_DATA_TAGS +TEXT_FULL = "* = tag; + = data-tag (tag and data)" + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +@pytest.mark.parametrize( + ("case", "tag_order", "columns", "html_legend", "text_legend"), + [ + # Plain tags first: tbl_cols=4 shows trial, session, …, two data columns. + ("hides every data-tag", "plain_first", 4, TAGS_AND_DATA, "* = tag"), + # Data-tags first: shows time, unit, …, two data columns. + ( + "hides every plain tag", + "data_tags_first", + 4, + DATA_AND_DATA_TAGS, + "+ = data-tag (tag and data)", + ), + # tbl_cols=1: the text shows one tag and the ellipsis; the HTML no column. + ("hides every data column", "plain_first", 1, "", "* = tag"), + ("hides nothing", "interleaved", 20, FULL, TEXT_FULL), + ("hides nothing by default", "interleaved", None, FULL, TEXT_FULL), + ], + ids=lambda value: value if isinstance(value, str) and " " in value else None, +) +def test_the_legend_names_the_marks_of_the_rendered_columns( + case: str, + tag_order: str, + columns: int | None, + html_legend: str, + text_legend: str, + layout: str, +) -> None: + """Each display's legend names the marks of the columns it rendered: a mark whose + columns Polars left out is not named; with nothing left out, every mark is.""" + view = _view(_source(TAG_ORDERS[tag_order], LAYOUTS[layout]).run()) + assert _legends(view, columns) == (html_legend, text_legend), case + + +@pytest.mark.parametrize("layout", list(LAYOUTS)) +def test_the_legend_follows_hidden_data_columns_with_every_column_group( + layout: str, +) -> None: + """With every column group shown, tbl_cols=4 shows two tags and two source-info + columns: the data columns and data-tags are left out, and no legend names them.""" + view = _view( + _source(TAG_ORDERS["plain_first"], LAYOUTS[layout]).head(all_info=True) + ) + assert _legends(view, 4) == ("bold = tag", "* = tag") + + +def test_the_legend_of_the_wide_table() -> None: + """The 100-column table: the HTML (75 columns by default) shows every kind of + column; the text (8 by default) shows plain tags and data, not a data-tag; under + tbl_cols=6 the HTML shows plain tags and data only.""" + plain = [f"p{i}" for i in range(5)] + data_tags = [f"t{i}" for i in range(85)] + data = [f"d{i}" for i in range(10)] + source = DictSource( + [{name: i for i, name in enumerate(plain + data_tags + data)}], + tag_columns=plain + data_tags, + tag_only_columns=plain, + source_id="wide", + ) + view = _view(source.run()) + assert _legends(view, None) == (FULL, "* = tag") + assert _legends(view, 6) == (TAGS_AND_DATA, "* = tag") + assert _legends(view, 200) == (FULL, TEXT_FULL) diff --git a/tests/test_core/streams/test_head_and_preview.py b/tests/test_core/streams/test_head_and_preview.py index 5e3b4d76d..c1bc22eda 100644 --- a/tests/test_core/streams/test_head_and_preview.py +++ b/tests/test_core/streams/test_head_and_preview.py @@ -9,6 +9,7 @@ from __future__ import annotations import io +import re from typing import Any from unittest import mock @@ -746,6 +747,75 @@ def _repr_html_(self) -> str: head = head_of(_PlainHead(), source) assert head.status is ViewStatus.ROWS assert head.header() == "ArrowTableSource[readings] — all 2 rows" + # The roles come from the stream, as for every other view (ITL-1304). + assert head.tag_columns == ("id",) + assert head.data_tag_columns == () + assert head.data_columns == ("x",) + assert "bold = tag; underlined = data" in head._repr_html_() + + +def test_head_of_an_adapted_head_marks_plain_tags_data_tags_and_data() -> None: + """A protocol head of a stream with two plain tags, two data-tags and two data + columns, in two table layouts, is shown with every column's mark.""" + from orcapod.core.streams.view import head_of + + class _Wrapped: + """A ``StreamViewProtocol`` result that only wraps another head's rows.""" + + def __init__(self, inner: Any) -> None: + self.table = inner.table + self.status = "rows" + self.total_rows = inner.table.num_rows + + def header(self) -> str: + """Return a fixed header.""" + return "wrapped" + + styles = { + "tag": "font-weight:bold;color:#2a7fb8", + "data-tag": "font-weight:bold;text-decoration:underline;color:#2a7fb8", + "data": "font-weight:normal;text-decoration:underline", + } + for layout in ( + ["amp", "label", "session", "unit", "trial", "time"], + ["time", "trial", "label", "unit", "amp", "session"], + ): + row = { + "session": "s", + "unit": 1, + "trial": 2, + "time": 3, + "amp": 0.5, + "label": "a", + } + source = DictSource( + [{name: row[name] for name in layout}], + tag_columns=["session", "unit", "trial", "time"], + tag_only_columns=["session", "trial"], + source_id="spikes", + ) + head = head_of(_Wrapped(source.head()), source) + assert head.tag_columns == ("session", "unit", "trial", "time") + assert head.data_tag_columns == ("unit", "time") + assert set(head.data_columns) == {"amp", "label"} + html_text = head._repr_html_() + role = { + "session": "tag", + "trial": "tag", + "unit": "data-tag", + "time": "data-tag", + } + first_row = html_text.split("", 1)[1].split("", 1)[0] + header = { + name: style + for style, name in re.findall( + r'([^<]*)', first_row + ) + } + assert list(header) == ["session", "unit", "trial", "time", *head.data_columns] + for name, style in header.items(): + assert style.startswith(styles[role.get(name, "data")]), name + assert "+unit" in str(head) and "*session" in str(head) def test_head_of_n_rows_renders_all_n_rows() -> None: diff --git a/tests/test_core/streams/test_view.py b/tests/test_core/streams/test_view.py index efc7c5f1a..5d118086d 100644 --- a/tests/test_core/streams/test_view.py +++ b/tests/test_core/streams/test_view.py @@ -225,17 +225,20 @@ def _two_tags() -> DictSource: def test_html_display_marks_exactly_the_tag_columns() -> None: - """Tag headers are bold; a rule follows the last tag column on every row.""" + """Tag headers are bold, data headers underlined (ITL-1304); a rule follows the + last tag column on every row.""" rows = _cells(_two_tags().run()) header = rows[0] assert [name for name, _ in header] == ["a", "b", "x", "y"] bold = [name for name, style in header if "font-weight:bold" in style] assert bold == ["a", "b"] + underlined = [name for name, style in header if "underline" in style] + assert underlined == ["x", "y"] for row in rows: ruled = [i for i, (_, style) in enumerate(row) if "border-right" in style] assert ruled == [1] html_text = _two_tags().run()._repr_html_() - assert "bold = tag" in html_text + assert "bold = tag; underlined = data" in html_text def test_html_display_of_odd_names_is_safe() -> None: @@ -250,16 +253,23 @@ def test_html_display_of_odd_names_is_safe() -> None: assert " None: - """With no tag column, no header is styled and no legend is shown.""" - view = ArrowTableStream(pa.table({"x": [3, 1, 2]})).run() +def test_a_view_without_tags_has_no_rule_and_no_tag_legend() -> None: + """With no tag column, no rule is drawn, the data headers are underlined and the + legend names the data mark only; the text form has no legend.""" + view = ArrowTableStream(pa.table({"x": [3, 1, 2], "z": [1, 2, 3]})).run() html_text = view._repr_html_() + assert "underlined = data" in html_text assert "bold = tag" not in html_text - assert "style=" not in html_text.split("", 1)[1] + assert "border-right" not in html_text + assert [style for _, style in _cells(view)[0]] == [ + "font-weight:normal;text-decoration:underline" + ] * 2 assert "* = tag" not in str(view) + assert str(view).split("\n")[1].startswith("shape:") def test_text_display_stars_the_tag_columns() -> None: