diff --git a/AGENTS.md b/AGENTS.md index 3f0a1ba..41f8551 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -455,6 +455,17 @@ src/morphobricks_preprocessing/ tuned per unit (edited), contradictions refused and tagged on their own; channel_matrix.py (pure) its rules (trusted, layout_groups, matrix_rows, set_template, fill) + notebook_channels_override.py the per-unit override of a unit the repeat rows list: an editor + that starts from the row's tags, shows each header name and + highlights the C indices where it disagrees; nothing is saved or + counted until Confirm (repeat_tags.Override, override_holds: the + confirmation holds while the unit's tags and own header names are + unchanged; one-click Confirm the same tags / Confirm all N like it for + listed units with a confirmed unit's headers; a refusal keeps the + aliases of its time) + repeat_review.py the refusals and confirmations kept in the draft file (pure: Override, + RefusedUnit, TagReview; draft_format's optional tag_review, restored + on opening by RepeatRows.restore before headers are trusted) strict_draft.py fast mode unticked (pure): StrictShadow, the strict page's draft kept beside the draft; every user save applies the same change to both (channel_answers.tagged, patched), no-click tags the draft only; diff --git a/CHANGELOG.md b/CHANGELOG.md index ea0ed45..ba982e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,41 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. ### Added +- **Tag by repeat: another output folder is another draft** (owner requirement): pointing only the + output folder at another draft of the same experiment reopens the channel grid on that draft + (the draft is part of its reopening key), so its refused units stay listed and untagged; the + header trust restores the draft's own record first when the memory is another draft's + (`MatrixView.trust_headers`), and the save stays refused until it is. +- **Tag by repeat: override a listed unit** (owner requirement): from the list of units whose + headers disagree with their repeat's row, **Override this unit (start from the row's tags)** + opens the unit's tags prefilled with the row's, header names shown and disagreements + highlighted. The unit counts as tagged only after **Confirm these tags**; the confirmation + holds while the unit's own tags and header names are unchanged (`repeat_tags.Override`, + `override_holds`; `notebook_channels_override`). A refused unit is counted only when the user + confirms that unit: aliases saved by confirming or tagging another unit never clear its + refusal, never tag it in fast mode (`RepeatRows.standing`) and never change its highlights + (the refusal keeps the aliases of its time, `Refusal.channels`; `repeat_fill(frozen=...)`). A + listed unit with the same header names, at every C index, as a confirmed one shows "same + headers as , which you confirmed as " with **Confirm the same tags**, and + **Confirm all N like it** when several are listed: one click each through the same + validation and save as the editor (all or none), never automatic. + A unit tagged by hand on the grid is counted too, but is not a source of **Confirm the same + tags** (only a confirmation from the editor or a one-click is). + - A label renamed or removed after a refusal no longer breaks the editor: that cell opens blank + (the unit stays unconfirmed until it is tagged), and a label gone is never offered by a + one-click button. Before, the dropdown raised and every later redraw raised too. + - Refusals and confirmations are kept in the draft file (optional `tag_review`, draft version + still 4, `repeat_review.py`; written only while not empty; read strictly) and restored on + opening, before headers are trusted: after a kernel restart a refused unit is still listed, + untagged and unsaved until that unit is confirmed, and the one-click offer is still made. + - Fast mode decides which refusals stand against the row's current reference unit, as the + list does, and **Confirm all N like it** buttons keep a stable order. + - The review belongs to the draft it was made in (experiment folder and draft file): a notebook + pointed at another folder or output forgets the refusals, confirmations and editor state of + the first and restores the new draft's own (empty without one), before headers are trusted; + one draft's record is never written into another, and switching back restores the first + from its file. A failed save of the review shows a line on the tagging grid and is retried + at the next change. - **Channel-identity check after the run** (contract §14.1, design `channel-identity-check-2026-11-21` in MorphoFeature's `claude/restart-doc`): from the image summaries the intensity checks already make (no pixel read), every imaging unit's channel is diff --git a/docs/contract.md b/docs/contract.md index d13dc0a..2fe02ea 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1356,7 +1356,7 @@ exclude=, missing_as_singleton=, memory_limit=, progress=)` (`conversion`), the The answers a user has given while describing an experiment, before any `morphobricks.toml` is published (experiment-v1 §10, §12). It lives in the output folder, is never named `morphobricks.toml`, has no `schema` key, and no consumer reads it as a description (`RunInputs` refuses a draft: `A_DRAFT_REFUSED`). It holds **answers only**: the folders, counts and proposals are derived again from the folder (`draft_from_discovery`) on every resume, so a changed folder is never hidden by an old file. Code: `draft_answers.py` (the answers, `apply_answers`, `description_from_draft`), `draft_format.py` (strict bytes), `run/draft_file.py` (`new_answers`, `save_draft`, `load_draft`, `publish_draft`). -One JSON object, UTF-8, two-space indent, sorted keys, LF, a final newline, no duplicate key and no `NaN`. Every key below is required; a key of this list is the only key allowed at its level. +One JSON object, UTF-8, two-space indent, sorted keys, LF, a final newline, no duplicate key and no `NaN`. Every key below is required except `tag_review`; a key of this list is the only key allowed at its level. | Key | Value | |---|---| @@ -1373,6 +1373,7 @@ One JSON object, UTF-8, two-space indent, sorted keys, LF, a final newline, no d | `masks` | Mask ID → `{source_type, representation, source_channels?, display_name?}` (the notebook's *Your masks* screen: one answer per mask type, `representation` `instances`, `binary` or `parent_labels` (*grouped labels*, Spec experiment-v1 §4.5b) with no default and never the mask step's `grouped` kind; the ID is the mask type's folder name when it is a valid mask ID, else typed by the user; `source_channels` are declared channel IDs) | | `channel_layout` | `null` for a strict per-unit draft, else the user's fast-mode statement (Spec ADR 0006, experiment-v1 §4.3a): `{channels, image_type, confirmed_on}`, the ordered channel IDs of the tagged unit, `channels` or `rgb`, and the day of the statement. A unit's object then also takes `channels_from` (`experiment`: published with this list materialised, or `unit`: tagged on its own); a unit with no answer in a fast-mode draft is drafted `experiment` (a new unit, P15), never `unit`. A marker in a strict draft is refused (`channels_from_without_layout`) | | `switch_mode` | `true` only when the user switched a published file between fast and strict mode (the notebook's tick); publication refuses a candidate whose mode differs from the published one without it, and a recorded switch that changes nothing (`mode_switch_unconfirmed`, experiment-v1 §10: no reader or reconciliation switches the mode). A published file reopens in its own mode: its `channel_layout` and markers are the draft's answers | +| `tag_review` | Optional, same version 4: written only while it is not empty, so a draft without it is read as before. What *Tag by repeat* refused and the user confirmed (`repeat_review.py`), so a new notebook on the draft keeps the owner rule that a refused unit counts only when that unit is confirmed: `{refused, confirmed}`, two lists. `refused`: `{unit, tags, reference, aliases}`, the unit as `[condition, repeat, technical repeat]`, the row's tags at the click, the row's reference unit (the same three folders, or `null` for a unit whose images disagree) and the aliases (label → header names) as they were when the unit was first refused, which its header is read against. `confirmed`: `{unit, tags, names}`, the tags the user confirmed and the unit's own header names (text or `null`) then. A unit is listed once in each list. Read strictly: `null`, an unknown or missing key, a wrong type or a unit twice is refused, never dropped | Rules. diff --git a/docs/user_guide.md b/docs/user_guide.md index 0ef5bcb..75f8bff 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -365,6 +365,27 @@ editing, or the confirmed ones. An image that cannot be drawn gets a sentence sa before the pairing: if you pair the `rep2` folders of different conditions with different biological repeats, every row of that folder (whatever its channel count) says so and fills nothing; tag those conditions on their own. + From a listed acquisition, **Override this unit (start from the row's tags)** opens that + acquisition's tags with the row's tags filled in. Under each channel the header name is + shown, and an orange box marks where it disagrees, so you change only what is different. + Nothing is saved while you edit; the acquisition counts as tagged only after **Confirm these + tags** (every channel tagged, each label once). If the acquisition's own header or its + tags change later, it is listed again. + A listed acquisition is counted only when you confirm *that* acquisition (**Confirm these + tags**, **Confirm the same tags**, or its own folder tagged on the grid). Confirming one + acquisition never counts another, and fast mode does not tag a listed acquisition from the + header names saved by confirming another: it stays listed with the same contradiction and + the same orange boxes. When a listed acquisition has the same header names, at every + channel, as one you confirmed, it says "same headers as *that one*, which you confirmed as + *tags*" and offers **Confirm the same tags**; when several listed acquisitions have them it + also offers **Confirm all N like it**. Nothing is counted until you click; the buttons save + exactly as **Confirm these tags** does (all N or none). + An acquisition you tagged by hand on the grid counts, but it is not offered as the source of + **Confirm the same tags** for others; only one confirmed with **Confirm these tags** (or by + a one-click button) is. If you rename or remove a label after an acquisition was listed, its + override opens with that channel left blank: choose a label that still exists. What is + listed and what you confirmed is saved with your answers: after you close and reopen the + notebook, a listed acquisition is still listed, and still not counted, until you confirm it. In fast mode a row offers only the acquisitions that do not fit the layout, and those it fills are tagged on their own (checked as in the strict mode); unticked, a row is offered for every repeat folder. On a reopen, a row shows the tags every acquisition of its folder diff --git a/pyproject.toml b/pyproject.toml index f1486e8..16f8299 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -188,7 +188,9 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.notebook_channels_grid" = "ui" "morphobricks_preprocessing.notebook_channels_matrix" = "ui" "morphobricks_preprocessing.notebook_channels_repeat" = "ui" +"morphobricks_preprocessing.notebook_channels_override" = "ui" "morphobricks_preprocessing.repeat_tags" = "pure" +"morphobricks_preprocessing.repeat_review" = "pure" "morphobricks_preprocessing.notebook_channels_rows" = "ui" "morphobricks_preprocessing.notebook_channels_labels" = "ui" "morphobricks_preprocessing.notebook_channels_type" = "ui" diff --git a/src/morphobricks_preprocessing/draft_answers.py b/src/morphobricks_preprocessing/draft_answers.py index a899213..4894142 100644 --- a/src/morphobricks_preprocessing/draft_answers.py +++ b/src/morphobricks_preprocessing/draft_answers.py @@ -37,6 +37,7 @@ ) from .description_transition import DATE from .draft import Draft, DraftError, OpenQuestion +from .repeat_review import TagReview CHANNELS = "channels" """The answer "an ordinary channel image": published as an absent ``image_type`` (§4.4b).""" @@ -146,6 +147,7 @@ class DraftAnswers: pairing: Mapping[tuple[str, str], str] = field(default_factory=dict) channel_layout: LayoutAnswer | None = None # the fast-mode statement; None: strict switch_mode: bool = False # only the user's switch of a published file's mode (section 10) + tag_review: TagReview | None = None # refused/confirmed units of Tag by repeat (draft only) class DraftIncomplete(DraftError): diff --git a/src/morphobricks_preprocessing/draft_format.py b/src/morphobricks_preprocessing/draft_format.py index e19fc1b..4ab38ed 100644 --- a/src/morphobricks_preprocessing/draft_format.py +++ b/src/morphobricks_preprocessing/draft_format.py @@ -4,7 +4,10 @@ seven tables of the user's answers (``conditions``, ``technical_repeats``, ``repeats``, ``pairing``, ``units``, ``channels``, ``masks``), the fast-mode statement ``channel_layout`` (``null`` for a strict draft; version 4, Spec ADR 0006) and ``switch_mode`` (true only when the -user switched a published file between fast and strict mode), every key required. Reading never +user switched a published file between fast and strict mode), every key required, and one +optional key, ``tag_review`` (the units *Tag by repeat* refused and the user confirmed, +:mod:`.repeat_review`; written only while not empty, so a draft without it is read as before, +and a ``tag_review`` that is malformed is refused like any other key). Reading never repairs: bytes that are not UTF-8 JSON, a duplicate key, ``NaN``, an unknown ``version``, a key the format does not have, a missing key, a value of the wrong type or a date that is not a real ``YYYY-MM-DD`` day are refused with :class:`DraftFileError`, whose ``code`` says which. @@ -32,6 +35,7 @@ UnitAnswer, valid_day, ) +from .repeat_review import Override, RefusedUnit, TagReview, review_to_json from .run.description_file import ABSENT DRAFT_FORMAT = "morphobricks-description-draft" @@ -59,6 +63,11 @@ "channel_layout", "switch_mode", ) +OPTIONAL_TOP = ("tag_review",) +"""Top-level keys a file may leave out (a draft written before they existed has none).""" +REVIEW_KEYS = ("refused", "confirmed") +REFUSED_KEYS = ("unit", "tags", "reference", "aliases") +CONFIRMED_KEYS = ("unit", "tags", "names") CONDITION_KEYS = ("id", "display_name", "reference", "target", "treatment_key") REPEAT_KEYS = ("id", "confirmed_on", "display_name") UNIT_KEYS = ("channels", "image_type", "display_name", "rgb_header_override", "channels_from") @@ -235,6 +244,53 @@ def _layout(value: object) -> LayoutAnswer | None: return LayoutAnswer(channels, kind, day) +def _unit_key(value: object, where: str) -> tuple[str, str, str]: + """Read a unit's folders: condition, source repeat and technical repeat, three texts.""" + keys = _texts(value, where) + if len(keys) != 3: + raise _bad(where, "three folder names are expected") + return keys[0], keys[1], keys[2] + + +def _review(value: object) -> TagReview: + """Read ``tag_review`` strictly: null, a unit twice or a wrong value is refused.""" + top = _table(value, "tag_review", REVIEW_KEYS, REVIEW_KEYS) + refused, confirmed = {}, {} + for number, raw in enumerate(_list(top["refused"], "tag_review.refused")): + where = f"tag_review.refused[{number}]" + item = _table(raw, where, REFUSED_KEYS, REFUSED_KEYS) + key = _unit_key(item["unit"], f"{where}.unit") + if key in refused: + raise _bad(f"{where}.unit", f"unit {'/'.join(key)} is listed twice") + reference = item["reference"] + aliases = { + k: _texts(v, f"{where}.aliases.{k}") + for k, v in _entries(item["aliases"], f"{where}.aliases").items() + } + refused[key] = RefusedUnit( + _texts(item["tags"], f"{where}.tags"), + None if reference is None else _unit_key(reference, f"{where}.reference"), + aliases, + ) + for number, raw in enumerate(_list(top["confirmed"], "tag_review.confirmed")): + where = f"tag_review.confirmed[{number}]" + item = _table(raw, where, CONFIRMED_KEYS, CONFIRMED_KEYS) + key = _unit_key(item["unit"], f"{where}.unit") + names = _list(item["names"], f"{where}.names") + if key in confirmed: + raise _bad(f"{where}.unit", f"unit {'/'.join(key)} is listed twice") + if not all(n is None or isinstance(n, str) for n in names): + raise _bad(f"{where}.names", "each entry is a header name (text) or null") + confirmed[key] = Override(_texts(item["tags"], f"{where}.tags"), tuple(names)) + return TagReview(refused, confirmed) + + +def _list(value: object, where: str) -> list: + if not isinstance(value, list): + raise _bad(where, "a list is expected") + return value + + def _base(doc: dict) -> str: base = doc.get("base_sha256") if not isinstance(base, str) or not (base == ABSENT or SHA256.fullmatch(base)): @@ -257,7 +313,7 @@ def _header(doc: object) -> dict: f"version {version!r} is not supported: this brick reads version {DRAFT_VERSION}", "unknown_version", ) - _table(doc, "the file", TOP) + _table(doc, "the file", (*TOP, *OPTIONAL_TOP)) if "base_sha256" not in doc: raise DraftFileError("base_sha256 is missing", BASE_MISSING) return doc @@ -281,7 +337,7 @@ def answers_from_bytes(data: bytes) -> DraftAnswers: except (UnicodeDecodeError, ValueError, RecursionError) as error: raise DraftFileError(f"the file is not UTF-8 JSON ({error})") from error doc = _header(raw) - _table(doc, "the file", TOP, TOP) + _table(doc, "the file", (*TOP, *OPTIONAL_TOP), TOP) base = _base(doc) commit = _text(doc["spec_commit"], "spec_commit") if not COMMIT.fullmatch(commit): @@ -304,6 +360,7 @@ def answers_from_bytes(data: bytes) -> DraftAnswers: _pairing(doc["pairing"]), _layout(doc["channel_layout"]), _flag(doc["switch_mode"]), + _review(doc["tag_review"]) if "tag_review" in doc else None, ) @@ -377,6 +434,8 @@ def answers_to_bytes(answers: DraftAnswers) -> bytes: }, "switch_mode": answers.switch_mode, } + if answers.tag_review is not None and not answers.tag_review.empty: + doc["tag_review"] = review_to_json(answers.tag_review) try: return (json.dumps(doc, ensure_ascii=False, indent=2) + "\n").encode("utf-8") except UnicodeEncodeError as error: diff --git a/src/morphobricks_preprocessing/notebook_channels.py b/src/morphobricks_preprocessing/notebook_channels.py index 4490263..75ea5a9 100644 --- a/src/morphobricks_preprocessing/notebook_channels.py +++ b/src/morphobricks_preprocessing/notebook_channels.py @@ -14,6 +14,8 @@ from __future__ import annotations +from pathlib import Path + import ipywidgets as widgets from . import notebook_style as ui @@ -21,6 +23,8 @@ from .channel_answers import all_colour from .channel_labels import UnitLayout from .channel_units import header_names, slot_count, unit_channel_counts, unit_layouts +from .description_file import DRAFT_FILENAME +from .discovery import default_output_folder from .draft_answers import DraftAnswers from .notebook_channel_thumbs import Thumbnails from .notebook_channels_grid import TagGrid @@ -66,6 +70,19 @@ def refusal(self) -> str: """Return the reason the last answer was refused.""" return str(self._nb._refusal or "the answers were refused") + def draft_id(self) -> tuple[str, str] | None: + """Return which draft the answers are: the experiment folder and its draft file. + + ``None`` with no experiment folder (the answers are then only in memory). The tag + review kept beside the grid (:mod:`.notebook_channels_repeat`) belongs to one draft and + is dropped when this changes. + """ + folder = ui.clean_path(self._nb.folder.value) + if not folder: + return None + output = self._nb._output_folder() or default_output_folder(folder) + return str(Path(folder).resolve()), str((Path(output) / DRAFT_FILENAME).resolve()) + def used_channels(self) -> tuple[str, ...]: """Return the channel IDs the lineage retired.""" base = self._nb._draft_base @@ -152,7 +169,19 @@ def _refresh_channels(self) -> None: bound = tuple( sorted((u.image, pre.header_fingerprints.get(u.image)) for u in layouts if u.image) ) - key = (str(pre.discovery.root), self.confirmed_mapping, layouts, slots, tuple(names), bound) + # The draft is part of the key: the grid reopens on another draft of the same experiment + # (only the output folder changed) and restores that draft's tag review, never keeps the + # memory of the one before. + draft = self.channel_grid.by_repeat.draft_id() + key = ( + str(pre.discovery.root), + self.confirmed_mapping, + layouts, + slots, + tuple(names), + bound, + draft, + ) if key == self._channels_key: self._refresh_masks_screen() return diff --git a/src/morphobricks_preprocessing/notebook_channels_grid.py b/src/morphobricks_preprocessing/notebook_channels_grid.py index 372655b..e106cd9 100644 --- a/src/morphobricks_preprocessing/notebook_channels_grid.py +++ b/src/morphobricks_preprocessing/notebook_channels_grid.py @@ -171,11 +171,12 @@ def thumbs(self) -> Thumbnails | None: def open(self, layouts: Sequence[UnitLayout], labels: list[str], thumbs: Thumbnails) -> None: """Show the grid for these units and labels (the confirmed label list of step A).""" - if layouts is not self.layouts: + if layouts is not self.layouts or self.by_repeat.other_draft(): self.alone = set() self.matrix.reset() self.matrix.opening() self.matrix.tick_for_mode() + self.by_repeat.restore(layouts) # refused units stay refused self.layouts, self.labels, self.rows.thumbs = layouts, labels, thumbs if self.place_types: self.types.open(layouts) @@ -563,8 +564,7 @@ def _summary(self) -> None: def shown_as(self, label: str) -> str | None: """Return the shown-as name of a saved label (the chip's tooltip), if it has one.""" - saved = self.store.answers().channels.get(label) - return None if saved is None else saved.display_name + return getattr(self.store.answers().channels.get(label), "display_name", None) def _usage_line(self, label: str, used: int, total: int) -> str: """Return the usage line of a label; one used in only some units is orange.""" diff --git a/src/morphobricks_preprocessing/notebook_channels_matrix.py b/src/morphobricks_preprocessing/notebook_channels_matrix.py index 1c47978..a78ef2b 100644 --- a/src/morphobricks_preprocessing/notebook_channels_matrix.py +++ b/src/morphobricks_preprocessing/notebook_channels_matrix.py @@ -131,7 +131,11 @@ def trust_headers(self) -> bool: """ if not self.grid.same_channels.value or not self.grid.labels: return False - units = [u for u in self.grid.layouts if not self.grid.colour(u)] + rows = self.grid.by_repeat + if rows.other_draft(): # the memory is another draft's: take this draft's record first + rows.restore(self.grid.layouts) + held = rows.standing() # a refused unit counts only when confirmed + units = [u for u in self.grid.layouts if not self.grid.colour(u) and u.key not in held] answers, cells = trusted(self.grid.store.answers(), units, self.grid.labels, self.saved) if not cells: return False diff --git a/src/morphobricks_preprocessing/notebook_channels_override.py b/src/morphobricks_preprocessing/notebook_channels_override.py new file mode 100644 index 0000000..ea93cf9 --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_channels_override.py @@ -0,0 +1,283 @@ +"""*Tag channels*: override one listed unit, starting from its row's tags (owner requirement). + +A unit whose image headers disagree with its repeat's row is listed +(:mod:`.notebook_channels_repeat`). From the list the user can override that unit: the editor +starts from the row's tags, shows each header name under its dropdown, and highlights the +C indices where the header disagrees, so that only what is different is changed. Nothing is +saved while the user edits (the draft lives here, like ``RepeatRows.pending``); the unit counts +as tagged only after **Confirm these tags**. The confirmation is the tags and the unit's own +header names (:class:`.repeat_tags.Override`); it lapses when either changes +(:func:`.repeat_tags.override_holds`). Channels are never guessed: a draft that is incomplete +or repeats a label is refused, and a refused save confirms nothing. + +Another listed unit with the same header names (at every C index) as a unit the user confirmed +stays listed and offers **Confirm the same tags** (and **Confirm all N like it** when several +do): the same save and record as the editor, one click per confirmation, never automatic. +Highlights are read against the aliases of the refusal (:attr:`.RepeatRows.refused`), so +confirming one unit never changes what another one shows. +""" + +from __future__ import annotations + +import html +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import ipywidgets as widgets + +from . import notebook_style as ui +from .channel_labels import tags_of +from .channel_matrix import difference_text, differences +from .notebook_channels_view import ( + CHOOSE, + ORANGE, + ORANGE_FILL, + blank_chip, + chip, + columns, + quoted, + unit_name, +) +from .repeat_tags import Override, header_names, override_holds + +if TYPE_CHECKING: + from .channel_labels import UnitLayout + from .draft_answers import UnitKey + from .notebook_channels_repeat import RepeatRows + +START = "Override this unit (start from the row's tags)" + + +class OverrideEditor: + """The per-unit override of the listed units, drawn under the rows.""" + + def __init__(self, rows: RepeatRows) -> None: + self.rows = rows + self.editing: UnitKey | None = None + """The unit being edited; its tags are in :attr:`drafts` and nowhere else.""" + self.drafts: dict[UnitKey, list[str | None]] = {} + self.confirmed: dict[UnitKey, Override] = {} + """The units whose tags the user confirmed, with what the header said then.""" + self.buttons: dict[UnitKey, widgets.Button] = {} + self.same_buttons: dict[UnitKey, widgets.Button] = {} + """**Confirm the same tags**, per listed unit like a confirmed one.""" + self.all_buttons: dict[UnitKey, widgets.Button] = {} + """**Confirm all N like it**, per confirmed unit that several listed units are like.""" + self.confirm_button: widgets.Button | None = None + self.cancel_button: widgets.Button | None = None + self.cells: dict[tuple[UnitKey, int], widgets.Dropdown] = {} + + def build(self, width: int) -> list[widgets.Widget]: + """Return the widgets: a button per listed unit with a reference, and the open editor.""" + self.buttons, self.cells, self.same_buttons, self.all_buttons = {}, {}, {}, {} + self.confirm_button = self.cancel_button = None + current = {u.key: u for u in self.rows.grid.layouts} + offered = self._offered(current) + if self.editing not in offered: + self.editing = None + likes = self._likes(offered, current) + out: list[widgets.Widget] = [] + for key in offered: + if key == self.editing: + out.append(self._editor(key, current[key], width)) + continue + button = ui.button(f" {START}", style="warning", icon="pencil") + button.on_click(lambda _, k=key: self.start(k)) + self.buttons[key] = button + box: list[widgets.Widget] = [ + widgets.HTML(f"{html.escape(unit_name(key))}"), + button, + ] + if key in likes: + box += self._same(key, *likes[key]) + out.append(widgets.VBox(box)) + for source in dict.fromkeys(src for src, _ in likes.values()): # first listed first + keys = [k for k, (src, _) in likes.items() if src == source] + if len(keys) > 1: + out.append(self._all(source, keys, likes[keys[0]][1])) + return out + + def _offered(self, current: dict[UnitKey, UnitLayout]) -> list[UnitKey]: + """Return the listed units that have a reference (a unit whose images disagree has none).""" + rows = self.rows + return [ + key + for key in rows.listed() + if key in current and key in rows.refused and rows.refused[key].lead is not None + ] + + def _likes( + self, offered: list[UnitKey], current: dict[UnitKey, UnitLayout] + ) -> dict[UnitKey, tuple[UnitKey, tuple[str, ...]]]: + """Return, per listed unit, the confirmed unit with the same header names and its tags. + + Same header names at every C index (none missing), and the confirmation still holds. When + confirmed units with those names hold different tags, none is offered (never a guess). + """ + grid = self.rows.grid + units = grid.store.answers().units + held: dict[tuple, dict[tuple[str, ...], UnitKey]] = {} + for key, over in self.confirmed.items(): + layout = current.get(key) + if layout is None or None in over.names or not set(over.tags) <= set(grid.labels): + continue + if override_holds(over, layout, tags_of(layout, units.get(key))): + held.setdefault(over.names, {}).setdefault(over.tags, key) + out = {} + for key in offered: + same = held.get(header_names(current[key]), {}) + if len(same) == 1: + tags, source = next(iter(same.items())) + out[key] = (source, tags) + return out + + def _same(self, key: UnitKey, source: UnitKey, tags: tuple[str, ...]) -> list[widgets.Widget]: + """Return the sentence and button of one listed unit like a confirmed one.""" + text = ( + f"same headers as {html.escape(unit_name(source))}, which you confirmed as " + f"{html.escape(', '.join(tags))}" + ) + button = ui.button(" Confirm the same tags", style="success", icon="check") + button.on_click(lambda _, k=key: self.confirm_same(k)) + self.same_buttons[key] = button + return [widgets.HTML(text), button] + + def _all(self, source: UnitKey, keys: list[UnitKey], tags: tuple[str, ...]) -> widgets.Widget: + """Return the button that confirms every listed unit like ``source`` in one save.""" + label = f" Confirm all {len(keys)} like {unit_name(source)}" + button = ui.button(label, style="success", icon="check") + button.on_click(lambda _, s=source: self.confirm_all(s)) + self.all_buttons[source] = button + return button + + def confirm_same(self, key: UnitKey) -> bool: + """Confirm one listed unit with the tags of the confirmed unit it is like.""" + likes = self._likes(*self._current()) + return key in likes and self._confirm({key: likes[key][1]}) + + def confirm_all(self, source: UnitKey) -> bool: + """Confirm every listed unit like ``source``; none if any would be refused.""" + likes = self._likes(*self._current()) + todo = {k: tags for k, (src, tags) in likes.items() if src == source} + return bool(todo) and self._confirm(todo) + + def _current(self) -> tuple[list[UnitKey], dict[UnitKey, UnitLayout]]: + """Return the listed units with a reference, and every unit as read now.""" + current = {u.key: u for u in self.rows.grid.layouts} + return self._offered(current), current + + def start(self, key: UnitKey) -> None: + """Open the editor on a unit with the row's tags; nothing is saved.""" + self.editing = key + self.drafts[key] = self._known(self.rows.refused[key].tags) + self.rows.grid.refresh() + + def _known(self, tags: Sequence[str | None]) -> list[str | None]: + """Return tags with a label that is no longer one left blank (renamed or removed).""" + return [t if t in self.rows.grid.labels else None for t in tags] + + def cancel(self) -> None: + """Close the editor and drop its draft; nothing was saved.""" + if self.editing is not None: + self.drafts.pop(self.editing, None) + self.editing = None + self.rows.grid.refresh() + + def _picked(self, key: UnitKey, index: int, value: str | None) -> None: + """Note one tag of the draft and redraw its highlights; nothing is saved.""" + self.drafts[key][index] = value + self.rows.grid.refresh() + + def _editor(self, key: UnitKey, layout: UnitLayout, width: int) -> widgets.Widget: + """Build the editor: a dropdown per C index, the header and its disagreement under it.""" + rows = self.rows + grid, refusal = rows.grid, rows.refused[key] + lead = refusal.lead + draft = self.drafts[key] = self._known(self.drafts[key]) # a label may change meanwhile + found = { # read against the aliases of the refusal, as before any confirmation + d.index: d for d in differences(layout, draft, lead, grid.labels, refusal.channels) + } + options = [(CHOOSE, None), *((label, label) for label in grid.labels)] + info = ( + f"{html.escape(unit_name(key))}: the row's tags are the start; " + "change only what is different" + ) + cells: list[widgets.Widget] = [widgets.HTML(info)] + for index in range(width): + if index >= layout.channels: + cells.append(widgets.HTML("")) + continue + drop = widgets.Dropdown( + options=options, value=draft[index], layout=widgets.Layout(width="99%") + ) + drop.observe(lambda c, k=key, i=index: self._picked(k, i, c["new"]), "value") + self.cells[(key, index)] = drop + cells.append( + widgets.VBox( + [ + drop, + widgets.HTML(f"C{index} {quoted(layout.name(index))}"), + widgets.HTML(self._note(index, draft, refusal.tags, found, grid.labels)), + ] + ) + ) + self.confirm_button = ui.button( + f" Confirm these tags for {unit_name(key)}", style="success", icon="check" + ) + self.confirm_button.on_click(lambda _: self.confirm()) + self.cancel_button = ui.button(" Cancel", icon="times") + self.cancel_button.on_click(lambda _: self.cancel()) + cells.append(widgets.VBox([self.confirm_button, self.cancel_button])) + return widgets.GridBox(cells, layout=columns(width)) + + @staticmethod + def _note(index: int, draft: list, row: tuple, found: dict, labels: list) -> str: + """Return what is under a cell: the header's disagreement, or as the row / changed.""" + if index in found: + return ( + f"
{html.escape(difference_text(found[index]))}
" + ) + tag = draft[index] + shown = chip(tag, labels) if tag else blank_chip("not tagged") + return f"{'as the row' if tag == row[index] else 'changed'} {shown}" + + def confirm(self) -> bool: + """Save the draft as this unit's tags, and count the unit as tagged only if that worked.""" + key = self.editing + if key is None or not self._confirm({key: self.drafts[key]}): + return False # refused: no confirmation, still listed, the editor stays open + self.editing = None + self.rows.grid.refresh() + return True + + def _confirm(self, drafts: dict[UnitKey, Sequence[str | None]]) -> bool: + """Save each unit's tags in one save and confirm them; nothing is saved if any is refused. + + The one path of the editor and of the one-click buttons: the same validation + (``RepeatRows._row_error``) and save (``_commit_user``). What a confirmation needs (the + unit's header names) is read before the save. + """ + rows = self.rows + grid, layouts = rows.grid, {u.key: u for u in rows.grid.layouts} + save, cells, records = {}, [], {} + for key, draft in drafts.items(): + if (why := rows._row_error(draft)) is not None: + rows.notice = ui.status("error", "Not saved.", [why]) + grid.refresh() + return False + layout = layouts[key] + save[key] = tuple(t for t in draft if t) + cells += [(key, i) for i in range(layout.channels)] + records[key] = Override(save[key], header_names(layout)) + if not rows._commit_user(save, cells): + return False + self.confirmed.update(records) + for key in save: + self.drafts.pop(key, None) + rows.persist() + grid.refresh() + return True + + +__all__ = ["START", "OverrideEditor"] diff --git a/src/morphobricks_preprocessing/notebook_channels_repeat.py b/src/morphobricks_preprocessing/notebook_channels_repeat.py index 4184bc2..c102a03 100644 --- a/src/morphobricks_preprocessing/notebook_channels_repeat.py +++ b/src/morphobricks_preprocessing/notebook_channels_repeat.py @@ -27,7 +27,8 @@ from __future__ import annotations import html -from collections.abc import Sequence +from collections.abc import Mapping, Sequence +from dataclasses import replace from typing import TYPE_CHECKING, NamedTuple import ipywidgets as widgets @@ -35,9 +36,13 @@ from . import notebook_style as ui from .channel_labels import tags_of from .channel_matrix import REFUSED, difference_text, differences +from .draft_answers import ChannelAnswer +from .notebook_channels_override import OverrideEditor from .notebook_channels_view import CHOOSE, columns, unit_name +from .repeat_review import RefusedUnit, TagReview from .repeat_tags import ( GroupKey, + override_holds, pairing_collision, repeat_apart, repeat_fill, @@ -64,6 +69,12 @@ class Refusal(NamedTuple): """The row's reference unit; None for a unit whose images disagree (:func:`repeat_apart`).""" tags: tuple[str, ...] """The row's tags at the click (what the header was compared with).""" + channels: Mapping[str, ChannelAnswer] + """The labels and aliases when the unit was first refused: what its header is read against. + + Aliases saved afterwards, by confirming or tagging other units, are not evidence for this + unit: only the user confirming it (or a changed image header) clears the refusal. + """ class RepeatRows: @@ -84,6 +95,12 @@ def __init__(self, grid: TagGrid) -> None: unit leaves this record after a save that fitted it succeeded (:meth:`apply`), or when the layouts change and it is gone or no longer contradicts its row (:meth:`reconcile`). """ + self.override = OverrideEditor(self) + """The per-unit override of a listed unit (:mod:`.notebook_channels_override`).""" + self.draft: object = None + """Which draft the record above belongs to (:meth:`other_draft`); None before the first.""" + self.unsaved = False + """True while the last save of the review was refused (retried at the next change).""" self.notice = "" """A one-shot message of the last click (shown once, then cleared).""" self.message = "" @@ -95,12 +112,15 @@ def listed(self) -> dict[UnitKey, str]: Derived from the current answers on every call: a unit is listed while its tags are incomplete or contradict its header, and leaves the list when they fit it, however it got there (an image type alone changes nothing). A unit whose images disagree stays listed - while they do: no tags make it one header. + while they do: no tags make it one header. Nothing is listed from the memory of another + draft (the notebook was pointed elsewhere and the grid is not open on it yet). """ + if self.other_draft(): + return {} answers = self.grid.store.answers() out = {} current = {u.key: u for u in self.grid.layouts} - for key, (text, _, lead, _) in self.refused.items(): + for key, (text, _, lead, _, _) in self.refused.items(): layout = current.get(key) # the unit as read now, never as at the click if layout is None: continue # no longer in the experiment (:meth:`reconcile` drops it) @@ -109,6 +129,9 @@ def listed(self) -> dict[UnitKey, str]: out[key] = text continue tags = tags_of(layout, answers.units.get(key)) + confirmed = self.override.confirmed.get(key) + if override_holds(confirmed, layout, tags): + continue # the user confirmed these tags (:mod:`.notebook_channels_override`) if None in tags or differences(layout, tags, lead, self.grid.labels, answers.channels): out[key] = text return out @@ -131,25 +154,135 @@ def reconcile(self) -> None: rows = self._rows() # the whole row: its reference never depends on the mode answers = grid.store.answers() for key, old in self.refused.items(): - group = next((g for g in rows.values() if any(u.key == key for u in g)), ()) - layout = next((u for u in group if u.key == key), None) + group, layout = self._placed(rows, key) if layout is None or key not in offered: continue why = repeat_apart(group).get(key) if why is not None: - kept[key] = Refusal(html.escape(why), layout, None, old.tags) + kept[key] = Refusal(html.escape(why), layout, None, old.tags, old.channels) continue lead = repeat_lead(group) if old.lead is None or lead is None: continue # its images agree again: nothing to compare was ever clicked own = tags_of(layout, answers.units.get(key)) - found = differences(layout, old.tags, lead, grid.labels, answers.channels) + found = self.contradictions(layout, old, lead) found = found or differences(layout, own, lead, grid.labels, answers.channels) if found: - kept[key] = Refusal(_found_text(found), layout, lead, old.tags) + kept[key] = Refusal(_found_text(found), layout, lead, old.tags, old.channels) elif None in own: # listed while its own tags are incomplete (:meth:`listed`) - kept[key] = Refusal("its own tags are incomplete", layout, lead, old.tags) + kept[key] = Refusal( + "its own tags are incomplete", layout, lead, old.tags, old.channels + ) self.refused = kept + self.override.confirmed = {k: v for k, v in self.override.confirmed.items() if k in kept} + self.persist() + + @staticmethod + def _placed(rows: Mapping, key: UnitKey) -> tuple[tuple, UnitLayout | None]: + """Return the row of units a unit is in, and the unit as read now (None when gone).""" + group = next((g for g in rows.values() if any(u.key == key for u in g)), ()) + return group, next((u for u in group if u.key == key), None) + + def persist(self) -> bool: + """Keep the refusals and confirmations in the draft file, when they changed. + + A new notebook on the draft restores them (:meth:`restore`): a refused unit counts only + once that unit is confirmed, whatever the session. A refused save is not silent (the + names card says "Not saved." and the grid shows a line, :attr:`unsaved`) and is retried + at the next persist, because the file still differs from memory; the record stays in + memory meanwhile, which is what this session reads. The record is only ever written into + the draft it came from: with another draft open nothing is written. Returns False when + the review could not be saved. + """ + store, mine = self.grid.store, self._review() + answers = store.answers() + ok = True + if self.other_draft(): + ok = False # memory is another draft's: never written into this one + elif (answers.tag_review or TagReview()) != mine: + ok = store.update(replace(answers, tag_review=mine)) + self.unsaved = not ok + return ok + + def other_draft(self) -> bool: + """Return True when the draft open now is not the one the record in memory belongs to.""" + return self.draft_id() != self.draft + + def draft_id(self) -> object: + """Return which draft the store holds (None for a store that cannot tell).""" + which = getattr(self.grid.store, "draft_id", None) + return which() if which is not None else None + + def _forget(self) -> None: + """Drop every refusal, confirmation and editor state: they belong to another draft.""" + self.refused, self.pending, self.notice, self.unsaved = {}, {}, "", False + self.override.confirmed = {} + self.override.editing, self.override.drafts = None, {} + + def _review(self) -> TagReview: + """Return what is refused and confirmed now, as the draft file keeps it.""" + refused = { + key: RefusedUnit( + old.tags, + None if old.lead is None else old.lead.key, + {k: tuple(a.header_names) for k, a in old.channels.items() if a.header_names}, + ) + for key, old in self.refused.items() + } + return TagReview(refused, dict(self.override.confirmed)) + + def restore(self, layouts: Sequence[UnitLayout]) -> None: + """Take the refusals and confirmations of the draft file (a notebook opened on it). + + Run before the headers are trusted and the refusals reconciled (:meth:`reconcile` + brings each up to date with the layouts, as after any re-check). The memory of the same + draft is not replaced: this session's record is the draft's. Another draft (the notebook + pointed at another folder or output) forgets the memory first and is restored from its + own file, empty when it has no review. A unit that is gone is not restored; a reference + that is gone is replaced by the current one at the next :meth:`reconcile`. + """ + if self.other_draft(): + self._forget() + self.draft = self.draft_id() + review = self.grid.store.answers().tag_review + if review is None or self.refused: + return + current = {u.key: u for u in layouts} + for key, saved in review.refused.items(): + if (layout := current.get(key)) is not None: + lead = layout if saved.reference is None else current.get(saved.reference, layout) + aliases = {k: ChannelAnswer(None, v) for k, v in saved.aliases.items()} + self.refused[key] = Refusal( + "", layout, None if saved.reference is None else lead, saved.tags, aliases + ) + self.override.confirmed = {k: v for k, v in review.confirmed.items() if k in self.refused} + + def contradictions(self, layout: UnitLayout, refusal: Refusal, lead: UnitLayout) -> tuple: + """Return where the unit's header contradicts the row's tags at the click. + + Read against the aliases of the refusal (:attr:`Refusal.channels`), never the ones + saved since: the one rule of :func:`.channel_matrix.differences`, on that snapshot. + """ + return differences(layout, refusal.tags, lead, self.grid.labels, refusal.channels) + + def standing(self) -> set[UnitKey]: + """Return the units whose refusal still stands, whatever aliases were saved since. + + Fast mode does not tag these from their header names + (:meth:`.notebook_channels_matrix.MatrixView.trust_headers`): a refused unit counts only + once the user confirms it. A confirmed unit holds tags, so trusts nothing either way. + """ + rows, out = self._rows(), set() + if self.other_draft(): + return out + for key, old in self.refused.items(): + group, layout = self._placed(rows, key) + if layout is None or old.lead is None: + continue + lead = None if key in repeat_apart(group) else repeat_lead(group) # the row as now + if lead is None or self.contradictions(layout, old, lead): + out.add(key) + return out def _rows(self) -> dict: """Return every repeat folder and channel count with all its units, in any mode.""" @@ -183,10 +316,20 @@ def build(self, width: int) -> None: lines, raw=True, ) - self.message = self.notice + (listed if lines else "") + failed = ( + ui.status( + "error", + "Not saved: the refusals and confirmations could not be written to the draft.", + ["They stay in this session and are saved again at the next change."], + ) + if self.unsaved + else "" + ) + self.message = self.notice + (listed if lines else "") + failed self.notice = "" + override = self.override.build(width) if not groups: - self.box.children = [widgets.HTML(self.message)] if self.message else [] + self.box.children = [*([widgets.HTML(self.message)] if self.message else []), *override] return rows: list[widgets.Widget] = [ ui.help_text( @@ -204,6 +347,7 @@ def build(self, width: int) -> None: rows += [self._row(key, group, width) for key, group in groups.items()] if self.message: rows.append(widgets.HTML(self.message)) + rows += override box = widgets.VBox(rows) box.add_class("mb-tag-block") self.box.children = [box] @@ -269,28 +413,46 @@ def apply(self, key: GroupKey, group: tuple) -> bool: members = repeat_members(self.grid.layouts, key[0]) # the whole folder name, not this row if pairing_collision(answers, members) is not None: return False - if len(named) != len(tags) or len(set(named)) != len(named): - self.notice = ui.status( - "error", "Not saved.", ["Tag every channel of the row, each label once."] - ) + if (why := self._row_error(tags)) is not None: + self.notice = ui.status("error", "Not saved.", [why]) self.grid.refresh() return False - save, cells, refused = repeat_fill(answers, group, named, self.grid.labels) + frozen = {k: old.channels for k, old in self.refused.items()} + save, cells, refused = repeat_fill(answers, group, named, self.grid.labels, frozen) for unit, found in refused.items(): layout = next(u for u in group if u.key == unit) + snapshot = frozen.get(unit, answers.channels) # kept from the first refusal self.refused[unit] = Refusal( - _found_text(found), layout, repeat_lead(group), tuple(named) + _found_text(found), layout, repeat_lead(group), tuple(named), snapshot ) for unit, why in repeat_apart(group).items(): layout = next(u for u in group if u.key == unit) - self.refused[unit] = Refusal(html.escape(why), layout, None, tuple(named)) + snapshot = frozen.get(unit, answers.channels) + self.refused[unit] = Refusal(html.escape(why), layout, None, tuple(named), snapshot) if not save: + self.persist() self.grid.refresh() return False - ok = self.grid.commit(save, cells) + ok = self._commit_user(save, cells) if ok: # a refusal is dropped only once the save that fitted the unit succeeded for unit in save: self.refused.pop(unit, None) + self.override.confirmed.pop(unit, None) + if not self.persist() and ok: + self.grid.refresh() # shows the line that the review is not saved + return ok + + @staticmethod + def _row_error(tags: Sequence[str | None]) -> str | None: + """Return why tags cannot be saved (a channel untagged or a label twice), else None.""" + named = [t for t in tags if t] + if len(named) != len(tags) or len(set(named)) != len(named): + return "Tag every channel of the row, each label once." + return None + + def _commit_user(self, save: dict, cells: list) -> bool: + """Save units' tags as the user's action; in fast mode they are then tagged on their own.""" + ok = self.grid.commit(save, cells) if ok and self.grid.same_channels.value: # the user's action: tagged on their own self.grid.matrix.own.update(save) self.grid.matrix.sync_statement() diff --git a/src/morphobricks_preprocessing/notebook_check_save.py b/src/morphobricks_preprocessing/notebook_check_save.py index 4ba5068..5682892 100644 --- a/src/morphobricks_preprocessing/notebook_check_save.py +++ b/src/morphobricks_preprocessing/notebook_check_save.py @@ -224,6 +224,7 @@ def _refresh_check_save(self) -> None: and self._check.can_publish and not self._moves_open() and not rows + and not self.channel_grid.by_repeat.other_draft() # its refusals are not read yet ) self.save_button.disabled = not ready or self._saved_current() self.save_note.value = ( @@ -239,6 +240,8 @@ def _save_blockers(self, todo: tuple[list, list[str]]) -> list[str]: """Return what stops the save button now (shown beside it), or nothing when saved.""" if not self.save_button.disabled or self._saved_current(): return [] # saved already (the green line says so): nothing is blocked + if self.channel_grid.by_repeat.other_draft(): + return ["the tag review is another draft's: open Channels again for this draft"] missing = len(todo[0]) + len(todo[1]) if missing: # and the Channels questions waiting, so none is found only afterwards line = f"{plural(missing, 'answer')} still missing (listed above the button)" diff --git a/src/morphobricks_preprocessing/repeat_review.py b/src/morphobricks_preprocessing/repeat_review.py new file mode 100644 index 0000000..ecb7a83 --- /dev/null +++ b/src/morphobricks_preprocessing/repeat_review.py @@ -0,0 +1,76 @@ +"""What *Tag by repeat* keeps of its refusals and confirmations, so a reopened draft keeps it. + +A unit whose image headers disagree with its repeat's row is refused, and counts only once the +user confirms that unit (:mod:`.notebook_channels_repeat`, :mod:`.notebook_channels_override`). +That record lives in the draft file (``tag_review`` of :mod:`.draft_format`, written only while +it is not empty), so a new notebook on the same draft does not tag a refused unit from the +aliases saved when another unit was confirmed. Pure data: no widget, no file. + +A refusal keeps what its header was read against: the row's tags at the click, the reference +unit, and the aliases (label to header names) as they were when the unit was first refused. +A confirmation keeps the tags and the unit's own header names it was confirmed for +(:class:`Override`, used by :mod:`.repeat_tags`). +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, NamedTuple + +if TYPE_CHECKING: + from .draft_answers import UnitKey + + +class Override(NamedTuple): + """A listed unit's confirmed tags, and the unit's own header names they were confirmed for.""" + + tags: tuple[str, ...] + names: tuple[str | None, ...] + """The unit's own header name at each C index at the confirmation (read before the save).""" + + +@dataclass(frozen=True) +class RefusedUnit: + """One refused unit: the row's tags, its reference unit and the aliases it is read against.""" + + tags: tuple[str, ...] + reference: UnitKey | None + """The row's reference unit; None for a unit whose images disagree with each other.""" + aliases: Mapping[str, tuple[str, ...]] = field(default_factory=dict) + """Label to the header names saved for it when this unit was first refused.""" + + +@dataclass(frozen=True) +class TagReview: + """The refused units and the confirmed ones of a draft.""" + + refused: Mapping[UnitKey, RefusedUnit] = field(default_factory=dict) + confirmed: Mapping[UnitKey, Override] = field(default_factory=dict) + + @property + def empty(self) -> bool: + """True when nothing is refused or confirmed (the file then has no ``tag_review``).""" + return not self.refused and not self.confirmed + + +def review_to_json(review: TagReview) -> dict[str, list[dict[str, object]]]: + """Return the JSON object of a review: units in key order, each with its own fields.""" + return { + "refused": [ + { + "unit": list(key), + "tags": list(unit.tags), + "reference": None if unit.reference is None else list(unit.reference), + "aliases": {k: list(v) for k, v in sorted(unit.aliases.items())}, + } + for key, unit in sorted(review.refused.items()) + ], + "confirmed": [ + {"unit": list(key), "tags": list(unit.tags), "names": list(unit.names)} + for key, unit in sorted(review.confirmed.items()) + ], + } + + +__all__ = ["Override", "RefusedUnit", "TagReview", "review_to_json"] diff --git a/src/morphobricks_preprocessing/repeat_tags.py b/src/morphobricks_preprocessing/repeat_tags.py index 6ac64e6..618a10a 100644 --- a/src/morphobricks_preprocessing/repeat_tags.py +++ b/src/morphobricks_preprocessing/repeat_tags.py @@ -27,17 +27,40 @@ from __future__ import annotations -from collections.abc import Collection, Sequence +from collections.abc import Collection, Mapping, Sequence from .channel_labels import UnitLayout, tags_of from .channel_matrix import Difference, apart_reason, differences, eligible from .dataset import canonical_repeat_groups from .draft_answers import DraftAnswers, UnitKey +from .repeat_review import Override GroupKey = tuple[str, int] """A row: the biological-repeat folder label and the channel count of its units.""" +def header_names(layout: UnitLayout) -> tuple[str | None, ...]: + """Return a unit's own header name at each C index (None where it has none).""" + return tuple(layout.name(i) for i in range(layout.channels)) + + +def override_holds( + override: Override | None, layout: UnitLayout, tags: Sequence[str | None] +) -> bool: + """Return True while the user's confirmation still covers the unit as it is read now. + + It covers the unit only while its tags are the confirmed ones and its own header names are + the ones it was confirmed for. Nothing else voids it: aliases saved later for other units + neither lapse it nor stand in for it. A changed header or tag lists the unit again, never + counted unasked. + """ + return ( + override is not None + and tuple(tags) == override.tags + and header_names(layout) == override.names + ) + + def repeat_groups( layouts: Sequence[UnitLayout], colour: Collection[UnitKey] = () ) -> dict[GroupKey, tuple[UnitLayout, ...]]: @@ -57,6 +80,7 @@ def repeat_fill( group: Sequence[UnitLayout], tags: Sequence[str], labels: Collection[str], + frozen: Mapping[UnitKey, Mapping] | None = None, ) -> tuple[dict[UnitKey, tuple[str, ...]], list[tuple[UnitKey, int]], dict]: """Return the tags to save for the row's units, the cells, and the units refused. @@ -64,9 +88,11 @@ def repeat_fill( another label than the row's at its C index, or says none and is not the first unit's name there (:func:`.channel_matrix.differences`; the first unit is :func:`repeat_lead`). A unit whose images disagree (:func:`repeat_apart`) is neither filled nor listed here: the caller - names it separately. + names it separately. ``frozen`` holds, for a unit already refused, the aliases of the time of + its refusal: aliases saved since (by confirming or tagging other units) never clear it. """ tags = tuple(tags) + frozen = frozen or {} save: dict[UnitKey, tuple[str, ...]] = {} cells: list[tuple[UnitKey, int]] = [] refused: dict[UnitKey, tuple[Difference, ...]] = {} @@ -75,7 +101,7 @@ def repeat_fill( for layout in group: if lead is None or layout.key in apart: continue - found = differences(layout, tags, lead, labels, answers.channels) + found = differences(layout, tags, lead, labels, frozen.get(layout.key, answers.channels)) if found: refused[layout.key] = found continue @@ -149,6 +175,9 @@ def pairing_collision(answers: DraftAnswers, group: Sequence[UnitLayout]) -> dic __all__ = [ "GroupKey", + "Override", + "header_names", + "override_holds", "pairing_collision", "repeat_fill", "repeat_groups", diff --git a/tests/test_draft_tag_review.py b/tests/test_draft_tag_review.py new file mode 100644 index 0000000..aac2559 --- /dev/null +++ b/tests/test_draft_tag_review.py @@ -0,0 +1,123 @@ +"""``tag_review`` of the draft file: the refused and confirmed units of *Tag by repeat*. + +Optional (a draft without it is read as before, and an empty review writes nothing); when present +it is read strictly, so a malformed section is refused with the file, never dropped. +""" + +import json +from dataclasses import replace + +import pytest + +from draft_file_support import complete +from morphobricks_preprocessing.draft_format import ( + DraftFileError, + answers_from_bytes, + answers_to_bytes, +) +from morphobricks_preprocessing.repeat_review import Override, RefusedUnit, TagReview + +GONE, OTHER = ("drug", "rep2", "t1"), ("drug", "rep2", "t2") +REVIEW = TagReview( + { + GONE: RefusedUnit(("DNA", "ACTIN"), ("ctrl", "rep2", "t1"), {"DNA": ("P", "Pb")}), + OTHER: RefusedUnit(("DNA", "ACTIN"), None), + }, + {GONE: Override(("DNA", "ACTIN"), ("P", None))}, +) + + +def _document(review=REVIEW): + return json.loads(answers_to_bytes(replace(complete(), tag_review=review))) + + +def _bytes(document): + return json.dumps(document).encode() + + +def test_the_review_round_trips_and_the_bytes_are_deterministic(): + answers = replace(complete(), tag_review=REVIEW) + data = answers_to_bytes(answers) + assert answers_from_bytes(data) == answers + assert answers_to_bytes(answers_from_bytes(data)) == data + section = json.loads(data)["tag_review"] + assert section["refused"][0] == { + "unit": list(GONE), + "tags": ["DNA", "ACTIN"], + "reference": ["ctrl", "rep2", "t1"], + "aliases": {"DNA": ["P", "Pb"]}, + } + assert section["confirmed"] == [ + {"unit": list(GONE), "tags": ["DNA", "ACTIN"], "names": ["P", None]} + ] + + +@pytest.mark.parametrize("review", [None, TagReview()]) +def test_no_or_an_empty_review_writes_no_section_and_a_file_without_one_is_read_as_before(review): + answers = replace(complete(), tag_review=review) + data = answers_to_bytes(answers) + assert b"tag_review" not in data + assert answers_from_bytes(data) == replace(complete(), tag_review=None) + assert data == answers_to_bytes(complete()) # the bytes of every draft that has none + + +def _mutations(): + def put(path, value): + def apply(doc): + node = doc["tag_review"] + for step in path[:-1]: + node = node[step] + node[path[-1]] = value + + return apply + + def drop(path): + def apply(doc): + node = doc["tag_review"] + for step in path[:-1]: + node = node[step] + del node[path[-1]] + + return apply + + return { + "null": lambda d: d.update(tag_review=None), + "not an object": lambda d: d.update(tag_review=[]), + "unknown key": put(["extra"], 1), + "no refused": drop(["refused"]), + "no confirmed": drop(["confirmed"]), + "refused not a list": put(["refused"], {}), + "refused unknown key": put(["refused", 0, "extra"], 1), + "refused no tags": drop(["refused", 0, "tags"]), + "refused no aliases": drop(["refused", 0, "aliases"]), + "unit of two folders": put(["refused", 0, "unit"], ["a", "b"]), + "unit not text": put(["refused", 0, "unit"], ["a", "b", 3]), + "tags not text": put(["refused", 0, "tags"], ["DNA", None]), + "reference of one folder": put(["refused", 1, "reference"], ["a"]), + "aliases not lists": put(["refused", 0, "aliases"], {"DNA": "P"}), + "aliases not an object": put(["refused", 0, "aliases"], []), + "names not text": put(["confirmed", 0, "names"], ["P", 3]), + "names not a list": put(["confirmed", 0, "names"], "P"), + "confirmed unknown key": put(["confirmed", 0, "extra"], 1), + "unit twice (refused)": lambda d: d["tag_review"]["refused"].append( + d["tag_review"]["refused"][0] + ), + "unit twice (confirmed)": lambda d: d["tag_review"]["confirmed"].append( + d["tag_review"]["confirmed"][0] + ), + } + + +@pytest.mark.parametrize("name", sorted(_mutations())) +def test_a_malformed_section_is_refused_clearly_never_silently_dropped(name): + document = _document() + _mutations()[name](document) + with pytest.raises(DraftFileError) as refusal: + answers_from_bytes(_bytes(document)) + assert "tag_review" in str(refusal.value) + + +def test_the_format_version_is_not_bumped_so_an_older_draft_still_opens(): + document = _document(None) + assert document["version"] == 4 and "tag_review" not in document + assert answers_from_bytes(_bytes(document)).tag_review is None diff --git a/tests/test_notebook_tag_by_repeat_drafts.py b/tests/test_notebook_tag_by_repeat_drafts.py new file mode 100644 index 0000000..148dd94 --- /dev/null +++ b/tests/test_notebook_tag_by_repeat_drafts.py @@ -0,0 +1,222 @@ +"""The tag review belongs to one draft: another folder or output never inherits it. + +Owner rule (22 November): a refused unit never counts until the user confirms that unit, and +aliases saved for other units never tag or clear it, also across restarts and draft switches. +TagGrid and RepeatRows live for the whole notebook, so the refusals and confirmations in memory +are tied to the draft they came from (``_NotebookStore.draft_id``). +""" + +from __future__ import annotations + +import shutil + +import pytest + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from dataclasses import replace # noqa: E402 + +from morphobricks_preprocessing.description_file import DRAFT_FILENAME # noqa: E402 +from morphobricks_preprocessing.draft_format import answers_from_bytes, answers_to_bytes # noqa: E402 +from test_notebook_channels import set_labels # noqa: E402 +from test_notebook_check_save import opened # noqa: E402 +from test_notebook_tag_by_repeat import EXTRA # noqa: E402 +from test_notebook_tag_by_repeat_oneclick import GONE, OTHER # noqa: E402 +from test_notebook_tag_by_repeat_review import _saved_fast # noqa: E402 + + +def _review(out): + return answers_from_bytes((out / DRAFT_FILENAME).read_bytes()).tag_review + + +def _copy_experiment(root, out, tmp_path, name): + """A second experiment folder and output (B) with the draft of A as it was saved.""" + root2, out2 = tmp_path / f"exp_{name}", tmp_path / f"out_{name}" + shutil.copytree(root, root2) + out2.mkdir() + shutil.copy(out / DRAFT_FILENAME, out2 / DRAFT_FILENAME) + return root2, out2 + + +def _point(nb, masks, root, out): + """Point the same notebook at another experiment folder and output, and reach the grid.""" + nb.masks_folder.value = "" + nb.folder.value = str(root) + nb.output.value = str(out) + nb.check_button.click() + nb.masks_folder.value = str(masks) + nb.check_button.click() + nb.preview_checked.set(True) + nb.show_preview() + nb.confirm_button.click() + if not nb.channel_labels.confirmed: # a draft without labels: the user names them first + set_labels(nb, list(EXTRA)) + + +def _untagged(nb, key): + own = nb.draft_answers.units.get(key) + return own is None or not any(own.channels) + + +def test_a_draft_with_a_review_replaces_the_memory_of_the_draft_before_it(tmp_path): + nb, root, masks, out = _saved_fast(tmp_path) # A: GONE confirmed, OTHER refused + root_b, out_b = _copy_experiment(root, out, tmp_path, "b") + # B's own record: only OTHER refused, nothing confirmed (as another session left it) + review_b = replace(_review(out_b), confirmed={}, refused={OTHER: _review(out_b).refused[OTHER]}) + answers_b = answers_from_bytes((out_b / DRAFT_FILENAME).read_bytes()) + (out_b / DRAFT_FILENAME).write_bytes(answers_to_bytes(replace(answers_b, tag_review=review_b))) + rows = nb.channel_grid.by_repeat + assert set(rows.override.confirmed) == {GONE} # A's confirmation, in memory + _point(nb, masks, root_b, out_b) + assert set(rows.refused) == {OTHER} and not rows.override.confirmed # B's, not A's + assert OTHER in rows.listed() and _untagged(nb, OTHER) # not tagged from A's aliases + assert set(_review(out_b).refused) == {OTHER} and not _review(out_b).confirmed + assert not rows.override.editing and not rows.override.drafts + + +def test_a_draft_without_a_review_clears_the_memory_and_shows_nothing_of_the_other(tmp_path): + nb, root, masks, out = _saved_fast(tmp_path) + root_b, out_b = tmp_path / "exp_c", tmp_path / "out_c" + shutil.copytree(root, root_b) + out_b.mkdir() # no draft at all in B + rows = nb.channel_grid.by_repeat + assert set(rows.refused) == {GONE, OTHER} + _point(nb, masks, root_b, out_b) + assert not rows.refused and not rows.override.confirmed and not rows.listed() + assert "not filled" not in rows.message and not rows.notice + review = ( + answers_from_bytes((out_b / DRAFT_FILENAME).read_bytes()).tag_review + if (out_b / DRAFT_FILENAME).exists() + else None + ) + assert review is None or (not review.refused and not review.confirmed) + + +def test_switching_back_restores_the_record_of_the_first_draft_from_its_file(tmp_path): + nb, root, masks, out = _saved_fast(tmp_path) + saved_a = _review(out) + root_b, out_b = tmp_path / "exp_d", tmp_path / "out_d" + shutil.copytree(root, root_b) + out_b.mkdir() + rows = nb.channel_grid.by_repeat + _point(nb, masks, root_b, out_b) + assert not rows.refused + _point(nb, masks, root, out) # back to A + assert _review(out) == saved_a # B never wrote into A's file + assert set(rows.refused) == {GONE, OTHER} and set(rows.override.confirmed) == {GONE} + assert set(rows.listed()) == {OTHER} and _untagged(nb, OTHER) + + +def test_a_failed_save_of_the_review_is_said_on_the_grid_and_retried(tmp_path, monkeypatch): + nb, root, masks, out = _saved_fast(tmp_path) + rows = nb.channel_grid.by_repeat + from morphobricks_preprocessing import notebook_description as nd + + def refuse(*_args, **_kwargs): + raise OSError("disk full") + + monkeypatch.setattr(nd, "save_draft", refuse) + before = (out / DRAFT_FILENAME).read_bytes() + rows.refused.pop(OTHER) # the review changes in memory; the save is refused + assert not rows.persist() and rows.unsaved + nb.channel_grid.refresh() + assert "Not saved" in rows.message + assert (out / DRAFT_FILENAME).read_bytes() == before # the file is as it was + monkeypatch.undo() + assert rows.persist() and not rows.unsaved # retried at the next persist + assert OTHER not in _review(out).refused + nb.channel_grid.refresh() + assert "Not saved" not in rows.message + + +def test_stale_entries_after_the_folder_changed_are_dropped_or_re_referenced(tmp_path): + nb, root, masks, out = _saved_fast(tmp_path) + ref = _review(out).refused[OTHER].reference + assert ref == ("ctrl", "rep2", "t1") + shutil.rmtree(root / "ctrl" / "rep2" / "t1") # OTHER's reference is removed + shutil.rmtree(root / "drug" / "rep2" / "t1") # GONE (a refused unit) is removed + for key in ("ctrl/rep2/t1", "drug/rep2/t1"): + shutil.rmtree(masks / "Nuclei" / key, ignore_errors=True) + fresh = opened(root, masks, out) # no crash + rows = fresh.channel_grid.by_repeat + assert GONE not in rows.refused and GONE not in rows.override.confirmed + assert OTHER in rows.refused and OTHER in rows.listed() # survivor, still listed + assert rows.refused[OTHER].lead is not None and rows.refused[OTHER].lead.key != ref + review = _review(out) + assert set(review.refused) == {OTHER} and review.refused[OTHER].reference != ref + assert _untagged(fresh, OTHER) + + +# Switching only the output folder (the same experiment) --------------------------------------- + + +def _output_b_refusing_other(root, out, tmp_path, name): + """An output folder B for the same experiment: its draft refuses OTHER, confirms nothing.""" + out_b = tmp_path / f"out_{name}" + out_b.mkdir() + answers = answers_from_bytes((out / DRAFT_FILENAME).read_bytes()) + only_other = {OTHER: answers.tag_review.refused[OTHER]} + review = replace(answers.tag_review, confirmed={}, refused=only_other) + answers_b = replace(answers, tag_review=review) + (out_b / DRAFT_FILENAME).write_bytes(answers_to_bytes(answers_b)) + return out_b + + +def test_pointing_only_the_output_at_another_draft_never_tags_its_refused_unit(tmp_path): + _, root, masks, out = _saved_fast(tmp_path) + nb = opened(root, masks, out) # a restart on A (GONE confirmed, aliases saved) + out_b = _output_b_refusing_other(root, out, tmp_path, "b") + grid, rows = nb.channel_grid, nb.channel_grid.by_repeat + before_b = (out_b / DRAFT_FILENAME).read_bytes() + nb.output.value = str(out_b) # the same experiment, another output (and draft) + assert not rows.other_draft() # the grid reopened on B: its own record, not A's + assert set(rows.refused) == {OTHER} and not rows.override.confirmed + grid.same_channels.value = False + grid.same_channels.value = True # untick and retick the statement + assert OTHER in rows.listed() and _untagged(nb, OTHER) + assert not nb.save_experiment() # the refused unit still stops the save + assert _review(out_b).refused.keys() == {OTHER} + assert answers_from_bytes((out_b / DRAFT_FILENAME).read_bytes()).units.get(OTHER) in ( + None, + answers_from_bytes(before_b).units.get(OTHER), + ) + + +def test_trusting_headers_with_the_memory_of_another_draft_restores_first(tmp_path): + _, root, masks, out = _saved_fast(tmp_path) + nb = opened(root, masks, out) + out_b = _output_b_refusing_other(root, out, tmp_path, "c") + grid, rows = nb.channel_grid, nb.channel_grid.by_repeat + nb.output.value = str(out_b) + rows.draft = ("another", "draft") # memory that is another draft's, whatever the way here + assert rows.other_draft() + grid.matrix.trust_headers() # a caller that never reopened the grid + assert not rows.other_draft() and set(rows.refused) == {OTHER} + assert OTHER in rows.listed() and _untagged(nb, OTHER) + + +def test_the_save_is_refused_while_the_memory_belongs_to_another_draft(tmp_path): + _, root, masks, out = _saved_fast(tmp_path) + nb = opened(root, masks, out) + rows = nb.channel_grid.by_repeat + rows.override.confirmed.clear() + rows.refused.clear() # nothing listed: only the draft check can stop the save + rows.draft = ("another", "draft") + nb._refresh_check_save() + assert nb.save_button.disabled + assert "another draft" in nb.save_blocker.value + + +def test_pointing_the_output_back_at_the_first_draft_restores_its_record(tmp_path): + _, root, masks, out = _saved_fast(tmp_path) + nb = opened(root, masks, out) + saved_a = _review(out) + out_b = _output_b_refusing_other(root, out, tmp_path, "d") + rows = nb.channel_grid.by_repeat + nb.output.value = str(out_b) + assert set(rows.override.confirmed) == set() + nb.output.value = str(out) # back to A, the output only + assert _review(out) == saved_a + assert set(rows.refused) == {GONE, OTHER} and set(rows.override.confirmed) == {GONE} + assert set(rows.listed()) == {OTHER} and _untagged(nb, OTHER) diff --git a/tests/test_notebook_tag_by_repeat_oneclick.py b/tests/test_notebook_tag_by_repeat_oneclick.py new file mode 100644 index 0000000..0b234a4 --- /dev/null +++ b/tests/test_notebook_tag_by_repeat_oneclick.py @@ -0,0 +1,203 @@ +"""A refused unit counts only when the user confirms THAT unit (owner decision of 22 November). + +Aliases saved by confirming or tagging another refused unit are not evidence for this one: it +stays listed with its refusal, in fast mode too (no header trust for it), and its editor keeps its +highlights. A listed unit with the same header names as a unit the user confirmed offers +**Confirm the same tags** (and **Confirm all N like it**): the same save and record as the +editor, one click each, nothing automatic. +""" + +from __future__ import annotations + +import pytest + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from morphobricks_preprocessing.notebook_channels_repeat import RepeatRows # noqa: E402 +from test_notebook_channels import set_labels # noqa: E402 +from test_notebook_check_save import answer_all, opened # noqa: E402 +from test_notebook_tag_by_repeat import EXTRA, TAGS, _experiment, _set_row # noqa: E402 +from test_notebook_tag_by_repeat_recheck import _recheck, _rewrite_header # noqa: E402 + +GONE, OTHER, THIRD = ("drug", "rep2", "t1"), ("drug", "rep2", "t2"), ("ctrl", "rep2", "t2") +LEAD = ("ctrl", "rep2", "t1") + + +def _like(units, fast): + """Names where ``units`` share headers (P, Q, Ch3) that no label says; the others X, Y, Ch3.""" + + def names(key): + if key[1] != "rep2": + return None + own = ["P", "Q", "Ch3"] if key in units else ["X", "Y", "Ch3"] + return [*own, "W"] if fast else own + + return names + + +def _fast(tmp_path, units=(GONE, OTHER)): + root, masks, out = _experiment(tmp_path, extra=True, names=_like(units, True)) + nb = opened(root, masks, out) + set_labels(nb, list(EXTRA)) + grid = nb.channel_grid + assert grid.same_channels.value + for index, tag in enumerate(TAGS): + grid.matrix.template_cells[(("ctrl", "rep1", "t1"), index)].value = tag + _set_row(nb, ("rep2", 4), EXTRA) + assert set(grid.by_repeat.listed()) == set(units) + return nb, root, grid.by_repeat + + +def _strict(tmp_path, statement_off): + root, masks, out = _experiment(tmp_path, names=_like((GONE, OTHER), False)) + nb = opened(root, masks, out) + set_labels(nb, list(TAGS)) + _set_row(nb, ("rep2", 3), TAGS) + rows = nb.channel_grid.by_repeat + assert set(rows.listed()) == {GONE, OTHER} + return nb, root, rows + + +def _confirm(nb, rows, key, how, tags): + """Confirm one listed unit: its editor's Confirm, or its cells tagged by hand.""" + if how == "override": + rows.override.buttons[key].click() + rows.override.confirm_button.click() + assert key in rows.override.confirmed + else: + nb.channel_grid.split(key) # out of its block: a click on a block tags every unit in it + for index, tag in enumerate(tags): + nb.channel_grid.cells[(key, index)].value = tag + + +def _text(rows): + out = [] + + def walk(items): + for w in items: + if isinstance(getattr(w, "value", None), str): + out.append(w.value) + if isinstance(getattr(w, "description", None), str): + out.append(w.description) + walk(getattr(w, "children", ())) + + walk(rows.box.children) + return " ".join(out) + + +@pytest.mark.parametrize("how", ["override", "hand"]) +def test_fast_mode_another_refused_unit_is_not_tagged_from_aliases_after_a_recheck(tmp_path, how): + nb, _, rows = _fast(tmp_path) + grid = nb.channel_grid + _confirm(nb, rows, GONE, how, EXTRA) + assert GONE not in rows.listed() and OTHER in rows.listed() + _recheck(nb) # fast mode trusts headers: the aliases saved for GONE say P, Q for its labels + assert set(rows.listed()) == {OTHER} and OTHER in rows.refused + assert ( + not any(nb.draft_answers.units[OTHER].channels) if OTHER in nb.draft_answers.units else True + ) + assert OTHER not in grid.matrix.own + assert not grid.complete and not nb.save_experiment() + _set_row(nb, ("rep2", 4), EXTRA) # the row again: still not a confirmation of OTHER + assert set(rows.listed()) == {OTHER} and not grid.complete + + +def test_fast_mode_one_click_counts_the_unit_with_the_confirmed_tags(tmp_path): + nb, _, rows = _fast(tmp_path) + grid, ov = nb.channel_grid, rows.override + assert not ov.same_buttons # nothing confirmed yet: nothing to offer + _confirm(nb, rows, GONE, "override", EXTRA) + _recheck(nb) + text = _text(rows) + assert ( + "same headers as drug / rep2 / t1, which you confirmed as DNA, ACTIN, PHASE, EXTRA" in text + ) + assert set(ov.same_buttons) == {OTHER} and not ov.all_buttons # one listed unit: no "all" + assert OTHER in rows.listed() # nothing counts until clicked + ov.same_buttons[OTHER].click() + assert not rows.listed() + assert nb.draft_answers.units[OTHER].channels == EXTRA and OTHER in grid.matrix.own + assert ov.confirmed[OTHER].tags == EXTRA and ov.confirmed[OTHER].names == ("P", "Q", "Ch3", "W") + answer_all(nb) + assert nb.draft_answers.units[OTHER].channels_from == "unit" + assert nb.save_experiment() + + +def test_confirm_all_confirms_every_listed_unit_like_the_confirmed_one(tmp_path): + nb, _, rows = _fast(tmp_path, (GONE, OTHER, THIRD)) + ov = rows.override + _confirm(nb, rows, GONE, "override", EXTRA) + assert set(ov.same_buttons) == {OTHER, THIRD} and set(ov.all_buttons) == {GONE} + assert ov.all_buttons[GONE].description.strip() == "Confirm all 2 like drug / rep2 / t1" + _recheck(nb) + assert set(rows.listed()) == {OTHER, THIRD} # untouched by the confirmation and the re-check + ov.all_buttons[GONE].click() + assert not rows.listed() and {OTHER, THIRD} <= set(ov.confirmed) + assert all(nb.draft_answers.units[k].channels == EXTRA for k in (GONE, OTHER, THIRD)) + + +def test_confirm_all_confirms_none_when_any_would_be_refused(tmp_path, monkeypatch): + nb, _, rows = _fast(tmp_path, (GONE, OTHER, THIRD)) + ov = rows.override + _confirm(nb, rows, GONE, "override", EXTRA) + before = nb.draft_answers + monkeypatch.setattr(RepeatRows, "_row_error", staticmethod(lambda tags: "refused")) + assert not ov.confirm_all(GONE) and not ov.confirm_same(OTHER) + assert nb.draft_answers == before and set(ov.confirmed) == {GONE} + assert set(rows.listed()) == {OTHER, THIRD} + monkeypatch.undo() + monkeypatch.setattr(type(nb.channel_grid), "commit", lambda self, tags, cells: False) + assert not ov.confirm_all(GONE) + assert set(ov.confirmed) == {GONE} and set(rows.listed()) == {OTHER, THIRD} + + +@pytest.mark.parametrize("how", ["override", "hand"]) +def test_strict_mode_the_other_unit_keeps_its_refusal_text_and_highlights( + tmp_path, statement_off, how +): + nb, _, rows = _strict(tmp_path, statement_off) + text_before = rows.listed()[OTHER] + assert "header ‘P’" in text_before + _confirm(nb, rows, GONE, how, TAGS) + assert set(rows.listed()) == {OTHER} + assert rows.listed()[OTHER] == text_before # not "its own tags are incomplete" + _recheck(nb) + assert rows.listed()[OTHER] == text_before and "incomplete" not in rows.refused[OTHER].text + assert not nb.channel_grid.complete + offered = _text(rows) + rows.override.buttons[OTHER].click() + text = _text(rows) + assert "#D97706" in text and "C0: header ‘P’" in text and "C1: header ‘Q’" in text + assert "C2: header" not in text + if how == "override": + assert "same headers as drug / rep2 / t1" in offered # offered, not applied + assert nb.draft_answers.units.get(OTHER) is None or not any( + nb.draft_answers.units[OTHER].channels + ) + + +def test_a_refused_unit_whose_own_header_changes_to_match_its_row_still_clears( + tmp_path, statement_off +): + nb, root, rows = _strict(tmp_path, statement_off) + _rewrite_header(root, OTHER, ["X", "Y", "Ch3"]) # now the row's own names + _recheck(nb) + assert OTHER in rows.listed() # listed while its own tags are incomplete, as before + _set_row(nb, ("rep2", 3), TAGS) # the row fills it: nothing contradicts any more + assert set(rows.listed()) == {GONE} and OTHER not in rows.refused + assert nb.draft_answers.units[OTHER].channels == TAGS + + +def test_a_unit_that_is_not_refused_is_still_tagged_by_hand_and_by_trusted_headers( + tmp_path, statement_off +): + nb, _, rows = _strict(tmp_path, statement_off) + grid = nb.channel_grid + assert rows.standing() == {GONE, OTHER} + assert LEAD not in rows.refused + assert nb.draft_answers.units[LEAD].channels == TAGS # filled by the row, as today + grid.split(GONE) + for index, tag in enumerate(TAGS): + grid.cells[(GONE, index)].value = tag # hand-tagging a refused unit is its confirmation + assert set(rows.listed()) == {OTHER} diff --git a/tests/test_notebook_tag_by_repeat_override.py b/tests/test_notebook_tag_by_repeat_override.py new file mode 100644 index 0000000..234f466 --- /dev/null +++ b/tests/test_notebook_tag_by_repeat_override.py @@ -0,0 +1,273 @@ +"""Override one listed unit of *Tag by repeat*, starting from its row's tags (owner requirement). + +A unit whose header disagrees with its repeat's row is listed. The user can override it from +the row's tags, with the disagreements highlighted; it counts as tagged only after Confirm, +and the confirmation lapses when the unit's tags, its header, the reference's header or the +saved aliases change. +""" + +from __future__ import annotations + +import pytest + +from morphobricks_preprocessing.channel_labels import UnitLayout, tags_of +from morphobricks_preprocessing.description import description_from_bytes +from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME +from morphobricks_preprocessing.repeat_tags import Override, header_names, override_holds + +LABELS = ("DNA", "ACTIN", "PHASE") + + +def _layout(key, names): + return UnitLayout(key, "/".join(key) + "/a.tif", 3, tuple(names)) + + +def test_pure_a_confirmation_holds_only_while_tags_and_the_units_own_header_are_unchanged(): + unit = _layout(("drug", "rep2", "t1"), ("P", "Q", "Ch3")) + confirmed = Override(LABELS, header_names(unit)) + assert confirmed.names == ("P", "Q", "Ch3") + assert override_holds(confirmed, unit, LABELS) + assert not override_holds(None, unit, LABELS) + assert not override_holds(confirmed, unit, ("ACTIN", "DNA", "PHASE")) # other tags + assert not override_holds(confirmed, unit, (*LABELS[:2], None)) + moved = _layout(unit.key, ("P", "R", "Ch3")) # the unit's header changed + assert not override_holds(confirmed, moved, LABELS) + + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from test_notebook_channels import set_labels # noqa: E402 +from test_notebook_check_save import answer_all, opened # noqa: E402 +from test_notebook_tag_by_repeat import TAGS, UNITS, _experiment, _set_row # noqa: E402 +from test_notebook_tag_by_repeat_recheck import ( # noqa: E402 + _recheck, + _rewrite_header, + _two_odd, +) + +GONE, KEPT = ("drug", "rep2", "t1"), ("drug", "rep1", "t1") +LEAD = ("ctrl", "rep2", "t1") + + +def _listed(tmp_path): + root, masks, out = _experiment(tmp_path, names=_two_odd) + nb = opened(root, masks, out) + set_labels(nb, [*TAGS, "EXTRA"]) # one more label, to change a tag without a duplicate + _set_row(nb, ("rep1", 3), TAGS) + _set_row(nb, ("rep2", 3), TAGS) + rows = nb.channel_grid.by_repeat + assert set(rows.listed()) == {GONE, KEPT} + return nb, root, out, rows + + +def _html(rows, key): + return " ".join( + w.value + for w in _walk(rows.override.build(3)) + if hasattr(w, "value") and isinstance(w.value, str) + ) + + +def _walk(widgets_): + for w in widgets_: + yield w + yield from _walk(getattr(w, "children", ())) + + +def _open_editor(nb, rows, key=GONE): + rows.override.buttons[key].click() + assert rows.override.editing == key + return rows.override + + +def _confirm_gone(nb, rows): + """Override GONE, then tag the other listed unit by hand so the draft can publish.""" + ov = _open_editor(nb, rows) + ov.confirm_button.click() + assert GONE in ov.confirmed + return ov + + +def test_start_prefills_the_rows_tags_highlights_the_differences_and_saves_nothing( + tmp_path, statement_off +): + nb, _, _, rows = _listed(tmp_path) + grid, before = nb.channel_grid, nb.draft_answers + ov = _open_editor(nb, rows) + assert [ov.cells[(GONE, i)].value for i in range(3)] == list(TAGS) + assert nb.draft_answers == before # nothing saved + text = " ".join( + w.value for w in _walk(rows.box.children) if isinstance(getattr(w, "value", None), str) + ) + assert "C0: header ‘P’" in text and "C1: header ‘Q’" in text and "C2: header" not in text + assert "#D97706" in text and "as the row" in text # orange box; C2 is as the row + assert not grid.complete and GONE in rows.listed() + assert not nb.save_experiment() + # changing the draft redraws the highlights and still saves nothing + ov.cells[(GONE, 2)].value = None + assert nb.draft_answers == before and rows.override.drafts[GONE][2] is None + assert "not tagged" in " ".join( + w.value for w in _walk(rows.box.children) if isinstance(getattr(w, "value", None), str) + ) + + +def test_no_button_for_a_unit_without_a_reference_and_cancel_drops_the_draft( + tmp_path, statement_off +): + nb, _, _, rows = _listed(tmp_path) + assert set(rows.override.buttons) == {GONE, KEPT} + ov = _open_editor(nb, rows) + ov.cancel_button.click() + assert ov.editing is None and GONE not in ov.drafts and not ov.confirmed + assert GONE in rows.listed() + + +def test_confirm_counts_the_unit_and_publishes_its_tags(tmp_path, statement_off): + nb, _, out, rows = _listed(tmp_path) + ov = _confirm_gone(nb, rows) + assert GONE not in rows.listed() and KEPT in rows.listed() + assert nb.draft_answers.units[GONE].channels == TAGS + assert ov.editing is None + ov2 = _open_editor(nb, rows, KEPT) + ov2.confirm_button.click() + assert not rows.listed() + answer_all(nb) + assert nb.save_experiment() + published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) + units = [ + u + for repeat in published.repeats.values() + for member in repeat.members.values() + for u in member.technical_repeats.values() + ] + assert len(units) == len(UNITS) and all(u.channels == TAGS for u in units) + + +def _fast_names(key): + if key[1] != "rep2": + return None + return ["P", "Q", "Ch3", "W"] if key == GONE else ["X", "Y", "Ch3", "W"] + + +def test_fast_mode_confirm_marks_the_unit_as_tagged_on_its_own(tmp_path): + from test_notebook_tag_by_repeat import EXTRA + + root, masks, out = _experiment(tmp_path, extra=True, names=_fast_names) + nb = opened(root, masks, out) + set_labels(nb, list(EXTRA)) + grid = nb.channel_grid + assert grid.same_channels.value + for index, tag in enumerate(TAGS): + grid.matrix.template_cells[(("ctrl", "rep1", "t1"), index)].value = tag + rows = grid.by_repeat + _set_row(nb, ("rep2", 4), EXTRA) + assert list(rows.listed()) == [GONE] + ov = _open_editor(nb, rows) + assert [ov.cells[(GONE, i)].value for i in range(4)] == list(EXTRA) + ov.confirm_button.click() + assert not rows.listed() + assert nb.draft_answers.units[GONE].channels == EXTRA + assert GONE in grid.matrix.own + answer_all(nb) + assert nb.draft_answers.units[GONE].channels_from == "unit" + assert nb.save_experiment() + + +@pytest.mark.parametrize("draft", [("DNA", None, "PHASE"), ("DNA", "DNA", "PHASE")]) +def test_confirm_is_refused_on_an_incomplete_or_duplicate_draft(tmp_path, statement_off, draft): + nb, _, _, rows = _listed(tmp_path) + before = nb.draft_answers + ov = _open_editor(nb, rows) + for i, tag in enumerate(draft): + ov.cells[(GONE, i)].value = tag + ov.confirm_button.click() + assert nb.draft_answers == before and not ov.confirmed + assert GONE in rows.listed() and ov.editing == GONE + assert "Tag every channel of the row" in rows.message + + +def test_a_failed_save_confirms_nothing(tmp_path, statement_off, monkeypatch): + nb, _, _, rows = _listed(tmp_path) + ov = _open_editor(nb, rows) + monkeypatch.setattr(type(nb.channel_grid), "commit", lambda self, tags, cells: False) + ov.confirm_button.click() + assert not ov.confirmed and GONE in rows.listed() + + +def test_editing_after_the_confirmation_voids_it(tmp_path, statement_off): + # the grid's own dropdown saves the new tag and the header name as its alias, so the unit is + # then answered by that edit (not listed); the confirmation no longer covers its tags + nb, _, _, rows = _listed(tmp_path) + ov = _confirm_gone(nb, rows) + grid = nb.channel_grid + layout = next(u for u in grid.layouts if u.key == GONE) + held = tags_of(layout, nb.draft_answers.units[GONE]) + assert override_holds(ov.confirmed[GONE], layout, held) + grid.cells[(GONE, 0)].value = "EXTRA" + edited = tags_of(layout, nb.draft_answers.units[GONE]) + assert edited[0] == "EXTRA" + assert not override_holds(ov.confirmed[GONE], layout, edited) + + +def test_a_recheck_that_changes_nothing_keeps_the_unit_unlisted(tmp_path, statement_off): + nb, _, _, rows = _listed(tmp_path) + _confirm_gone(nb, rows) + _recheck(nb) + assert GONE not in rows.listed() + assert nb.draft_answers.units[GONE].channels == TAGS + + +def test_a_changed_unit_header_voids_the_confirmation_but_keeps_the_saved_tags( + tmp_path, statement_off +): + nb, root, _, rows = _listed(tmp_path) + _confirm_gone(nb, rows) + _rewrite_header(root, GONE, ["P", "R", "Ch3"]) # a name nobody confirmed + _recheck(nb) + assert GONE in rows.listed() + assert nb.draft_answers.units[GONE].channels == TAGS + + +def test_a_changed_reference_header_leaves_a_confirmed_unit_counted(tmp_path, statement_off): + # saving the tags also saves the unit's header names as the labels' aliases, so its + # names then say a label and no longer depend on the reference's header + nb, root, _, rows = _listed(tmp_path) + _confirm_gone(nb, rows) + _rewrite_header(root, LEAD, ["Z", "Y", "Ch3"]) + _recheck(nb) + assert GONE not in rows.listed() + assert nb.draft_answers.units[GONE].channels == TAGS + + +def test_a_removed_unit_drops_its_confirmation(tmp_path, statement_off): + import shutil + + nb, root, _, rows = _listed(tmp_path) + rows.override.confirmed[GONE] = Override( + TAGS, ("P", "Q", "Ch3") + ) # as if a confirmation were held + shutil.rmtree(root.joinpath(*GONE)) + _recheck(nb) + assert GONE not in rows.override.confirmed + + +def test_a_row_save_that_fills_the_unit_drops_its_confirmation(tmp_path, statement_off): + nb, root, _, rows = _listed(tmp_path) + _confirm_gone(nb, rows) + _rewrite_header(root, GONE, [None, None, None]) + _recheck(nb) + assert GONE in rows.override.confirmed or GONE not in rows.refused + _set_row(nb, ("rep2", 3), TAGS) + assert GONE not in rows.override.confirmed + + +def test_the_confirmation_survives_a_mode_switch_and_a_reopen(tmp_path, statement_off): + nb, _, _, rows = _listed(tmp_path) + _confirm_gone(nb, rows) + grid = nb.channel_grid + for fast in (True, False): + grid.same_channels.value = fast + grid.open(grid.layouts, grid.labels, grid.rows.thumbs) + assert GONE not in rows.listed(), fast + assert nb.draft_answers.units[GONE].channels == TAGS, fast diff --git a/tests/test_notebook_tag_by_repeat_review.py b/tests/test_notebook_tag_by_repeat_review.py new file mode 100644 index 0000000..e697b9a --- /dev/null +++ b/tests/test_notebook_tag_by_repeat_review.py @@ -0,0 +1,184 @@ +"""Review of the per-unit override: a changed label, a new session, the current reference. + +The owner rule of 22 November: a refused unit counts only when the user confirms THAT unit, in +every session. The refusals and confirmations are kept in the draft file (``tag_review``), and a +label renamed or removed after a refusal never breaks the override editor. +""" + +from __future__ import annotations + +import pytest + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from morphobricks_preprocessing.description_file import DRAFT_FILENAME # noqa: E402 +from morphobricks_preprocessing.draft_format import answers_from_bytes # noqa: E402 +from test_notebook_channels import set_labels # noqa: E402 +from test_notebook_check_save import opened # noqa: E402 +from test_notebook_tag_by_repeat import EXTRA, TAGS, _experiment, _set_row # noqa: E402 +from test_notebook_tag_by_repeat_oneclick import ( # noqa: E402 + GONE, + OTHER, + _confirm, + _fast, + _like, + _strict, + _text, +) + + +def _rename(nb, old, new): + """Rename one label on the labels card (open it, retype the label, confirm again).""" + card = nb.channel_labels + card.confirm.button.click() + row = next(r for r in card.rows if r.id_box.value == old) + row.id_box.value = new + card.confirm.button.click() + assert card.confirmed and new in nb.channel_grid.labels + + +def _picked(rows, key, tags): + """Choose each tag in the open editor's dropdowns (nothing is saved before Confirm).""" + for index, tag in enumerate(tags): + rows.override.cells[(key, index)].value = tag + + +def _renamed_then_override(nb, rows, old, tags): + """Rename ``old`` after the refusal; the override opens blank there and confirms.""" + assert old in rows.refused[GONE].tags + _rename(nb, old, "RENAMED") + assert old in rows.refused[GONE].tags # the refusal is as it was; the label is gone + rows.override.buttons[GONE].click() # at 4bdb64e: TraitError, the editor never opens + index = rows.refused[GONE].tags.index(old) + assert rows.override.editing == GONE + assert rows.override.drafts[GONE][index] is None # blank, never the old label + nb.channel_grid.refresh() # every later refresh worked (it raised, and kept raising) + assert rows.override.cells[(GONE, index)].value is None + renamed = ["RENAMED" if t == old else t for t in tags] + _picked(rows, GONE, renamed) + assert rows.override.confirm() and GONE not in rows.listed() + assert nb.draft_answers.units[GONE].channels == tuple(renamed) + assert rows.override.confirmed[GONE].tags == tuple(renamed) + + +def test_fast_a_label_renamed_after_the_refusal_opens_the_override_blank_and_it_confirms(tmp_path): + nb, _, rows = _fast(tmp_path) + _renamed_then_override(nb, rows, EXTRA[3], EXTRA) + + +def test_strict_a_label_renamed_after_the_refusal_opens_the_override_blank_and_it_confirms( + tmp_path, statement_off +): + nb, _, rows = _strict(tmp_path, statement_off) + _renamed_then_override(nb, rows, TAGS[2], TAGS) + + +def test_a_label_renamed_while_the_editor_is_open_is_blanked_not_raised(tmp_path): + nb, _, rows = _fast(tmp_path) + rows.override.buttons[GONE].click() + assert rows.override.drafts[GONE][3] == "EXTRA" + _rename(nb, "EXTRA", "RENAMED") # the labels card is above the editor + assert rows.override.editing == GONE and rows.override.drafts[GONE][3] is None + assert rows.override.cells[(GONE, 3)].value is None + assert not rows.override.confirm() # not every channel is tagged: refused, editor stays + assert rows.override.editing == GONE + + +def test_the_one_click_offer_never_offers_a_label_that_is_gone(tmp_path): + nb, _, rows = _fast(tmp_path) + _confirm(nb, rows, GONE, "override", EXTRA) + assert OTHER in rows.override.same_buttons + _rename(nb, "EXTRA", "RENAMED") + assert not rows.override.same_buttons and not rows.override.all_buttons + assert "which you confirmed as" not in _text(rows) + assert not rows.override.confirm_same(OTHER) + assert OTHER in rows.listed() + + +# A new session on the same draft ------------------------------------------------------------ + + +def _saved_fast(tmp_path): + """Fast mode: GONE and OTHER refused, GONE confirmed (aliases P, Q saved), draft on disk.""" + root, masks, out = _experiment(tmp_path, extra=True, names=_like((GONE, OTHER), True)) + nb = opened(root, masks, out) + set_labels(nb, list(EXTRA)) + for index, tag in enumerate(TAGS): + nb.channel_grid.matrix.template_cells[(("ctrl", "rep1", "t1"), index)].value = tag + _set_row(nb, ("rep2", 4), EXTRA) + rows = nb.channel_grid.by_repeat + assert set(rows.listed()) == {GONE, OTHER} + _confirm(nb, rows, GONE, "override", EXTRA) + return nb, root, masks, out + + +def test_a_new_notebook_on_the_draft_keeps_the_refused_unit_refused(tmp_path): + _, root, masks, out = _saved_fast(tmp_path) + nb = opened(root, masks, out) # a fresh notebook (a kernel restart) on the saved draft + grid, rows = nb.channel_grid, nb.channel_grid.by_repeat + assert grid.same_channels.value + assert set(rows.listed()) == {OTHER} and set(rows.refused) == {GONE, OTHER} + assert set(rows.override.confirmed) == {GONE} + own = nb.draft_answers.units.get(OTHER) + assert own is None or not any(own.channels) # not tagged from the aliases saved for GONE + assert OTHER not in grid.matrix.own and not grid.complete + assert not nb.save_experiment() + assert set(rows.override.same_buttons) == {OTHER} # the one-click offer is still made + rows.override.same_buttons[OTHER].click() + assert not rows.listed() and nb.draft_answers.units[OTHER].channels == EXTRA + + +def test_the_review_is_in_the_draft_file_and_a_draft_without_it_opens_as_before(tmp_path): + nb, root, masks, out = _saved_fast(tmp_path) + review = answers_from_bytes((out / DRAFT_FILENAME).read_bytes()).tag_review + assert set(review.refused) == {GONE, OTHER} and set(review.confirmed) == {GONE} + assert review.confirmed[GONE].tags == EXTRA and review.refused[OTHER].reference == ( + "ctrl", + "rep2", + "t1", + ) + assert review.refused[OTHER].tags == EXTRA # the row's tags at the click + rows = nb.channel_grid.by_repeat + rows.refused.clear() + rows.override.confirmed.clear() + rows.persist() # nothing refused any more: the section is not written at all + assert b"tag_review" not in (out / DRAFT_FILENAME).read_bytes() + fresh = opened(root, masks, out) + assert not fresh.channel_grid.by_repeat.refused + assert not fresh.channel_grid.by_repeat.override.confirmed + + +def test_a_refused_unit_that_was_confirmed_by_hand_is_restored_listed_no_more(tmp_path): + nb, root, masks, out = _saved_fast(tmp_path) + assert GONE in nb.channel_grid.by_repeat.refused + fresh = opened(root, masks, out) + assert GONE in fresh.channel_grid.by_repeat.refused # the refusal is kept + assert GONE not in fresh.channel_grid.by_repeat.listed() # its confirmation still holds + + +# The reference is the current one --------------------------------------------------------- + + +def test_standing_reads_the_row_as_it_is_now_not_as_at_the_click(tmp_path): + nb, _, rows = _fast(tmp_path) + layouts = {u.key: u for u in nb.channel_grid.layouts} + assert rows.standing() == {GONE, OTHER} + # The click-time reference had the names OTHER has (P, Q), so nothing contradicted: the row's + # reference now is the first unit of the row (X, Y), which OTHER's header contradicts. + rows.refused[OTHER] = rows.refused[OTHER]._replace(lead=layouts[GONE]) + assert OTHER in rows.standing() # at 4bdb64e: not standing, so tagged from its header names + _confirm(nb, rows, GONE, "override", EXTRA) # the aliases P, Q are saved for GONE + nb.channel_grid.matrix.trust_headers() + assert OTHER in rows.standing() and OTHER not in nb.channel_grid.matrix.own + own = nb.draft_answers.units.get(OTHER) + assert own is None or not any(own.channels) + + +def test_confirm_all_buttons_keep_the_order_of_the_listed_units(tmp_path, monkeypatch): + nb, _, rows = _fast(tmp_path) + sources = [("s", f"rep{n}", "t1") for n in (7, 3, 9, 1, 8, 2)] # no order a set would give + likes = {("u", src[1], f"t{n}"): (src, EXTRA) for src in sources for n in (1, 2)} + monkeypatch.setattr(type(rows.override), "_likes", lambda self, offered, current: likes) + rows.override.build(4) + assert list(rows.override.all_buttons) == sources